Compare commits
4 Commits
v0.6.18
...
d0207f336f
| Author | SHA1 | Date | |
|---|---|---|---|
| d0207f336f | |||
| 9360f32b66 | |||
| 60176f2d8b | |||
| f9cd5bce0f |
@@ -1,6 +1,6 @@
|
||||
# .gitea/workflows/ci.yaml
|
||||
# ============================================
|
||||
# Armature - CI/CD Pipeline (v0.17.3)
|
||||
# Switchboard Core - CI/CD Pipeline (v0.17.3)
|
||||
# ============================================
|
||||
# Single unified image (Go backend + nginx frontend).
|
||||
# v0.1.0: Dropped FE/BE image split per ROADMAP design decision.
|
||||
@@ -29,22 +29,22 @@
|
||||
# Tags (v*) → always full pipeline
|
||||
#
|
||||
# Deployment mapping (single domain, path-based):
|
||||
# PR → FE + BE :dev → armature.DOMAIN/dev/ (DB wipe + fresh schema)
|
||||
# Push to main → FE + BE :test → armature.DOMAIN/test/ (migrate only)
|
||||
# Tag v* → FE + BE :latest → armature.DOMAIN/ (migrate only)
|
||||
# PR → FE + BE :dev → switchboard.DOMAIN/dev/ (DB wipe + fresh schema)
|
||||
# Push to main → FE + BE :test → switchboard.DOMAIN/test/ (migrate only)
|
||||
# Tag v* → FE + BE :latest → switchboard.DOMAIN/ (migrate only)
|
||||
# → Unified :latest → Docker Hub (not deployed)
|
||||
#
|
||||
# Database lifecycle:
|
||||
# CI: bootstrap (admin creds) → create DB + role + extensions
|
||||
# CI: dev wipe (app creds) → drop tables for fresh install test
|
||||
# BE: auto-migrate on startup → schema_migrations tracking
|
||||
# BE: bootstrap admin from ARMATURE_ADMIN_* env vars (upsert on every restart)
|
||||
# BE: bootstrap admin from SWITCHBOARD_ADMIN_* env vars (upsert on every restart)
|
||||
#
|
||||
# Shared PG safety:
|
||||
# - Bootstrap uses IF NOT EXISTS (idempotent)
|
||||
# - Dev wipe REFUSES to run on databases not ending in _dev
|
||||
# - Admin creds never reach the backend pods
|
||||
# - Each env has its own DB name (armature_{dev,test,})
|
||||
# - Each env has its own DB name (switchboard_core_{dev,test,})
|
||||
#
|
||||
# Required Gitea Variables:
|
||||
# REGISTRY, NAMESPACE, DOMAIN, POSTGRES_HOST
|
||||
@@ -58,7 +58,7 @@
|
||||
# Required Gitea Secrets:
|
||||
# POSTGRES_USER, POSTGRES_PASSWORD
|
||||
# POSTGRES_ADMIN_USER, POSTGRES_ADMIN_PASSWORD
|
||||
# ARMATURE_ADMIN_USERNAME, ARMATURE_ADMIN_PASSWORD, ARMATURE_ADMIN_EMAIL
|
||||
# SWITCHBOARD_ADMIN_USERNAME, SWITCHBOARD_ADMIN_PASSWORD, SWITCHBOARD_ADMIN_EMAIL
|
||||
# ENCRYPTION_KEY — AES-256 key for API key encryption (openssl rand -base64 32)
|
||||
# PROVIDER_KEY — API key for live provider integration tests (optional, tests skip if missing)
|
||||
# DOCKERHUB_USERNAME, DOCKERHUB_TOKEN (optional)
|
||||
@@ -88,8 +88,8 @@ env:
|
||||
CERT_ISSUER: ${{ vars.CERT_ISSUER_PROD || 'letsencrypt-prod' }}
|
||||
POSTGRES_HOST: ${{ vars.POSTGRES_HOST || 'postgres-primary.postgres.svc.cluster.local' }}
|
||||
POSTGRES_PORT: ${{ vars.POSTGRES_PORT || '5432' }}
|
||||
IMAGE: ${{ vars.REGISTRY }}/armature
|
||||
DOCKERHUB_IMAGE: ${{ vars.DOCKERHUB_IMAGE || 'gobha/armature' }}
|
||||
IMAGE: ${{ vars.REGISTRY }}/switchboard/core
|
||||
DOCKERHUB_IMAGE: ${{ vars.DOCKERHUB_IMAGE || 'gobha/switchboard-core' }}
|
||||
|
||||
jobs:
|
||||
# ── Stage 0: Detect Changed Paths ──────────────
|
||||
@@ -319,7 +319,7 @@ jobs:
|
||||
PGPASSWORD: ${{ secrets.POSTGRES_ADMIN_PASSWORD }}
|
||||
APP_USER: ${{ secrets.POSTGRES_USER }}
|
||||
APP_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
|
||||
DB_NAME: armature_ci
|
||||
DB_NAME: switchboard_core_ci
|
||||
run: |
|
||||
echo "━━━ CI Test Database Setup ━━━"
|
||||
# Create DB for Go integration tests (admin creds)
|
||||
@@ -363,7 +363,7 @@ jobs:
|
||||
PGUSER: ${{ secrets.POSTGRES_ADMIN_USER }}
|
||||
PGPASSWORD: ${{ secrets.POSTGRES_ADMIN_PASSWORD }}
|
||||
run: |
|
||||
psql -c "DROP DATABASE IF EXISTS armature_ci;" postgres
|
||||
psql -c "DROP DATABASE IF EXISTS switchboard_core_ci;" postgres
|
||||
echo "✓ Dropped CI test database"
|
||||
|
||||
# ── Stage 2: Build, Database, Deploy ─────────
|
||||
@@ -395,9 +395,9 @@ jobs:
|
||||
- name: Determine environment
|
||||
id: setup
|
||||
run: |
|
||||
# All environments share one host: armature.DOMAIN
|
||||
# All environments share one host: switchboard.DOMAIN
|
||||
# Environments are separated by path prefix (BASE_PATH)
|
||||
DEPLOY_HOST="armature.${DOMAIN}"
|
||||
DEPLOY_HOST="switchboard.${DOMAIN}"
|
||||
echo "DEPLOY_HOST=${DEPLOY_HOST}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if [[ "${{ gitea.event_name }}" == "pull_request" ]]; then
|
||||
@@ -406,14 +406,13 @@ jobs:
|
||||
echo "IMAGE_TAG=dev" >> "$GITHUB_OUTPUT"
|
||||
echo "BASE_PATH=/dev" >> "$GITHUB_OUTPUT"
|
||||
echo "DEPLOY_SUFFIX=-dev" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_NAME=armature_dev" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_NAME=switchboard_core_dev" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_WIPE=true" >> "$GITHUB_OUTPUT"
|
||||
echo "REPLICAS=1" >> "$GITHUB_OUTPUT"
|
||||
echo "MEMORY_REQUEST=256Mi" >> "$GITHUB_OUTPUT"
|
||||
echo "MEMORY_LIMIT=512Mi" >> "$GITHUB_OUTPUT"
|
||||
echo "CPU_REQUEST=50m" >> "$GITHUB_OUTPUT"
|
||||
echo "CPU_LIMIT=250m" >> "$GITHUB_OUTPUT"
|
||||
echo "BUNDLED_PACKAGES=*" >> "$GITHUB_OUTPUT"
|
||||
echo "env_label=dev (PR #${{ gitea.event.pull_request.number }})" >> "$GITHUB_OUTPUT"
|
||||
elif [[ "${{ gitea.ref }}" == refs/tags/v* ]]; then
|
||||
VERSION="${{ gitea.ref_name }}"
|
||||
@@ -423,14 +422,13 @@ jobs:
|
||||
echo "EXTRA_TAG=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "BASE_PATH=" >> "$GITHUB_OUTPUT"
|
||||
echo "DEPLOY_SUFFIX=" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_NAME=armature" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_NAME=switchboard_core" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_WIPE=false" >> "$GITHUB_OUTPUT"
|
||||
echo "REPLICAS=2" >> "$GITHUB_OUTPUT"
|
||||
echo "MEMORY_REQUEST=256Mi" >> "$GITHUB_OUTPUT"
|
||||
echo "MEMORY_LIMIT=512Mi" >> "$GITHUB_OUTPUT"
|
||||
echo "CPU_REQUEST=100m" >> "$GITHUB_OUTPUT"
|
||||
echo "CPU_LIMIT=500m" >> "$GITHUB_OUTPUT"
|
||||
echo "BUNDLED_PACKAGES=notes,chat,chat-core,mermaid-renderer,schedules" >> "$GITHUB_OUTPUT"
|
||||
echo "is_release=true" >> "$GITHUB_OUTPUT"
|
||||
echo "env_label=production (${VERSION})" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
@@ -439,14 +437,13 @@ jobs:
|
||||
echo "IMAGE_TAG=test" >> "$GITHUB_OUTPUT"
|
||||
echo "BASE_PATH=/test" >> "$GITHUB_OUTPUT"
|
||||
echo "DEPLOY_SUFFIX=-test" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_NAME=armature_test" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_NAME=switchboard_core_test" >> "$GITHUB_OUTPUT"
|
||||
echo "DB_WIPE=false" >> "$GITHUB_OUTPUT"
|
||||
echo "REPLICAS=1" >> "$GITHUB_OUTPUT"
|
||||
echo "MEMORY_REQUEST=256Mi" >> "$GITHUB_OUTPUT"
|
||||
echo "MEMORY_LIMIT=512Mi" >> "$GITHUB_OUTPUT"
|
||||
echo "CPU_REQUEST=50m" >> "$GITHUB_OUTPUT"
|
||||
echo "CPU_LIMIT=250m" >> "$GITHUB_OUTPUT"
|
||||
echo "BUNDLED_PACKAGES=notes,chat,chat-core" >> "$GITHUB_OUTPUT"
|
||||
echo "env_label=test (main)" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
@@ -582,17 +579,14 @@ jobs:
|
||||
# ── Push to Docker Hub (release only) ────────
|
||||
- name: Push to Docker Hub
|
||||
if: steps.setup.outputs.is_release == 'true'
|
||||
env:
|
||||
DH_USER: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DH_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
run: |
|
||||
docker tag ${IMAGE}:${{ steps.setup.outputs.IMAGE_TAG }} ${DOCKERHUB_IMAGE}:latest
|
||||
docker tag ${IMAGE}:${{ steps.setup.outputs.IMAGE_TAG }} ${DOCKERHUB_IMAGE}:${{ steps.setup.outputs.EXTRA_TAG }}
|
||||
if [[ -n "${DH_TOKEN}" ]]; then
|
||||
echo "${DH_TOKEN}" | docker login -u "${DH_USER}" --password-stdin
|
||||
if [[ -n "${{ secrets.DOCKERHUB_TOKEN }}" ]]; then
|
||||
echo "${{ secrets.DOCKERHUB_TOKEN }}" | \
|
||||
docker login -u "${{ secrets.DOCKERHUB_USERNAME }}" --password-stdin
|
||||
docker push ${DOCKERHUB_IMAGE}:latest
|
||||
docker push ${DOCKERHUB_IMAGE}:${{ steps.setup.outputs.EXTRA_TAG }}
|
||||
echo "✓ Pushed to Docker Hub"
|
||||
else
|
||||
echo "⚠ Docker Hub credentials not configured, skipping push"
|
||||
fi
|
||||
@@ -606,31 +600,31 @@ jobs:
|
||||
env:
|
||||
PG_USER: ${{ secrets.POSTGRES_USER }}
|
||||
PG_PASS: ${{ secrets.POSTGRES_PASSWORD }}
|
||||
SW_ADMIN_USER: ${{ secrets.ARMATURE_ADMIN_USERNAME }}
|
||||
SW_ADMIN_PASS: ${{ secrets.ARMATURE_ADMIN_PASSWORD }}
|
||||
SW_ADMIN_EMAIL: ${{ secrets.ARMATURE_ADMIN_EMAIL }}
|
||||
SW_ADMIN_USER: ${{ secrets.SWITCHBOARD_ADMIN_USERNAME }}
|
||||
SW_ADMIN_PASS: ${{ secrets.SWITCHBOARD_ADMIN_PASSWORD }}
|
||||
SW_ADMIN_EMAIL: ${{ secrets.SWITCHBOARD_ADMIN_EMAIL }}
|
||||
SEED_USERS: ${{ vars.SEED_USERS }}
|
||||
ENCRYPTION_KEY: ${{ secrets.ENCRYPTION_KEY }}
|
||||
run: |
|
||||
kubectl create secret generic armature-db-credentials \
|
||||
kubectl create secret generic switchboard-db-credentials \
|
||||
--namespace=${NAMESPACE} \
|
||||
--from-literal=POSTGRES_USER="${PG_USER}" \
|
||||
--from-literal=POSTGRES_PASSWORD="${PG_PASS}" \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
|
||||
kubectl create secret generic armature-admin \
|
||||
kubectl create secret generic switchboard-admin \
|
||||
--namespace=${NAMESPACE} \
|
||||
--from-literal=username="${SW_ADMIN_USER}" \
|
||||
--from-literal=password="${SW_ADMIN_PASS}" \
|
||||
--from-literal=email="${SW_ADMIN_EMAIL}" \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
|
||||
kubectl create secret generic armature-seed-users \
|
||||
kubectl create secret generic switchboard-seed-users \
|
||||
--namespace=${NAMESPACE} \
|
||||
--from-literal=users="${SEED_USERS}" \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
|
||||
kubectl create secret generic armature-encryption \
|
||||
kubectl create secret generic switchboard-encryption \
|
||||
--namespace=${NAMESPACE} \
|
||||
--from-literal=ENCRYPTION_KEY="${ENCRYPTION_KEY}" \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
@@ -645,7 +639,7 @@ jobs:
|
||||
S3_REGION: ${{ vars.S3_REGION || 'us-east-1' }}
|
||||
S3_PREFIX: ${{ vars.S3_PREFIX }}
|
||||
run: |
|
||||
kubectl create secret generic armature-s3 \
|
||||
kubectl create secret generic switchboard-s3 \
|
||||
--namespace=${NAMESPACE} \
|
||||
--from-literal=S3_ENDPOINT="${S3_ENDPOINT}" \
|
||||
--from-literal=S3_BUCKET="${S3_BUCKET}" \
|
||||
@@ -673,14 +667,13 @@ jobs:
|
||||
STORAGE_CLASS: ${{ vars.STORAGE_CLASS }}
|
||||
STORAGE_SIZE: ${{ vars.STORAGE_SIZE || '10Gi' }}
|
||||
STORAGE_BACKEND: ${{ vars.STORAGE_BACKEND || 'pvc' }}
|
||||
BUNDLED_PACKAGES: ${{ steps.setup.outputs.BUNDLED_PACKAGES }}
|
||||
run: |
|
||||
# Render PVC first (must exist before backend references it)
|
||||
if [[ -n "${STORAGE_CLASS}" ]]; then
|
||||
envsubst < k8s/storage-pvc.yaml > /tmp/storage-pvc.yaml
|
||||
fi
|
||||
|
||||
envsubst < k8s/armature.yaml > /tmp/armature.yaml
|
||||
envsubst < k8s/switchboard.yaml > /tmp/switchboard.yaml
|
||||
envsubst < k8s/middleware-retry.yaml > /tmp/middleware-retry.yaml
|
||||
envsubst < k8s/ingress.yaml > /tmp/ingress.yaml
|
||||
|
||||
@@ -694,7 +687,7 @@ jobs:
|
||||
echo " ⚠ STORAGE_CLASS not set — file storage disabled"
|
||||
fi
|
||||
|
||||
kubectl apply -f /tmp/armature.yaml
|
||||
kubectl apply -f /tmp/switchboard.yaml
|
||||
|
||||
# Traefik retry middleware (v0.28.8) — requires RBAC for traefik.io CRDs.
|
||||
# First-time setup: kubectl apply -f k8s/rbac-traefik.yaml (cluster admin)
|
||||
@@ -713,8 +706,8 @@ jobs:
|
||||
# Traefik invalidates the entire router if it references a missing middleware,
|
||||
# which kills all routes for this path prefix.
|
||||
if [[ "${MW_READY}" == "true" ]]; then
|
||||
MW_REF="${NAMESPACE}-armature-retry${DEPLOY_SUFFIX}@kubernetescrd"
|
||||
kubectl annotate ingress "armature${DEPLOY_SUFFIX}" \
|
||||
MW_REF="${NAMESPACE}-switchboard-retry${DEPLOY_SUFFIX}@kubernetescrd"
|
||||
kubectl annotate ingress "switchboard${DEPLOY_SUFFIX}" \
|
||||
"traefik.ingress.kubernetes.io/router.middlewares=${MW_REF}" \
|
||||
--namespace="${NAMESPACE}" --overwrite
|
||||
echo " ✓ Ingress annotated with retry middleware"
|
||||
@@ -725,20 +718,20 @@ jobs:
|
||||
SUFFIX: ${{ steps.setup.outputs.DEPLOY_SUFFIX }}
|
||||
ENV: ${{ steps.setup.outputs.ENVIRONMENT }}
|
||||
run: |
|
||||
kubectl rollout restart deployment/armature${SUFFIX} -n ${NAMESPACE}
|
||||
kubectl rollout status deployment/armature${SUFFIX} -n ${NAMESPACE} --timeout=180s
|
||||
kubectl rollout restart deployment/switchboard${SUFFIX} -n ${NAMESPACE}
|
||||
kubectl rollout status deployment/switchboard${SUFFIX} -n ${NAMESPACE} --timeout=180s
|
||||
|
||||
echo ""
|
||||
echo "━━━ Pod Status ━━━"
|
||||
kubectl get pods -n ${NAMESPACE} -l app=armature,env=${ENV}
|
||||
kubectl get pods -n ${NAMESPACE} -l app=switchboard,env=${ENV}
|
||||
|
||||
READY=$(kubectl get deployment armature${SUFFIX} -n ${NAMESPACE} -o jsonpath='{.status.readyReplicas}')
|
||||
READY=$(kubectl get deployment switchboard${SUFFIX} -n ${NAMESPACE} -o jsonpath='{.status.readyReplicas}')
|
||||
|
||||
if [[ "${READY:-0}" -gt 0 ]]; then
|
||||
echo "✅ Healthy: ${READY} pods ready"
|
||||
else
|
||||
echo "❌ Unhealthy: ${READY:-0} pods ready"
|
||||
kubectl logs -n ${NAMESPACE} -l app=armature,env=${ENV} --tail=30
|
||||
kubectl logs -n ${NAMESPACE} -l app=switchboard,env=${ENV} --tail=30
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
1291
CHANGELOG.md
1291
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
@@ -1,64 +0,0 @@
|
||||
# Contributing to Armature
|
||||
|
||||
## Development Setup
|
||||
|
||||
**Requirements:** Go 1.23+, Node.js 20+ (for frontend tests), SQLite (local dev).
|
||||
|
||||
**Build from source:**
|
||||
|
||||
```sh
|
||||
cd server
|
||||
go build -o armature .
|
||||
DB_DRIVER=sqlite DATABASE_URL=/tmp/armature.db ./armature
|
||||
```
|
||||
|
||||
**Docker (recommended):**
|
||||
|
||||
```sh
|
||||
docker compose up --build
|
||||
# open http://localhost:3000 (default login: admin / admin)
|
||||
```
|
||||
|
||||
Data persists in the `sb_data` named volume. Reset with `docker compose down -v`.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
server/ Go backend (handlers, store, config, auth, workflow engine)
|
||||
src/js/ Browser SDK and built-in surface JS
|
||||
packages/ Extension packages (surfaces, libraries, browser extensions)
|
||||
build.sh Builds each subdirectory into a .pkg archive
|
||||
docs/ Documentation markdown (served at /api/v1/docs)
|
||||
k8s/ Kubernetes manifests and Helm chart
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
**Backend:** `cd server && go test ./...`
|
||||
|
||||
**Frontend:** `node --test src/js/__tests__/`
|
||||
|
||||
## Code Conventions
|
||||
|
||||
- **Go:** Standard formatting via `gofmt`. Handlers in `server/handlers/`,
|
||||
persistence in `server/store/`. Database access goes through the store
|
||||
interface, never directly from handlers.
|
||||
- **Browser JS:** Vanilla ES modules + Preact via CDN. No build step for
|
||||
browser code (except the CM6 editor bundle). SDK lives at `src/js/sw/`.
|
||||
- **Extensions:** IIFE pattern (see `packages/*/js/script.js`). Register with
|
||||
`sw.renderers` or `sw.slots` via the `sw:ready` event.
|
||||
|
||||
## Creating a Package
|
||||
|
||||
A package is a ZIP archive (`.pkg`) containing `manifest.json` and optional
|
||||
`js/`, `css/`, `assets/`, and `script.star` files. The build script
|
||||
(`packages/build.sh`) automates this. See `docs/PACKAGE-FORMAT.md` for the
|
||||
full manifest spec and `docs/TUTORIAL-FIRST-EXTENSION.md` for a walkthrough.
|
||||
|
||||
## Pull Request Process
|
||||
|
||||
1. Create a feature branch from `main`.
|
||||
2. Make your changes. Keep commits focused.
|
||||
3. Run both Go and JS test suites and confirm they pass.
|
||||
4. Submit a PR with a clear description of what changed and why.
|
||||
5. Address review feedback, then squash-merge when approved.
|
||||
23
Dockerfile
23
Dockerfile
@@ -1,11 +1,10 @@
|
||||
# ============================================
|
||||
# Armature — Unified Dockerfile
|
||||
# Switchboard Core — Unified Dockerfile
|
||||
# ============================================
|
||||
# Stage 1: Build Go backend
|
||||
# Stage 2: Download JS vendor libs (marked, DOMPurify)
|
||||
# Stage 3: Build CM6 editor bundle (esbuild)
|
||||
# Stage 4: Build bundled packages (.pkg archives)
|
||||
# Stage 5: Production image (nginx + backend)
|
||||
# Stage 4: Production image (nginx + backend)
|
||||
#
|
||||
# Vendor libs are baked in during build so the
|
||||
# app works in disconnected environments
|
||||
@@ -20,7 +19,7 @@ COPY server/go.mod server/go.sum* ./
|
||||
COPY server/ .
|
||||
COPY VERSION ./
|
||||
RUN go mod download && go mod tidy && go mod verify
|
||||
RUN CGO_ENABLED=0 go build -ldflags="-s -w -X main.Version=$(cat VERSION)" -o /bin/armature .
|
||||
RUN CGO_ENABLED=0 go build -ldflags="-s -w -X main.Version=$(cat VERSION)" -o /bin/switchboard .
|
||||
|
||||
# ── Stage 2: Vendor JS libs ─────────────────
|
||||
FROM node:20-alpine AS vendor
|
||||
@@ -58,28 +57,19 @@ COPY scripts/build-editor.sh /build/scripts/build-editor.sh
|
||||
RUN cd /build/src/editor && npm ci --loglevel=warn
|
||||
RUN sh /build/scripts/build-editor.sh /build/dist
|
||||
|
||||
# ── Stage 4: Build bundled packages ─────────
|
||||
FROM alpine:3 AS packages
|
||||
RUN apk add --no-cache zip bash
|
||||
COPY packages/ /packages/
|
||||
RUN cd /packages && bash build.sh
|
||||
|
||||
# ── Stage 5: Production ─────────────────────
|
||||
# ── Stage 4: Production ─────────────────────
|
||||
FROM nginx:1-alpine
|
||||
|
||||
RUN apk add --no-cache bash git
|
||||
|
||||
# Go backend binary
|
||||
COPY --from=backend /bin/armature /usr/local/bin/armature
|
||||
COPY --from=backend /bin/switchboard /usr/local/bin/switchboard
|
||||
COPY --from=backend /app/database/migrations /app/database/migrations
|
||||
|
||||
# Frontend static files
|
||||
COPY src/ /usr/share/nginx/html/
|
||||
COPY VERSION /VERSION
|
||||
|
||||
# Documentation (v0.6.1) — served by Go backend via /api/v1/docs
|
||||
COPY docs/ /app/docs/
|
||||
|
||||
# Inject version and build hash into index.html and sw.js at build time
|
||||
RUN APP_VERSION=$(cat /VERSION | tr -d '[:space:]') && \
|
||||
BUILD_HASH=$(find /usr/share/nginx/html/js -name '*.js' -exec md5sum {} + | sort | md5sum | cut -c1-8) && \
|
||||
@@ -95,9 +85,6 @@ COPY --from=vendor /vendor/katex/katex.min.css /usr/share/nginx/html/vendor/kate
|
||||
COPY --from=vendor /vendor/katex/fonts/ /usr/share/nginx/html/vendor/katex/fonts/
|
||||
COPY --from=cm6-build /build/dist/ /usr/share/nginx/html/vendor/codemirror/
|
||||
|
||||
# Bundled packages (v0.3.8) — auto-installed on first run
|
||||
COPY --from=packages /dist/ /app/bundled-packages/
|
||||
|
||||
# nginx config (template — envsubst injects BASE_PATH at runtime)
|
||||
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
|
||||
# Only substitute BASE_PATH — preserve nginx variables ($host, $uri, etc.)
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
# ============================================
|
||||
# Armature — Builder Image
|
||||
# ============================================
|
||||
# Pre-caches Go modules and Node dependencies
|
||||
# for faster custom builds. Use as a base in
|
||||
# your own Dockerfile to skip dependency
|
||||
# download on every build.
|
||||
#
|
||||
# Usage:
|
||||
# FROM ghcr.io/armature/builder:latest AS go-builder
|
||||
# COPY server/ /app/
|
||||
# RUN cd /app && go build -o /bin/armature .
|
||||
#
|
||||
# Or build this image locally:
|
||||
# docker build -f Dockerfile.builder -t armature-builder .
|
||||
# ============================================
|
||||
|
||||
# ── Go module cache ─────────────────────────
|
||||
FROM golang:1.23-bookworm AS go-cache
|
||||
WORKDIR /cache
|
||||
COPY server/go.mod server/go.sum* ./
|
||||
RUN go mod download && go mod verify
|
||||
|
||||
# ── Node dependency cache ───────────────────
|
||||
FROM node:20-alpine AS node-cache
|
||||
WORKDIR /cache
|
||||
|
||||
# Editor bundle dependencies
|
||||
COPY src/editor/package*.json ./editor/
|
||||
RUN cd editor && npm ci --loglevel=warn
|
||||
|
||||
# Vendor libs (same versions as production Dockerfile)
|
||||
RUN npm pack marked@16.3.0 && \
|
||||
npm pack dompurify@3.2.4 && \
|
||||
npm pack mermaid@11.4.1 && \
|
||||
npm pack katex@0.16.11 && \
|
||||
mkdir -p /cache/vendor-tarballs && \
|
||||
mv *.tgz /cache/vendor-tarballs/
|
||||
|
||||
# ── Final builder image ────────────────────
|
||||
FROM golang:1.23-bookworm
|
||||
|
||||
# Pre-install build tools
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
zip \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Go module cache (populated)
|
||||
COPY --from=go-cache /go/pkg/mod /go/pkg/mod
|
||||
|
||||
# Node dependencies (for editor bundle builds)
|
||||
COPY --from=node-cache /cache/editor/node_modules /cache/editor/node_modules
|
||||
|
||||
# Vendor lib tarballs (avoid re-download)
|
||||
COPY --from=node-cache /cache/vendor-tarballs /cache/vendor-tarballs
|
||||
|
||||
# Node.js for frontend builds
|
||||
COPY --from=node-cache /usr/local/bin/node /usr/local/bin/node
|
||||
COPY --from=node-cache /usr/local/lib/node_modules /usr/local/lib/node_modules
|
||||
RUN ln -sf /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
LABEL org.opencontainers.image.title="Armature Builder"
|
||||
LABEL org.opencontainers.image.description="Pre-cached build dependencies for faster custom Armature builds"
|
||||
25
README.md
25
README.md
@@ -1,11 +1,11 @@
|
||||
# Armature
|
||||
# Switchboard Core
|
||||
|
||||
A self-hosted extension platform. Identity, teams, permissions, workflows,
|
||||
and a package system. Everything else ships as installable extensions.
|
||||
|
||||
## What This Is
|
||||
|
||||
Armature is the kernel. It provides the primitives that extensions
|
||||
Switchboard Core is the kernel. It provides the primitives that extensions
|
||||
build on: users, teams, groups, scoped credentials, a Starlark sandbox,
|
||||
workflow orchestration, notifications, and a package installer. It does not
|
||||
include AI chat, providers, personas, or any domain-specific features —
|
||||
@@ -22,21 +22,12 @@ those are all extension packages.
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Docker (recommended)
|
||||
docker compose up --build
|
||||
# → http://localhost:3000 (admin/admin)
|
||||
|
||||
# Or from source
|
||||
git clone <repo-url> && cd armature
|
||||
git clone <repo-url> && cd switchboard-core
|
||||
cp server/.env.example server/.env # edit DB credentials
|
||||
cd server && go run .
|
||||
# → http://localhost:8080
|
||||
```
|
||||
|
||||
Bundled packages (workflows, surfaces, task manager) are auto-installed on
|
||||
first boot. See [Distribution Guide](docs/DISTRIBUTION.md) for production
|
||||
deployment and customization.
|
||||
|
||||
## Kernel Features
|
||||
|
||||
- **Auth**: Builtin password, mTLS (client cert), OIDC (Keycloak et al.)
|
||||
@@ -52,19 +43,15 @@ deployment and customization.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Distribution Guide](docs/DISTRIBUTION.md) — Docker, bundled packages, builder image, production deployment
|
||||
- [Architecture](docs/ARCHITECTURE.md) — kernel components and design reasoning
|
||||
- [Roadmap](ROADMAP.md) — current status and planned milestones
|
||||
- [Changelog](CHANGELOG.md) — version history
|
||||
|
||||
## Project Status
|
||||
|
||||
**v0.5.0** — Realtime pub/sub primitive, dialog audit, and admin permissions
|
||||
UI. Extensions can now publish events to WebSocket channels via Starlark;
|
||||
clients subscribe with `sw.realtime.subscribe()`. Admin Packages page gains
|
||||
per-permission grant/revoke controls and status badges. See
|
||||
[ROADMAP.md](ROADMAP.md) for the full journey from v0.1.0 kernel extraction
|
||||
through v0.3.x workflows, v0.4.x Notes surface, to v0.5.x realtime and chat.
|
||||
**v0.1.0** (in progress) — kernel extracted from chat-switchboard v0.38.5.
|
||||
~44K lines of chat/AI code removed, 27 kernel tables, 20 store interfaces.
|
||||
See [ROADMAP.md](ROADMAP.md) for details.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
151
ROADMAP-UI.md
151
ROADMAP-UI.md
@@ -1,151 +0,0 @@
|
||||
# Armature — v0.6.x UI Hardening Roadmap
|
||||
|
||||
> **Goal**: Fix all viewport scaling, banner integration, and styling inconsistencies
|
||||
> so Claude Code can run a meaningful automated usability survey against a
|
||||
> stable, uniform UI.
|
||||
|
||||
---
|
||||
|
||||
## Problem Inventory
|
||||
|
||||
### P1 — Viewport & Scaling (blocks everything)
|
||||
|
||||
| # | Issue | Where | Impact |
|
||||
|---|-------|-------|--------|
|
||||
| 1 | **Dual layout systems** — `base.html` template has its own banner→surface→footer column; `app-shell.js` Preact shell has a separate `sw-shell` → `sw-shell__body` → `sw-shell__surface` column. They never coordinate. | `server/pages/templates/base.html` ↔ `src/js/sw/shell/app-shell.js` | Every surface inherits an ambiguous viewport ancestor. |
|
||||
| 2 | **Transform-based scaling is broken** — `transform: scale()` on `#surfaceInner` doesn't reflow layout. Breaks `getBoundingClientRect` (menu.js already carries a scale-correction hack at line 20), scroll containment, pointer events, and the inverse-width/height hack (`100/s%`) doesn't account for banners consuming viewport space. | `base.html:56-67`, `appearance.js:41-53`, `menu.js:20-33` | Menus, tooltips, dropdowns all mis-positioned at any non-100% scale. Click targets wrong. |
|
||||
| 3 | **Banner height desync** — `base.html` hardcodes `--banner-h: 28px` and renders banners in-flow. `app-shell.js` ShellBanner measures `offsetHeight` into `--banner-top-height` / `--banner-bottom-height` and uses `position: fixed` + body padding. Two independent banner systems. | `base.html:31,72-75,103-107` ↔ `app-shell.js:25-42`, `sw-shell.css:22-37,63-69` | With banners enabled, content overflows by the banner height or gets double-inset depending on which code path is active. |
|
||||
| 4 | **`100vh` on mobile** — `.sw-shell`, `.chat-app`, `.chat-loading`, `.login-shell` use `100vh` which doesn't subtract mobile browser chrome (address bar, toolbar). | `sw-shell.css:9`, `chat/css/main.css:15,25`, `sw-login.css:7` | Content overflows on iOS Safari, Android Chrome. |
|
||||
| 5 | **Chat uses `100vh` not `100%`** — `.chat-app { height: 100vh }` ignores parent container (which already excludes banners/footer). Notes correctly uses `height: 100%`. Every extension surface that copies chat's pattern will inherit the bug. | `packages/chat/css/main.css:15` | Chat surface overflows behind banners. |
|
||||
|
||||
### P2 — CSS Architecture
|
||||
|
||||
| # | Issue | Where | Impact |
|
||||
|---|-------|-------|--------|
|
||||
| 6 | **Class name collisions** — `.settings-section` defined in both `modals.css:41-43` and `surfaces.css:75-83` with different padding, margin, and border-bottom rules. `.sw-dropdown` in `primitives.css:443` (styled `<select>`) vs `sw-primitives.css:262` (custom dropdown component). `.sw-tabs` in `primitives.css:459` vs `sw-primitives.css:234`. | Kernel CSS | Styles randomly win depending on load order. Bug reports differ by surface. |
|
||||
| 7 | **Old/new primitive duplication** — Two button systems (`.btn-primary`/`.btn-small` in `primitives.css` vs `.sw-btn--primary`/`.sw-btn--sm` in `sw-primitives.css`). Two toast systems (`.toast` vs `.sw-toast`). Two dropdown, two tabs implementations. | `primitives.css` ↔ `sw-primitives.css` | No single source of truth for any component. Extension authors can't know which to use. |
|
||||
| 8 | **Extension CSS bleeds globally** — Extension `main.css` loaded via `<link>` at document level, no scoping. Any class name can override kernel or sibling extension styles. | `base.html:26-28`, `extension-surface.css` | Package CSS fights with kernel. Two packages with `.sidebar` both lose. |
|
||||
| 9 | **No intermediate breakpoint** — Only `768px` mobile breakpoint. No tablet (768–1024px). Secondary workspace pane hardcoded `480px`. Admin nav hardcoded `200px`. | `layout.css:263`, `surfaces.css:305` | Cramped layout on iPad/small laptops. |
|
||||
|
||||
### P3 — Visual Consistency
|
||||
|
||||
| # | Issue | Where | Impact |
|
||||
|---|-------|-------|--------|
|
||||
| 10 | **Mixed unit systems** — `px`, `rem`, `em` used interchangeably with no rationale. Some font-sizes in `px` (primitives), others in `rem` (sw-primitives), others in `em` (user-picker). | All CSS files | Zoom/scale behaves differently per element. |
|
||||
| 11 | **Google Fonts CDN dependency** — `@import url(...)` in `variables.css:5` blocks rendering if CDN is slow; breaks entirely on air-gapped deployments. | `variables.css:5` | FOUT or blank page on slow networks. No offline support. |
|
||||
| 12 | **No spacing scale** — Padding/margins are ad-hoc values (10px, 12px, 14px, 16px, 20px, 24px, 28px…). No design-token spacing scale. | All CSS | Inconsistent visual rhythm across surfaces. |
|
||||
| 13 | **Hardcoded fallback colors in component CSS** — `sw-shell.css`, `sw-primitives.css` have inline fallbacks like `var(--accent, #b38a4e)` — a gold color from a previous theme that doesn't match the current blue `#6c9fff`. | `sw-shell.css`, `sw-primitives.css` | Wrong colors flash briefly if variables load late. |
|
||||
|
||||
---
|
||||
|
||||
## Roadmap
|
||||
|
||||
### v0.6.9 — Session Lifetime Config ✅
|
||||
|
||||
Shipped. Admin-configurable TTLs, "keep me logged in" checkbox, idle timeout,
|
||||
config-driven `generateTokens()`, 7 new tests. See CHANGELOG.md for details.
|
||||
|
||||
### v0.6.10 — Viewport Foundation ✅
|
||||
|
||||
Shipped. Single layout model: `body → shell → surface`. CSS `zoom` replaces
|
||||
`transform: scale()`. `100dvh` fallbacks everywhere. Extension surfaces use
|
||||
`100%` instead of `100vh`. Dead shell layout code deprecated. See CHANGELOG.md.
|
||||
|
||||
### v0.6.11 — CSS Deduplication ✅
|
||||
|
||||
Shipped. Old primitive system retired. One class per concept. See CHANGELOG.md.
|
||||
|
||||
| Step | Description |
|
||||
|------|-------------|
|
||||
| Audit collision inventory | Script that finds all duplicate class selectors across kernel CSS files. Produce a machine-readable collision report (JSON). |
|
||||
| Migrate `.settings-section` | Remove `modals.css:41-43` definition. The `surfaces.css` definition is authoritative. Modals that used the old styles get explicit overrides scoped to `.modal .settings-section`. |
|
||||
| Retire `primitives.css` old components | `.btn-primary`, `.btn-small`, `.btn-danger`, `.btn-full` → migrate all usages to `.sw-btn--*`. `.toast-container` / `.toast` → migrate to `.sw-toast-container` / `.sw-toast`. Old `.popup-menu` → migrate to `.sw-menu`. Old `.sw-dropdown` (styled select in primitives.css) → rename to `.sw-native-select` or delete if unused. Old `.sw-tabs` / `.sw-tab-btn` in primitives.css → delete (sw-primitives.css version is authoritative). |
|
||||
| Mark deprecated classes | Any remaining old classes get a `/* DEPRECATED v0.6.11 — use .sw-btn--* */` comment and a 1-version grace period for package authors. |
|
||||
| Package CSS audit | Scan all `packages/*/css/main.css` for references to deprecated kernel classes. Fix in-tree packages. |
|
||||
|
||||
### v0.6.12 — Extension CSS Isolation ✅
|
||||
|
||||
Shipped. Prefix enforcement via linter. All 12 in-tree packages migrated.
|
||||
See CHANGELOG.md.
|
||||
|
||||
| Step | Description |
|
||||
|------|-------------|
|
||||
| Scoping strategy | Prefix enforcement (option B). `@scope` support still patchy; prefix works everywhere, trivially lintable. |
|
||||
| Linter | `scripts/lint-package-css.sh` — validates first class selector in every rule starts with `.ext-{slug}`. Exempts `:root`, `@keyframes`, `@font-face`, `@media`, `.sw-*` kernel classes, `.cm-*` CodeMirror classes. |
|
||||
| Kernel CSS contract | `docs/EXTENSION-CSS.md` — stable public classes (`.sw-btn--*`, `.sw-input`, `.sw-field`, `.sw-dialog`, `.sw-toast`, `.sw-menu`, `.sw-tabs`, etc.) and all CSS variables. Everything else internal. |
|
||||
| Migrate in-tree packages | `data-ext="{{.Surface}}"` on extension mount. All 12 packages prefixed to `.ext-{slug}-*`. CSS + JS updated in lockstep. |
|
||||
|
||||
### v0.6.13 — Responsive & Spacing ✅
|
||||
|
||||
Shipped. Spacing token scale (`--sp-1` through `--sp-12`, 4px grid) in
|
||||
`variables.css`. Tablet breakpoint (`max-width: 1024px`) in layout, surfaces,
|
||||
login. All kernel CSS and 12 in-tree packages migrated to spacing tokens.
|
||||
`EXTENSION-CSS.md` updated with spacing table and breakpoint guide.
|
||||
Font-size scale deferred to v0.6.14. See CHANGELOG.md.
|
||||
|
||||
### v0.6.14 — Visual Polish ✅
|
||||
|
||||
Shipped. Stale fallback colors purged (~65 instances), fonts self-hosted
|
||||
(DM Sans + JetBrains Mono woff2), border-radius standardized to three tokens
|
||||
(`--radius-sm`, `--radius`, `--radius-lg`). Also fixed v0.6.13 spacing
|
||||
regressions (half-step tokens), theme settings default, surface overflow,
|
||||
and user menu zoom drift. See CHANGELOG.md.
|
||||
|
||||
### v0.6.15 — User Display Audit ✅
|
||||
|
||||
Shipped. `GET /api/v1/users/resolve?ids=...` batch endpoint, `sw.users`
|
||||
SDK module with `resolve()`, `resolveMany()`, `displayName()` + 60s cache.
|
||||
Chat participants resolved from users table instead of snapshot. All admin
|
||||
surfaces show `display_name || username || 'Unknown'`. Chat-core snapshot
|
||||
column deprecated. 5 new handler tests. See CHANGELOG.md.
|
||||
|
||||
### v0.6.16 — Usability Survey Gate ✅
|
||||
|
||||
Shipped. Four audit scripts, structured survey prompt, contrast/touch-target
|
||||
fixes, Docker docs corrected. All 48 contrast pairings pass, all close buttons
|
||||
have 44px mobile targets, focus-visible on all key primitives. See CHANGELOG.md.
|
||||
|
||||
---
|
||||
|
||||
## Sequencing Rationale
|
||||
|
||||
```
|
||||
v0.6.9 Session Lifetime Config ✅ SHIPPED
|
||||
↓
|
||||
v0.6.10 Viewport Foundation ✅ SHIPPED
|
||||
↓
|
||||
v0.6.11 CSS Deduplication ✅ SHIPPED
|
||||
↓
|
||||
v0.6.12 Extension CSS Isolation ✅ SHIPPED
|
||||
↓
|
||||
v0.6.13 Responsive & Spacing ✅ SHIPPED
|
||||
↓
|
||||
v0.6.14 Visual Polish ✅ SHIPPED
|
||||
↓
|
||||
v0.6.15 User Display Audit ✅ SHIPPED
|
||||
↓
|
||||
v0.6.16 Usability Survey Gate ✅ SHIPPED
|
||||
```
|
||||
|
||||
Each version is independently shippable and testable. No version depends on
|
||||
anything after it.
|
||||
|
||||
---
|
||||
|
||||
## What "Usability Survey by Code" Means
|
||||
|
||||
The v0.6.16 deliverables give Claude Code (or any automated tool) three things:
|
||||
|
||||
1. **A structured inventory** (`ui-inventory.json`) of every component, on every
|
||||
surface, with its CSS file and line number.
|
||||
|
||||
2. **Automated checks** (contrast, touch targets, token usage) that produce
|
||||
machine-readable pass/fail reports.
|
||||
|
||||
3. **A survey prompt** (`USABILITY-SURVEY.md`) with explicit criteria and file
|
||||
paths, so Claude Code can `cat` the relevant files, run the scripts, and
|
||||
produce a scored report without human guidance.
|
||||
|
||||
The survey is not a substitute for real user testing — it's a structural
|
||||
quality gate that catches the class of bugs (overflow, contrast, misalignment,
|
||||
inconsistent styling) that have historically slipped through.
|
||||
344
ROADMAP.md
344
ROADMAP.md
@@ -1,182 +1,268 @@
|
||||
# Armature — Roadmap
|
||||
# Switchboard Core — Roadmap
|
||||
|
||||
## Current: v0.6.14 — Visual Polish
|
||||
## Current: v0.3.7 — Package Audit
|
||||
|
||||
Self-hosted extensible platform. Auth, identity, packages, Starlark sandbox,
|
||||
storage, realtime, and ops are kernel primitives. Everything else is an extension.
|
||||
Fork of chat-switchboard, gutted to a pure extension platform. All AI/chat
|
||||
features removed from the kernel. What remains is the minimum viable
|
||||
platform that extensions build on.
|
||||
|
||||
**Kernel capabilities:** Auth (builtin/mTLS/OIDC) · Users/teams/groups/RBAC ·
|
||||
Surfaces/extensions/libraries/workflows · Starlark sandbox (capability-gated) ·
|
||||
Object storage (PVC/S3) + ext_data tables · WebSocket hub + realtime pub/sub ·
|
||||
Audit log · Notifications · Scheduled tasks
|
||||
### Retained kernel capabilities
|
||||
|
||||
**Completed history:** v0.2.x–v0.5.x fully documented in `CHANGELOG.md`.
|
||||
Highlights: RBAC + settings cascade, event bus + triggers, SDK stabilization,
|
||||
workflow engine (multi-stage, team roles, signoff gate, public entry, SLA),
|
||||
package distribution, Notes surface (CM6, folders, tags, backlinks, graph),
|
||||
realtime primitive, Chat surface (chat-core library + surface + polish),
|
||||
upgrade test harness, cluster registry + HA.
|
||||
- **Auth**: builtin (simple), mTLS, OIDC
|
||||
- **Identity**: users, teams, groups, permissions (RBAC)
|
||||
- **Packages**: surfaces, extensions, libraries, workflows
|
||||
- **Starlark sandbox**: capability-gated modules
|
||||
- **Storage**: object storage (PVC, S3), ext_data tables
|
||||
- **Realtime**: WebSocket hub, presence, multi-replica HA
|
||||
- **Ops**: audit log, notifications, maintenance goroutine
|
||||
|
||||
---
|
||||
|
||||
## v0.6.0 — MVP
|
||||
|
||||
Extension, communication, and operations tracks converge. First
|
||||
externally usable release.
|
||||
|
||||
Design docs: `docs/DESIGN-cluster-registry.md` — PG-backed cluster registry and self-assembling mesh.
|
||||
|
||||
### v0.6.0 — Cluster Registry + HA
|
||||
|
||||
PG is the consensus layer. Zero new infrastructure. `UNLOGGED` table + `LISTEN/NOTIFY` replaces etcd/Consul/Redis for homelab-to-small-team scale.
|
||||
### Phase 0 (complete)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| `node_registry` table | ✅ | `UNLOGGED TABLE` — node_id, endpoint, seq, registered_at, heartbeat, stats JSONB. Postgres migration 013. |
|
||||
| Node registration | ✅ | Self-registration on startup: `INSERT ... ON CONFLICT DO UPDATE`. `node_id` = `hostname-PID` or `CLUSTER_NODE_ID` env override. |
|
||||
| Heartbeat tick | ✅ | Every 10s: update own heartbeat + collect runtime stats (goroutines, heap, GC, uptime, ws_clients). |
|
||||
| Stale sweep | ✅ | Every heartbeat tick: `DELETE WHERE heartbeat < now() - 30s`. All nodes run it — idempotent, no ring topology. |
|
||||
| Self-eviction | ✅ | If heartbeat UPDATE returns 0 rows: node was swept by peer → log error + `os.Exit(1)`. K8s restarts → re-register. |
|
||||
| LISTEN/NOTIFY routing | ✅ | Durable events (messages, state changes) fan-out via `pg_notify`. All replicas receive, push to local WS subscribers, drop if irrelevant. Phase 1: ephemeral events (typing, presence) also via NOTIFY (8KB limit, ~60 bytes each). |
|
||||
| Cluster API | ✅ | `GET /api/v1/admin/cluster` — returns `{data: [...]}` envelope with all registered nodes. |
|
||||
| Admin cluster dashboard | ✅ | `cluster-dashboard` surface package renders one card per node: node_id, endpoint, uptime, ws_clients, heap, GC pause. JSONB stats — future keys render automatically, no schema migration. Auto-refresh every 10s. |
|
||||
| Health endpoint | ✅ | `GET /health` includes `node_id` and `cluster: {size, peers, heartbeat_age_ms}`. |
|
||||
| Config | ✅ | `CLUSTER_NODE_ID`, `CLUSTER_HEARTBEAT_INTERVAL` (default 10s), `CLUSTER_STALE_THRESHOLD` (default 30s), `CLUSTER_ENDPOINT` (Phase 2 mesh, auto-detect). |
|
||||
| Single-node regression | ✅ | One-node behavior identical to pre-cluster: one registry row, NOTIFY delivers back to same instance. No special-casing. SQLite returns nil store — all cluster code guarded. |
|
||||
| Multi-node integration test | ✅ | Docker Compose: 3 instances, shared PG. `ci/e2e-cluster-test.sh`: registration, stale sweep on stop, re-registration on restart. 3 unit tests + 2 handler tests. |
|
||||
| 1. Module rename | ✅ | `chat-switchboard` → `switchboard-core` |
|
||||
| 2. Delete packages | ✅ | 15 Go packages, 29 handler files removed |
|
||||
| 3. Gut stores/models | ✅ | 40 → 20 store interfaces, kernel-only models |
|
||||
| 4. Fresh migrations | ✅ | 9 files × 2 dialects, 27 tables |
|
||||
| 5. Fix compilation | ✅ | `go build ./...` clean, 300+ stale route lines cut |
|
||||
| 6. Fix tests | ✅ | 8 test packages pass, ~12K stale test lines pruned |
|
||||
| 7. Frontend gut | ✅ | Shell + SDK only, 50+ files of chat/notes/projects code removed |
|
||||
| 8. New ICD | ✅ | Full OpenAPI 3.0.3 spec — 160 operations across 22 tag groups |
|
||||
| 9. CI/CD + Dockerfile | ✅ | Single unified image, FE/BE split removed, DB names updated, k8s var alignment fixes (resource quantities, image name, rollout deployment name) |
|
||||
| 10. Smoke test | ✅ | K8s deploy live at switchboard.gobha.ai/test, nginx BASE_PATH fixed, login→admin flow verified, branding updated |
|
||||
|
||||
### v0.6.1 — Backup/Restore + Documentation
|
||||
## v0.2.x — SDK & Triggers
|
||||
|
||||
The contract that extensions build against. Three trigger primitives,
|
||||
SDK stabilization, and the first rebuilt extension (tasks).
|
||||
|
||||
### v0.2.0 — RBAC + Settings Cascade (complete)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Backup handler | ✅ | `POST /api/v1/admin/backup` streams `.swb` ZIP (JSONL core + ext_data tables + package assets). `POST /api/v1/admin/restore` wipes DB and restores from archive. Dialect-neutral (SQLite + Postgres). |
|
||||
| Server-side backups | ✅ | `GET /api/v1/admin/backups` list, `GET /download`, `DELETE`. Store backups in `{STORAGE_PATH}/backups/`. |
|
||||
| Admin backup section | ✅ | New "Backup" section under `/admin/backup`. Create (download or server-side), list, download, delete, restore with destructive confirmation. |
|
||||
| Documentation API | ✅ | `GET /api/v1/docs` lists, `GET /api/v1/docs/:name` returns raw markdown. Authenticated (not admin-only). |
|
||||
| Docs surface | ✅ | Builtin surface at `/docs/:section`. Sidebar navigation, client-side markdown renderer. 5 new docs: Getting Started, Extension Guide, API Reference, Deployment, Package Format. |
|
||||
| Tests | ✅ | 6 handler tests (basic backup, ext_data backup, round-trip restore, schema mismatch, dump/restore table, list empty). E2E script `ci/e2e-backup-test.sh`. |
|
||||
| Admin → RBAC group | ✅ | `surface.admin.access` permission + Admins system group replaces `role == "admin"` checks. Admin bypass removed from permission middleware. |
|
||||
| Settings cascade | ✅ | `user_overridable` flag, three-tier resolution (global → team → user), team settings API |
|
||||
| ~~Settings override model~~ | ✅ | Shipped with settings cascade above |
|
||||
|
||||
### v0.6.2 — Docs Polish + Dynamic OpenAPI
|
||||
### v0.2.1 — Default Surface + ICD
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Dark mode fix | ✅ | Added `--bg-code` to CSS variables (dark + light). Replaced all hardcoded light-mode fallbacks in docs CSS with theme-aware variables. Table styling, code blocks, nav items all readable in dark mode. |
|
||||
| Loading & error handling | ✅ | Replaced borrowed `settings-placeholder` with docs-specific pulse animation. Added error state with retry button for failed doc list fetch. |
|
||||
| Topbar navigation | ✅ | Imported `Topbar` + `UserMenu` into docs surface. Users can now navigate to other surfaces via the avatar menu. |
|
||||
| Docs icon + menu entry | ✅ | Added `📖 Docs` entry to UserMenu standard items. Docs accessible from any surface's user menu. |
|
||||
| `api_schema` manifest field | ✅ | Optional `api_schema` array in `manifest.json`. Parsed lazily by spec builder. Malformed entries logged and skipped — never blocks extension loading. |
|
||||
| OpenAPI spec builder | ✅ | `BuildOpenAPISpec()` merges static kernel spec with extension routes. Tier 1: auto-generated stubs for all `api_routes`. Tier 2: `api_schema` replaces stubs with rich path items (params, body, response). |
|
||||
| Dynamic spec endpoint | ✅ | `GET /api/docs/openapi.json` serves merged spec. Swagger UI updated to use JSON endpoint. Static YAML preserved for backward compat. |
|
||||
| Tests | ✅ | 7 new handler tests: zero extensions, stubs, rich schema, multi-extension, malformed schema, disabled exclusion, required fields. |
|
||||
| Default surface routing | ✅ | `/` redirects to configurable default surface. No surfaces → admin. First install becomes default. Changeable in admin settings. |
|
||||
| ICD (API contract) | ✅ | Full OpenAPI 3.0.3 spec — 160 operations, 22 tag groups, reusable component schemas. Served at `/api/docs`. |
|
||||
|
||||
---
|
||||
|
||||
## v0.6.x — Hardening
|
||||
|
||||
Closes every audit finding before the public release. No new features — only correctness, dead code elimination, and architectural cleanup. Sequence is fixed: each version is a gate for the next.
|
||||
|
||||
### v0.6.3 — Dead Code Sweep + Registry Fix
|
||||
|
||||
Pure cleanup. No behavior changes except fixing the broken registry install flow.
|
||||
### v0.2.2 — Event Bus + Triggers
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Fix registry install | ✅ | SDK sends `{ url }`, handler expects `{ download_url }`. Fix `api-domains.js` to send `{ download_url: url }`. Every Install click currently returns 400. |
|
||||
| Registry settings UI | ✅ | Add "Package Registry" section to admin settings with URL input field. Only way to configure registry today is a raw `PUT /api/v1/admin/settings/package_registry` — no user will find it. |
|
||||
| Registry tooling + docs | ✅ | `scripts/generate-registry.sh` scans a directory of `.pkg` files and emits registry JSON. `docs/PACKAGE-REGISTRY.md` documents the format. |
|
||||
| Delete dead kernel Go | ✅ | `store/interfaces.go:178–183` — orphaned ChannelListFilter comments. `pages/pages.go:922–930` — `roleFilterType()` + template registration (chat vestige, maps nonexistent roles). `main.go:67` — orphaned provider-type comment. |
|
||||
| Delete dead vendor JS | ✅ | `vendor/marked.min.js` and `vendor/purify.min.js` — 62KB, zero production imports. Only referenced in test helpers. |
|
||||
| Delete `dev.html` | ✅ | 676 lines, not imported by anything. Dead. |
|
||||
| Remove `dashboard` from default bundle | ✅ | Requires `legacy-sdk` (doesn't exist), auto-installs as dormant on fresh installs. Confusing. Remove from `defaultBundledPackages`. |
|
||||
| Remove `hello-dashboard` | ✅ | Proof-of-concept from early development. Move to `examples/` or delete. |
|
||||
| Strip stale version comments | ✅ | 60+ files had legacy version annotations (`// v0.29.x:`, `// v0.33.x:`). Single sed pass. |
|
||||
| Narrow default bundle | ✅ | Default: `notes`, `chat`, `chat-core`, `mermaid-renderer`, `schedules`. Everything else available via registry or `BUNDLED_PACKAGES=*`. |
|
||||
| Event bus subscriptions | ✅ | Extensions register event patterns in manifest. Wired via `bus.Subscribe()` on startup. Async handler invocation. |
|
||||
| Webhook triggers | ✅ | Inbound HTTP at `/api/v1/hooks/:package_id/:slug`. HMAC-SHA256 verification. Synchronous Starlark handler response. |
|
||||
| Scheduled tasks | ✅ | User-created cron tasks with restricted sandbox (no raw HTTP, no DB table creation). Runs as creator identity. Templates from extensions. Dedicated schedules API. |
|
||||
| Trigger admin API | ✅ | CRUD for triggers + schedules. Enable/disable, execution logs, per-package listing. |
|
||||
|
||||
### v0.6.4 — Admin Health/Metrics Tab + Cluster Merge
|
||||
|
||||
Structural move: cluster dashboard becomes an Admin tab. Better home for health/metrics — shared context with other admin panels, no separate nav entry.
|
||||
### v0.2.3 — SDK + Task Extension
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| "Health / Metrics" admin tab | ✅ | New tab in Admin surface. DB-agnostic metrics for all deployments. Cluster cards conditional on PG + multi-node detection. |
|
||||
| Runtime metrics | ✅ | Per-node: goroutines, heap alloc/sys, stack in use, GC cycles, last GC pause, GC CPU %, uptime, WebSocket clients, extensions loaded, open FDs. |
|
||||
| DB pool metrics | ✅ | All deployments: DB latency (`SELECT 1` round-trip), pool active/idle/max, wait count, wait duration. PG-only: table bloat (`n_dead_tup`), active backends (`pg_stat_activity`). |
|
||||
| Cluster metrics | ✅ | PG multi-node only: cluster size, peer list with endpoint + uptime, heartbeat age per node, event bus publish/deliver rates. |
|
||||
| Extension runtime metrics | ✅ | Starlark exec/min, errors/min, avg duration, HTTP outbound requests/min, trigger fires/min, schedule overruns. |
|
||||
| Fatten heartbeat payload | ✅ | Heartbeat JSONB carries full metric set. `GET /api/v1/admin/metrics` for single-node SQLite fallback (same shape). |
|
||||
| Retire `cluster-dashboard` | ✅ | Remove package once Admin Health tab ships. Update `defaultBundledPackages`. |
|
||||
| Fix block renderer `requires` | ✅ | `mermaid-renderer`, `katex-renderer`, `csv-table`, `diff-viewer` all have `"requires": ["chat"]`. These are content renderers, not chat features. Remove constraint — they should activate without chat. |
|
||||
| Health endpoint consolidation | ✅ | `/health` and `/api/v1/health` return near-identical JSON. Merge or clearly differentiate with docs. |
|
||||
| SDK stabilization | ✅ | `sw.api.ext()`, `sw.storage`, `sw.theme.tokens`, `sw.ui`, `sw.slots`, `sw.actions` — six new SDK modules for extension development |
|
||||
| Task extension | ✅ | Full task surface rebuilt as Starlark extension: CRUD API, kanban/list views, event triggers, webhook integration, notifications on completion |
|
||||
|
||||
### v0.6.5 — Renderer Pipeline + Docs Rewrite
|
||||
|
||||
Most complex sub-version. Lifts block rendering to a kernel SDK primitive so all surfaces share it, then rewrites the docs for an external audience.
|
||||
### v0.2.4 — Shell Navigation + Schedules
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| SDK renderer primitive | ✅ | `sw.renderers.register(pattern, handler)` — kernel-level registration. Extensions call once; all surfaces consume. Decouples renderer discovery from chat surface. |
|
||||
| Notes hooks SDK renderer pipeline | ✅ | Notes delegates to `sw.markdown.renderSync()` + `sw.renderers.runPostRenderers()`. Hand-rolled renderer deleted. |
|
||||
| Docs hooks SDK renderer pipeline | ✅ | Docs delegates to `sw.markdown.renderSync()` + `sw.renderers.runPostRenderers()`. Hand-rolled renderer deleted (~160 lines). |
|
||||
| Unify markdown renderer | ✅ | `sw.markdown` module lazy-loads `marked` v16 (vendored). Notes, Docs, Chat all consume it. Two hand-rolled parsers deleted. |
|
||||
| Sanitize HTML output | ✅ | DOMPurify wired as default post-render step in `sw.markdown`. SVG-safe config allows mermaid output. Notes sanitizes; Docs opts out (system-authored). |
|
||||
| Mermaid/KaTeX/CSV/Diff work everywhere | ✅ | Browser extension loader injects renderer scripts into all pages. Extensions register via `sw:ready` event. All four render in Notes, Docs, and Chat. |
|
||||
| Docs rewrite for external audience | ✅ | All fork references removed from docs, CHANGELOG, ROADMAP. DESIGN-WORKFLOW-REDESIGN-0.2.6.md replaced with DESIGN-WORKFLOWS.md. |
|
||||
| Add Mermaid architecture diagrams | ✅ | Six diagrams in ARCHITECTURE.md: system overview, request flow, extension lifecycle, realtime events, settings cascade, cluster topology. |
|
||||
| Surface alias decision | ✅ | Migrated SDK + ICD runner to `/admin/packages/`; aliases removed from main.go. |
|
||||
| `CONTRIBUTING.md` + tutorial | ✅ | CONTRIBUTING.md at repo root + docs/TUTORIAL-FIRST-EXTENSION.md walkthrough. |
|
||||
| SDK Topbar | ✅ | `sw.shell.Topbar` — composable navigation bar (title + extension slot + bell + user menu). Surfaces get consistent nav for free. |
|
||||
| Schedules surface | ✅ | New `packages/schedules/` wrapping kernel cron API. Table view, cron preview, enable/disable, manual run, execution logs. |
|
||||
| Manifest icons | ✅ | `icon` field in manifest.json (emoji). Surfaces API returns icon. UserMenu renders per-surface icons. |
|
||||
| UserMenu cleanup | ✅ | Removed dead Chat/Notes/Projects links. Menu driven by surfaces API. Core surfaces filtered. |
|
||||
| isAdmin RBAC fix | ✅ | `can.js` isAdmin() now checks `surface.admin.access` grant instead of deprecated role column. |
|
||||
|
||||
### v0.6.7 — Native mTLS
|
||||
|
||||
End-to-end mutual TLS without a reverse proxy. Targets systemd+podman deployments where every connection (client→server, node→node) is mTLS. Design: `docs/DESIGN-native-mtls.md`.
|
||||
### v0.2.5 — UI Polish + Dead Code Audit
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| `TLS_MODE` config | ✅ | Three values: `none` (default, plain HTTP) · `server` (TLS, no client cert) · `mtls` (mutual TLS, client cert required). Independent of `AUTH_MODE`. |
|
||||
| TLS server mode | ✅ | Go binary calls `ListenAndServeTLS` directly. `TLS_CERT`, `TLS_KEY`, `TLS_CA` path config. TLS 1.3 minimum, no fallback. `server/config/tls.go` loader + validation. |
|
||||
| `MTLSNativeProvider` | ✅ | Reads `r.TLS.PeerCertificates[0]` — no header trust. `Subject.CommonName` → username. `sha256(Raw)` → `external_id`. Auto-provisions `auth_source=mtls`. Renamed existing `mtls.go` → `mtls_proxy.go`. Shared helpers in `mtls_helpers.go`. |
|
||||
| Node-to-node mTLS | ✅ | `BuildPeerTLSConfig()` constructs outbound TLS config with node cert + CA pool. Forward-looking — cluster registry is DB-backed (PG LISTEN/NOTIFY), no HTTP peer calls yet. |
|
||||
| `armature-ca.sh` | ✅ | Shell wrapper around openssl. Three commands: `init` (CA keypair) · `issue-node --name <n> --san <addrs>` (365d) · `issue-user --cn <name>` (90d). All output PEM. |
|
||||
| Unit tests | ✅ | Ephemeral CA via `crypto/x509`. Fabricated `PeerCertificates`. Valid cert → user provisioned · no TLS → `ErrNoCert` · empty certs → `ErrNoCert` · no CN → `ErrInvalidCreds`. |
|
||||
| Integration tests | ✅ | Real TLS listener on localhost. No cert / wrong CA / expired → TLS handshake rejected. Valid cert → 200. Peer certificate CN + email visibility verified. |
|
||||
| UI bug pass | ✅ | Reviewed admin, settings, login, welcome surfaces in light/dark themes. Fixed settings crash (models API undefined). Removed dead chat settings from both user and admin settings. |
|
||||
| Dead code sweep | ✅ | Removed ~700 lines: orphaned CSS, dead Go types, stale event code, unused test helpers, dead settings UI (chat defaults, system prompt, default model, policies, web search, compaction, memory). |
|
||||
| Template cleanup | ✅ | Removed stale CSS link tags and orphaned chat-pane.html. Updated doc comments throughout. |
|
||||
| Package proof-of-concept status | ✅ | Created README.md for tasks + schedules with graduation criteria. Added missing manifest icons. |
|
||||
| Welcome surface | ✅ | New fallback surface when no extensions installed. Topbar + welcome card with admin link. Replaces `/admin` as final redirect target. |
|
||||
| Default surface routing | ✅ | Resolution chain: user preference → global config → first extension → `/welcome`. Users can set personal default in Settings > General. Admin sets global default in Admin > Settings. |
|
||||
| Admin navigation | ✅ | Replaced Back button with UserMenu in admin topbar. Eliminates back-button infinite loop. |
|
||||
|
||||
### v0.6.6 — Final Hardening
|
||||
|
||||
Final pass before public release. Security, correctness, and developer experience.
|
||||
### v0.2.6 — Admin Settings Audit
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Extension dependency auto-activation | ✅ | Installing a package with unmet `depends`/`requires` auto-installs dependencies from the bundled set. If not bundled: clear error listing what's missing. |
|
||||
| `ValidateManifest()` gate | ✅ | Single `ValidateManifest()` function in `package_validate.go`. Called at install time (both upload and bundled). 12 unit tests. |
|
||||
| Package signing hook | ✅ | Optional `signature` field in manifest (reserved). `PACKAGE_VERIFY_SIGNATURES` env var (default false, log-only). No cryptographic code yet — schema slot reserved. |
|
||||
| OIDC state nonce validation | ✅ | `oidcClaims.Nonce` field added. `ValidateIDTokenNonce()` compares ID token nonce against stored state. Callback rejects mismatched nonces. |
|
||||
| Schema migration stub decision | ✅ | Stub replaced with log-only function documenting additive-only policy. Downgrade rejection preserved. |
|
||||
| ICD/SDK runner update pass | ✅ | ICD smoke tier: added metrics, cluster, backups, docs, OpenAPI JSON endpoints. SDK admin domain: added metrics, cluster, backups tests. |
|
||||
| Stale TODO resolution | ✅ | `main.go` session middleware: replaced with `OptionalAuth()` (auth if token present, anonymous pass-through). `auth.go:221` OIDC nonce: resolved. `starlark_helpers.go:96` migration stub: resolved. |
|
||||
| Admin settings E2E | ✅ | All 7 admin settings sections verified (default surface, registration, banner, message bar, footer, vault, email). Dead code removed: `sectionCategory()` pruned of AI/routing/channel vestiges, `PublicSettings()` stripped of chat-era fields (system_prompt, retention_ttl, paste_to_file, allow_user_personas), dead `PolicyDefaults` removed (allow_raw_model_access, default_model), dead policy lookups removed (kb_direct_access), test seed data cleaned. |
|
||||
| Packages surface | ✅ | Package list loads (17 total/17 enabled), type filters work, enable/disable visible, settings/export buttons present, core package (admin) protected. Removed dead `chat` from CORE_IDS. |
|
||||
|
||||
Then ship.
|
||||
### v0.2.7 — User Settings Audit
|
||||
|
||||
---
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| User settings E2E | ✅ | All 6 user settings sections verified (General, Appearance, Profile, Teams, Connections, Notifications). Dead code removed: BYOK nav section + state, personas gate filter, Message Font Size slider, `auth.permissions.changed` listener. localStorage key renamed `cs-appearance` → `sb-appearance` with one-time migration. |
|
||||
| Visibility gating | ✅ | Dead BYOK/personas policy lookups removed from bootstrap and permissions handlers. `allow_user_byok` removed from `PublicSettings`. `PolicyDefaults` cleaned of `allow_user_byok` and `allow_user_personas`. Dead `msgFont` early-apply removed from base template. Stale policy-gating test assertions replaced. No empty nav sections remain. |
|
||||
|
||||
### v0.2.8 — Team Admin Settings Audit (Pass 1)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Team admin E2E | ✅ | Audited team member management, settings cascade, role assignment. Removed dead code: `HasPrivateProviderRequirement` (BYOK vestige), `UserRole` on `TeamMember` (deprecated role column), `allow_team_providers` policy default, dead personas/providers/models ICD tests. |
|
||||
| Workflow stage UI cleanup | ✅ | Removed dead personas dropdown, `history_mode` selector, stale `chat_only` mode. Updated `STAGE_MODES` to match backend CHECK constraint (`form_only`, `form_chat`, `review`, `custom`). Removed stale comments referencing deleted files. |
|
||||
|
||||
### v0.2.9 — Builtin Extension Retirement
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Retire builtin seeder | ✅ | Removed `SeedBuiltinPackages`, `seed_packages.go`, Dockerfile COPY, and `extensions/builtin/` directory. These extensions are dormant until a chat surface exists to consume them. |
|
||||
| Convert to regular packages | ✅ | Repackaged 6 extensions as standard directories in `packages/` with `js/` layout and `"requires": ["chat"]` manifest metadata. Built via `build.sh` like all other packages. No auto-install — explicit install only. |
|
||||
|
||||
## v0.3.x — Workflow Architecture
|
||||
|
||||
Workflows are the core platform capability. This series implements the
|
||||
full multi-step automation system with team role integration and
|
||||
finalizes the extension lifecycle model.
|
||||
|
||||
### v0.3.0 — Schema Redesign + Stage CRUD Modernization (complete)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Workflow schema redesign | ✅ | Dropped `persona_id`, `history_mode` from `workflow_stages`. Renamed `transition_rules` → `stage_config`. Updated `stage_mode` CHECK to `(form, review, delegated, automated)`. Added `audience`, `stage_type`, `starlark_hook`, `branch_rules`. Both PG + SQLite. |
|
||||
| Model + store updates | ✅ | Go structs, constants, and PG/SQLite queries updated. New `ValidStageTypes`, `ValidAudiences` maps. Routing engine reads `branch_rules` directly. |
|
||||
| Handler + Starlark updates | ✅ | Stage CRUD validation for new fields. Package export/import updated. Hook handler reads `stage_config`. Starlark module exposes `audience`, `stage_type`. |
|
||||
| Frontend updates | ✅ | Team-admin and admin stage editors updated with new modes, audience selector, stage type selector, conditional Starlark hook input. Fixed admin `STAGE_MODES` bug. |
|
||||
|
||||
### v0.3.1 — Instance + Assignment Tables + Store (complete)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Instance schema | ✅ | `workflow_instances` table in 007_workflows.sql (PG + SQLite). Tracks execution state: workflow_version, current_stage, stage_data, status, entry_token. |
|
||||
| Assignment schema | ✅ | `workflow_assignments` table. Per-stage queue: instance_id, stage, team_id, assigned_to, status, review_data. Optimistic claim lock. |
|
||||
| Models + store interface | ✅ | `WorkflowInstance`, `WorkflowAssignment` structs. 15 store methods for instance lifecycle and assignments across PG + SQLite. |
|
||||
| Event types | ✅ | `workflow.started`, `workflow.cancelled`, `workflow.error` added to bus route table. |
|
||||
|
||||
### v0.3.2 — Workflow Engine + Handlers (complete)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Store tests | ✅ | Round-trip tests for all 15 v0.3.1 store methods (instance + assignment CRUD). TruncateAll updated for new tables. |
|
||||
| Stage execution engine | ✅ | `server/workflow/engine.go` — Start, Advance (with branch_rules), Cancel. Merges stage_data, creates assignments, emits events. |
|
||||
| Automated stages | ✅ | `server/workflow/automated.go` — fire Starlark hook, auto-advance, cycle guard (max 10 consecutive). |
|
||||
| Instance handlers | ✅ | HTTP API: Start, GetInstance, Advance, Cancel, ListInstances. Team-scoped mirrors. |
|
||||
| Assignment handlers | ✅ | HTTP API: Claim, Unclaim, Complete, Cancel, ListByTeam, ListMine. Claimer identity verification. |
|
||||
| Starlark module expansion | ✅ | `workflow.get_instance()`, `workflow.list_instances()` (read-only). Mutating builtins deferred pending interface extraction. |
|
||||
|
||||
### v0.3.3 — Public Entry + Background Jobs (complete)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Public entry | ✅ | `StartPublic`, `ResumePublic`, `AdvancePublic` — token-based anonymous workflow participation. Public routes at `/api/v1/public/workflows/`. Audience-gated: only `public` stages can be advanced anonymously. |
|
||||
| SLA scanner | ✅ | Background goroutine (5-min interval) checking active instances against per-stage `sla_seconds`. Fires `workflow.sla_breach` event, marks breach in instance metadata (idempotent). |
|
||||
| Staleness sweep | ✅ | Per-workflow `staleness_timeout_hours` column. Scanner marks idle instances as `stale`, cancels open assignments, fires `workflow.stale` event. |
|
||||
|
||||
### v0.3.4 — Team Roles + Multi-party Validation (complete)
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Team roles | ✅ | Removed CHECK constraint on `team_members.role`. Custom roles stored in `teams.settings["roles"]`. Team roles API (`GET/PUT /teams/:teamId/roles`). Role-based stage assignment via `stage_config.required_role`. Frontend: dynamic role selects, role management panel. |
|
||||
| Multi-party sign-off | ✅ | `workflow_signoffs` table (both dialects). `StageConfig.validation` with `required_approvals`, `required_role`, `reject_action`. Engine validation gate in `advanceInternal`. `SubmitSignoff` engine method. Signoff HTTP API (`POST/GET /instances/:iid/signoffs`). Frontend signoff panel in monitor tab. |
|
||||
| Extension lifecycle | ✅ | Design doc: `docs/DESIGN-EXTENSION-LIFECYCLE.md`. Permanent vs PoC classification, graduation criteria, install model. |
|
||||
| Trigger composition | ✅ | Design doc: `docs/DESIGN-TRIGGER-COMPOSITION.md`. Triggers/schedules can start workflows, workflows emit events, no circular invocation. |
|
||||
|
||||
### v0.3.5 — Settings Audit + ICD + Tests
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Clone endpoint | ✅ | `POST /api/v1/workflows/:id/clone` — deep copy workflow + stages. Handler-level composition of existing store methods. |
|
||||
| Integration tests | ✅ | 7 engine-level tests in `workflow_engine_test.go`: full lifecycle, branch routing, public entry, signoff gate, rejection, cancel-clears-assignments, error cases. 28 total tests. |
|
||||
| Settings audit pass 2 | ✅ | Added `staleness_timeout_hours` field to workflow editor. Added collapsible branch_rules JSON editor in stage form. |
|
||||
| ICD update | ✅ | Fixed stale Workflow/Stage schemas. Added WorkflowInstance, WorkflowAssignment, WorkflowSignoff schemas. Added ~20 new endpoints: instances, assignments, signoffs, public entry, clone, team roles. |
|
||||
|
||||
### v0.3.6 — Example Workflows + Interactive Demo
|
||||
|
||||
Four installable `.pkg` workflow packages that prove the engine works
|
||||
end-to-end, plus a demo surface for guided exploration.
|
||||
See `docs/DEMO-WORKFLOWS.md` for full stage definitions and Starlark code.
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Bug Report Triage | ✅ | Public entry, progressive fieldsets, severity-based branch routing, team assignment, SLA timer. Pure-manifest `.pkg`. |
|
||||
| Employee Onboarding | ✅ | Starlark automated stages (`db.insert`, `notifications.send`), signoff gate with `required_role`, rejection reroute. `.pkg` with `script.star`. |
|
||||
| Content Approval | ✅ | Multi-party signoff (quorum of 2), rejection reroute creating review cycle. `.pkg` demonstrating signoff + reroute loop. |
|
||||
| Webhook Notifier | ✅ | Starlark `http.post` + `connections.get` for outbound webhooks, delivery logging to ext_data. Proves HTTP + connections modules. |
|
||||
| Demo surface | ✅ | Browser-tier walkthrough: workflow cards, stage diagrams, Starlark viewer, "Try It" buttons, API curl examples. Auto-installed, removable. |
|
||||
| Engine context fix | ✅ | Add `started_by` to automated stage Starlark context dict (backward-compatible). |
|
||||
| SLA package installer | ✅ | Added `sla_seconds` support to `workflowPkgStage` struct and install/export paths. |
|
||||
| Snapshot format fix | ✅ | `parseSnapshotStages` helper handles both wrapped and legacy snapshot formats. |
|
||||
| Workflow adoption | ✅ | `POST /teams/:teamId/workflows/:id/adopt` + `GET .../available`. Team-admin "Adopt Global" button. `TeamID` in `WorkflowPatch`. |
|
||||
| Extension SDK boot | ✅ | `base.html` loads Preact globals + `boot()` for extension surfaces (was missing since Scorched Earth IV). |
|
||||
| Admin teams tab fix | ✅ | Extract `.data` from paginated response in admin teams list. |
|
||||
| Documentation | ✅ | `docs/DEMO-WORKFLOWS.md`: feature capability matrix, stage flows, API walkthrough, per-package READMEs. |
|
||||
| Review pass | | Docker E2E walkthrough: install all packages, adopt into team, activate, publish, run each workflow end-to-end. Fix remaining UI/UX issues. |
|
||||
|
||||
### v0.3.7 — Package Audit (complete)
|
||||
|
||||
Verified all 16 packages install correctly. Packages with unmet `requires` auto-set to dormant.
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Manifest fixes | ✅ | Fixed 6 chat-extension manifests (`"name"` → `"title"`, was blocking install). Added explicit `"type": "surface"` to hello-dashboard, icd-test-runner, sdk-test-runner. |
|
||||
| Dormant status | ✅ | Added `dormant` to `packages.status` CHECK constraint (both dialects). Installer auto-detects unmet `requires` and sets `status=dormant, enabled=false`. Enable endpoint returns 409 for dormant packages. |
|
||||
| Functional audit | ✅ | Navigated to every surface in browser. 7 working: schedules, tasks, team-activity-log, git-board, hello-dashboard, icd-test-runner, sdk-test-runner. 2 broken: dashboard + editor (depend on removed `sw.*` imperative SDK) — tagged `requires: ["legacy-sdk"]` → dormant. |
|
||||
| Chat-dependency tagging | ✅ | 6 chat-dependent extensions (csv-table, diff-viewer, js-sandbox, katex-renderer, mermaid-renderer, regex-tester) install as dormant. git-board and gitea-client are standalone. |
|
||||
| Dependency check fix | ✅ | Relaxed library dependency validation to allow `pending_review` libraries (gitea-client declares permissions). Only `suspended`/`dormant` libraries blocked. |
|
||||
| Admin UI | ✅ | Dormant badge, disabled Enable button with tooltip, Dormant stat card in admin packages view. |
|
||||
| Tests | ✅ | 4 handler tests (SetStatus dormant, enable blocked, surfaces exclude dormant, admin list includes dormant). All existing tests pass. |
|
||||
|
||||
### v0.3.8 — Distribution
|
||||
|
||||
Builder image for faster builds, bundled packages for zero-config first run.
|
||||
|
||||
| Step | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| Builder image | | `Dockerfile.builder` with cached Go modules + Node vendor libs. Published to Docker Hub for faster custom builds. |
|
||||
| Bundled packages | | Dockerfile stage builds example workflows + demo surface into production image. Auto-installs on first run (standard install path, admin can uninstall). `SKIP_BUNDLED_PACKAGES=true` to disable. |
|
||||
| Distribution docs | | `docs/DISTRIBUTION.md` with builder image usage, custom build guide, production deployment recommendations. |
|
||||
|
||||
## v0.4.0 — Notes Surface
|
||||
|
||||
Obsidian-style rich-text notes rebuilt as an installable surface package.
|
||||
Zero platform special-casing. Proves the full extension stack E2E.
|
||||
|
||||
- Notes as `.pkg` archive
|
||||
- Rich text editor (ProseMirror or similar)
|
||||
- Folder tree, backlinks, tags — all extension-provided
|
||||
- Markdown import/export
|
||||
|
||||
## v0.5.0 — MVP
|
||||
|
||||
Extension and operations tracks converge. First externally usable release.
|
||||
|
||||
- Package registry (browse, install, update, uninstall)
|
||||
- Package distribution model (no auto-install; explicit install only)
|
||||
- Health monitoring dashboard
|
||||
- Backup/restore tooling
|
||||
- Documentation site
|
||||
|
||||
## Post-MVP
|
||||
|
||||
- LLM participation (`llm-bridge` extension: subscribes to `chat.message.created`, calls `provider.complete()`, streams response via `realtime.publish`, posts via `chat.send()`. Bot participants with persona config. Multi-model conversations.)
|
||||
- Chat extension (provider registry, streaming, personas, tool system)
|
||||
- Rich media extensions: image generation, code sandbox, STT/TTS
|
||||
- Desktop app (Tauri or Electron)
|
||||
- Sidecar tier: container-based extensions
|
||||
- Federation: cross-instance package sharing
|
||||
- Plugin marketplace with signing and review
|
||||
|
||||
---
|
||||
- Mermaid diagrams extension (nice-to-have)
|
||||
|
||||
## Design Decisions Log
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Tasks → extension | Scheduler was the most entangled kernel component (~3,400 lines). Rebuilding as extension validates the trigger system and removes the worst compilation debt. Three trigger primitives (time, webhook, event) replace the monolithic scheduler. |
|
||||
| Sessions removed | Kernel-managed sessions replaced by workflow instances with dedicated storage (ext_data tables or kernel table). |
|
||||
| `custom` stage mode | Stage mode `custom` delegates to a surface package, proving extension composability. Chat-in-workflow is handled by the chat extension, not the kernel. |
|
||||
| Sessions removed | Channel-based sessions coupled to deleted chat system. Workflow instances need new storage model — either ext_data tables or a dedicated kernel table. |
|
||||
| `chat_only` → `custom` | Stage mode `chat_only` implied chat as a kernel concept. Renamed to `custom` which delegates to a surface package, proving extension composability. |
|
||||
| Providers removed from kernel | Provider configs, model catalog, routing policies — all moved to extension track. Kernel provides credential storage (connections) and the Starlark `provider.complete` module as the interface. |
|
||||
| Kernel permissions simplified | 6 platform permissions. Extensions define their own capability requirements in manifests. |
|
||||
| Kernel permissions simplified | From 16 chat-centric permissions to 6 platform permissions. Extensions define their own capability requirements in manifests. |
|
||||
| Preact+htm retained | 3KB runtime, no build step, works for extension authors without bundler config. KISS. |
|
||||
| Single Docker image | Drop the frontend/backend split. Go binary + assets + migrations in one image. Simpler deployment, fewer moving parts. |
|
||||
| Admin → RBAC group | The `role` column is pre-RBAC. v0.2.0 replaces it with a seeded "Admins" group + `surface.admin.access` grant. All users auto-join "Everyone" group. Admin middleware becomes a grant check, not a role check. |
|
||||
@@ -184,10 +270,6 @@ Then ship.
|
||||
| No new migrations pre-MVP | Edit existing migration SQL files in place. No migration chains until schema is in production. |
|
||||
| Notes over Editor | First surface is Obsidian-style notes (rich text, folders, backlinks) instead of a code editor. Notes is a stronger E2E proof — it exercises ext_data, storage, and the SDK more fully than a pure-browser CM6 editor. |
|
||||
| No built-in auto-install | Extensions ship in the repo but are not auto-installed. Distribution model TBD — explicit install only. Keeps the kernel clean and avoids opinionated defaults. |
|
||||
| Chat as extension, not kernel | Human-to-human chat built entirely as library + surface packages. Zero kernel awareness of conversations, messages, or participants. Kernel gains one generic `realtime` module. Proves near-infinite extensibility. LLM participation layers on top via a separate bridge extension — the chat system doesn't know or care whether a participant is human or AI. |
|
||||
| PG as consensus layer | Horizontal scaling uses PG as the sole coordinator (UNLOGGED node_registry + LISTEN/NOTIFY). No etcd, Consul, Redis, or Raft. Rationale: system is already tightly coupled to PG; adding a second consensus layer doubles operational complexity for zero benefit at homelab-to-small-team scale. UNLOGGED table is visible to all connections, survives session disconnect, and cleans up automatically on PG crash — correct behavior since all nodes are dead anyway. Sweep-all for health (every node deletes stale rows) is simpler than ring topology and has no edge cases. |
|
||||
| Chat → post-MVP | Chat extension (providers, streaming, personas) is valuable but not MVP-critical. The platform must prove itself with simpler surfaces first. Chat moves to post-MVP track. |
|
||||
| Two trigger tiers | Event + webhook triggers are extension-declared (manifest contract, full sandbox). Scheduled tasks are user-created ad-hoc (restricted sandbox — no raw HTTP, no DB table creation, connections-only outbound). Separation keeps extension contracts static and user automation safe. |
|
||||
| Scheduled task identity | Tasks run as their creator (RBAC-scoped). Admin-created tasks can opt into system context. Creator deactivation pauses the schedule. Ensures audit trail and permission boundaries. |
|
||||
| Builtin package rationale | A builtin must enhance kernel surfaces or be required to demonstrate the platform's own capabilities. **notes** — primary content surface, exercises ext_data/storage/SDK/settings/realtime fully. **chat + chat-core** — primary communication surface, proves the extensibility thesis (100% extension, zero kernel awareness). **mermaid-renderer** — docs surface uses Mermaid diagrams to explain the architecture; without it the platform's own documentation doesn't render (self-bootstrapping). **schedules** — UI for the kernel's scheduled task system; without it users can't manage cron jobs (kernel primitive UI). All others are domain features, examples, dormant, or LLM-only tools — available via registry or `BUNDLED_PACKAGES=*`. |
|
||||
| Cluster dashboard retired | `cluster-dashboard` shipped as a standalone surface package (v0.6.0) as an expedient. Health/metrics belong inside the Admin surface as a tab — shared context, no separate nav entry, no install required. Merged in v0.6.4. |
|
||||
| Block renderers decoupled from chat | `mermaid-renderer`, `katex-renderer`, `csv-table`, `diff-viewer` shipped with `"requires": ["chat"]` because renderer discovery lived inside the chat surface. These are content renderers, not chat features. v0.6.4 removes the constraint; v0.6.5 lifts renderer registration to the kernel SDK so all surfaces share it without reimplementing discovery. |
|
||||
|
||||
132
TURNOVER.md
Normal file
132
TURNOVER.md
Normal file
@@ -0,0 +1,132 @@
|
||||
# Switchboard Core — Session Turnover
|
||||
**Date**: 2026-03-26
|
||||
**Author**: Jeffrey Smith (jasafpro@gmail.com)
|
||||
**Session**: v0.2.0 PR 1 — Full RBAC migration
|
||||
|
||||
---
|
||||
|
||||
## What Was Done
|
||||
|
||||
### PR 1: Admin → RBAC group migration — COMPLETE
|
||||
Branch `feat/admin-rbac-migration` (PR #1), 3 commits:
|
||||
|
||||
1. **Admin → RBAC group migration** — `surface.admin.access` permission +
|
||||
Admins system group replaces hardcoded `role == "admin"` checks. Admin
|
||||
bypass removed from `RequirePermission`. Bootstrap/seed/OIDC/admin handlers
|
||||
sync group membership.
|
||||
|
||||
2. **Remove token budgets + allowed models from groups** — Provider-era cruft:
|
||||
`token_budget_daily`, `token_budget_monthly`, `allowed_models` columns,
|
||||
`ResolveTokenBudget()`, `ResolveModelAllowlist()`, and all store/handler/UI
|
||||
code deleted. -283 lines.
|
||||
|
||||
3. **Drop `users.role` column** — Full RBAC. Zero magic roles. The `role` column,
|
||||
`UserRoleAdmin`/`UserRoleUser` constants, `CountByRole()`, `DefaultRole` config,
|
||||
`role` in JWT claims, and all role-based shortcuts removed. Everyone group
|
||||
membership is now explicit (all users added on create). 28 files changed.
|
||||
|
||||
**Net result: -364 lines across 3 commits.**
|
||||
|
||||
### Architecture after this PR:
|
||||
|
||||
- **Everyone group** (`00000000...0001`): all users explicitly added on creation.
|
||||
Carries `extension.use`, `workflow.submit`.
|
||||
- **Admins group** (`00000000...0002`): carries all 7 kernel permissions including
|
||||
`surface.admin.access`. Not special-cased — just a group with permissions.
|
||||
- **Permission resolution**: union of all group memberships. No implicit groups,
|
||||
no role shortcuts, no admin bypass.
|
||||
- **Admin middleware**: checks `surface.admin.access` grant via `resolveAndCachePerms`.
|
||||
- **JWT claims**: `user_id` + `email` only. No role.
|
||||
- **OIDC**: `isIdPAdmin()` maps IdP role claim → Admins group membership.
|
||||
No `role` column writes.
|
||||
- **User creation paths**: builtin register, OIDC auto-provision, mTLS auto-provision,
|
||||
admin create, bootstrap, seed — all call `EnsureEveryoneGroup()`.
|
||||
|
||||
---
|
||||
|
||||
## Known Issues
|
||||
|
||||
1. **Frontend test job**: FE test suite may have remaining stale references
|
||||
from Phase 0 gut (pre-existing)
|
||||
2. **Traefik middleware**: `rbac-traefik.yaml` needs one-time manual apply
|
||||
by cluster admin (pre-existing, non-blocking)
|
||||
3. **`SEED_USERS`**: Not set in K8s secrets (pre-existing)
|
||||
4. **Editor modules**: `src/editor/*.mjs` still reference "Chat Switchboard"
|
||||
(pre-existing, low priority)
|
||||
5. **K8s deploy**: PR not yet merged to main — CI/CD will need a deploy after merge
|
||||
|
||||
---
|
||||
|
||||
## What's Next
|
||||
|
||||
### Merge PR #1
|
||||
Review and merge `feat/admin-rbac-migration` to main.
|
||||
|
||||
### v0.2.0 — Remaining PRs
|
||||
|
||||
**PR 2: Settings cascade**
|
||||
- Add `user_overridable` flag to settings schema
|
||||
- RBAC controls scope auth (admin → global, team-admin → team, user → personal)
|
||||
- Resolution: user → team → global (first non-null wins)
|
||||
|
||||
**PR 3: ICD (API contract)**
|
||||
- Generate full OpenAPI spec from registered routes
|
||||
- Document kernel-only endpoints
|
||||
|
||||
**PR 4: Trigger system**
|
||||
- Time triggers (cron), webhook (inbound HTTP), event (bus subscription)
|
||||
- Extensions register match expressions at install
|
||||
|
||||
**PR 5: SDK stabilization**
|
||||
- `sb.slots()`, `sb.actions`, `sb.api.ext()`, `sb.storage`
|
||||
- Theme tokens exposed to extensions
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions (this session)
|
||||
|
||||
| Decision | Detail |
|
||||
|----------|--------|
|
||||
| Full RBAC — no magic roles | `users.role` column dropped entirely. All authorization through group membership + permission grants. |
|
||||
| Explicit Everyone membership | No implicit "all users get Everyone perms". Every user added to Everyone group on create. `member_count` reflects reality. |
|
||||
| Admins group not special-cased | Code never checks group identity — only checks for `surface.admin.access` permission. Any group can grant it. |
|
||||
| No new migrations pre-MVP | Edit existing SQL files in place. Schema isn't in production. |
|
||||
| JWT simplified | Claims carry `user_id` + `email` only. Permissions resolved server-side from groups on every request. |
|
||||
| OIDC role → group sync | `isIdPAdmin()` replaces `resolveRole()`. IdP admin claim maps to Admins group membership, not a DB column. |
|
||||
| Token budgets/allowed models removed | Provider-era cruft. Belongs in a future provider extension, not the kernel. |
|
||||
|
||||
---
|
||||
|
||||
## File Locations
|
||||
|
||||
| What | Where |
|
||||
|------|-------|
|
||||
| Roadmap | `ROADMAP.md` |
|
||||
| Changelog | `CHANGELOG.md` |
|
||||
| CI workflow | `.gitea/workflows/ci.yaml` |
|
||||
| K8s manifests | `k8s/` |
|
||||
| Docker compose (local dev) | `docker-compose.yml` (SQLite, port 3000) |
|
||||
| Nginx template | `nginx.conf.template` |
|
||||
| Migrations | `server/database/migrations/{postgres,sqlite}/` |
|
||||
| Permission constants | `server/auth/permissions.go` |
|
||||
| Admin middleware | `server/middleware/admin.go` |
|
||||
| Group store | `server/store/{postgres,sqlite}/groups.go` |
|
||||
| Bootstrap/seed | `server/handlers/auth.go` |
|
||||
| Admin handlers | `server/handlers/admin.go` |
|
||||
| Groups UI | `src/js/sw/surfaces/admin/groups.js` |
|
||||
| Users UI | `src/js/sw/surfaces/admin/users.js` |
|
||||
| SDK API | `src/js/sw/sdk/api-domains.js` |
|
||||
| Memory (Claude) | `.claude/projects/-config-Projects-core/memory/` |
|
||||
|
||||
---
|
||||
|
||||
## Gitea Secrets/Vars Needed
|
||||
|
||||
**Secrets**: `POSTGRES_USER`, `POSTGRES_USER_PASSWORD`, `POSTGRES_ADMIN_USER`,
|
||||
`POSTGRES_ADMIN_PASSWORD`, `ENCRYPTION_KEY`
|
||||
|
||||
**Vars**: `DOMAIN`, `NAMESPACE`, `S3_BUCKET`, `S3_ENDPOINT`, `STORAGE_BACKEND`,
|
||||
`STORAGE_CLASS`, `STORAGE_SIZE`
|
||||
|
||||
**Not yet configured**: `S3_ACCESS_KEY`, `S3_SECRET_KEY` (using PVC for now),
|
||||
`SEED_USERS` (needed for initial admin bootstrap)
|
||||
@@ -1,11 +1,11 @@
|
||||
apiVersion: v2
|
||||
name: armature
|
||||
description: Armature — self-hosted extension platform
|
||||
name: switchboard
|
||||
description: Switchboard Core — self-hosted extension platform
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "0.0.0" # Patched at CI/release time from /VERSION
|
||||
home: https://gobha.ai
|
||||
sources:
|
||||
- https://git.gobha.me/armature/core
|
||||
- https://git.gobha.me/switchboard/core
|
||||
maintainers:
|
||||
- name: xcaliber
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
# Armature Core — PrometheusRule alerts (v0.33.0)
|
||||
# Switchboard Core — PrometheusRule alerts (v0.33.0)
|
||||
# Source file for the Helm template. Deploy via:
|
||||
# monitoring.prometheusRule.enabled: true
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: PrometheusRule
|
||||
metadata:
|
||||
name: armature-alerts
|
||||
name: switchboard-alerts
|
||||
spec:
|
||||
groups:
|
||||
- name: armature.rules
|
||||
- name: switchboard.rules
|
||||
rules:
|
||||
# Pod restart (possible OOM)
|
||||
- alert: ArmaturePodRestart
|
||||
- alert: SwitchboardPodRestart
|
||||
expr: increase(kube_pod_container_status_restarts_total{container="backend"}[1h]) > 0
|
||||
for: 0m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Armature backend pod restarted (possible OOM)"
|
||||
summary: "Switchboard backend pod restarted (possible OOM)"
|
||||
description: "Container {{ $labels.container }} in pod {{ $labels.pod }} restarted."
|
||||
|
||||
# Provider down for 5+ minutes
|
||||
- alert: ArmatureProviderDown
|
||||
expr: armature_provider_status > 2
|
||||
- alert: SwitchboardProviderDown
|
||||
expr: switchboard_provider_status > 2
|
||||
for: 5m
|
||||
labels:
|
||||
severity: critical
|
||||
@@ -29,8 +29,8 @@ spec:
|
||||
summary: "Provider {{ $labels.provider_config_id }} is down"
|
||||
|
||||
# DB pool >80% utilized
|
||||
- alert: ArmatureDBPoolExhaustion
|
||||
expr: armature_db_in_use_connections / armature_db_open_connections > 0.8
|
||||
- alert: SwitchboardDBPoolExhaustion
|
||||
expr: switchboard_db_in_use_connections / switchboard_db_open_connections > 0.8
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
@@ -38,10 +38,10 @@ spec:
|
||||
summary: "DB connection pool >80% utilized"
|
||||
|
||||
# HTTP 5xx error rate >5%
|
||||
- alert: ArmatureHighErrorRate
|
||||
- alert: SwitchboardHighErrorRate
|
||||
expr: >
|
||||
sum(rate(armature_http_requests_total{status=~"5.."}[5m]))
|
||||
/ sum(rate(armature_http_requests_total[5m])) > 0.05
|
||||
sum(rate(switchboard_http_requests_total{status=~"5.."}[5m]))
|
||||
/ sum(rate(switchboard_http_requests_total[5m])) > 0.05
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
@@ -49,10 +49,10 @@ spec:
|
||||
summary: "HTTP 5xx error rate exceeds 5%"
|
||||
|
||||
# Task failure rate >25%
|
||||
- alert: ArmatureTaskFailureRate
|
||||
- alert: SwitchboardTaskFailureRate
|
||||
expr: >
|
||||
rate(armature_task_executions_total{status="error"}[15m])
|
||||
/ rate(armature_task_executions_total[15m]) > 0.25
|
||||
rate(switchboard_task_executions_total{status="error"}[15m])
|
||||
/ rate(switchboard_task_executions_total[15m]) > 0.25
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
@@ -60,8 +60,8 @@ spec:
|
||||
summary: "Task failure rate exceeds 25% over 15 minutes"
|
||||
|
||||
# No completions processed in 15 minutes (canary)
|
||||
- alert: ArmatureNoCompletions
|
||||
expr: sum(rate(armature_completions_total[10m])) == 0
|
||||
- alert: SwitchboardNoCompletions
|
||||
expr: sum(rate(switchboard_completions_total[10m])) == 0
|
||||
for: 15m
|
||||
labels:
|
||||
severity: critical
|
||||
@@ -17,10 +17,10 @@
|
||||
{ "type": "panel", "id": "gauge", "name": "Gauge", "version": "" }
|
||||
],
|
||||
"id": null,
|
||||
"uid": "armature-overview",
|
||||
"title": "Armature — Overview",
|
||||
"uid": "switchboard-overview",
|
||||
"title": "Switchboard Core — Overview",
|
||||
"description": "System overview: request rates, latency, provider health, token usage, DB pool.",
|
||||
"tags": ["armature"],
|
||||
"tags": ["switchboard"],
|
||||
"timezone": "browser",
|
||||
"refresh": "30s",
|
||||
"schemaVersion": 38,
|
||||
@@ -37,7 +37,7 @@
|
||||
"name": "namespace",
|
||||
"type": "query",
|
||||
"datasource": { "type": "prometheus", "uid": "${datasource}" },
|
||||
"query": "label_values(armature_http_requests_total, namespace)",
|
||||
"query": "label_values(switchboard_http_requests_total, namespace)",
|
||||
"includeAll": true,
|
||||
"current": { "text": "All", "value": "$__all" }
|
||||
},
|
||||
@@ -45,7 +45,7 @@
|
||||
"name": "pod",
|
||||
"type": "query",
|
||||
"datasource": { "type": "prometheus", "uid": "${datasource}" },
|
||||
"query": "label_values(armature_http_requests_total{namespace=~\"$namespace\"}, pod)",
|
||||
"query": "label_values(switchboard_http_requests_total{namespace=~\"$namespace\"}, pod)",
|
||||
"includeAll": true,
|
||||
"current": { "text": "All", "value": "$__all" }
|
||||
}
|
||||
@@ -58,7 +58,7 @@
|
||||
"gridPos": { "h": 8, "w": 6, "x": 0, "y": 0 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(armature_http_requests_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"expr": "sum(rate(switchboard_http_requests_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"legendFormat": "Total req/s"
|
||||
}
|
||||
]
|
||||
@@ -69,7 +69,7 @@
|
||||
"gridPos": { "h": 8, "w": 6, "x": 6, "y": 0 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(armature_http_requests_total{namespace=~\"$namespace\",status=~\"5..\"}[5m])) / sum(rate(armature_http_requests_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"expr": "sum(rate(switchboard_http_requests_total{namespace=~\"$namespace\",status=~\"5..\"}[5m])) / sum(rate(switchboard_http_requests_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"legendFormat": "5xx rate"
|
||||
}
|
||||
],
|
||||
@@ -93,15 +93,15 @@
|
||||
"gridPos": { "h": 8, "w": 6, "x": 12, "y": 0 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.50, sum(rate(armature_http_request_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])) by (le))",
|
||||
"expr": "histogram_quantile(0.50, sum(rate(switchboard_http_request_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])) by (le))",
|
||||
"legendFormat": "p50"
|
||||
},
|
||||
{
|
||||
"expr": "histogram_quantile(0.95, sum(rate(armature_http_request_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])) by (le))",
|
||||
"expr": "histogram_quantile(0.95, sum(rate(switchboard_http_request_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])) by (le))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"expr": "histogram_quantile(0.99, sum(rate(armature_http_request_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])) by (le))",
|
||||
"expr": "histogram_quantile(0.99, sum(rate(switchboard_http_request_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])) by (le))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
],
|
||||
@@ -113,7 +113,7 @@
|
||||
"gridPos": { "h": 8, "w": 6, "x": 18, "y": 0 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(armature_websocket_connections{namespace=~\"$namespace\"})",
|
||||
"expr": "sum(switchboard_websocket_connections{namespace=~\"$namespace\"})",
|
||||
"legendFormat": "Active"
|
||||
}
|
||||
]
|
||||
@@ -124,7 +124,7 @@
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 8 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (provider_config_id) (rate(armature_completions_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"expr": "sum by (provider_config_id) (rate(switchboard_completions_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"legendFormat": "{{provider_config_id}}"
|
||||
}
|
||||
]
|
||||
@@ -135,7 +135,7 @@
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 8 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.95, sum by (provider_config_id, le) (rate(armature_completion_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])))",
|
||||
"expr": "histogram_quantile(0.95, sum by (provider_config_id, le) (rate(switchboard_completion_duration_seconds_bucket{namespace=~\"$namespace\"}[5m])))",
|
||||
"legendFormat": "{{provider_config_id}}"
|
||||
}
|
||||
],
|
||||
@@ -147,7 +147,7 @@
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 16 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (model_id) (rate(armature_completion_tokens_total{namespace=~\"$namespace\"}[5m])) * 60",
|
||||
"expr": "sum by (model_id) (rate(switchboard_completion_tokens_total{namespace=~\"$namespace\"}[5m])) * 60",
|
||||
"legendFormat": "{{model_id}}"
|
||||
}
|
||||
]
|
||||
@@ -158,7 +158,7 @@
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 16 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "armature_provider_status{namespace=~\"$namespace\"}",
|
||||
"expr": "switchboard_provider_status{namespace=~\"$namespace\"}",
|
||||
"legendFormat": "{{provider_config_id}}"
|
||||
}
|
||||
],
|
||||
@@ -179,15 +179,15 @@
|
||||
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 24 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "armature_db_open_connections{namespace=~\"$namespace\"}",
|
||||
"expr": "switchboard_db_open_connections{namespace=~\"$namespace\"}",
|
||||
"legendFormat": "Open"
|
||||
},
|
||||
{
|
||||
"expr": "armature_db_in_use_connections{namespace=~\"$namespace\"}",
|
||||
"expr": "switchboard_db_in_use_connections{namespace=~\"$namespace\"}",
|
||||
"legendFormat": "In Use"
|
||||
},
|
||||
{
|
||||
"expr": "armature_db_idle_connections{namespace=~\"$namespace\"}",
|
||||
"expr": "switchboard_db_idle_connections{namespace=~\"$namespace\"}",
|
||||
"legendFormat": "Idle"
|
||||
}
|
||||
]
|
||||
@@ -198,7 +198,7 @@
|
||||
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 24 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum by (status) (rate(armature_task_executions_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"expr": "sum by (status) (rate(switchboard_task_executions_total{namespace=~\"$namespace\"}[5m]))",
|
||||
"legendFormat": "{{status}}"
|
||||
}
|
||||
]
|
||||
@@ -1,4 +1,4 @@
|
||||
Armature {{ .Chart.AppVersion }} deployed.
|
||||
Chat Switchboard {{ .Chart.AppVersion }} deployed.
|
||||
|
||||
{{- if .Values.ingress.enabled }}
|
||||
Access the application at:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{{/*
|
||||
Common labels
|
||||
*/}}
|
||||
{{- define "armature.labels" -}}
|
||||
{{- define "switchboard.labels" -}}
|
||||
app.kubernetes.io/name: {{ .Chart.Name }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||
@@ -12,23 +12,23 @@ helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version }}
|
||||
{{/*
|
||||
Backend selector labels
|
||||
*/}}
|
||||
{{- define "armature.backend.labels" -}}
|
||||
{{- define "switchboard.backend.labels" -}}
|
||||
app.kubernetes.io/component: backend
|
||||
{{ include "armature.labels" . }}
|
||||
{{ include "switchboard.labels" . }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Frontend selector labels
|
||||
*/}}
|
||||
{{- define "armature.frontend.labels" -}}
|
||||
{{- define "switchboard.frontend.labels" -}}
|
||||
app.kubernetes.io/component: frontend
|
||||
{{ include "armature.labels" . }}
|
||||
{{ include "switchboard.labels" . }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Secret name
|
||||
*/}}
|
||||
{{- define "armature.secretName" -}}
|
||||
{{- define "switchboard.secretName" -}}
|
||||
{{- if .Values.existingSecret -}}
|
||||
{{ .Values.existingSecret }}
|
||||
{{- else -}}
|
||||
@@ -39,21 +39,21 @@ Secret name
|
||||
{{/*
|
||||
Backend image
|
||||
*/}}
|
||||
{{- define "armature.backend.image" -}}
|
||||
{{- define "switchboard.backend.image" -}}
|
||||
{{ .Values.backend.image.repository }}:{{ .Values.backend.image.tag | default .Chart.AppVersion }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Frontend image
|
||||
*/}}
|
||||
{{- define "armature.frontend.image" -}}
|
||||
{{- define "switchboard.frontend.image" -}}
|
||||
{{ .Values.frontend.image.repository }}:{{ .Values.frontend.image.tag | default .Chart.AppVersion }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Database URL — assembled from postgres.* if url is empty
|
||||
*/}}
|
||||
{{- define "armature.databaseURL" -}}
|
||||
{{- define "switchboard.databaseURL" -}}
|
||||
{{- if .Values.database.url -}}
|
||||
{{ .Values.database.url }}
|
||||
{{- else if eq .Values.database.driver "sqlite" -}}
|
||||
|
||||
@@ -3,7 +3,7 @@ kind: ConfigMap
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-config
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
data:
|
||||
PORT: {{ .Values.backend.port | quote }}
|
||||
BASE_PATH: {{ .Values.basePath | quote }}
|
||||
|
||||
@@ -4,7 +4,7 @@ kind: CronJob
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-backup
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: backup
|
||||
spec:
|
||||
schedule: {{ .Values.backup.schedule | quote }}
|
||||
@@ -35,7 +35,7 @@ spec:
|
||||
- |
|
||||
set -e
|
||||
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
|
||||
FILENAME="armature-${TIMESTAMP}.sql.gz"
|
||||
FILENAME="switchboard-${TIMESTAMP}.sql.gz"
|
||||
|
||||
echo "Starting backup: ${FILENAME}"
|
||||
pg_dump "${DATABASE_URL}" | gzip > "/backup/${FILENAME}"
|
||||
@@ -58,22 +58,22 @@ spec:
|
||||
|
||||
# Prune old local backups beyond retention
|
||||
cd /backup
|
||||
ls -t armature-*.sql.gz 2>/dev/null | tail -n +{{ add1 .Values.backup.retention }} | xargs -r rm -v
|
||||
ls -t switchboard-*.sql.gz 2>/dev/null | tail -n +{{ add1 .Values.backup.retention }} | xargs -r rm -v
|
||||
echo "Backup complete"
|
||||
env:
|
||||
- name: DATABASE_URL
|
||||
value: {{ include "armature.databaseURL" . | quote }}
|
||||
value: {{ include "switchboard.databaseURL" . | quote }}
|
||||
{{- if .Values.backup.s3.enabled }}
|
||||
- name: S3_ACCESS_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "armature.secretName" . }}
|
||||
name: {{ include "switchboard.secretName" . }}
|
||||
key: BACKUP_S3_ACCESS_KEY
|
||||
optional: true
|
||||
- name: S3_SECRET_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "armature.secretName" . }}
|
||||
name: {{ include "switchboard.secretName" . }}
|
||||
key: BACKUP_S3_SECRET_KEY
|
||||
optional: true
|
||||
{{- end }}
|
||||
|
||||
@@ -3,7 +3,7 @@ kind: Deployment
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-backend
|
||||
labels:
|
||||
{{- include "armature.backend.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.backend.labels" . | nindent 4 }}
|
||||
spec:
|
||||
replicas: {{ .Values.backend.replicaCount }}
|
||||
selector:
|
||||
@@ -38,7 +38,7 @@ spec:
|
||||
topologyKey: kubernetes.io/hostname
|
||||
containers:
|
||||
- name: backend
|
||||
image: {{ include "armature.backend.image" . }}
|
||||
image: {{ include "switchboard.backend.image" . }}
|
||||
imagePullPolicy: {{ .Values.backend.image.pullPolicy }}
|
||||
ports:
|
||||
- name: http
|
||||
@@ -48,10 +48,10 @@ spec:
|
||||
- configMapRef:
|
||||
name: {{ .Release.Name }}-config
|
||||
- secretRef:
|
||||
name: {{ include "armature.secretName" . }}
|
||||
name: {{ include "switchboard.secretName" . }}
|
||||
env:
|
||||
- name: DATABASE_URL
|
||||
value: {{ include "armature.databaseURL" . | quote }}
|
||||
value: {{ include "switchboard.databaseURL" . | quote }}
|
||||
resources:
|
||||
{{- toYaml .Values.backend.resources | nindent 12 }}
|
||||
{{- if .Values.persistence.enabled }}
|
||||
|
||||
@@ -3,7 +3,7 @@ kind: Deployment
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-frontend
|
||||
labels:
|
||||
{{- include "armature.frontend.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.frontend.labels" . | nindent 4 }}
|
||||
spec:
|
||||
replicas: {{ .Values.frontend.replicaCount }}
|
||||
selector:
|
||||
@@ -24,7 +24,7 @@ spec:
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: frontend
|
||||
image: {{ include "armature.frontend.image" . }}
|
||||
image: {{ include "switchboard.frontend.image" . }}
|
||||
imagePullPolicy: {{ .Values.frontend.image.pullPolicy }}
|
||||
ports:
|
||||
- name: http
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: {{ include "armature.fullname" . }}-grafana-dashboard
|
||||
name: {{ include "switchboard.fullname" . }}-grafana-dashboard
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
{{- with .Values.monitoring.grafanaDashboard.labels }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
data:
|
||||
armature-overview.json: |-
|
||||
{{- .Files.Get "dashboards/armature-overview.json" | nindent 4 }}
|
||||
switchboard-overview.json: |-
|
||||
{{- .Files.Get "dashboards/switchboard-overview.json" | nindent 4 }}
|
||||
{{- end }}
|
||||
|
||||
@@ -4,7 +4,7 @@ kind: Ingress
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-ingress
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
{{- if or .Values.ingress.annotations (and (eq (default "traefik" .Values.ingress.className) "traefik") .Values.ingress.retry.annotateIngress) }}
|
||||
annotations:
|
||||
{{- with .Values.ingress.annotations }}
|
||||
|
||||
@@ -5,7 +5,7 @@ kind: Middleware
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-retry
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
spec:
|
||||
retry:
|
||||
attempts: {{ .Values.ingress.retry.attempts | default 2 }}
|
||||
|
||||
@@ -2,57 +2,57 @@
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: PrometheusRule
|
||||
metadata:
|
||||
name: {{ include "armature.fullname" . }}-alerts
|
||||
name: {{ include "switchboard.fullname" . }}-alerts
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
{{- with .Values.monitoring.prometheusRule.labels }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
groups:
|
||||
- name: armature.rules
|
||||
- name: switchboard.rules
|
||||
rules:
|
||||
- alert: ArmaturePodRestart
|
||||
- alert: SwitchboardPodRestart
|
||||
expr: increase(kube_pod_container_status_restarts_total{container="backend"}[1h]) > 0
|
||||
for: 0m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Armature backend pod restarted (possible OOM)"
|
||||
- alert: ArmatureProviderDown
|
||||
expr: armature_provider_status > 2
|
||||
summary: "Switchboard backend pod restarted (possible OOM)"
|
||||
- alert: SwitchboardProviderDown
|
||||
expr: switchboard_provider_status > 2
|
||||
for: 5m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Provider {{`{{ $labels.provider_config_id }}`}} is down"
|
||||
- alert: ArmatureDBPoolExhaustion
|
||||
expr: armature_db_in_use_connections / armature_db_open_connections > 0.8
|
||||
- alert: SwitchboardDBPoolExhaustion
|
||||
expr: switchboard_db_in_use_connections / switchboard_db_open_connections > 0.8
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "DB connection pool >80% utilized"
|
||||
- alert: ArmatureHighErrorRate
|
||||
- alert: SwitchboardHighErrorRate
|
||||
expr: |
|
||||
sum(rate(armature_http_requests_total{status=~"5.."}[5m]))
|
||||
/ sum(rate(armature_http_requests_total[5m])) > 0.05
|
||||
sum(rate(switchboard_http_requests_total{status=~"5.."}[5m]))
|
||||
/ sum(rate(switchboard_http_requests_total[5m])) > 0.05
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "HTTP 5xx error rate exceeds 5%"
|
||||
- alert: ArmatureTaskFailureRate
|
||||
- alert: SwitchboardTaskFailureRate
|
||||
expr: |
|
||||
rate(armature_task_executions_total{status="error"}[15m])
|
||||
/ rate(armature_task_executions_total[15m]) > 0.25
|
||||
rate(switchboard_task_executions_total{status="error"}[15m])
|
||||
/ rate(switchboard_task_executions_total[15m]) > 0.25
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Task failure rate exceeds 25%"
|
||||
- alert: ArmatureNoCompletions
|
||||
expr: sum(rate(armature_completions_total[10m])) == 0
|
||||
- alert: SwitchboardNoCompletions
|
||||
expr: sum(rate(switchboard_completions_total[10m])) == 0
|
||||
for: 15m
|
||||
labels:
|
||||
severity: critical
|
||||
|
||||
@@ -4,7 +4,7 @@ kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-backup
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: backup
|
||||
spec:
|
||||
accessModes:
|
||||
|
||||
@@ -4,7 +4,7 @@ kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-data
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
spec:
|
||||
accessModes:
|
||||
- {{ .Values.persistence.accessMode }}
|
||||
|
||||
@@ -4,7 +4,7 @@ kind: Secret
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-secrets
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
type: Opaque
|
||||
stringData:
|
||||
JWT_SECRET: {{ required "jwtSecret is required" .Values.jwtSecret | quote }}
|
||||
@@ -15,11 +15,11 @@ stringData:
|
||||
POSTGRES_PASSWORD: {{ .Values.database.postgres.password | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.admin.password }}
|
||||
ARMATURE_ADMIN_USERNAME: {{ .Values.admin.username | quote }}
|
||||
ARMATURE_ADMIN_PASSWORD: {{ .Values.admin.password | quote }}
|
||||
SWITCHBOARD_ADMIN_USERNAME: {{ .Values.admin.username | quote }}
|
||||
SWITCHBOARD_ADMIN_PASSWORD: {{ .Values.admin.password | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.admin.email }}
|
||||
ARMATURE_ADMIN_EMAIL: {{ .Values.admin.email | quote }}
|
||||
SWITCHBOARD_ADMIN_EMAIL: {{ .Values.admin.email | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.s3.accessKey }}
|
||||
S3_ACCESS_KEY: {{ .Values.storage.s3.accessKey | quote }}
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: ServiceMonitor
|
||||
metadata:
|
||||
name: {{ include "armature.fullname" . }}
|
||||
name: {{ include "switchboard.fullname" . }}
|
||||
labels:
|
||||
{{- include "armature.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.labels" . | nindent 4 }}
|
||||
{{- with .Values.monitoring.serviceMonitor.labels }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "armature.selectorLabels" . | nindent 6 }}
|
||||
{{- include "switchboard.selectorLabels" . | nindent 6 }}
|
||||
app.kubernetes.io/component: backend
|
||||
endpoints:
|
||||
- port: http
|
||||
|
||||
@@ -3,7 +3,7 @@ kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-backend
|
||||
labels:
|
||||
{{- include "armature.backend.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.backend.labels" . | nindent 4 }}
|
||||
annotations:
|
||||
prometheus.io/scrape: "true"
|
||||
prometheus.io/port: {{ .Values.backend.port | quote }}
|
||||
@@ -25,7 +25,7 @@ kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-frontend
|
||||
labels:
|
||||
{{- include "armature.frontend.labels" . | nindent 4 }}
|
||||
{{- include "switchboard.frontend.labels" . | nindent 4 }}
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Armature — Helm values
|
||||
# helm install armature ./chart
|
||||
# Switchboard Core — Helm values
|
||||
# helm install switchboard ./chart
|
||||
|
||||
# ── Images ─────────────────────────────────
|
||||
backend:
|
||||
image:
|
||||
repository: git.gobha.me/armature/core
|
||||
repository: git.gobha.me/switchboard/core
|
||||
tag: "" # defaults to Chart.appVersion
|
||||
pullPolicy: IfNotPresent
|
||||
replicaCount: 2 # v0.32.0: multi-replica HA
|
||||
@@ -19,7 +19,7 @@ backend:
|
||||
|
||||
frontend:
|
||||
image:
|
||||
repository: git.gobha.me/armature/core
|
||||
repository: git.gobha.me/switchboard/core
|
||||
tag: "" # defaults to Chart.appVersion
|
||||
pullPolicy: IfNotPresent
|
||||
replicaCount: 1
|
||||
@@ -41,12 +41,12 @@ database:
|
||||
postgres:
|
||||
host: postgresql
|
||||
port: 5432
|
||||
user: armature
|
||||
user: switchboard
|
||||
password: "" # set via secret
|
||||
database: armature
|
||||
database: switchboard
|
||||
sslmode: disable
|
||||
# For sqlite: path inside the container (requires persistence)
|
||||
sqlitePath: /data/armature.db
|
||||
sqlitePath: /data/switchboard.db
|
||||
|
||||
# ── Core ───────────────────────────────────
|
||||
basePath: "" # URL prefix, e.g. "/dev"
|
||||
@@ -85,7 +85,7 @@ ingress:
|
||||
enabled: true
|
||||
className: traefik
|
||||
annotations: {}
|
||||
host: armature.local
|
||||
host: switchboard.local
|
||||
tls:
|
||||
enabled: false
|
||||
secretName: ""
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# e2e-backup-test.sh — Backup/restore E2E test (v0.6.1)
|
||||
#
|
||||
# Requires: docker compose running with a single instance.
|
||||
# Usage:
|
||||
# docker compose up --build -d
|
||||
# ./ci/e2e-backup-test.sh
|
||||
# docker compose down -v
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
BASE="http://localhost:8080"
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
pass() { PASS=$((PASS + 1)); echo " PASS: $1"; }
|
||||
fail() { FAIL=$((FAIL + 1)); echo " FAIL: $1"; }
|
||||
|
||||
# ── Wait for service ─────────────────────────
|
||||
echo "=== Waiting for service ==="
|
||||
for i in $(seq 1 30); do
|
||||
if curl -sf "$BASE/health" > /dev/null 2>&1; then
|
||||
echo " service ready"
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
if [ "$i" -eq 30 ]; then
|
||||
echo "FATAL: service did not become healthy"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# ── Login as admin ───────────────────────────
|
||||
echo "=== Authenticating ==="
|
||||
TOKEN=$(curl -sf "$BASE/api/v1/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"login":"admin","password":"admin"}' | jq -r '.access_token')
|
||||
|
||||
if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
|
||||
echo "FATAL: login failed"
|
||||
exit 1
|
||||
fi
|
||||
echo " admin token acquired"
|
||||
|
||||
auth() { echo "Authorization: Bearer $TOKEN"; }
|
||||
|
||||
# ── Seed test data ───────────────────────────
|
||||
echo "=== Seeding test data ==="
|
||||
|
||||
# Create a test user
|
||||
curl -sf "$BASE/api/v1/auth/register" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"backup-test-user","email":"bktest@test.com","password":"testpass123"}' > /dev/null
|
||||
|
||||
USER_COUNT=$(curl -sf "$BASE/api/v1/admin/users" -H "$(auth)" | jq '.data | length')
|
||||
echo " users: $USER_COUNT"
|
||||
|
||||
# ── Test 1: List backups (empty) ─────────────
|
||||
echo "=== Test 1: List backups (empty) ==="
|
||||
LIST=$(curl -sf "$BASE/api/v1/admin/backups" -H "$(auth)")
|
||||
COUNT=$(echo "$LIST" | jq '.data | length')
|
||||
if [ "$COUNT" -eq 0 ]; then
|
||||
pass "empty backup list"
|
||||
else
|
||||
fail "expected 0 backups, got $COUNT"
|
||||
fi
|
||||
|
||||
# ── Test 2: Create server-side backup ────────
|
||||
echo "=== Test 2: Create server-side backup ==="
|
||||
RESULT=$(curl -sf "$BASE/api/v1/admin/backup?store=true" \
|
||||
-X POST \
|
||||
-H "$(auth)")
|
||||
FILENAME=$(echo "$RESULT" | jq -r '.data.filename')
|
||||
if [ -n "$FILENAME" ] && [ "$FILENAME" != "null" ]; then
|
||||
pass "created backup: $FILENAME"
|
||||
else
|
||||
fail "backup creation failed: $RESULT"
|
||||
fi
|
||||
|
||||
# ── Test 3: List backups (has one) ───────────
|
||||
echo "=== Test 3: List backups (has one) ==="
|
||||
LIST=$(curl -sf "$BASE/api/v1/admin/backups" -H "$(auth)")
|
||||
COUNT=$(echo "$LIST" | jq '.data | length')
|
||||
if [ "$COUNT" -eq 1 ]; then
|
||||
pass "one backup listed"
|
||||
else
|
||||
fail "expected 1 backup, got $COUNT"
|
||||
fi
|
||||
|
||||
# ── Test 4: Download backup ──────────────────
|
||||
echo "=== Test 4: Download backup ==="
|
||||
TMPFILE=$(mktemp /tmp/backup-test-XXXXXX.swb)
|
||||
HTTP_CODE=$(curl -sf -o "$TMPFILE" -w "%{http_code}" \
|
||||
"$BASE/api/v1/admin/backups/$FILENAME" -H "$(auth)")
|
||||
if [ "$HTTP_CODE" = "200" ] && [ -s "$TMPFILE" ]; then
|
||||
pass "download OK ($(wc -c < "$TMPFILE") bytes)"
|
||||
else
|
||||
fail "download failed (HTTP $HTTP_CODE)"
|
||||
fi
|
||||
|
||||
# ── Test 5: Streaming backup (direct download) ──
|
||||
echo "=== Test 5: Streaming backup ==="
|
||||
STREAM_FILE=$(mktemp /tmp/backup-stream-XXXXXX.swb)
|
||||
HTTP_CODE=$(curl -sf -o "$STREAM_FILE" -w "%{http_code}" \
|
||||
-X POST "$BASE/api/v1/admin/backup" -H "$(auth)")
|
||||
if [ "$HTTP_CODE" = "200" ] && [ -s "$STREAM_FILE" ]; then
|
||||
pass "streaming download OK ($(wc -c < "$STREAM_FILE") bytes)"
|
||||
else
|
||||
fail "streaming download failed (HTTP $HTTP_CODE)"
|
||||
fi
|
||||
|
||||
# ── Test 6: Delete backup ────────────────────
|
||||
echo "=== Test 6: Delete backup ==="
|
||||
DEL=$(curl -sf -X DELETE "$BASE/api/v1/admin/backups/$FILENAME" -H "$(auth)")
|
||||
DELETED=$(echo "$DEL" | jq -r '.data.deleted')
|
||||
if [ "$DELETED" = "$FILENAME" ]; then
|
||||
pass "deleted backup"
|
||||
else
|
||||
fail "delete failed: $DEL"
|
||||
fi
|
||||
|
||||
# Verify deletion
|
||||
LIST=$(curl -sf "$BASE/api/v1/admin/backups" -H "$(auth)")
|
||||
COUNT=$(echo "$LIST" | jq '.data | length')
|
||||
if [ "$COUNT" -eq 0 ]; then
|
||||
pass "backup list empty after delete"
|
||||
else
|
||||
fail "expected 0 backups after delete, got $COUNT"
|
||||
fi
|
||||
|
||||
# ── Cleanup ──────────────────────────────────
|
||||
rm -f "$TMPFILE" "$STREAM_FILE"
|
||||
|
||||
# ── Summary ──────────────────────────────────
|
||||
echo ""
|
||||
echo "=== Results: $PASS passed, $FAIL failed ==="
|
||||
if [ "$FAIL" -gt 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,247 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# ═══════════════════════════════════════════════
|
||||
# E2E Chat Test — Multi-user / Multi-replica
|
||||
# ═══════════════════════════════════════════════
|
||||
#
|
||||
# Prerequisites:
|
||||
# docker compose -f docker-compose-e2e.yml up --build -d
|
||||
#
|
||||
# Tests:
|
||||
# 1. Auth as alice + bob
|
||||
# 2. Alice creates conversation, adds bob
|
||||
# 3. Alice sends message via REST
|
||||
# 4. Bob reads messages, verifies receipt
|
||||
# 5. Cross-replica: send via replica-1, read via replica-2
|
||||
# 6. WebSocket realtime delivery (via ws-listener)
|
||||
#
|
||||
# Exit codes: 0 = pass, 1 = failure
|
||||
set -euo pipefail
|
||||
|
||||
LB="http://localhost:3000"
|
||||
R1="http://localhost:8081"
|
||||
R2="http://localhost:8082"
|
||||
MAX_RETRIES=30
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m'
|
||||
|
||||
pass=0
|
||||
fail=0
|
||||
|
||||
ok() { pass=$((pass + 1)); echo -e " ${GREEN}✓${NC} $1"; }
|
||||
fail() { fail=$((fail + 1)); echo -e " ${RED}✗${NC} $1"; }
|
||||
|
||||
# ── Wait for LB ─────────────────────────────
|
||||
|
||||
echo -e "${YELLOW}Waiting for load balancer...${NC}"
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
if curl -sf "$LB/api/v1/auth/login" -o /dev/null 2>/dev/null || \
|
||||
curl -sf "$LB" -o /dev/null 2>/dev/null; then
|
||||
echo -e "${GREEN}LB ready after ${i}s${NC}"
|
||||
break
|
||||
fi
|
||||
if [ "$i" -eq "$MAX_RETRIES" ]; then
|
||||
echo -e "${RED}LB not ready after ${MAX_RETRIES}s${NC}"
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# ── Helper: login ────────────────────────────
|
||||
|
||||
login() {
|
||||
local user=$1 pass=$2 host=${3:-$LB}
|
||||
local resp
|
||||
resp=$(curl -sf "$host/api/v1/auth/login" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"login\":\"$user\",\"password\":\"$pass\"}")
|
||||
echo "$resp" | grep -o '"access_token":"[^"]*"' | head -1 | sed 's/.*"access_token":"\([^"]*\)".*/\1/'
|
||||
}
|
||||
|
||||
authed() {
|
||||
# Usage: authed $TOKEN GET /api/v1/... [host]
|
||||
local token=$1 method=$2 path=$3 host=${4:-$LB}
|
||||
shift 3; shift 0 2>/dev/null || true
|
||||
curl -sf -X "$method" "$host$path" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H 'Content-Type: application/json' \
|
||||
"$@"
|
||||
}
|
||||
|
||||
# ── 1. Auth ──────────────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}1. Authentication${NC}"
|
||||
|
||||
ALICE_TOKEN=$(login alice password123)
|
||||
if [ -n "$ALICE_TOKEN" ]; then ok "alice logged in"; else fail "alice login failed"; exit 1; fi
|
||||
|
||||
BOB_TOKEN=$(login bob password456)
|
||||
if [ -n "$BOB_TOKEN" ]; then ok "bob logged in"; else fail "bob login failed"; exit 1; fi
|
||||
|
||||
ADMIN_TOKEN=$(login admin admin)
|
||||
if [ -n "$ADMIN_TOKEN" ]; then ok "admin logged in"; else fail "admin login failed"; exit 1; fi
|
||||
|
||||
# ── 2. Install chat packages ────────────────
|
||||
|
||||
echo -e "\n${YELLOW}2. Install chat-core + chat packages${NC}"
|
||||
|
||||
# Check if chat-core is installed; if not, install via bundled packages or API
|
||||
# (Packages may already be installed from bundled set)
|
||||
PKGS=$(authed "$ADMIN_TOKEN" GET "/api/v1/packages" 2>/dev/null || echo "[]")
|
||||
if echo "$PKGS" | grep -q '"chat-core"'; then
|
||||
ok "chat-core already installed"
|
||||
else
|
||||
echo " (chat-core not installed — bundled packages may need BUNDLED_PACKAGES config)"
|
||||
ok "chat-core check done (may need manual install)"
|
||||
fi
|
||||
|
||||
# ── 3. Create conversation ───────────────────
|
||||
|
||||
echo -e "\n${YELLOW}3. Create conversation + send messages${NC}"
|
||||
|
||||
# Get alice's user ID
|
||||
ALICE_ME=$(authed "$ALICE_TOKEN" GET "/api/v1/profile" 2>/dev/null || echo "{}")
|
||||
ALICE_ID=$(echo "$ALICE_ME" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
BOB_ME=$(authed "$BOB_TOKEN" GET "/api/v1/profile" 2>/dev/null || echo "{}")
|
||||
BOB_ID=$(echo "$BOB_ME" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
# Create conversation via chat-core API
|
||||
CONV=$(authed "$ALICE_TOKEN" POST "/s/chat-core/api/conversations" "" \
|
||||
-d "{\"title\":\"E2E Test Chat\",\"type\":\"group\",\"participants\":[{\"id\":\"$BOB_ID\",\"display_name\":\"bob\"}],\"creator_display_name\":\"alice\"}" 2>/dev/null || echo "{}")
|
||||
CONV_ID=$(echo "$CONV" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
ok "conversation created: ${CONV_ID:0:8}..."
|
||||
else
|
||||
fail "conversation creation failed"
|
||||
echo " Response: $CONV"
|
||||
fi
|
||||
|
||||
# ── 4. Send + read messages ──────────────────
|
||||
|
||||
echo -e "\n${YELLOW}4. Message send + read${NC}"
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
# Alice sends a message
|
||||
MSG1=$(authed "$ALICE_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "" \
|
||||
-d '{"content":"Hello from alice!","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
MSG1_ID=$(echo "$MSG1" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
if [ -n "$MSG1_ID" ]; then ok "alice sent message"; else fail "alice send failed"; fi
|
||||
|
||||
# Bob reads messages
|
||||
MSGS=$(authed "$BOB_TOKEN" GET "/s/chat-core/api/messages/$CONV_ID?limit=50" 2>/dev/null || echo "{}")
|
||||
if echo "$MSGS" | grep -q "Hello from alice"; then
|
||||
ok "bob received alice's message"
|
||||
else
|
||||
fail "bob did not receive message"
|
||||
echo " Response: ${MSGS:0:200}"
|
||||
fi
|
||||
|
||||
# Bob sends a reply
|
||||
MSG2=$(authed "$BOB_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "" \
|
||||
-d '{"content":"Hello from bob!","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
MSG2_ID=$(echo "$MSG2" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
if [ -n "$MSG2_ID" ]; then ok "bob sent reply"; else fail "bob send failed"; fi
|
||||
fi
|
||||
|
||||
# ── 5. Cross-replica consistency ─────────────
|
||||
|
||||
echo -e "\n${YELLOW}5. Cross-replica consistency${NC}"
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
# Login to each replica directly
|
||||
ALICE_R1=$(login alice password123 "$R1")
|
||||
BOB_R2=$(login bob password456 "$R2")
|
||||
|
||||
# Alice sends via replica 1
|
||||
MSG3=$(curl -sf -X POST "$R1/s/chat-core/api/messages/$CONV_ID" \
|
||||
-H "Authorization: Bearer $ALICE_R1" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"content":"Cross-replica test message","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
|
||||
if echo "$MSG3" | grep -q '"id"'; then
|
||||
ok "alice sent via replica-1"
|
||||
else
|
||||
fail "alice send via replica-1 failed"
|
||||
fi
|
||||
|
||||
# Small delay for pg replication
|
||||
sleep 1
|
||||
|
||||
# Bob reads via replica 2
|
||||
MSGS_R2=$(curl -sf "$R2/s/chat-core/api/messages/$CONV_ID?limit=50" \
|
||||
-H "Authorization: Bearer $BOB_R2" 2>/dev/null || echo "{}")
|
||||
|
||||
if echo "$MSGS_R2" | grep -q "Cross-replica test message"; then
|
||||
ok "bob sees cross-replica message via replica-2"
|
||||
else
|
||||
fail "cross-replica message not visible"
|
||||
echo " Response: ${MSGS_R2:0:200}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# ── 6. Search ────────────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}6. Conversation search${NC}"
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
SEARCH=$(authed "$ALICE_TOKEN" GET "/s/chat-core/api/search?q=alice" 2>/dev/null || echo "{}")
|
||||
|
||||
if echo "$SEARCH" | grep -q "Hello from alice"; then
|
||||
ok "search found message content"
|
||||
else
|
||||
fail "search did not find message"
|
||||
echo " Response: ${SEARCH:0:200}"
|
||||
fi
|
||||
|
||||
SEARCH_CONV=$(authed "$ALICE_TOKEN" GET "/s/chat-core/api/search?q=E2E%20Test" 2>/dev/null || echo "{}")
|
||||
if echo "$SEARCH_CONV" | grep -q "E2E Test Chat"; then
|
||||
ok "search found conversation by title"
|
||||
else
|
||||
fail "search did not find conversation by title"
|
||||
fi
|
||||
fi
|
||||
|
||||
# ── 7. Message pagination ────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}7. Message pagination${NC}"
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
# Send several more messages to test pagination
|
||||
for i in $(seq 1 5); do
|
||||
authed "$ALICE_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "" \
|
||||
-d "{\"content\":\"Pagination test message $i\",\"content_type\":\"text\"}" >/dev/null 2>&1
|
||||
done
|
||||
|
||||
# Fetch with limit=3
|
||||
PAGE1=$(authed "$ALICE_TOKEN" GET "/s/chat-core/api/messages/$CONV_ID?limit=3" 2>/dev/null || echo "{}")
|
||||
HAS_MORE=$(echo "$PAGE1" | grep -o '"has_more":true' || echo "")
|
||||
CURSOR=$(echo "$PAGE1" | grep -o '"next_cursor":"[^"]*"' | cut -d'"' -f4 || echo "")
|
||||
|
||||
if [ -n "$HAS_MORE" ] && [ -n "$CURSOR" ]; then
|
||||
ok "pagination: first page has_more=true with cursor"
|
||||
|
||||
# Fetch second page
|
||||
PAGE2=$(authed "$ALICE_TOKEN" GET "/s/chat-core/api/messages/$CONV_ID?limit=3&cursor=$CURSOR" 2>/dev/null || echo "{}")
|
||||
if echo "$PAGE2" | grep -q '"messages"'; then
|
||||
ok "pagination: second page returned messages"
|
||||
else
|
||||
fail "pagination: second page failed"
|
||||
fi
|
||||
else
|
||||
fail "pagination: expected has_more and cursor"
|
||||
fi
|
||||
fi
|
||||
|
||||
# ── Summary ──────────────────────────────────
|
||||
|
||||
echo -e "\n════════════════════════════════════════"
|
||||
echo -e "Results: ${GREEN}$pass passed${NC}, ${RED}$fail failed${NC}"
|
||||
echo "════════════════════════════════════════"
|
||||
|
||||
[ "$fail" -eq 0 ] && exit 0 || exit 1
|
||||
@@ -1,145 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# e2e-cluster-test.sh — Cluster registry E2E test (v0.6.0)
|
||||
#
|
||||
# Requires: docker-compose-e2e.yml running with 3 replicas.
|
||||
# Usage:
|
||||
# docker compose -f docker-compose-e2e.yml up --build -d
|
||||
# ./ci/e2e-cluster-test.sh
|
||||
# docker compose -f docker-compose-e2e.yml down -v
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
LB="http://localhost:3000"
|
||||
DIRECT_1="http://localhost:8081"
|
||||
STALE_WAIT=20 # seconds — must exceed CLUSTER_STALE_THRESHOLD (15s)
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
pass() { PASS=$((PASS + 1)); echo " PASS: $1"; }
|
||||
fail() { FAIL=$((FAIL + 1)); echo " FAIL: $1"; }
|
||||
|
||||
# ── Wait for all 3 replicas ──────────────────
|
||||
echo "=== Waiting for replicas ==="
|
||||
for port in 8081 8082 8083; do
|
||||
for i in $(seq 1 30); do
|
||||
if curl -sf "http://localhost:$port/health" > /dev/null 2>&1; then
|
||||
echo " replica :$port ready"
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
if [ "$i" -eq 30 ]; then
|
||||
echo "FATAL: replica :$port did not become healthy"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
# ── Login as admin ────────────────────────────
|
||||
echo "=== Authenticating ==="
|
||||
TOKEN=$(curl -sf "$LB/api/v1/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"login":"admin","password":"admin"}' | jq -r '.access_token')
|
||||
|
||||
if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
|
||||
echo "FATAL: login failed"
|
||||
exit 1
|
||||
fi
|
||||
echo " admin token acquired"
|
||||
|
||||
auth() { echo "Authorization: Bearer $TOKEN"; }
|
||||
|
||||
# Wait for heartbeat to propagate (at least 2 tick cycles at 5s each)
|
||||
echo "=== Waiting for heartbeat convergence ==="
|
||||
sleep 12
|
||||
|
||||
# ── Test 1: All 3 nodes registered ───────────
|
||||
echo "=== Test 1: Cluster shows 3 nodes ==="
|
||||
NODES=$(curl -sf "$LB/api/v1/admin/cluster" -H "$(auth)")
|
||||
COUNT=$(echo "$NODES" | jq '.data | length')
|
||||
if [ "$COUNT" -eq 3 ]; then
|
||||
pass "cluster has 3 nodes"
|
||||
else
|
||||
fail "cluster has $COUNT nodes (expected 3)"
|
||||
echo " response: $NODES"
|
||||
fi
|
||||
|
||||
# Verify all expected node IDs present
|
||||
for nid in node-1 node-2 node-3; do
|
||||
if echo "$NODES" | jq -e ".data[] | select(.node_id == \"$nid\")" > /dev/null 2>&1; then
|
||||
pass "$nid present"
|
||||
else
|
||||
fail "$nid missing from cluster"
|
||||
fi
|
||||
done
|
||||
|
||||
# ── Test 2: Health endpoint includes cluster ──
|
||||
echo "=== Test 2: Health includes cluster info ==="
|
||||
HEALTH=$(curl -sf "$DIRECT_1/health")
|
||||
CLUSTER_SIZE=$(echo "$HEALTH" | jq '.cluster.size // 0')
|
||||
if [ "$CLUSTER_SIZE" -eq 3 ]; then
|
||||
pass "health shows cluster.size=3"
|
||||
else
|
||||
fail "health shows cluster.size=$CLUSTER_SIZE (expected 3)"
|
||||
fi
|
||||
|
||||
NODE_ID=$(echo "$HEALTH" | jq -r '.node_id // ""')
|
||||
if [ -n "$NODE_ID" ]; then
|
||||
pass "health includes node_id=$NODE_ID"
|
||||
else
|
||||
fail "health missing node_id"
|
||||
fi
|
||||
|
||||
# ── Test 3: Stats contain expected keys ───────
|
||||
echo "=== Test 3: Node stats ==="
|
||||
STATS=$(echo "$NODES" | jq '.data[0].stats')
|
||||
for key in goroutines heap_alloc uptime_sec ws_clients; do
|
||||
if echo "$STATS" | jq -e ".$key" > /dev/null 2>&1; then
|
||||
pass "stats.$key present"
|
||||
else
|
||||
fail "stats.$key missing"
|
||||
fi
|
||||
done
|
||||
|
||||
# ── Test 4: Stop one replica → stale sweep ────
|
||||
echo "=== Test 4: Stop node-3, wait for sweep ==="
|
||||
docker compose -f docker-compose-e2e.yml stop armature-3
|
||||
|
||||
echo " waiting ${STALE_WAIT}s for stale sweep..."
|
||||
sleep "$STALE_WAIT"
|
||||
|
||||
NODES_AFTER=$(curl -sf "$LB/api/v1/admin/cluster" -H "$(auth)")
|
||||
COUNT_AFTER=$(echo "$NODES_AFTER" | jq '.data | length')
|
||||
if [ "$COUNT_AFTER" -eq 2 ]; then
|
||||
pass "cluster swept to 2 nodes after stopping node-3"
|
||||
else
|
||||
fail "cluster has $COUNT_AFTER nodes after stop (expected 2)"
|
||||
fi
|
||||
|
||||
# ── Test 5: Restart replica → re-registers ────
|
||||
echo "=== Test 5: Restart node-3 ==="
|
||||
docker compose -f docker-compose-e2e.yml start armature-3
|
||||
|
||||
# Wait for startup + at least one heartbeat
|
||||
for i in $(seq 1 30); do
|
||||
if curl -sf "http://localhost:8083/health" > /dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
sleep 8 # allow heartbeat to register
|
||||
|
||||
NODES_RESTART=$(curl -sf "$LB/api/v1/admin/cluster" -H "$(auth)")
|
||||
COUNT_RESTART=$(echo "$NODES_RESTART" | jq '.data | length')
|
||||
if [ "$COUNT_RESTART" -eq 3 ]; then
|
||||
pass "cluster back to 3 nodes after restart"
|
||||
else
|
||||
fail "cluster has $COUNT_RESTART nodes after restart (expected 3)"
|
||||
fi
|
||||
|
||||
# ── Summary ───────────────────────────────────
|
||||
echo ""
|
||||
echo "=== Results: $PASS passed, $FAIL failed ==="
|
||||
if [ "$FAIL" -gt 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,40 +0,0 @@
|
||||
events {
|
||||
worker_connections 128;
|
||||
}
|
||||
|
||||
http {
|
||||
upstream armature {
|
||||
server armature-1:80;
|
||||
server armature-2:80;
|
||||
server armature-3:80;
|
||||
}
|
||||
|
||||
# WebSocket upgrade map
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
location / {
|
||||
proxy_pass http://armature;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# WebSocket endpoint
|
||||
location /ws {
|
||||
proxy_pass http://armature;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_read_timeout 86400s;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# ═══════════════════════════════════════════════
|
||||
# E2E Rolling Upgrade Test — Multi-Replica
|
||||
# ═══════════════════════════════════════════════
|
||||
#
|
||||
# Tests rolling upgrade with two replicas sharing Postgres:
|
||||
# 1. Build old + new images
|
||||
# 2. Start 2 replicas (old) + nginx LB + postgres
|
||||
# 3. Seed data via LB
|
||||
# 4. Upgrade replica-1 → new, verify cross-replica reads
|
||||
# 5. Upgrade replica-2 → new, verify full cluster
|
||||
#
|
||||
# Uses nginx for load balancing (same as e2e-chat-test).
|
||||
#
|
||||
# Usage:
|
||||
# ./ci/e2e-upgrade-rolling.sh
|
||||
#
|
||||
# Exit codes: 0 = pass, 1 = failure
|
||||
set -euo pipefail
|
||||
|
||||
LB="http://localhost:3000"
|
||||
R1="http://localhost:8081"
|
||||
R2="http://localhost:8082"
|
||||
MAX_RETRIES=45
|
||||
COMPOSE_FILE="docker-compose-e2e.yml"
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m'
|
||||
|
||||
pass=0
|
||||
fail=0
|
||||
|
||||
ok() { pass=$((pass + 1)); echo -e " ${GREEN}✓${NC} $1"; }
|
||||
fail() { fail=$((fail + 1)); echo -e " ${RED}✗${NC} $1"; }
|
||||
|
||||
cleanup() {
|
||||
echo -e "\n${YELLOW}Cleanup...${NC}"
|
||||
docker compose -f "$COMPOSE_FILE" down -v 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
wait_for_health() {
|
||||
local host=$1 name=${2:-$host}
|
||||
echo -e "${YELLOW}Waiting for $name...${NC}"
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
if curl -sf "$host/api/v1/auth/login" -o /dev/null 2>/dev/null || \
|
||||
curl -sf "$host" -o /dev/null 2>/dev/null; then
|
||||
echo -e "${GREEN}$name ready after ${i}s${NC}"
|
||||
return 0
|
||||
fi
|
||||
if [ "$i" -eq "$MAX_RETRIES" ]; then
|
||||
echo -e "${RED}$name not ready after ${MAX_RETRIES}s${NC}"
|
||||
return 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
login() {
|
||||
local user=$1 pass=$2 host=${3:-$LB}
|
||||
local resp
|
||||
resp=$(curl -sf "$host/api/v1/auth/login" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"login\":\"$user\",\"password\":\"$pass\"}")
|
||||
echo "$resp" | grep -o '"access_token":"[^"]*"' | head -1 | sed 's/.*"access_token":"\([^"]*\)".*/\1/'
|
||||
}
|
||||
|
||||
authed() {
|
||||
local token=$1 method=$2 path=$3 host=${4:-$LB}
|
||||
shift 3; shift 0 2>/dev/null || true
|
||||
curl -sf -X "$method" "$host$path" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H 'Content-Type: application/json' \
|
||||
"$@"
|
||||
}
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 1: Build Images
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 1: Build Images ═══${NC}"
|
||||
|
||||
echo "Building 'old' image from HEAD..."
|
||||
docker build -t armature:v-old . -q
|
||||
ok "old image built"
|
||||
|
||||
echo "Building 'new' image from working tree..."
|
||||
docker build -t armature:v-new . -q
|
||||
ok "new image built"
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 2: Start Both Replicas on Old Image
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 2: Start Cluster (Old Version) ═══${NC}"
|
||||
|
||||
# Override the build with old image
|
||||
ARMATURE_IMAGE=armature:v-old \
|
||||
docker compose -f "$COMPOSE_FILE" up postgres -d
|
||||
|
||||
# Wait for postgres
|
||||
sleep 3
|
||||
|
||||
# Start replicas using old image
|
||||
docker run -d --name sb-old-1 --network "$(basename "$(pwd)")_default" \
|
||||
-e PORT=8080 -e BASE_PATH="" \
|
||||
-e DB_DRIVER=postgres \
|
||||
-e "DATABASE_URL=postgres://armature:e2e-password@postgres:5432/armature_e2e?sslmode=disable" \
|
||||
-e JWT_SECRET=e2e-jwt-secret \
|
||||
-e "ENCRYPTION_KEY=e2e-encryption-key-32chars!!!!!" \
|
||||
-e ARMATURE_ADMIN_USERNAME=admin \
|
||||
-e ARMATURE_ADMIN_PASSWORD=admin \
|
||||
-e STORAGE_BACKEND=pvc -e STORAGE_PATH=/data/storage \
|
||||
-e "CORS_ALLOWED_ORIGINS=*" -e EXT_ALLOW_PRIVATE_IPS=true \
|
||||
-e LOG_FORMAT=text -e LOG_LEVEL=info \
|
||||
-e "SEED_USERS=alice:password123:user,bob:password456:user" \
|
||||
-p 8081:80 armature:v-old 2>/dev/null || true
|
||||
|
||||
docker run -d --name sb-old-2 --network "$(basename "$(pwd)")_default" \
|
||||
-e PORT=8080 -e BASE_PATH="" \
|
||||
-e DB_DRIVER=postgres \
|
||||
-e "DATABASE_URL=postgres://armature:e2e-password@postgres:5432/armature_e2e?sslmode=disable" \
|
||||
-e JWT_SECRET=e2e-jwt-secret \
|
||||
-e "ENCRYPTION_KEY=e2e-encryption-key-32chars!!!!!" \
|
||||
-e ARMATURE_ADMIN_USERNAME=admin \
|
||||
-e ARMATURE_ADMIN_PASSWORD=admin \
|
||||
-e STORAGE_BACKEND=pvc -e STORAGE_PATH=/data/storage \
|
||||
-e "CORS_ALLOWED_ORIGINS=*" -e EXT_ALLOW_PRIVATE_IPS=true \
|
||||
-e LOG_FORMAT=text -e LOG_LEVEL=info \
|
||||
-e "SEED_USERS=alice:password123:user,bob:password456:user" \
|
||||
-p 8082:80 armature:v-old 2>/dev/null || true
|
||||
|
||||
# Start nginx LB
|
||||
docker compose -f "$COMPOSE_FILE" up lb -d
|
||||
|
||||
wait_for_health "$R1" "replica-1"
|
||||
wait_for_health "$R2" "replica-2"
|
||||
wait_for_health "$LB" "load balancer"
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 3: Seed Data via LB
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 3: Seed Data ═══${NC}"
|
||||
|
||||
ADMIN_TOKEN=$(login admin admin)
|
||||
if [ -z "$ADMIN_TOKEN" ]; then fail "admin login failed"; exit 1; fi
|
||||
ok "admin logged in"
|
||||
|
||||
ALICE_TOKEN=$(login alice password123)
|
||||
if [ -z "$ALICE_TOKEN" ]; then fail "alice login failed"; exit 1; fi
|
||||
|
||||
BOB_TOKEN=$(login bob password456)
|
||||
if [ -z "$BOB_TOKEN" ]; then fail "bob login failed"; exit 1; fi
|
||||
|
||||
ALICE_ID=$(authed "$ALICE_TOKEN" GET "/api/v1/profile" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
BOB_ID=$(authed "$BOB_TOKEN" GET "/api/v1/profile" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
# Seed a note
|
||||
NOTE=$(authed "$ALICE_TOKEN" POST "/s/notes/api/notes" "" \
|
||||
-d '{"title":"Rolling Upgrade Note","body":"Must survive rolling upgrade."}' 2>/dev/null || echo "{}")
|
||||
NOTE_ID=$(echo "$NOTE" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$NOTE_ID" ]; then ok "note seeded"; else fail "note seed failed"; fi
|
||||
|
||||
# Seed a conversation + message
|
||||
CONV=$(authed "$ALICE_TOKEN" POST "/s/chat-core/api/conversations" "" \
|
||||
-d "{\"title\":\"Rolling Test\",\"type\":\"group\",\"participants\":[{\"id\":\"$BOB_ID\",\"display_name\":\"bob\"}],\"creator_display_name\":\"alice\"}" 2>/dev/null || echo "{}")
|
||||
CONV_ID=$(echo "$CONV" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$CONV_ID" ]; then ok "conversation seeded"; else fail "conversation seed failed"; fi
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
authed "$ALICE_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "" \
|
||||
-d '{"content":"Before rolling upgrade","content_type":"text"}' >/dev/null 2>&1
|
||||
ok "message seeded"
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 4: Upgrade Replica-1, Verify Cross-Replica
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 4: Rolling Upgrade — Replica 1 ═══${NC}"
|
||||
|
||||
echo "Stopping old replica-1..."
|
||||
docker stop sb-old-1 && docker rm sb-old-1 2>/dev/null || true
|
||||
|
||||
echo "Starting new replica-1..."
|
||||
docker run -d --name sb-new-1 --network "$(basename "$(pwd)")_default" \
|
||||
-e PORT=8080 -e BASE_PATH="" \
|
||||
-e DB_DRIVER=postgres \
|
||||
-e "DATABASE_URL=postgres://armature:e2e-password@postgres:5432/armature_e2e?sslmode=disable" \
|
||||
-e JWT_SECRET=e2e-jwt-secret \
|
||||
-e "ENCRYPTION_KEY=e2e-encryption-key-32chars!!!!!" \
|
||||
-e ARMATURE_ADMIN_USERNAME=admin \
|
||||
-e ARMATURE_ADMIN_PASSWORD=admin \
|
||||
-e STORAGE_BACKEND=pvc -e STORAGE_PATH=/data/storage \
|
||||
-e "CORS_ALLOWED_ORIGINS=*" -e EXT_ALLOW_PRIVATE_IPS=true \
|
||||
-e LOG_FORMAT=text -e LOG_LEVEL=info \
|
||||
-e "SEED_USERS=alice:password123:user,bob:password456:user" \
|
||||
-p 8081:80 armature:v-new
|
||||
|
||||
wait_for_health "$R1" "new replica-1"
|
||||
|
||||
# Cross-replica reads: new replica reads old data
|
||||
R1_TOKEN=$(login alice password123 "$R1")
|
||||
if [ -n "$R1_TOKEN" ]; then ok "alice login on new replica-1"; else fail "alice login on new replica-1"; fi
|
||||
|
||||
if [ -n "$NOTE_ID" ] && [ -n "$R1_TOKEN" ]; then
|
||||
R1_NOTE=$(authed "$R1_TOKEN" GET "/s/notes/api/notes/$NOTE_ID" "$R1" 2>/dev/null || echo "{}")
|
||||
if echo "$R1_NOTE" | grep -q "Rolling Upgrade Note"; then
|
||||
ok "new replica-1 reads old data"
|
||||
else
|
||||
fail "new replica-1 cannot read old data"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Write on new replica, read on old
|
||||
if [ -n "$CONV_ID" ] && [ -n "$R1_TOKEN" ]; then
|
||||
NEW_MSG=$(authed "$R1_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "$R1" \
|
||||
-d '{"content":"From new replica-1","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
if echo "$NEW_MSG" | grep -q '"id"'; then ok "write on new replica-1"; else fail "write on new replica-1"; fi
|
||||
|
||||
# Read from old replica-2
|
||||
R2_TOKEN=$(login alice password123 "$R2")
|
||||
if [ -n "$R2_TOKEN" ]; then
|
||||
R2_MSGS=$(authed "$R2_TOKEN" GET "/s/chat-core/api/messages/$CONV_ID?limit=50" "$R2" 2>/dev/null || echo "[]")
|
||||
if echo "$R2_MSGS" | grep -q "From new replica-1"; then
|
||||
ok "old replica-2 reads new replica-1 writes"
|
||||
else
|
||||
fail "old replica-2 cannot read new replica-1 writes"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 5: Upgrade Replica-2, Verify Full Cluster
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 5: Rolling Upgrade — Replica 2 ═══${NC}"
|
||||
|
||||
echo "Stopping old replica-2..."
|
||||
docker stop sb-old-2 && docker rm sb-old-2 2>/dev/null || true
|
||||
|
||||
echo "Starting new replica-2..."
|
||||
docker run -d --name sb-new-2 --network "$(basename "$(pwd)")_default" \
|
||||
-e PORT=8080 -e BASE_PATH="" \
|
||||
-e DB_DRIVER=postgres \
|
||||
-e "DATABASE_URL=postgres://armature:e2e-password@postgres:5432/armature_e2e?sslmode=disable" \
|
||||
-e JWT_SECRET=e2e-jwt-secret \
|
||||
-e "ENCRYPTION_KEY=e2e-encryption-key-32chars!!!!!" \
|
||||
-e ARMATURE_ADMIN_USERNAME=admin \
|
||||
-e ARMATURE_ADMIN_PASSWORD=admin \
|
||||
-e STORAGE_BACKEND=pvc -e STORAGE_PATH=/data/storage \
|
||||
-e "CORS_ALLOWED_ORIGINS=*" -e EXT_ALLOW_PRIVATE_IPS=true \
|
||||
-e LOG_FORMAT=text -e LOG_LEVEL=info \
|
||||
-e "SEED_USERS=alice:password123:user,bob:password456:user" \
|
||||
-p 8082:80 armature:v-new
|
||||
|
||||
wait_for_health "$R2" "new replica-2"
|
||||
|
||||
# Verify full cluster: all data accessible
|
||||
echo -e "\n${YELLOW}Verifying full cluster on new version...${NC}"
|
||||
|
||||
R2_TOKEN=$(login alice password123 "$R2")
|
||||
if [ -n "$R2_TOKEN" ]; then ok "alice login on new replica-2"; else fail "alice login on new replica-2"; fi
|
||||
|
||||
if [ -n "$NOTE_ID" ] && [ -n "$R2_TOKEN" ]; then
|
||||
R2_NOTE=$(authed "$R2_TOKEN" GET "/s/notes/api/notes/$NOTE_ID" "$R2" 2>/dev/null || echo "{}")
|
||||
if echo "$R2_NOTE" | grep -q "Rolling Upgrade Note"; then
|
||||
ok "new replica-2 reads all data"
|
||||
else
|
||||
fail "new replica-2 cannot read data"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -n "$CONV_ID" ] && [ -n "$R2_TOKEN" ]; then
|
||||
R2_ALL_MSGS=$(authed "$R2_TOKEN" GET "/s/chat-core/api/messages/$CONV_ID?limit=50" "$R2" 2>/dev/null || echo "[]")
|
||||
MSG_COUNT=$(echo "$R2_ALL_MSGS" | grep -o '"id"' | wc -l)
|
||||
if [ "$MSG_COUNT" -ge 2 ]; then
|
||||
ok "all messages accessible on new cluster ($MSG_COUNT msgs)"
|
||||
else
|
||||
fail "messages lost during rolling upgrade (got $MSG_COUNT)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Write on replica-2, read on replica-1 (both new)
|
||||
if [ -n "$CONV_ID" ] && [ -n "$R2_TOKEN" ]; then
|
||||
R2_MSG=$(authed "$R2_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "$R2" \
|
||||
-d '{"content":"From new replica-2","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
if echo "$R2_MSG" | grep -q '"id"'; then ok "write on new replica-2"; else fail "write on new replica-2"; fi
|
||||
|
||||
# Read from replica-1
|
||||
sleep 1
|
||||
R1_TOKEN=$(login alice password123 "$R1")
|
||||
R1_CHECK=$(authed "$R1_TOKEN" GET "/s/chat-core/api/messages/$CONV_ID?limit=50" "$R1" 2>/dev/null || echo "[]")
|
||||
if echo "$R1_CHECK" | grep -q "From new replica-2"; then
|
||||
ok "new replica-1 reads new replica-2 writes (pg_notify works)"
|
||||
else
|
||||
# pg_notify fan-out is async — try REST (which always works since shared DB)
|
||||
ok "cross-replica write visible via REST (shared DB)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check logs for errors
|
||||
echo -e "\n${YELLOW}Checking logs...${NC}"
|
||||
for name in sb-new-1 sb-new-2; do
|
||||
LOGS=$(docker logs "$name" 2>&1 || echo "")
|
||||
if echo "$LOGS" | grep -qi "panic\|fatal"; then
|
||||
fail "$name has panic/fatal in logs"
|
||||
else
|
||||
ok "$name logs clean"
|
||||
fi
|
||||
done
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Summary
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══════════════════════════════════════${NC}"
|
||||
echo -e " ${GREEN}Passed: $pass${NC} ${RED}Failed: $fail${NC}"
|
||||
echo -e "${YELLOW}═══════════════════════════════════════${NC}"
|
||||
|
||||
# Extra cleanup for standalone containers
|
||||
docker stop sb-new-1 sb-new-2 2>/dev/null || true
|
||||
docker rm sb-new-1 sb-new-2 2>/dev/null || true
|
||||
|
||||
if [ "$fail" -gt 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,330 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# ═══════════════════════════════════════════════
|
||||
# E2E Upgrade Test — Data Integrity Across Upgrade
|
||||
# ═══════════════════════════════════════════════
|
||||
#
|
||||
# Tests that a kernel upgrade preserves all seeded data:
|
||||
# 1. Build "old" image from current commit
|
||||
# 2. Start old image, seed data (notes, conversations, settings)
|
||||
# 3. Stop old, start "new" image (built from working tree)
|
||||
# 4. Verify data integrity post-upgrade
|
||||
#
|
||||
# Usage:
|
||||
# ./ci/e2e-upgrade-test.sh
|
||||
#
|
||||
# Exit codes: 0 = pass, 1 = failure
|
||||
set -euo pipefail
|
||||
|
||||
COMPOSE_FILE="docker-compose-upgrade.yml"
|
||||
HOST="http://localhost:3001"
|
||||
MAX_RETRIES=45
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m'
|
||||
|
||||
pass=0
|
||||
fail=0
|
||||
|
||||
ok() { pass=$((pass + 1)); echo -e " ${GREEN}✓${NC} $1"; }
|
||||
fail() { fail=$((fail + 1)); echo -e " ${RED}✗${NC} $1"; }
|
||||
|
||||
cleanup() {
|
||||
echo -e "\n${YELLOW}Cleanup...${NC}"
|
||||
docker compose -f "$COMPOSE_FILE" down -v 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# ── Helpers ────────────────────────────────────
|
||||
|
||||
wait_for_health() {
|
||||
local host=$1
|
||||
echo -e "${YELLOW}Waiting for $host...${NC}"
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
if curl -sf "$host/api/v1/auth/login" -o /dev/null 2>/dev/null || \
|
||||
curl -sf "$host" -o /dev/null 2>/dev/null; then
|
||||
echo -e "${GREEN}Ready after ${i}s${NC}"
|
||||
return 0
|
||||
fi
|
||||
if [ "$i" -eq "$MAX_RETRIES" ]; then
|
||||
echo -e "${RED}Not ready after ${MAX_RETRIES}s${NC}"
|
||||
return 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
login() {
|
||||
local user=$1 pass=$2 host=${3:-$HOST}
|
||||
local resp
|
||||
resp=$(curl -sf "$host/api/v1/auth/login" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"login\":\"$user\",\"password\":\"$pass\"}")
|
||||
echo "$resp" | grep -o '"access_token":"[^"]*"' | head -1 | sed 's/.*"access_token":"\([^"]*\)".*/\1/'
|
||||
}
|
||||
|
||||
authed() {
|
||||
local token=$1 method=$2 path=$3 host=${4:-$HOST}
|
||||
shift 3; shift 0 2>/dev/null || true
|
||||
curl -sf -X "$method" "$host$path" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H 'Content-Type: application/json' \
|
||||
"$@"
|
||||
}
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 1: Build Images
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 1: Build Images ═══${NC}"
|
||||
|
||||
# Build "old" image from last commit (before current changes)
|
||||
echo "Building 'old' image from HEAD commit..."
|
||||
git stash -q 2>/dev/null || true
|
||||
docker build --no-cache -t armature:v-old . -q
|
||||
git stash pop -q 2>/dev/null || true
|
||||
ok "old image built"
|
||||
|
||||
# Build "new" image from working tree (with current changes)
|
||||
echo "Building 'new' image from working tree..."
|
||||
docker build --no-cache -t armature:v-new . -q
|
||||
ok "new image built"
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 2: Start Old, Seed Data
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 2: Seed Data on Old Version ═══${NC}"
|
||||
|
||||
docker compose -f "$COMPOSE_FILE" up postgres armature-old -d
|
||||
wait_for_health "$HOST"
|
||||
|
||||
# Auth
|
||||
ADMIN_TOKEN=$(login admin admin)
|
||||
if [ -z "$ADMIN_TOKEN" ]; then fail "admin login failed"; exit 1; fi
|
||||
ok "admin logged in"
|
||||
|
||||
ALICE_TOKEN=$(login alice password123)
|
||||
if [ -z "$ALICE_TOKEN" ]; then fail "alice login failed"; exit 1; fi
|
||||
ok "alice logged in"
|
||||
|
||||
BOB_TOKEN=$(login bob password456)
|
||||
if [ -z "$BOB_TOKEN" ]; then fail "bob login failed"; exit 1; fi
|
||||
ok "bob logged in"
|
||||
|
||||
# Get user IDs
|
||||
ALICE_ID=$(authed "$ALICE_TOKEN" GET "/api/v1/profile" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
BOB_ID=$(authed "$BOB_TOKEN" GET "/api/v1/profile" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
# Grant all permissions for extension packages (workaround for v0.5.4 PG grant bug)
|
||||
echo -e "\n${YELLOW}Granting extension permissions...${NC}"
|
||||
for pkg in notes chat-core workflow-chat workflow-demo; do
|
||||
authed "$ADMIN_TOKEN" POST "/api/v1/admin/extensions/$pkg/permissions/grant-all" "" 2>/dev/null || true
|
||||
done
|
||||
ok "permissions granted"
|
||||
|
||||
# ── Seed notes ────────────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}Seeding notes...${NC}"
|
||||
|
||||
NOTE1=$(authed "$ALICE_TOKEN" POST "/s/notes/api/notes" "" \
|
||||
-d '{"title":"Upgrade Test Note","body":"This note must survive the upgrade."}' 2>/dev/null || echo "{}")
|
||||
NOTE1_ID=$(echo "$NOTE1" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$NOTE1_ID" ]; then ok "note created: ${NOTE1_ID:0:8}..."; else fail "note creation failed"; fi
|
||||
|
||||
NOTE2=$(authed "$ALICE_TOKEN" POST "/s/notes/api/notes" "" \
|
||||
-d '{"title":"Second Note","body":"Content of second note."}' 2>/dev/null || echo "{}")
|
||||
NOTE2_ID=$(echo "$NOTE2" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$NOTE2_ID" ]; then ok "second note created"; else fail "second note creation failed"; fi
|
||||
|
||||
# ── Seed conversations ────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}Seeding conversations...${NC}"
|
||||
|
||||
CONV=$(authed "$ALICE_TOKEN" POST "/s/chat-core/api/conversations" "" \
|
||||
-d "{\"title\":\"Upgrade Test Chat\",\"type\":\"group\",\"participants\":[{\"id\":\"$BOB_ID\",\"display_name\":\"bob\"}],\"creator_display_name\":\"alice\"}" 2>/dev/null || echo "{}")
|
||||
CONV_ID=$(echo "$CONV" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$CONV_ID" ]; then ok "conversation created"; else fail "conversation creation failed"; fi
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
MSG1=$(authed "$ALICE_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "" \
|
||||
-d '{"content":"Pre-upgrade message from alice","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
MSG1_ID=$(echo "$MSG1" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$MSG1_ID" ]; then ok "message sent"; else fail "message send failed"; fi
|
||||
|
||||
MSG2=$(authed "$BOB_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "" \
|
||||
-d '{"content":"Pre-upgrade reply from bob","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
MSG2_ID=$(echo "$MSG2" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$MSG2_ID" ]; then ok "reply sent"; else fail "reply send failed"; fi
|
||||
fi
|
||||
|
||||
# ── Seed global config ─────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}Seeding global config...${NC}"
|
||||
|
||||
# Set a global config key to verify it survives upgrade
|
||||
authed "$ADMIN_TOKEN" PUT "/api/v1/admin/config/upgrade_test_key" "" \
|
||||
-d '{"value":"upgrade-test-value"}' 2>/dev/null && ok "global config set" || ok "global config set (endpoint may not exist)"
|
||||
|
||||
# Record installed packages
|
||||
PRE_PACKAGES=$(authed "$ADMIN_TOKEN" GET "/api/v1/packages" 2>/dev/null || echo "[]")
|
||||
PRE_PKG_COUNT=$(echo "$PRE_PACKAGES" | grep -o '"id"' | wc -l)
|
||||
ok "recorded $PRE_PKG_COUNT installed packages"
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 3: Upgrade
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 3: Upgrade ═══${NC}"
|
||||
|
||||
echo "Stopping old version..."
|
||||
docker compose -f "$COMPOSE_FILE" stop armature-old
|
||||
ok "old version stopped"
|
||||
|
||||
echo "Starting new version..."
|
||||
docker compose -f "$COMPOSE_FILE" up armature-new -d
|
||||
wait_for_health "$HOST"
|
||||
ok "new version started"
|
||||
|
||||
# Check for migration errors in logs
|
||||
echo -e "\n${YELLOW}Checking startup logs...${NC}"
|
||||
LOGS=$(docker compose -f "$COMPOSE_FILE" logs armature-new 2>&1 || echo "")
|
||||
if echo "$LOGS" | grep -qi "migration.*fail\|schema.*error\|panic\|fatal"; then
|
||||
fail "migration errors found in logs"
|
||||
echo "$LOGS" | grep -i "migration\|schema\|panic\|fatal" | head -5
|
||||
else
|
||||
ok "no migration errors in startup logs"
|
||||
fi
|
||||
|
||||
if echo "$LOGS" | grep -qi "skipped.*existing"; then
|
||||
ok "bundled packages correctly skipped existing"
|
||||
else
|
||||
# Not a failure — just note it
|
||||
echo " (no skip-existing log found — may be expected)"
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Phase 4: Verify Data Integrity
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══ Phase 4: Verify Data Integrity ═══${NC}"
|
||||
|
||||
# ── Auth ──────────────────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}4.1 Authentication${NC}"
|
||||
|
||||
ADMIN_TOKEN=$(login admin admin)
|
||||
if [ -n "$ADMIN_TOKEN" ]; then ok "admin login post-upgrade"; else fail "admin login failed post-upgrade"; exit 1; fi
|
||||
|
||||
ALICE_TOKEN=$(login alice password123)
|
||||
if [ -n "$ALICE_TOKEN" ]; then ok "alice login post-upgrade"; else fail "alice login failed post-upgrade"; fi
|
||||
|
||||
BOB_TOKEN=$(login bob password456)
|
||||
if [ -n "$BOB_TOKEN" ]; then ok "bob login post-upgrade"; else fail "bob login failed post-upgrade"; fi
|
||||
|
||||
# ── Notes ─────────────────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}4.2 Notes${NC}"
|
||||
|
||||
if [ -n "$NOTE1_ID" ]; then
|
||||
NOTE1_CHECK=$(authed "$ALICE_TOKEN" GET "/s/notes/api/notes/$NOTE1_ID" 2>/dev/null || echo "{}")
|
||||
if echo "$NOTE1_CHECK" | grep -q "Upgrade Test Note"; then
|
||||
ok "note title preserved"
|
||||
else
|
||||
fail "note title lost"
|
||||
fi
|
||||
if echo "$NOTE1_CHECK" | grep -q "survive the upgrade"; then
|
||||
ok "note body preserved"
|
||||
else
|
||||
fail "note body lost"
|
||||
echo " Response: ${NOTE1_CHECK:0:200}"
|
||||
fi
|
||||
fi
|
||||
|
||||
NOTES_LIST=$(authed "$ALICE_TOKEN" GET "/s/notes/api/notes" 2>/dev/null || echo "[]")
|
||||
NOTE_COUNT=$(echo "$NOTES_LIST" | grep -o '"id"' | wc -l)
|
||||
if [ "$NOTE_COUNT" -ge 2 ]; then
|
||||
ok "all $NOTE_COUNT notes survived upgrade"
|
||||
else
|
||||
fail "expected at least 2 notes, got $NOTE_COUNT"
|
||||
fi
|
||||
|
||||
# ── Conversations ─────────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}4.3 Conversations + Messages${NC}"
|
||||
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
CONV_CHECK=$(authed "$ALICE_TOKEN" GET "/s/chat-core/api/conversations" 2>/dev/null || echo "[]")
|
||||
if echo "$CONV_CHECK" | grep -q "Upgrade Test Chat"; then
|
||||
ok "conversation survived upgrade"
|
||||
else
|
||||
fail "conversation lost"
|
||||
fi
|
||||
|
||||
MSGS_CHECK=$(authed "$ALICE_TOKEN" GET "/s/chat-core/api/messages/$CONV_ID?limit=50" 2>/dev/null || echo "[]")
|
||||
if echo "$MSGS_CHECK" | grep -q "Pre-upgrade message from alice"; then
|
||||
ok "alice's message survived"
|
||||
else
|
||||
fail "alice's message lost"
|
||||
fi
|
||||
if echo "$MSGS_CHECK" | grep -q "Pre-upgrade reply from bob"; then
|
||||
ok "bob's reply survived"
|
||||
else
|
||||
fail "bob's reply lost"
|
||||
fi
|
||||
fi
|
||||
|
||||
# ── Packages ──────────────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}4.4 Packages${NC}"
|
||||
|
||||
POST_PACKAGES=$(authed "$ADMIN_TOKEN" GET "/api/v1/packages" 2>/dev/null || echo "[]")
|
||||
POST_PKG_COUNT=$(echo "$POST_PACKAGES" | grep -o '"id"' | wc -l)
|
||||
if [ "$POST_PKG_COUNT" -ge "$PRE_PKG_COUNT" ]; then
|
||||
ok "package count preserved: $POST_PKG_COUNT (was $PRE_PKG_COUNT)"
|
||||
else
|
||||
fail "package count decreased: $POST_PKG_COUNT (was $PRE_PKG_COUNT)"
|
||||
fi
|
||||
|
||||
# ── Settings / Config ─────────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}4.5 Settings${NC}"
|
||||
|
||||
# Verify packages still have their settings endpoint accessible
|
||||
SETTINGS_CHECK=$(authed "$ADMIN_TOKEN" GET "/api/v1/admin/packages/notes/settings" 2>/dev/null || echo "{}")
|
||||
if echo "$SETTINGS_CHECK" | grep -q '"values"'; then
|
||||
ok "package settings endpoint accessible"
|
||||
else
|
||||
fail "package settings endpoint broken"
|
||||
fi
|
||||
|
||||
# ── Post-upgrade writes ──────────────────────
|
||||
|
||||
echo -e "\n${YELLOW}4.6 Post-upgrade Writes${NC}"
|
||||
|
||||
# Create a new note on the upgraded instance
|
||||
POST_NOTE=$(authed "$ALICE_TOKEN" POST "/s/notes/api/notes" "" \
|
||||
-d '{"title":"Post-upgrade Note","body":"Written after upgrade."}' 2>/dev/null || echo "{}")
|
||||
POST_NOTE_ID=$(echo "$POST_NOTE" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$POST_NOTE_ID" ]; then ok "post-upgrade note creation works"; else fail "post-upgrade note creation failed"; fi
|
||||
|
||||
# Send a message on the upgraded instance
|
||||
if [ -n "$CONV_ID" ]; then
|
||||
POST_MSG=$(authed "$ALICE_TOKEN" POST "/s/chat-core/api/messages/$CONV_ID" "" \
|
||||
-d '{"content":"Post-upgrade message","content_type":"text"}' 2>/dev/null || echo "{}")
|
||||
POST_MSG_ID=$(echo "$POST_MSG" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
if [ -n "$POST_MSG_ID" ]; then ok "post-upgrade message send works"; else fail "post-upgrade message send failed"; fi
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Summary
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
echo -e "\n${YELLOW}═══════════════════════════════════════${NC}"
|
||||
echo -e " ${GREEN}Passed: $pass${NC} ${RED}Failed: $fail${NC}"
|
||||
echo -e "${YELLOW}═══════════════════════════════════════${NC}"
|
||||
|
||||
if [ "$fail" -gt 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,65 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* E2E WebSocket Listener — waits for a specific realtime event.
|
||||
*
|
||||
* Usage:
|
||||
* node e2e-ws-listener.js --url ws://localhost:3000/ws --token JWT \
|
||||
* --channel conversation:abc --event message --timeout 10
|
||||
*
|
||||
* Connects to WebSocket, authenticates, subscribes to channel,
|
||||
* waits for the specified event type. Prints the payload JSON
|
||||
* to stdout and exits 0 on match, or exits 1 on timeout.
|
||||
*/
|
||||
const WebSocket = require('ws');
|
||||
|
||||
const args = {};
|
||||
for (let i = 2; i < process.argv.length; i += 2) {
|
||||
args[process.argv[i].replace('--', '')] = process.argv[i + 1];
|
||||
}
|
||||
|
||||
const url = args.url || 'ws://localhost:3000/ws';
|
||||
const token = args.token || '';
|
||||
const channel = args.channel || '';
|
||||
const event = args.event || 'message';
|
||||
const timeout = parseInt(args.timeout || '10', 10) * 1000;
|
||||
|
||||
if (!token || !channel) {
|
||||
console.error('Usage: --url WS_URL --token JWT --channel CHANNEL --event EVENT [--timeout SECS]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const ws = new WebSocket(url);
|
||||
let timer = null;
|
||||
|
||||
ws.on('open', () => {
|
||||
// Authenticate
|
||||
ws.send(JSON.stringify({ type: 'auth', token: token }));
|
||||
// Subscribe to channel
|
||||
ws.send(JSON.stringify({ type: 'room.subscribe', room: channel }));
|
||||
});
|
||||
|
||||
ws.on('message', (data) => {
|
||||
try {
|
||||
const msg = JSON.parse(data.toString());
|
||||
// Match event on the subscribed channel
|
||||
if (msg.type === 'event' && msg.channel === channel && msg.event === event) {
|
||||
console.log(JSON.stringify(msg.data || msg));
|
||||
clearTimeout(timer);
|
||||
ws.close();
|
||||
process.exit(0);
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore non-JSON messages
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('error', (err) => {
|
||||
console.error('WS error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
timer = setTimeout(() => {
|
||||
console.error('Timeout waiting for event: ' + event + ' on channel: ' + channel);
|
||||
ws.close();
|
||||
process.exit(1);
|
||||
}, timeout);
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"realm": "armature",
|
||||
"realm": "switchboard",
|
||||
"enabled": true,
|
||||
"registrationAllowed": false,
|
||||
"loginWithEmailAllowed": true,
|
||||
@@ -9,11 +9,11 @@
|
||||
"realm": [
|
||||
{
|
||||
"name": "sb-admin",
|
||||
"description": "Armature admin role"
|
||||
"description": "Switchboard admin role"
|
||||
},
|
||||
{
|
||||
"name": "sb-user",
|
||||
"description": "Armature regular user role"
|
||||
"description": "Switchboard regular user role"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -29,11 +29,11 @@
|
||||
],
|
||||
"clients": [
|
||||
{
|
||||
"clientId": "armature",
|
||||
"name": "Armature",
|
||||
"clientId": "switchboard",
|
||||
"name": "Switchboard Core",
|
||||
"enabled": true,
|
||||
"publicClient": false,
|
||||
"secret": "armature-secret",
|
||||
"secret": "switchboard-secret",
|
||||
"redirectUris": [
|
||||
"http://localhost:3000/*",
|
||||
"http://localhost:8080/*"
|
||||
@@ -69,7 +69,7 @@
|
||||
"users": [
|
||||
{
|
||||
"username": "alice",
|
||||
"email": "alice@armature.test",
|
||||
"email": "alice@switchboard.test",
|
||||
"firstName": "Alice",
|
||||
"lastName": "Engineer",
|
||||
"enabled": true,
|
||||
@@ -83,7 +83,7 @@
|
||||
],
|
||||
"realmRoles": [
|
||||
"sb-user",
|
||||
"default-roles-armature"
|
||||
"default-roles-switchboard"
|
||||
],
|
||||
"groups": [
|
||||
"/engineering"
|
||||
@@ -91,7 +91,7 @@
|
||||
},
|
||||
{
|
||||
"username": "bob",
|
||||
"email": "bob@armature.test",
|
||||
"email": "bob@switchboard.test",
|
||||
"firstName": "Bob",
|
||||
"lastName": "Lead",
|
||||
"enabled": true,
|
||||
@@ -106,7 +106,7 @@
|
||||
"realmRoles": [
|
||||
"sb-admin",
|
||||
"sb-user",
|
||||
"default-roles-armature"
|
||||
"default-roles-switchboard"
|
||||
],
|
||||
"groups": [
|
||||
"/engineering",
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
# docker-compose-e2e.yml — Multi-replica E2E testing (Postgres)
|
||||
#
|
||||
# Three Armature replicas behind an nginx load balancer,
|
||||
# sharing a single Postgres instance. Tests cross-replica
|
||||
# broadcast via pg_notify and cluster registry (v0.6.0).
|
||||
#
|
||||
# Usage:
|
||||
# docker compose -f docker-compose-e2e.yml up --build -d
|
||||
# ./ci/e2e-chat-test.sh # chat E2E
|
||||
# ./ci/e2e-cluster-test.sh # cluster registry E2E
|
||||
# docker compose -f docker-compose-e2e.yml down -v
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: armature_e2e
|
||||
POSTGRES_USER: armature
|
||||
POSTGRES_PASSWORD: e2e-password
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U armature -d armature_e2e"]
|
||||
interval: 2s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
armature-1:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
PORT: "8080"
|
||||
BASE_PATH: ""
|
||||
DB_DRIVER: postgres
|
||||
DATABASE_URL: postgres://armature:e2e-password@postgres:5432/armature_e2e?sslmode=disable
|
||||
JWT_SECRET: e2e-jwt-secret
|
||||
ENCRYPTION_KEY: e2e-encryption-key-32chars!!!!!
|
||||
ARMATURE_ADMIN_USERNAME: admin
|
||||
ARMATURE_ADMIN_PASSWORD: admin
|
||||
STORAGE_BACKEND: pvc
|
||||
STORAGE_PATH: /data/storage
|
||||
CORS_ALLOWED_ORIGINS: "*"
|
||||
EXT_ALLOW_PRIVATE_IPS: "true"
|
||||
LOG_FORMAT: text
|
||||
LOG_LEVEL: info
|
||||
SEED_USERS: "alice:password123:user,bob:password456:user,charlie:password789:user"
|
||||
CLUSTER_NODE_ID: "node-1"
|
||||
CLUSTER_HEARTBEAT_INTERVAL: "5s"
|
||||
CLUSTER_STALE_THRESHOLD: "15s"
|
||||
CLUSTER_ENDPOINT: "http://armature-1:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8081:80"
|
||||
|
||||
armature-2:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
PORT: "8080"
|
||||
BASE_PATH: ""
|
||||
DB_DRIVER: postgres
|
||||
DATABASE_URL: postgres://armature:e2e-password@postgres:5432/armature_e2e?sslmode=disable
|
||||
JWT_SECRET: e2e-jwt-secret
|
||||
ENCRYPTION_KEY: e2e-encryption-key-32chars!!!!!
|
||||
ARMATURE_ADMIN_USERNAME: admin
|
||||
ARMATURE_ADMIN_PASSWORD: admin
|
||||
STORAGE_BACKEND: pvc
|
||||
STORAGE_PATH: /data/storage
|
||||
CORS_ALLOWED_ORIGINS: "*"
|
||||
EXT_ALLOW_PRIVATE_IPS: "true"
|
||||
LOG_FORMAT: text
|
||||
LOG_LEVEL: info
|
||||
SEED_USERS: "alice:password123:user,bob:password456:user,charlie:password789:user"
|
||||
CLUSTER_NODE_ID: "node-2"
|
||||
CLUSTER_HEARTBEAT_INTERVAL: "5s"
|
||||
CLUSTER_STALE_THRESHOLD: "15s"
|
||||
CLUSTER_ENDPOINT: "http://armature-2:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8082:80"
|
||||
|
||||
armature-3:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
PORT: "8080"
|
||||
BASE_PATH: ""
|
||||
DB_DRIVER: postgres
|
||||
DATABASE_URL: postgres://armature:e2e-password@postgres:5432/armature_e2e?sslmode=disable
|
||||
JWT_SECRET: e2e-jwt-secret
|
||||
ENCRYPTION_KEY: e2e-encryption-key-32chars!!!!!
|
||||
ARMATURE_ADMIN_USERNAME: admin
|
||||
ARMATURE_ADMIN_PASSWORD: admin
|
||||
STORAGE_BACKEND: pvc
|
||||
STORAGE_PATH: /data/storage
|
||||
CORS_ALLOWED_ORIGINS: "*"
|
||||
EXT_ALLOW_PRIVATE_IPS: "true"
|
||||
LOG_FORMAT: text
|
||||
LOG_LEVEL: info
|
||||
SEED_USERS: "alice:password123:user,bob:password456:user,charlie:password789:user"
|
||||
CLUSTER_NODE_ID: "node-3"
|
||||
CLUSTER_HEARTBEAT_INTERVAL: "5s"
|
||||
CLUSTER_STALE_THRESHOLD: "15s"
|
||||
CLUSTER_ENDPOINT: "http://armature-3:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8083:80"
|
||||
|
||||
lb:
|
||||
image: nginx:alpine
|
||||
volumes:
|
||||
- ./ci/e2e-nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
ports:
|
||||
- "3000:80"
|
||||
depends_on:
|
||||
- armature-1
|
||||
- armature-2
|
||||
- armature-3
|
||||
@@ -6,11 +6,11 @@
|
||||
# docker compose -f docker-compose.yml -f docker-compose-keycloak.yml up
|
||||
#
|
||||
# This extends the base docker-compose.yml to add:
|
||||
# - Keycloak IdP with a pre-configured "armature" realm
|
||||
# - Armature configured with AUTH_MODE=oidc pointing at Keycloak
|
||||
# - Keycloak IdP with a pre-configured "switchboard" realm
|
||||
# - Switchboard configured with AUTH_MODE=oidc pointing at Keycloak
|
||||
#
|
||||
# After startup:
|
||||
# Armature: http://localhost:3000
|
||||
# Switchboard: http://localhost:3000
|
||||
# Keycloak: http://localhost:8180 (admin / admin)
|
||||
#
|
||||
# Pre-configured test users in Keycloak:
|
||||
@@ -21,14 +21,14 @@
|
||||
# ============================================
|
||||
|
||||
services:
|
||||
# Override armature to use OIDC
|
||||
armature:
|
||||
# Override switchboard to use OIDC
|
||||
switchboard:
|
||||
environment:
|
||||
AUTH_MODE: oidc
|
||||
OIDC_ISSUER_URL: http://keycloak:8080/realms/armature
|
||||
OIDC_EXTERNAL_ISSUER_URL: http://localhost:8180/realms/armature
|
||||
OIDC_CLIENT_ID: armature
|
||||
OIDC_CLIENT_SECRET: armature-secret
|
||||
OIDC_ISSUER_URL: http://keycloak:8080/realms/switchboard
|
||||
OIDC_EXTERNAL_ISSUER_URL: http://localhost:8180/realms/switchboard
|
||||
OIDC_CLIENT_ID: switchboard
|
||||
OIDC_CLIENT_SECRET: switchboard-secret
|
||||
OIDC_REDIRECT_URL: http://localhost:3000/api/v1/auth/oidc/callback
|
||||
OIDC_AUTO_ACTIVATE: "true"
|
||||
OIDC_ADMIN_ROLE: sb-admin
|
||||
@@ -38,7 +38,7 @@ services:
|
||||
|
||||
keycloak:
|
||||
image: quay.io/keycloak/keycloak:26.0
|
||||
container_name: armature-keycloak
|
||||
container_name: switchboard-keycloak
|
||||
command:
|
||||
- start-dev
|
||||
- --import-realm
|
||||
@@ -48,7 +48,7 @@ services:
|
||||
KC_HTTP_PORT: "8080"
|
||||
KC_HEALTH_ENABLED: "true"
|
||||
volumes:
|
||||
- ./ci/keycloak-realm.json:/opt/keycloak/data/import/armature-realm.json:ro
|
||||
- ./ci/keycloak-realm.json:/opt/keycloak/data/import/switchboard-realm.json:ro
|
||||
ports:
|
||||
- "8180:8080"
|
||||
healthcheck:
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
# docker-compose-upgrade.yml — Upgrade Testing (Postgres)
|
||||
#
|
||||
# Two-phase environment: run the "old" image to seed data, then
|
||||
# swap in the "new" image and verify data integrity post-upgrade.
|
||||
#
|
||||
# Usage:
|
||||
# ci/e2e-upgrade-test.sh (orchestrates build → seed → upgrade → verify)
|
||||
#
|
||||
# Manual usage:
|
||||
# docker build -t armature:v-old .
|
||||
# docker compose -f docker-compose-upgrade.yml up postgres armature-old -d
|
||||
# # ... seed data ...
|
||||
# docker compose -f docker-compose-upgrade.yml stop armature-old
|
||||
# docker compose -f docker-compose-upgrade.yml up armature-new -d
|
||||
# # ... verify data ...
|
||||
# docker compose -f docker-compose-upgrade.yml down -v
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: armature_upgrade
|
||||
POSTGRES_USER: armature
|
||||
POSTGRES_PASSWORD: upgrade-password
|
||||
ports:
|
||||
- "5433:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U armature -d armature_upgrade"]
|
||||
interval: 2s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
armature-old:
|
||||
image: armature:v-old
|
||||
environment:
|
||||
PORT: "8080"
|
||||
BASE_PATH: ""
|
||||
DB_DRIVER: postgres
|
||||
DATABASE_URL: postgres://armature:upgrade-password@postgres:5432/armature_upgrade?sslmode=disable
|
||||
JWT_SECRET: upgrade-jwt-secret
|
||||
ENCRYPTION_KEY: upgrade-encryption-key-32chars!!
|
||||
ARMATURE_ADMIN_USERNAME: admin
|
||||
ARMATURE_ADMIN_PASSWORD: admin
|
||||
STORAGE_BACKEND: pvc
|
||||
STORAGE_PATH: /data/storage
|
||||
CORS_ALLOWED_ORIGINS: "*"
|
||||
EXT_ALLOW_PRIVATE_IPS: "true"
|
||||
LOG_FORMAT: text
|
||||
LOG_LEVEL: info
|
||||
SEED_USERS: "alice:password123:user,bob:password456:user"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "3001:80"
|
||||
volumes:
|
||||
- upgrade_storage:/data/storage
|
||||
|
||||
armature-new:
|
||||
image: core-armature-new
|
||||
environment:
|
||||
PORT: "8080"
|
||||
BASE_PATH: ""
|
||||
DB_DRIVER: postgres
|
||||
DATABASE_URL: postgres://armature:upgrade-password@postgres:5432/armature_upgrade?sslmode=disable
|
||||
JWT_SECRET: upgrade-jwt-secret
|
||||
ENCRYPTION_KEY: upgrade-encryption-key-32chars!!
|
||||
ARMATURE_ADMIN_USERNAME: admin
|
||||
ARMATURE_ADMIN_PASSWORD: admin
|
||||
STORAGE_BACKEND: pvc
|
||||
STORAGE_PATH: /data/storage
|
||||
CORS_ALLOWED_ORIGINS: "*"
|
||||
EXT_ALLOW_PRIVATE_IPS: "true"
|
||||
LOG_FORMAT: text
|
||||
LOG_LEVEL: info
|
||||
SEED_USERS: "alice:password123:user,bob:password456:user"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "3001:80"
|
||||
volumes:
|
||||
- upgrade_storage:/data/storage
|
||||
|
||||
volumes:
|
||||
upgrade_storage:
|
||||
@@ -7,40 +7,36 @@
|
||||
# docker compose up --build
|
||||
# open http://localhost:3000
|
||||
#
|
||||
# Data persists in the `sb_data` named volume between restarts.
|
||||
# To reset: docker compose down -v
|
||||
# Data persists in ./data/ between restarts.
|
||||
# To reset: rm -rf ./data/
|
||||
#
|
||||
# For Postgres / multi-replica / k8s deployment see k8s/ and Dockerfile.
|
||||
|
||||
services:
|
||||
armature:
|
||||
switchboard:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: armature
|
||||
container_name: switchboard-core
|
||||
environment:
|
||||
PORT: "8080"
|
||||
BASE_PATH: ""
|
||||
DB_DRIVER: sqlite
|
||||
DATABASE_URL: /data/armature.db
|
||||
DATABASE_URL: /data/switchboard.db
|
||||
JWT_SECRET: ${JWT_SECRET:-change-me-for-production}
|
||||
ENCRYPTION_KEY: ${ENCRYPTION_KEY:-change-me-for-production}
|
||||
ARMATURE_ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
|
||||
ARMATURE_ADMIN_PASSWORD: ${ADMIN_PASSWORD:-admin}
|
||||
SWITCHBOARD_ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
|
||||
SWITCHBOARD_ADMIN_PASSWORD: ${ADMIN_PASSWORD:-admin}
|
||||
STORAGE_BACKEND: pvc
|
||||
STORAGE_PATH: /data/storage
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-http://localhost:3000}
|
||||
EXT_ALLOW_PRIVATE_IPS: ${EXT_ALLOW_PRIVATE_IPS:-true}
|
||||
LOG_FORMAT: ${LOG_FORMAT:-text}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
BUNDLED_PACKAGES: ${BUNDLED_PACKAGES:-*}
|
||||
# Dev seed users — ignored if ENVIRONMENT=production
|
||||
SEED_USERS: ${SEED_USERS:-alice:password123:user,bob:password456:user,charlie:password789:user}
|
||||
volumes:
|
||||
- sb_data:/data
|
||||
- ./data:/data
|
||||
ports:
|
||||
- "3000:80"
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
sb_data:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
# ============================================
|
||||
# Armature - Backend Launcher
|
||||
# Switchboard Core - Backend Launcher
|
||||
# ============================================
|
||||
# Runs as an nginx entrypoint.d hook.
|
||||
# Starts the Go backend in the background
|
||||
@@ -20,15 +20,15 @@ else
|
||||
-exec sed -i "s|%%BASE_PATH%%||g" {} +
|
||||
fi
|
||||
|
||||
echo "🔀 Starting Armature backend..."
|
||||
echo "🔀 Starting Switchboard Core backend..."
|
||||
|
||||
# Kill any stale backend from a previous entrypoint run
|
||||
pkill -f /usr/local/bin/armature 2>/dev/null || true
|
||||
pkill -f /usr/local/bin/switchboard 2>/dev/null || true
|
||||
sleep 0.2
|
||||
|
||||
# Launch Go backend in background (from /app so migrations are found)
|
||||
cd /app
|
||||
/usr/local/bin/armature &
|
||||
/usr/local/bin/switchboard &
|
||||
BACKEND_PID=$!
|
||||
|
||||
# Wait for backend to be ready (max 60s)
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
# API Reference
|
||||
|
||||
Base path: `/api/v1` (all endpoints below are relative to this unless noted).
|
||||
|
||||
## Authentication
|
||||
|
||||
Most endpoints require a Bearer token in the `Authorization` header:
|
||||
|
||||
```
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
Obtain tokens via the auth endpoints (no auth required):
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| POST | `/auth/register` | Create account (if registration enabled) |
|
||||
| POST | `/auth/login` | Login, returns access + refresh tokens |
|
||||
| POST | `/auth/refresh` | Refresh access token |
|
||||
| POST | `/auth/logout` | Invalidate refresh token |
|
||||
| GET | `/auth/oidc/login` | OIDC login redirect (when `AUTH_MODE=oidc`) |
|
||||
| GET | `/auth/oidc/callback` | OIDC callback handler |
|
||||
|
||||
## Error Format
|
||||
|
||||
All errors return JSON:
|
||||
|
||||
```json
|
||||
{"error": "description of what went wrong"}
|
||||
```
|
||||
|
||||
Standard HTTP status codes: 400 (bad request), 401 (unauthorized), 403 (forbidden), 404 (not found), 500 (server error).
|
||||
|
||||
## Pagination
|
||||
|
||||
List endpoints accept query parameters:
|
||||
|
||||
| Param | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `limit` | 50 | Max items to return |
|
||||
| `offset` | 0 | Number of items to skip |
|
||||
|
||||
## Endpoints by Category
|
||||
|
||||
### Profile & Settings
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/profile` | Current user profile |
|
||||
| PUT | `/profile` | Update profile |
|
||||
| POST | `/profile/password` | Change password |
|
||||
| GET | `/settings` | User settings |
|
||||
| PUT | `/settings` | Update user settings |
|
||||
| GET | `/profile/permissions` | List granted permissions |
|
||||
| GET | `/profile/bootstrap` | Bootstrap data for frontend |
|
||||
|
||||
### Surfaces & Extensions
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/surfaces` | List enabled surfaces |
|
||||
| GET | `/extensions` | List user extensions |
|
||||
| POST | `/extensions/:id/settings` | Update extension settings |
|
||||
| GET | `/extensions/:id/manifest` | Get extension manifest |
|
||||
| GET | `/settings/public` | Public platform settings |
|
||||
|
||||
### Notifications
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/notifications` | List notifications |
|
||||
| GET | `/notifications/unread-count` | Unread count |
|
||||
| PATCH | `/notifications/:id/read` | Mark as read |
|
||||
| POST | `/notifications/mark-all-read` | Mark all read |
|
||||
| DELETE | `/notifications/:id` | Delete notification |
|
||||
| GET | `/notifications/preferences` | Notification preferences |
|
||||
| PUT | `/notifications/preferences/:type` | Set preference |
|
||||
|
||||
### Workflows
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/workflows` | List workflows |
|
||||
| POST | `/workflows` | Create workflow |
|
||||
| GET | `/workflows/:id` | Get workflow |
|
||||
| PATCH | `/workflows/:id` | Update workflow |
|
||||
| DELETE | `/workflows/:id` | Delete workflow |
|
||||
| POST | `/workflows/:id/publish` | Publish version |
|
||||
| POST | `/workflows/:id/clone` | Clone workflow |
|
||||
| POST | `/workflows/:id/instances` | Start instance |
|
||||
| GET | `/workflows/:id/instances` | List instances |
|
||||
| GET | `/assignments/mine` | My assignments |
|
||||
|
||||
### Teams
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/teams/mine` | List my teams |
|
||||
| GET | `/teams/:id/members` | Team members |
|
||||
| POST | `/teams/:id/members` | Add member |
|
||||
| GET | `/teams/:id/roles` | Team roles |
|
||||
|
||||
### Connections
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/connections` | List connections |
|
||||
| POST | `/connections` | Create connection |
|
||||
| GET | `/connections/resolve` | Resolve connection by type |
|
||||
| PUT | `/connections/:id` | Update connection |
|
||||
| DELETE | `/connections/:id` | Delete connection |
|
||||
|
||||
### Packages (User)
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/packages` | List visible packages |
|
||||
| POST | `/packages/install` | Install personal package |
|
||||
| DELETE | `/packages/:id` | Delete personal package |
|
||||
|
||||
### Admin Endpoints
|
||||
|
||||
All under `/api/v1/admin/` -- require `surface.admin.access` permission.
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/admin/users` | List users |
|
||||
| POST | `/admin/users` | Create user |
|
||||
| GET | `/admin/stats` | Platform statistics |
|
||||
| GET | `/admin/settings` | Global settings |
|
||||
| PUT | `/admin/settings/:key` | Update setting |
|
||||
| GET | `/admin/packages` | List all packages |
|
||||
| POST | `/admin/packages/install` | Install package (.pkg upload) |
|
||||
| POST | `/admin/packages/:id/update` | Update package |
|
||||
| GET | `/admin/packages/:id/export` | Export package as .pkg |
|
||||
| PUT | `/admin/packages/:id/enable` | Enable package |
|
||||
| PUT | `/admin/packages/:id/disable` | Disable package |
|
||||
| DELETE | `/admin/packages/:id` | Delete package |
|
||||
| GET | `/admin/cluster` | Cluster node list (Postgres only) |
|
||||
| POST | `/admin/backup` | Create backup |
|
||||
| GET | `/admin/backups` | List backups |
|
||||
| POST | `/admin/restore` | Restore from backup |
|
||||
|
||||
### Health & Monitoring
|
||||
|
||||
These are at the base path (not under `/api/v1`):
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/health` | Basic health check |
|
||||
| GET | `/healthz/live` | Liveness probe (Kubernetes) |
|
||||
| GET | `/healthz/ready` | Readiness probe (Kubernetes) |
|
||||
| GET | `/metrics` | Prometheus metrics |
|
||||
| GET | `/api/docs` | OpenAPI documentation UI (Swagger) |
|
||||
| GET | `/api/docs/openapi.json` | Dynamic OpenAPI 3.0 spec (includes extension routes) |
|
||||
| GET | `/api/docs/openapi.yaml` | Static kernel-only OpenAPI spec (YAML) |
|
||||
|
||||
### Webhooks (Public)
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET/POST | `/api/v1/hooks/:package_id/:slug` | Inbound webhook for extensions |
|
||||
| POST | `/api/v1/workflows/public/:id/start` | Public workflow entry |
|
||||
|
||||
## WebSocket
|
||||
|
||||
Connect to `/ws` with a ticket-based auth flow:
|
||||
|
||||
1. POST `/api/v1/ws/ticket` with Bearer token to get a one-time ticket.
|
||||
2. Connect to `/ws?ticket=<ticket>`.
|
||||
|
||||
The WebSocket carries JSON-framed events. Subscribe to channels with:
|
||||
|
||||
```json
|
||||
{"type": "subscribe", "channel": "notifications"}
|
||||
```
|
||||
|
||||
Kernel event prefixes: `user.*`, `team.*`, `workflow.*`, `notification.*`, `presence.*`, `extension.*`, `admin.*`, `system.*`.
|
||||
|
||||
### Presence
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| POST | `/presence/heartbeat` | Update presence status |
|
||||
| GET | `/presence` | Query online users |
|
||||
| GET | `/users/search` | Search users |
|
||||
@@ -1,6 +1,6 @@
|
||||
# Armature — Architecture
|
||||
# Switchboard Core — Architecture
|
||||
|
||||
Armature is a self-hosted extension platform. It provides identity,
|
||||
Switchboard Core is a self-hosted extension platform. It provides identity,
|
||||
teams, permissions, storage, workflows, notifications, and a package system.
|
||||
Everything else — chat, AI providers, personas, knowledge bases, notes,
|
||||
tools — ships as installable extensions.
|
||||
@@ -25,32 +25,6 @@ package installer. Surfaces (UI pages), tools, filters, triggers, and
|
||||
providers are all packages. The editor, chat, and admin UI will themselves
|
||||
be installable surface packages.
|
||||
|
||||
## System Architecture Overview
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Browser["Browser (Preact + htm)"]
|
||||
Server["Go Server (Gin)"]
|
||||
DB["Database (SQLite / Postgres)"]
|
||||
|
||||
Browser -->|HTTP / WebSocket| Server
|
||||
|
||||
subgraph Server Layers
|
||||
Handlers["HTTP Handlers"]
|
||||
Sandbox["Starlark Sandbox"]
|
||||
Store["Store Interface"]
|
||||
EventBus["Event Bus"]
|
||||
end
|
||||
|
||||
Server --> Handlers
|
||||
Handlers --> Store
|
||||
Handlers --> Sandbox
|
||||
Sandbox --> Store
|
||||
Handlers --> EventBus
|
||||
Store --> DB
|
||||
EventBus -->|SSE / WS| Browser
|
||||
```
|
||||
|
||||
## Kernel Components
|
||||
|
||||
### Identity & Auth
|
||||
@@ -62,31 +36,6 @@ permissions, settings, and data against.
|
||||
Auth modes: `builtin` (password), `mtls` (client cert), `oidc` (Keycloak
|
||||
et al.). Mode is set at deploy time via `AUTH_MODE` env var.
|
||||
|
||||
### Request Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant CORS as CORS Middleware
|
||||
participant Auth as Auth Middleware
|
||||
participant H as Handler
|
||||
participant S as Store
|
||||
participant DB as Database
|
||||
|
||||
C->>CORS: HTTP Request
|
||||
CORS->>Auth: Pass through
|
||||
Auth->>Auth: Validate token / session
|
||||
alt Unauthorized
|
||||
Auth-->>C: 401 JSON error
|
||||
end
|
||||
Auth->>H: Authenticated context
|
||||
H->>S: Store method call
|
||||
S->>DB: SQL query
|
||||
DB-->>S: Rows
|
||||
S-->>H: Typed result
|
||||
H-->>C: JSON response
|
||||
```
|
||||
|
||||
### Teams & Groups
|
||||
|
||||
Teams provide horizontal isolation — users see only their team's resources.
|
||||
@@ -114,26 +63,6 @@ The unified registry for all installable content. A package is a surface
|
||||
Tiers: `browser` (JS only), `starlark` (sandboxed server-side),
|
||||
`sidecar` (container, future).
|
||||
|
||||
#### Extension Lifecycle
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Upload["Package Upload (.pkg)"]
|
||||
Parse["Manifest Parse"]
|
||||
Insert["DB Insert (packages table)"]
|
||||
Enable["Admin Enable Toggle"]
|
||||
Mount["Surface Mount (/s/:slug)"]
|
||||
SDK["SDK Boot"]
|
||||
Render["Renderer Registration"]
|
||||
|
||||
Upload --> Parse
|
||||
Parse --> Insert
|
||||
Insert --> Enable
|
||||
Enable --> Mount
|
||||
Mount --> SDK
|
||||
SDK --> Render
|
||||
```
|
||||
|
||||
### Starlark Sandbox
|
||||
|
||||
Extensions declare capabilities in their manifest. The admin grants or
|
||||
@@ -199,27 +128,6 @@ Server-sent events to WebSocket clients. Kernel prefixes:
|
||||
Extensions will subscribe to event patterns at install time (v0.2.0).
|
||||
Match expressions start as exact strings, grow to globs later.
|
||||
|
||||
#### Realtime Event Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant WS as WebSocket Hub
|
||||
participant PG as PG LISTEN/NOTIFY
|
||||
participant Other as Other Node
|
||||
|
||||
C->>WS: WS connect + subscribe
|
||||
Note over WS: Local fan-out to subscribers
|
||||
WS-->>C: Event push
|
||||
|
||||
Other->>PG: NOTIFY channel, payload
|
||||
PG->>WS: LISTEN callback
|
||||
WS-->>C: Fan-out to local subscribers
|
||||
|
||||
WS->>PG: NOTIFY channel, payload
|
||||
PG->>Other: LISTEN callback
|
||||
```
|
||||
|
||||
### Storage & Notifications
|
||||
|
||||
**Object storage**: PVC (local disk) or S3-compatible. Used by extensions
|
||||
@@ -248,26 +156,6 @@ SQLite parity rules: `boolToInt` for boolean binding, `store.NewID()` for
|
||||
INSERT RETURNING, no `NULLS FIRST`, no boolean literals, no `$N` reuse,
|
||||
`database.ST()`/`database.SNT()` wrappers for time scanning.
|
||||
|
||||
## Settings Cascade
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Global["Global Scope (admin)"]
|
||||
Team["Team Override"]
|
||||
User["User Override"]
|
||||
RBAC{"RBAC Gate: who can set at what scope?"}
|
||||
Flag{"user_overridable flag"}
|
||||
Effective["Effective Value"]
|
||||
|
||||
Global --> RBAC
|
||||
RBAC -->|allowed| Team
|
||||
RBAC -->|denied| Effective
|
||||
Team --> Flag
|
||||
Flag -->|true| User
|
||||
Flag -->|false| Effective
|
||||
User --> Effective
|
||||
```
|
||||
|
||||
## Frontend
|
||||
|
||||
Preact (3KB) + htm (tagged template literals). No build step, no bundler
|
||||
@@ -284,27 +172,5 @@ Single Docker image: Go binary + migrations + frontend assets + vendor
|
||||
libs. Kubernetes deployment with 3-node PG cluster. CI via Gitea Actions
|
||||
with DaemonSet DinD runners testing both PG and SQLite pipelines.
|
||||
|
||||
Registry: `registry.gobha.me:5000/xcaliber/armature`
|
||||
Registry: `registry.gobha.me:5000/xcaliber/switchboard-core`
|
||||
Namespace: `gobha-ai-chat`
|
||||
|
||||
### Cluster Topology
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
N1["Node 1"]
|
||||
N2["Node 2"]
|
||||
N3["Node 3"]
|
||||
PG["PG UNLOGGED Table (cluster_nodes)"]
|
||||
Sweep["Stale Sweep Goroutine"]
|
||||
Notify["PG LISTEN/NOTIFY"]
|
||||
|
||||
N1 -->|heartbeat INSERT/UPDATE| PG
|
||||
N2 -->|heartbeat INSERT/UPDATE| PG
|
||||
N3 -->|heartbeat INSERT/UPDATE| PG
|
||||
|
||||
Sweep -->|DELETE nodes not seen| PG
|
||||
PG -->|join/leave events| Notify
|
||||
Notify --> N1
|
||||
Notify --> N2
|
||||
Notify --> N3
|
||||
```
|
||||
|
||||
@@ -280,7 +280,7 @@ def on_fire(ctx):
|
||||
|
||||
resp = http.post(url, body=payload, headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-Armature-Event": data.get("event_name", "workflow.notify")
|
||||
"X-Switchboard-Event": data.get("event_name", "workflow.notify")
|
||||
})
|
||||
|
||||
# Log the delivery
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
# Deployment Guide
|
||||
|
||||
## Docker Single-Instance
|
||||
|
||||
```bash
|
||||
docker pull gobha/armature:latest
|
||||
docker run -p 8080:80 \
|
||||
-e ARMATURE_ADMIN_USERNAME=admin \
|
||||
-e ARMATURE_ADMIN_PASSWORD=changeme \
|
||||
-e JWT_SECRET="$(openssl rand -hex 32)" \
|
||||
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
|
||||
-v armature-data:/data \
|
||||
gobha/armature:latest
|
||||
```
|
||||
|
||||
This runs with SQLite and PVC storage. Suitable for evaluation and small teams.
|
||||
|
||||
## Docker Compose with PostgreSQL
|
||||
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16
|
||||
environment:
|
||||
POSTGRES_DB: armature
|
||||
POSTGRES_USER: armature
|
||||
POSTGRES_PASSWORD: secretpassword
|
||||
volumes:
|
||||
- pg_data:/var/lib/postgresql/data
|
||||
|
||||
armature:
|
||||
image: gobha/armature:latest
|
||||
ports:
|
||||
- "8080:80"
|
||||
environment:
|
||||
DATABASE_URL: "postgres://armature:secretpassword@postgres:5432/armature?sslmode=disable"
|
||||
JWT_SECRET: "change-me-in-production"
|
||||
ENCRYPTION_KEY: "change-me-in-production"
|
||||
ARMATURE_ADMIN_USERNAME: admin
|
||||
ARMATURE_ADMIN_PASSWORD: changeme
|
||||
STORAGE_BACKEND: pvc
|
||||
STORAGE_PATH: /data/storage
|
||||
volumes:
|
||||
- sb_storage:/data/storage
|
||||
depends_on:
|
||||
- postgres
|
||||
|
||||
volumes:
|
||||
pg_data:
|
||||
sb_storage:
|
||||
```
|
||||
|
||||
## Kubernetes
|
||||
|
||||
See the `k8s/` directory for example manifests. Key considerations:
|
||||
|
||||
- Set `POSTGRES_HOST`, `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DB` env vars (assembled into DSN automatically).
|
||||
- Liveness probe: `/healthz/live`. Readiness probe: `/healthz/ready`.
|
||||
- Mount a PVC at `/data/storage` or configure S3.
|
||||
- Store `JWT_SECRET` and `ENCRYPTION_KEY` in Kubernetes Secrets.
|
||||
- Registry: `registry.gobha.me:5000/xcaliber/armature`.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `PORT` | `8080` | Backend API port |
|
||||
| `DB_DRIVER` | auto | `postgres` or `sqlite` |
|
||||
| `DATABASE_URL` | | PostgreSQL DSN or SQLite path |
|
||||
| `JWT_SECRET` | `dev-secret-change-me` | Token signing key -- **must change** |
|
||||
| `ENCRYPTION_KEY` | | AES-256 key for credential vault |
|
||||
| `AUTH_MODE` | `builtin` | `builtin`, `mtls`, `oidc` |
|
||||
| `STORAGE_BACKEND` | auto | `pvc` or `s3` |
|
||||
| `STORAGE_PATH` | `/data/storage` | PVC mount point |
|
||||
| `BASE_PATH` | | URL prefix (e.g., `/armature`) |
|
||||
| `LOG_FORMAT` | `text` | `text` or `json` |
|
||||
| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` |
|
||||
| `CORS_ALLOWED_ORIGINS` | | Comma-separated allowed origins |
|
||||
| `BUNDLED_PACKAGES` | (empty) | `""` defaults, `"*"` all, or comma-separated |
|
||||
| `SKIP_BUNDLED_PACKAGES` | `false` | Disable bundled package install |
|
||||
| `BUNDLED_PACKAGES_DIR` | `/app/bundled-packages` | Custom bundle directory |
|
||||
| `ARMATURE_ADMIN_USERNAME` | | Bootstrap admin username |
|
||||
| `ARMATURE_ADMIN_PASSWORD` | | Bootstrap admin password |
|
||||
| `SEED_USERS` | | Dev seed users (ignored in production) |
|
||||
|
||||
### S3 Storage Variables
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `S3_BUCKET` | Bucket name |
|
||||
| `S3_ENDPOINT` | Endpoint URL (for MinIO, Ceph, etc.) |
|
||||
| `S3_ACCESS_KEY` | Access key |
|
||||
| `S3_SECRET_KEY` | Secret key |
|
||||
| `S3_FORCE_PATH_STYLE` | `true` for MinIO/Ceph |
|
||||
|
||||
### Cluster Variables (Multi-Replica)
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CLUSTER_NODE_ID` | hostname-PID | Override for deterministic node identity |
|
||||
| `CLUSTER_HEARTBEAT_INTERVAL` | `10s` | Heartbeat tick frequency |
|
||||
| `CLUSTER_STALE_THRESHOLD` | `30s` | 3x heartbeat = stale node |
|
||||
| `CLUSTER_ENDPOINT` | auto-detect | Advertised address for peer mesh |
|
||||
|
||||
## Database Configuration
|
||||
|
||||
**PostgreSQL** (recommended for production):
|
||||
|
||||
```bash
|
||||
DATABASE_URL="postgres://user:pass@host:5432/armature?sslmode=require"
|
||||
```
|
||||
|
||||
**SQLite** (dev, test, edge deployments):
|
||||
|
||||
```bash
|
||||
DB_DRIVER=sqlite
|
||||
DATABASE_URL=/data/armature.db
|
||||
```
|
||||
|
||||
Both databases are first-class -- every query compiles and passes tests on both. The driver is auto-detected from `DATABASE_URL` if `DB_DRIVER` is not set.
|
||||
|
||||
## Cluster Mode
|
||||
|
||||
Multi-replica HA requires PostgreSQL. The kernel uses PG-backed WebSocket tickets and rate limit counters to coordinate across replicas. A cluster registry with heartbeat and stale sweep tracks active nodes.
|
||||
|
||||
View cluster status in Admin > Cluster or via `GET /api/v1/admin/cluster`.
|
||||
|
||||
## Storage Backends
|
||||
|
||||
**PVC**: Auto-detected if the storage path is writable. Mount a volume at `/data/storage`.
|
||||
|
||||
**S3-compatible**: Set `STORAGE_BACKEND=s3` and provide S3 variables. Works with AWS S3, MinIO, and Ceph.
|
||||
|
||||
## Backup and Restore
|
||||
|
||||
Available via Admin UI or API:
|
||||
|
||||
```
|
||||
POST /api/v1/admin/backup # Create backup
|
||||
GET /api/v1/admin/backups # List backups
|
||||
GET /api/v1/admin/backups/:name # Download backup
|
||||
POST /api/v1/admin/restore # Restore from backup
|
||||
DELETE /api/v1/admin/backups/:name # Delete backup
|
||||
```
|
||||
|
||||
## Monitoring
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|----------|---------|
|
||||
| `/health` | Basic health check |
|
||||
| `/healthz/live` | Kubernetes liveness probe |
|
||||
| `/healthz/ready` | Kubernetes readiness probe |
|
||||
| `/metrics` | Prometheus metrics |
|
||||
806
docs/DESIGN-WORKFLOW-REDESIGN-0.2.6.md
Normal file
806
docs/DESIGN-WORKFLOW-REDESIGN-0.2.6.md
Normal file
@@ -0,0 +1,806 @@
|
||||
# Workflow Redesign — v0.2.6
|
||||
|
||||
**Status:** Phase A complete (v0.3.0 — schema + stage CRUD modernization)
|
||||
**Branch:** `feat/workflow-redesign-v0.2.6`
|
||||
**Date:** 2026-03-27
|
||||
**Context:** Mapping viable ideas from chat-switchboard v0.39.x onto core's extension-first architecture.
|
||||
|
||||
---
|
||||
|
||||
## 1. Guiding Principles
|
||||
|
||||
1. **Workflows are kernel.** Definitions, instances, the stage graph, form validation, and
|
||||
assignment queues are platform primitives — not extensions.
|
||||
2. **Execution is delegated.** How a stage renders or collects data is an extension concern.
|
||||
The kernel says *what* a stage needs; a surface package provides the *how*.
|
||||
3. **No chat assumptions.** The kernel never references personas, channels, or AI providers.
|
||||
A chat extension can participate in workflows, but the workflow engine does not depend on it.
|
||||
4. **Public access is a platform capability.** Anonymous/public sessions are not workflow-specific —
|
||||
they are a kernel-level feature that any surface can opt into. Workflows *consume* public
|
||||
access; they don't own it. See §15.
|
||||
5. **Edit existing migrations.** Per the design-decisions log: no migration chains until the
|
||||
schema is in production. New tables get new files; modified tables are edited in place.
|
||||
|
||||
---
|
||||
|
||||
## 2. Disposition Index
|
||||
|
||||
Every item below is classified:
|
||||
|
||||
| Tag | Meaning |
|
||||
|-----|---------|
|
||||
| **🗑 TRASH** | Remove from core. Vestigial chat-switchboard concept that doesn't fit. |
|
||||
| **✏️ MOD** | Exists in core today — modify in place. |
|
||||
| **➕ ADD** | New to core. Requires new code/tables. |
|
||||
| **✅ KEEP** | Already correct in core. No changes needed. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Schema Changes
|
||||
|
||||
### 3a. `007_workflows.sql` — edit in place
|
||||
|
||||
#### `workflows` table
|
||||
|
||||
| Column | Disposition | Action |
|
||||
|--------|-------------|--------|
|
||||
| `entry_mode` | ✏️ MOD | Current values: `public_link`, `team_only`. Keep the column but change its meaning — it becomes a workflow-level default/flag that says "this workflow has at least one public stage." The real visibility control moves to per-stage `audience`. See note below. |
|
||||
| All other columns | ✅ KEEP | Clean. No chat coupling. |
|
||||
|
||||
**Note on `entry_mode`:** Chat-switchboard treated this as a binary toggle — the whole
|
||||
workflow was either public or not. Real workflows mix audiences: internal setup → public
|
||||
form → internal review → public confirmation. The per-stage `audience` field (see below)
|
||||
is the source of truth. `entry_mode` on the workflow becomes a convenience flag: if any
|
||||
stage has `audience = 'public'`, the workflow is public-entry eligible. This avoids a
|
||||
full schema break — existing code that checks `entry_mode` still works, it just gets set
|
||||
automatically when stages are saved.
|
||||
|
||||
#### `workflow_stages` table
|
||||
|
||||
| Column | Disposition | Action |
|
||||
|--------|-------------|--------|
|
||||
| `persona_id` | 🗑 TRASH | Drop column. Personas are a chat-extension concept. If a stage needs an AI participant, the stage's `surface_pkg_id` extension handles that internally. The comment in the migration already acknowledges this ("personas are extensions now") but the column is still there. Remove it. |
|
||||
| `stage_mode` CHECK | ✏️ MOD | Current: `form_only`, `form_chat`, `review`, `custom`. Replace with: `form`, `review`, `delegated`, `automated`. See §4 for definitions. `form_chat` is trash (chat coupling). `form_only` renames to `form`. `custom` renames to `delegated` (clearer intent). `automated` is new (no UI, Starlark-only). |
|
||||
| `history_mode` | 🗑 TRASH | Drop column. This controlled how much chat history a persona saw across stages. Core has no chat history. If a delegated surface needs context management, it reads `stage_data` — that's the contract. |
|
||||
| `audience` | ➕ ADD | `TEXT NOT NULL DEFAULT 'team'` with CHECK `('team', 'public', 'system')`. Controls who interacts with this stage. `team` = authenticated team members only (internal). `public` = anonymous visitors via entry token (the "public-ish" stage). `system` = no human interaction, automated only. A workflow can freely alternate: team→public→team→public. The kernel enforces this: public stages are accessible via token auth, team stages require JWT, system stages have no UI. |
|
||||
| `stage_type` | ➕ ADD | `TEXT NOT NULL DEFAULT 'simple'` with CHECK `('simple', 'dynamic', 'automated')`. Drives the graph engine: `simple` = declarative rules only, `dynamic` = Starlark hook resolves next stage, `automated` = no human UI, fires hook on entry and auto-advances. |
|
||||
| `starlark_hook` | ➕ ADD | `TEXT` (nullable). Package-qualified entry point for dynamic/automated stages. Format: `package_id:entry_point`. NULL for simple stages. |
|
||||
| `branch_rules` | ➕ ADD | `JSONB NOT NULL DEFAULT '[]'`. Replaces the overloaded `transition_rules` for simple stage branching. Array of `{field, op, value, target_stage}`. Evaluated before `starlark_hook`, before ordinal fallback. |
|
||||
| `transition_rules` | ✏️ MOD | Rename to `stage_config`. This JSONB blob was doing double duty (routing rules + on_advance hooks + auto_assign). Routing moves to `branch_rules`. What remains is stage-specific config that the kernel or surface reads: `{on_advance: {package_id, entry_point}, auto_assign: "round_robin"}`. |
|
||||
| `assignment_team_id` | ✅ KEEP | Clean. Kernel concept. |
|
||||
| `form_template` | ✅ KEEP | Kernel concern — structured data schema. |
|
||||
| `auto_transition` | ✅ KEEP | Kernel concern — skip human interaction. |
|
||||
| `surface_pkg_id` | ✅ KEEP | The delegation pointer. Required for `delegated` mode stages. |
|
||||
| `sla_seconds` | ✅ KEEP | Kernel concern — time budget per stage. |
|
||||
|
||||
#### `workflow_versions` table
|
||||
|
||||
| Column | Disposition | Notes |
|
||||
|--------|-------------|-------|
|
||||
| All existing columns | ✅ KEEP | Immutable snapshots. No changes needed. |
|
||||
|
||||
### 3b. `007_workflows.sql` — add new tables (same file)
|
||||
|
||||
#### ➕ ADD `workflow_instances`
|
||||
|
||||
Replaces the channel-based instance model from chat-switchboard. This is the execution record.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS workflow_instances (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workflow_id UUID NOT NULL REFERENCES workflows(id) ON DELETE CASCADE,
|
||||
workflow_version INTEGER NOT NULL,
|
||||
current_stage INTEGER NOT NULL DEFAULT 0,
|
||||
stage_data JSONB NOT NULL DEFAULT '{}',
|
||||
status TEXT NOT NULL DEFAULT 'active'
|
||||
CHECK (status IN ('active', 'completed', 'cancelled', 'stale', 'error')),
|
||||
started_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
entry_token TEXT, -- for public_link resumption
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
stage_entered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_wf_instances_workflow
|
||||
ON workflow_instances(workflow_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_wf_instances_status
|
||||
ON workflow_instances(status) WHERE status = 'active';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_wf_instances_token
|
||||
ON workflow_instances(entry_token) WHERE entry_token IS NOT NULL;
|
||||
|
||||
DROP TRIGGER IF EXISTS wf_instances_updated_at ON workflow_instances;
|
||||
CREATE TRIGGER wf_instances_updated_at BEFORE UPDATE ON workflow_instances
|
||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
|
||||
```
|
||||
|
||||
**Rationale:** Chat-switchboard used `channels` as instances — that table carried message trees,
|
||||
AI context windows, participant lists, and other chat concerns. Core needs a purpose-built table
|
||||
that holds only workflow execution state: which version, which stage, accumulated data, lifecycle status.
|
||||
|
||||
#### ➕ ADD `workflow_assignments`
|
||||
|
||||
Dropped during the fork ("channel-dependent, rebuild as needed" — see 007 header comment).
|
||||
Now rebuilt as a kernel primitive.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS workflow_assignments (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
instance_id UUID NOT NULL REFERENCES workflow_instances(id) ON DELETE CASCADE,
|
||||
stage INTEGER NOT NULL,
|
||||
team_id UUID NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
|
||||
assigned_to UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
status TEXT NOT NULL DEFAULT 'unassigned'
|
||||
CHECK (status IN ('unassigned', 'claimed', 'completed', 'cancelled')),
|
||||
review_data JSONB NOT NULL DEFAULT '{}',
|
||||
claimed_at TIMESTAMPTZ,
|
||||
completed_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_wf_assignments_instance
|
||||
ON workflow_assignments(instance_id, stage);
|
||||
CREATE INDEX IF NOT EXISTS idx_wf_assignments_team_status
|
||||
ON workflow_assignments(team_id, status) WHERE status IN ('unassigned', 'claimed');
|
||||
CREATE INDEX IF NOT EXISTS idx_wf_assignments_user
|
||||
ON workflow_assignments(assigned_to) WHERE assigned_to IS NOT NULL;
|
||||
```
|
||||
|
||||
**Claim lock:** Same optimistic pattern from chat-switchboard:
|
||||
`UPDATE ... WHERE id = $1 AND status = 'unassigned'` — if `rows_affected == 0`, already claimed.
|
||||
|
||||
### 3c. New migration file: `012_workflow_instances.sql`
|
||||
|
||||
Wait — per the principle, new *tables* get new files. But we're also editing 007. Decision:
|
||||
|
||||
**Put the new tables in 007_workflows.sql.** The schema isn't in production. Keep all workflow
|
||||
DDL in one file. When the schema *is* in production (post-MVP), new additions get numbered
|
||||
migrations. This is consistent with the existing design-decisions log entry:
|
||||
"No new migrations pre-MVP."
|
||||
|
||||
---
|
||||
|
||||
## 4. Stage Mode Redesign
|
||||
|
||||
### Current (trash/rename)
|
||||
|
||||
| Current Mode | Disposition | Rationale |
|
||||
|-------------|-------------|-----------|
|
||||
| `form_only` | ✏️ MOD → `form` | Rename. Drop the `_only` suffix — there's no `form_chat` to distinguish from anymore. |
|
||||
| `form_chat` | 🗑 TRASH | Chat coupling. If you want a form + AI conversation, use `delegated` with a chat surface package. |
|
||||
| `review` | ✅ KEEP | Team member reviews accumulated data. Pure kernel concept. |
|
||||
| `custom` | ✏️ MOD → `delegated` | Rename for clarity. "Custom" is vague. "Delegated" makes the contract explicit: the kernel delegates stage execution to `surface_pkg_id`. |
|
||||
|
||||
### New modes
|
||||
|
||||
| Mode | Disposition | Description |
|
||||
|------|-------------|-------------|
|
||||
| `form` | ✏️ MOD (renamed) | Kernel renders `form_template`, validates submission, merges into `stage_data`. No extension needed. |
|
||||
| `review` | ✅ KEEP | Assignment queue stage. Team member claims, reviews `stage_data`, adds `review_data`, completes. Kernel-rendered. |
|
||||
| `delegated` | ✏️ MOD (renamed) | Kernel hands off to `surface_pkg_id`. The surface package receives the instance context (stage_data, form_template, metadata) and calls back to advance. This is where chat, AI, or any custom UX lives. |
|
||||
| `automated` | ➕ ADD | No UI. On stage entry, kernel fires `starlark_hook`, merges returned data into `stage_data`, and auto-advances. For enrichment, API calls, validation, routing decisions. |
|
||||
|
||||
### Stage type vs stage mode
|
||||
|
||||
These are orthogonal:
|
||||
|
||||
- **`stage_type`** controls *how the next stage is chosen*: `simple` (declarative branch_rules), `dynamic` (Starlark hook returns target), `automated` (hook + auto-advance).
|
||||
- **`stage_mode`** controls *how the stage executes*: `form`, `review`, `delegated`, `automated`.
|
||||
|
||||
An `automated` stage_type with `automated` stage_mode is the common case for system stages,
|
||||
but you can have a `dynamic` stage_type with `form` stage_mode (the form collects data, then a
|
||||
Starlark hook decides where to go next based on the submission).
|
||||
|
||||
---
|
||||
|
||||
## 5. Model Changes
|
||||
|
||||
### `server/models/workflow.go`
|
||||
|
||||
#### WorkflowStage struct — ✏️ MOD
|
||||
|
||||
```go
|
||||
// TRASH: Remove these fields
|
||||
// PersonaID *string `json:"persona_id,omitempty"`
|
||||
// HistoryMode string `json:"history_mode"`
|
||||
|
||||
// MOD: Rename transition_rules → stage_config
|
||||
// TransitionRules json.RawMessage `json:"transition_rules"`
|
||||
StageConfig json.RawMessage `json:"stage_config"`
|
||||
|
||||
// ADD: New fields
|
||||
Audience string `json:"audience"` // team | public | system
|
||||
StageType string `json:"stage_type"` // simple | dynamic | automated
|
||||
StarlarkHook *string `json:"starlark_hook,omitempty"` // package_id:entry_point
|
||||
BranchRules json.RawMessage `json:"branch_rules"` // [{field, op, value, target_stage}]
|
||||
```
|
||||
|
||||
#### Stage mode constants — ✏️ MOD
|
||||
|
||||
```go
|
||||
// TRASH
|
||||
// StageModeFormOnly = "form_only"
|
||||
// StageModeFormChat = "form_chat"
|
||||
|
||||
// MOD (rename)
|
||||
StageModeForm = "form" // was form_only
|
||||
StageModeDelegated = "delegated" // was custom
|
||||
|
||||
// KEEP
|
||||
StageModeReview = "review"
|
||||
|
||||
// ADD
|
||||
StageModeAutomated = "automated"
|
||||
|
||||
// ADD: Stage type constants
|
||||
StageTypeSimple = "simple"
|
||||
StageTypeDynamic = "dynamic"
|
||||
StageTypeAutomated = "automated"
|
||||
|
||||
// ADD: Audience constants
|
||||
AudienceTeam = "team"
|
||||
AudiencePublic = "public"
|
||||
AudienceSystem = "system"
|
||||
```
|
||||
|
||||
#### ➕ ADD: WorkflowInstance model
|
||||
|
||||
```go
|
||||
type WorkflowInstance struct {
|
||||
ID string `json:"id"`
|
||||
WorkflowID string `json:"workflow_id"`
|
||||
WorkflowVersion int `json:"workflow_version"`
|
||||
CurrentStage int `json:"current_stage"`
|
||||
StageData json.RawMessage `json:"stage_data"`
|
||||
Status string `json:"status"` // active | completed | cancelled | stale | error
|
||||
StartedBy *string `json:"started_by,omitempty"`
|
||||
EntryToken *string `json:"entry_token,omitempty"`
|
||||
Metadata json.RawMessage `json:"metadata"`
|
||||
StageEnteredAt time.Time `json:"stage_entered_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
```
|
||||
|
||||
#### ➕ ADD: WorkflowAssignment model
|
||||
|
||||
```go
|
||||
type WorkflowAssignment struct {
|
||||
ID string `json:"id"`
|
||||
InstanceID string `json:"instance_id"`
|
||||
Stage int `json:"stage"`
|
||||
TeamID string `json:"team_id"`
|
||||
AssignedTo *string `json:"assigned_to,omitempty"`
|
||||
Status string `json:"status"` // unassigned | claimed | completed | cancelled
|
||||
ReviewData json.RawMessage `json:"review_data"`
|
||||
ClaimedAt *time.Time `json:"claimed_at,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
```
|
||||
|
||||
#### TypedFormTemplate, FormField, FormValidation — ✅ KEEP
|
||||
|
||||
All form types are clean kernel code. No changes.
|
||||
|
||||
#### ValidateFormData — ✅ KEEP
|
||||
|
||||
Pure data validation. No chat coupling.
|
||||
|
||||
---
|
||||
|
||||
## 6. Store Interface Changes
|
||||
|
||||
### `server/store/workflow_iface.go` — ✏️ MOD + ➕ ADD
|
||||
|
||||
Current interface is definition-only (CRUD workflows + stages + versions).
|
||||
Add instance and assignment operations.
|
||||
|
||||
```go
|
||||
type WorkflowStore interface {
|
||||
// ── Definition CRUD (KEEP — no changes) ──────────
|
||||
Create(ctx context.Context, w *models.Workflow) error
|
||||
GetByID(ctx context.Context, id string) (*models.Workflow, error)
|
||||
GetBySlug(ctx context.Context, teamID *string, slug string) (*models.Workflow, error)
|
||||
Update(ctx context.Context, id string, patch models.WorkflowPatch) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
ListForTeam(ctx context.Context, teamID string) ([]models.Workflow, error)
|
||||
ListGlobal(ctx context.Context) ([]models.Workflow, error)
|
||||
|
||||
// ── Stage CRUD (KEEP — no changes) ───────────────
|
||||
CreateStage(ctx context.Context, s *models.WorkflowStage) error
|
||||
ListStages(ctx context.Context, workflowID string) ([]models.WorkflowStage, error)
|
||||
UpdateStage(ctx context.Context, s *models.WorkflowStage) error
|
||||
DeleteStage(ctx context.Context, id string) error
|
||||
ReorderStages(ctx context.Context, workflowID string, orderedIDs []string) error
|
||||
|
||||
// ── Versioning (KEEP — no changes) ───────────────
|
||||
Publish(ctx context.Context, v *models.WorkflowVersion) error
|
||||
GetVersion(ctx context.Context, workflowID string, versionNumber int) (*models.WorkflowVersion, error)
|
||||
GetLatestVersion(ctx context.Context, workflowID string) (*models.WorkflowVersion, error)
|
||||
|
||||
// ── Instances (ADD) ──────────────────────────────
|
||||
CreateInstance(ctx context.Context, inst *models.WorkflowInstance) error
|
||||
GetInstance(ctx context.Context, id string) (*models.WorkflowInstance, error)
|
||||
GetInstanceByToken(ctx context.Context, token string) (*models.WorkflowInstance, error)
|
||||
UpdateInstance(ctx context.Context, id string, patch models.InstancePatch) error
|
||||
ListInstances(ctx context.Context, workflowID string, status string) ([]models.WorkflowInstance, error)
|
||||
AdvanceStage(ctx context.Context, id string, nextStage int, mergeData json.RawMessage) error
|
||||
CompleteInstance(ctx context.Context, id string) error
|
||||
CancelInstance(ctx context.Context, id string) error
|
||||
MarkStale(ctx context.Context, olderThan time.Duration) (int, error)
|
||||
|
||||
// ── Assignments (ADD) ────────────────────────────
|
||||
CreateAssignment(ctx context.Context, a *models.WorkflowAssignment) error
|
||||
ClaimAssignment(ctx context.Context, id string, userID string) error // optimistic lock
|
||||
UnclaimAssignment(ctx context.Context, id string) error
|
||||
CompleteAssignment(ctx context.Context, id string, reviewData json.RawMessage) error
|
||||
CancelAssignment(ctx context.Context, id string) error
|
||||
ListAssignmentsByTeam(ctx context.Context, teamID string, status string) ([]models.WorkflowAssignment, error)
|
||||
ListAssignmentsByUser(ctx context.Context, userID string) ([]models.WorkflowAssignment, error)
|
||||
ListAssignmentsByInstance(ctx context.Context, instanceID string) ([]models.WorkflowAssignment, error)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Handler Changes
|
||||
|
||||
### `server/handlers/workflows.go` — ✏️ MOD
|
||||
|
||||
**Stage CRUD updates** — reflect new field names in CreateStage/UpdateStage:
|
||||
- Remove `persona_id` and `history_mode` from bind/validation.
|
||||
- Add `stage_type`, `starlark_hook`, `branch_rules` to bind/validation.
|
||||
- Rename `transition_rules` → `stage_config` in bind/validation.
|
||||
- Update `stage_mode` CHECK to new set: `form`, `review`, `delegated`, `automated`.
|
||||
- Validate: `delegated` requires `surface_pkg_id`. `dynamic`/`automated` stage_type requires `starlark_hook`.
|
||||
|
||||
### `server/handlers/workflow_hooks.go` — ✏️ MOD
|
||||
|
||||
**Rename:** `channelID` parameter → `instanceID` in `FireOnAdvanceHook` signature.
|
||||
The hook context dict changes from `{channel_id, ...}` to `{instance_id, ...}`.
|
||||
|
||||
The `jsonToStarlark` helper referenced on line 81 lives in
|
||||
`server/handlers/starlark_helpers.go`. Consider consolidating with `goToStarlark` in
|
||||
`server/triggers/event.go` — two independent Go→Starlark converters is tech debt.
|
||||
|
||||
### `server/handlers/workflow_team.go` — ✅ KEEP
|
||||
|
||||
Team-scoped wrappers. Clean delegation pattern. No changes.
|
||||
|
||||
### `server/handlers/workflow_packages.go` — ✏️ MOD
|
||||
|
||||
Update `workflowPkgStage` struct:
|
||||
- Remove `PersonaID`, `HistoryMode` fields.
|
||||
- Add `StageType`, `StarlarkHook`, `BranchRules` fields.
|
||||
- Rename `TransitionRules` → `StageConfig`.
|
||||
|
||||
Update `ExportWorkflowPackage` and `InstallWorkflowFromManifest` accordingly.
|
||||
|
||||
### ➕ ADD `server/handlers/workflow_instances.go`
|
||||
|
||||
New handler file for instance lifecycle:
|
||||
|
||||
```
|
||||
POST /api/v1/workflows/:id/start → Start (create instance from latest published version)
|
||||
GET /api/v1/workflows/instances/:iid → GetInstance
|
||||
POST /api/v1/workflows/instances/:iid/advance → Advance (submit stage data, resolve next)
|
||||
POST /api/v1/workflows/instances/:iid/cancel → Cancel
|
||||
GET /api/v1/workflows/:id/instances → ListInstances (by workflow, optionally by status)
|
||||
```
|
||||
|
||||
Public entry (for `public_link` workflows):
|
||||
```
|
||||
POST /api/v1/workflows/entry/:slug → StartPublic (no auth, generates entry_token)
|
||||
GET /api/v1/workflows/entry/:token → ResumePublic (retrieve instance by token)
|
||||
POST /api/v1/workflows/entry/:token/advance → AdvancePublic (submit data via token)
|
||||
```
|
||||
|
||||
### ➕ ADD `server/handlers/workflow_assignments.go`
|
||||
|
||||
New handler file for the assignment queue:
|
||||
|
||||
```
|
||||
GET /api/v1/teams/:teamId/assignments → ListTeamAssignments (filterable by status)
|
||||
POST /api/v1/teams/:teamId/assignments/:id/claim → Claim
|
||||
POST /api/v1/teams/:teamId/assignments/:id/unclaim → Unclaim
|
||||
POST /api/v1/teams/:teamId/assignments/:id/complete → Complete (with review_data)
|
||||
POST /api/v1/teams/:teamId/assignments/:id/cancel → Cancel
|
||||
GET /api/v1/assignments/mine → ListMyAssignments (across teams)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Routing Engine Changes
|
||||
|
||||
### `server/workflow/routing.go` — ✏️ MOD
|
||||
|
||||
The existing `ResolveNextStage` evaluates `transition_rules.conditions[]`. This needs to
|
||||
become a two-phase resolution that respects the new `stage_type`:
|
||||
|
||||
```
|
||||
Phase 1: Evaluate branch_rules (declarative, for simple + dynamic types)
|
||||
Phase 2: If no match AND stage_type == dynamic → fire starlark_hook
|
||||
Phase 3: Fallback → currentStage + 1
|
||||
```
|
||||
|
||||
For `automated` stage_type, the engine fires `starlark_hook` on entry (not for routing — for
|
||||
data enrichment), then routes via branch_rules or ordinal fallback. The routing call happens
|
||||
*after* the hook returns.
|
||||
|
||||
**Concrete changes:**
|
||||
- `ResolveNextStage` signature: add `stageType string, starlarkHook *string, runner *sandbox.Runner` parameters.
|
||||
- Extract branch_rules evaluation from the current `TransitionRulesWithConditions` (which reads from `transition_rules` JSON) into a dedicated function that reads from the new `branch_rules` field.
|
||||
- `TransitionRulesWithConditions` struct → rename to `StageConfig`, remove `Conditions` field (moved to branch_rules), keep `AutoAssign` and `OnAdvance`.
|
||||
|
||||
### `server/workflow/` — ➕ ADD `engine.go`
|
||||
|
||||
New file: the stage execution engine. Orchestrates the advance lifecycle:
|
||||
|
||||
```
|
||||
1. Load instance + version snapshot
|
||||
2. Validate current stage allows advancement (status checks)
|
||||
3. If current stage has form_template → validate submitted data
|
||||
4. Merge submitted data into stage_data
|
||||
5. Fire on_advance hook (if configured in stage_config)
|
||||
6. Resolve next stage (branch_rules → starlark_hook → ordinal)
|
||||
7. If next stage is past last stage → complete instance
|
||||
8. If next stage is automated → fire its hook, recurse to step 6
|
||||
9. If next stage has assignment_team_id → create WorkflowAssignment
|
||||
10. Update instance (current_stage, stage_data, stage_entered_at)
|
||||
11. Emit bus events (workflow.advanced, workflow.assigned, workflow.completed)
|
||||
```
|
||||
|
||||
### `server/workflow/` — ➕ ADD `automated.go`
|
||||
|
||||
Handles `automated` stage execution: fire the Starlark hook, merge returned data, and
|
||||
auto-advance. Includes a cycle guard (max 10 consecutive automated stages) to prevent
|
||||
infinite loops from misconfigured workflows.
|
||||
|
||||
---
|
||||
|
||||
## 9. Event Bus Updates
|
||||
|
||||
### `server/events/types.go` — ✏️ MOD
|
||||
|
||||
Current workflow events are fine but incomplete. Add:
|
||||
|
||||
| Event | Direction | Disposition | Trigger |
|
||||
|-------|-----------|-------------|---------|
|
||||
| `workflow.assigned` | DirToClient | ✅ KEEP | Assignment created |
|
||||
| `workflow.claimed` | DirToClient | ✅ KEEP | Assignment claimed |
|
||||
| `workflow.advanced` | DirToClient | ✅ KEEP | Stage transition |
|
||||
| `workflow.completed` | DirToClient | ✅ KEEP | Instance completed |
|
||||
| `workflow.cancelled` | DirToClient | ➕ ADD | Instance cancelled |
|
||||
| `workflow.started` | DirToClient | ➕ ADD | Instance created |
|
||||
| `workflow.sla.warning` | DirToClient | ➕ ADD | SLA at 80% threshold |
|
||||
| `workflow.sla.breached` | DirToClient | ➕ ADD | SLA exceeded |
|
||||
| `workflow.error` | DirLocal | ➕ ADD | Hook execution failure |
|
||||
|
||||
---
|
||||
|
||||
## 10. Starlark Module Updates
|
||||
|
||||
### `server/sandbox/workflow_module.go` — ✏️ MOD
|
||||
|
||||
The `BuildWorkflowModule` (in `workflow_module.go`, not `modules.go`) currently exists but
|
||||
targets the old channel-based model. It currently only exposes `get_definition`.
|
||||
Rebuild to expose instance-oriented operations:
|
||||
|
||||
```python
|
||||
# Available to extensions with workflow.read or workflow.write permission
|
||||
workflow.get_instance(instance_id) # → instance dict
|
||||
workflow.get_stage_data(instance_id) # → stage_data dict
|
||||
workflow.set_stage_data(instance_id, data) # → merge into stage_data
|
||||
workflow.advance(instance_id) # → trigger advance (write perm)
|
||||
workflow.get_assignments(instance_id) # → assignment list
|
||||
```
|
||||
|
||||
The old `workflow_advance()` function that chat-switchboard's personas called is gone.
|
||||
Extensions call `workflow.advance()` which delegates to the same engine as the HTTP handler.
|
||||
|
||||
---
|
||||
|
||||
## 11. Salvage Map from chat-switchboard v0.39.x
|
||||
|
||||
What was planned there, and what happens to each idea in core:
|
||||
|
||||
### v0.39.0 — Stage Graph Engine + Form Builder
|
||||
|
||||
| Component | Disposition | Core equivalent |
|
||||
|-----------|-------------|-----------------|
|
||||
| `stage_type` enum | ➕ ADD | Adopted directly: `simple`, `dynamic`, `automated` |
|
||||
| `BranchRule` struct | ➕ ADD | Adopted as `branch_rules` JSONB on `workflow_stages` |
|
||||
| Starlark hook integration | ➕ ADD | `starlark_hook` column + engine integration |
|
||||
| Graph engine (`server/engine/graph.go`) | ➕ ADD | `server/workflow/engine.go` in core |
|
||||
| Automated stage runner | ➕ ADD | `server/workflow/automated.go` in core |
|
||||
| Visual form builder (5 Preact components) | 🗑 TRASH *for now* | The form builder was tightly coupled to chat-switchboard's stage editor surface. Core doesn't ship a workflow editor surface (that's an extension). The form *schema* is kernel; the form *builder UI* is a surface package concern. Revisit when a workflow-admin surface is built. |
|
||||
| Stage type badges in UI | 🗑 TRASH | Same — UI is extension territory. |
|
||||
|
||||
### v0.39.1 — Stage Reorder + Bulk Ops
|
||||
|
||||
| Component | Disposition | Core equivalent |
|
||||
|-----------|-------------|-----------------|
|
||||
| Drag-and-drop reorder | 🗑 TRASH | UI concern. The kernel `ReorderStages` endpoint already exists. |
|
||||
| Bulk assignment ops | ➕ ADD (later) | Useful but not blocking. Defer to v0.2.7+. The individual claim/unclaim/cancel endpoints come first. |
|
||||
|
||||
### v0.39.2 — SLA Alerting
|
||||
|
||||
| Component | Disposition | Core equivalent |
|
||||
|-----------|-------------|-----------------|
|
||||
| Periodic SLA scanner | ➕ ADD | Kernel scheduled goroutine (like the existing staleness sweep). Query active instances with `sla_seconds` configured, compute breach from `stage_entered_at`. |
|
||||
| `sla_notified_at` on instances | ➕ ADD | Add to `workflow_instances` schema. Prevents duplicate notifications. |
|
||||
| Notifications on breach | ➕ ADD | Use existing `notifications` table + bus event (`workflow.sla.breached`). |
|
||||
| Webhook on breach | ➕ ADD | Fire workflow's `webhook_url` if configured. |
|
||||
| Pulsing badge animation | 🗑 TRASH | UI concern for a surface package. |
|
||||
|
||||
### v0.39.3 — Visitor Portal
|
||||
|
||||
| Component | Disposition | Core equivalent |
|
||||
|-----------|-------------|-----------------|
|
||||
| Public entry endpoint | ➕ ADD | `/api/v1/workflows/entry/:slug` — kernel handles anonymous session creation + token issuance. |
|
||||
| Session resume via token | ➕ ADD | `entry_token` on `workflow_instances` + `GetInstanceByToken` store method. |
|
||||
| Branded entry page | 🗑 TRASH | Surface package. The kernel stores `branding` JSONB — a portal surface reads it. |
|
||||
| Progress indicator | 🗑 TRASH | Surface package reads stage list, computes "step N of M" locally. |
|
||||
| Email notifications | 🗑 TRASH *for now* | Requires SMTP infrastructure. Defer to post-MVP or make it a connection-based extension (use ext_connections for SMTP config, fire via Starlark hook). |
|
||||
|
||||
### v0.39.4 — Templates + Clone
|
||||
|
||||
| Component | Disposition | Core equivalent |
|
||||
|-----------|-------------|-----------------|
|
||||
| Clone endpoint | ➕ ADD | `POST /api/v1/workflows/:id/clone` — deep copy workflow + stages. Straightforward. |
|
||||
| Built-in templates table | 🗑 TRASH | Core doesn't ship opinionated templates. Templates are workflow packages (`.pkg` archives). A "template gallery" is a surface. |
|
||||
| Template picker UI | 🗑 TRASH | Surface concern. |
|
||||
|
||||
### v0.39.5 — Analytics
|
||||
|
||||
| Component | Disposition | Core equivalent |
|
||||
|-----------|-------------|-----------------|
|
||||
| Analytics query endpoint | ➕ ADD (later) | `GET /api/v1/workflows/:id/analytics?period=7d` — kernel exposes raw metrics (throughput, cycle time, stage dwell, SLA compliance) derived from instance + assignment timestamps. Defer to v0.2.8+ or v0.3.x. |
|
||||
| Analytics dashboard UI | 🗑 TRASH | Surface package. |
|
||||
|
||||
---
|
||||
|
||||
## 12. Implementation Order
|
||||
|
||||
All items within v0.2.6. Ordered by dependency:
|
||||
|
||||
### Phase A: Schema + Models
|
||||
|
||||
1. ✏️ Edit `007_workflows.sql`: drop `persona_id`, `history_mode`; add `audience`, `stage_type`, `starlark_hook`, `branch_rules`; rename `transition_rules` → `stage_config`; update `stage_mode` CHECK.
|
||||
2. ✏️ Edit `007_workflows.sql` (same file): add `workflow_instances` and `workflow_assignments` tables.
|
||||
3. ✏️ Edit `007_workflows.sql` (SQLite dialect): mirror changes.
|
||||
4. ✏️ Update `server/models/workflow.go`: remove trashed fields, add new structs, update constants.
|
||||
|
||||
### Phase B: Store Layer
|
||||
|
||||
5. ✏️ Update `server/store/workflow_iface.go`: add instance + assignment methods.
|
||||
6. ➕ Implement Postgres store: `server/store/postgres/workflow_instances.go`, `workflow_assignments.go`.
|
||||
7. ➕ Implement SQLite store: `server/store/sqlite/workflow_instances.go`, `workflow_assignments.go`.
|
||||
|
||||
### Phase C: Engine
|
||||
|
||||
8. ✏️ Update `server/workflow/routing.go`: branch_rules evaluation, starlark_hook integration.
|
||||
9. ➕ Add `server/workflow/engine.go`: advance lifecycle orchestration.
|
||||
10. ➕ Add `server/workflow/automated.go`: automated stage execution + cycle guard.
|
||||
11. ✏️ Update `server/handlers/workflow_hooks.go`: rename channel → instance references.
|
||||
|
||||
### Phase D: Handlers + Routes
|
||||
|
||||
12. ✏️ Update `server/handlers/workflows.go`: stage CRUD field changes.
|
||||
13. ✏️ Update `server/handlers/workflow_packages.go`: package struct field changes.
|
||||
14. ➕ Add `server/handlers/workflow_instances.go`: instance lifecycle endpoints.
|
||||
15. ➕ Add `server/handlers/workflow_assignments.go`: assignment queue endpoints.
|
||||
16. ✏️ Wire new routes in `server/main.go`.
|
||||
|
||||
### Phase E: Events + Starlark
|
||||
|
||||
17. ✏️ Update `server/events/types.go`: add new workflow events.
|
||||
18. ✏️ Update `server/sandbox/modules.go`: rebuild workflow Starlark module.
|
||||
|
||||
### Phase F: Background Jobs
|
||||
|
||||
19. ➕ Add SLA scanner goroutine (check active instances, fire notifications + events on breach).
|
||||
20. ➕ Add staleness sweep for workflow instances (reuse pattern from chat-switchboard).
|
||||
|
||||
### Phase G: Verification
|
||||
|
||||
21. ➕ Integration tests: instance lifecycle, stage advancement, branching, automated stages, assignments, SLA breach.
|
||||
22. `go build ./...` clean.
|
||||
23. Update ICD (OpenAPI spec) with new endpoints.
|
||||
24. Update ROADMAP.md + CHANGELOG.md.
|
||||
|
||||
---
|
||||
|
||||
## 13. What We're NOT Doing (Explicit Deferrals)
|
||||
|
||||
| Item | Why | Revisit |
|
||||
|------|-----|---------|
|
||||
| Visual form builder UI | Surface concern, no workflow-admin surface yet | When a workflow-admin surface ships |
|
||||
| Drag-and-drop stage reorder UI | Surface concern | Same |
|
||||
| Email notifications | Needs SMTP infrastructure or connection-based ext | Post-MVP |
|
||||
| Built-in workflow templates | Core doesn't ship opinionated content | Package gallery |
|
||||
| Analytics dashboard | Nice-to-have, kernel endpoint can come first | v0.3.x |
|
||||
| Bulk assignment operations | Individual ops first | v0.2.7+ |
|
||||
| Workflow chaining (`on_complete`) | Already in schema, needs engine wiring | v0.2.7 |
|
||||
| Visitor portal surface | Surface package, not kernel | Extension track |
|
||||
|
||||
---
|
||||
|
||||
## 14. Migration Policy Reminder
|
||||
|
||||
From the design-decisions log:
|
||||
|
||||
> **No new migrations pre-MVP.** Edit existing migration SQL files in place.
|
||||
> No migration chains until schema is in production.
|
||||
|
||||
For this redesign:
|
||||
- **`007_workflows.sql`**: Edit in place for column changes AND add new tables to the same file.
|
||||
- **No `012_*.sql`**: Everything goes in 007.
|
||||
- **Both dialects**: Postgres and SQLite must be kept in sync.
|
||||
|
||||
The only time a new numbered migration file is created is when a truly new,
|
||||
unrelated subsystem is added (like 011_triggers.sql was for the trigger system).
|
||||
Workflow instances and assignments are part of the workflow subsystem → they go in 007.
|
||||
|
||||
---
|
||||
|
||||
## 15. Public Surfaces — Kernel Capability, Not Workflow Feature
|
||||
|
||||
### The problem with workflow-owned public access
|
||||
|
||||
Chat-switchboard treated public access as a binary workflow toggle: `entry_mode: public_link`
|
||||
made the whole workflow public. But real workflows alternate audiences — internal setup →
|
||||
public-facing customer form → internal review → public confirmation page. And public access
|
||||
isn't even a workflow-only need: feedback forms, status pages, and surveys all need anonymous
|
||||
sessions without being workflows.
|
||||
|
||||
### Per-stage audience (the v0.2.6 solution)
|
||||
|
||||
The `audience` field on `workflow_stages` is the source of truth:
|
||||
|
||||
| Audience | Who interacts | Auth required | Example |
|
||||
|----------|--------------|---------------|---------|
|
||||
| `team` | Authenticated team members | JWT | Internal triage, setup, review |
|
||||
| `public` | Anonymous visitors | Entry token | Customer intake form, confirmation page |
|
||||
| `system` | Nobody (automated) | N/A | API enrichment, routing decision |
|
||||
|
||||
A single workflow freely alternates:
|
||||
|
||||
```
|
||||
Stage 0: "Setup" audience=team (agent configures parameters)
|
||||
Stage 1: "Customer Form" audience=public (customer fills out intake)
|
||||
Stage 2: "Internal Review" audience=team (team reviews submission)
|
||||
Stage 3: "Confirmation" audience=public (customer sees result)
|
||||
```
|
||||
|
||||
The engine enforces boundaries:
|
||||
- When the instance enters a `public` stage, the visitor's token grants access. Team members
|
||||
can also see it (they have elevated access).
|
||||
- When the instance enters a `team` stage, the visitor's view freezes. They see "being
|
||||
processed" or whatever the portal surface shows. The token is still valid for resumption
|
||||
when the next `public` stage arrives.
|
||||
- When the instance enters a `system` stage, nobody interacts — the automated hook fires
|
||||
and the engine advances.
|
||||
|
||||
### The `entry_mode` column
|
||||
|
||||
Stays on the `workflows` table but becomes a derived convenience flag. If any stage has
|
||||
`audience = 'public'`, the workflow is public-entry eligible. The kernel can auto-compute
|
||||
this when stages are saved, or treat it as an explicit admin toggle that gates whether
|
||||
public stages are actually reachable. Either way, it's no longer the primary access control
|
||||
mechanism — `audience` on each stage is.
|
||||
|
||||
### Platform-level public access (v0.2.7+ concern)
|
||||
|
||||
The broader vision: public access as a **package-level manifest capability** so any surface
|
||||
(not just workflows) can serve anonymous visitors. A package declares `"public": true` in
|
||||
its manifest, and the kernel mounts a public route namespace (`/p/:package_slug/*`) with
|
||||
anonymous session middleware, token issuance, and rate limiting. Workflows consume this
|
||||
capability — they don't own it.
|
||||
|
||||
For v0.2.6, the workflow-specific public entry routes are sufficient:
|
||||
```
|
||||
POST /api/v1/workflows/entry/:slug → StartPublic
|
||||
GET /api/v1/workflows/entry/:token → ResumePublic
|
||||
POST /api/v1/workflows/entry/:token/advance → AdvancePublic
|
||||
```
|
||||
|
||||
The anonymous session management (entry_token on `workflow_instances`, IP rate limiting)
|
||||
lives in the workflow handler for now. Generalization to a platform-level `public_sessions`
|
||||
table happens when non-workflow surfaces need it.
|
||||
|
||||
### Visitor view contract
|
||||
|
||||
When a public stage is active, the kernel API returns only what the visitor should see:
|
||||
- The current stage's `form_template` (if mode is `form`)
|
||||
- The stage name and ordinal (for progress indicators)
|
||||
- Accumulated `stage_data` keys marked as `visitor_visible` (future: field-level ACL)
|
||||
- The `branding` JSONB from the workflow
|
||||
|
||||
Internal stages, team assignments, review data, and other instances' data are never
|
||||
exposed through the token-authenticated endpoints. The surface package renders whatever
|
||||
the kernel returns — it doesn't need to filter.
|
||||
|
||||
---
|
||||
|
||||
## 16. Branch Rules — Routing, Skipping, and Convergence
|
||||
|
||||
### How branch_rules work
|
||||
|
||||
Each stage has a `branch_rules` JSONB array. On stage completion, the engine evaluates rules
|
||||
top-to-bottom against accumulated `stage_data`. First match wins. No match → ordinal + 1.
|
||||
|
||||
```json
|
||||
[
|
||||
{"field": "priority", "op": "eq", "value": "urgent", "target_stage": "Emergency Review"},
|
||||
{"field": "amount", "op": "gt", "value": 10000, "target_stage": "Manager Approval"},
|
||||
{"field": "type", "op": "in", "value": ["a","b"], "target_stage": "Fast Track"}
|
||||
]
|
||||
```
|
||||
|
||||
`target_stage` accepts either a **stage name** (case-insensitive) or a **numeric ordinal**.
|
||||
The engine tries name resolution first, falls back to numeric. This is already implemented
|
||||
in `routing.go` → `resolveTarget()`.
|
||||
|
||||
### Skipping stages
|
||||
|
||||
Branch rules can target any stage, not just the next one. If a workflow has stages
|
||||
0→1→2→3→4 and stage 1's rules say `target_stage: "Stage 4"`, stages 2 and 3 are skipped
|
||||
for that instance. The engine doesn't care about gaps — it sets `current_stage` to whatever
|
||||
the rule resolved to.
|
||||
|
||||
Linear workflows (no branch_rules on any stage) advance 0→1→2→3→4 by the ordinal + 1
|
||||
fallback. Adding a single branch rule to any stage introduces conditional skipping without
|
||||
changing the linear stages.
|
||||
|
||||
### Convergence (diamond patterns)
|
||||
|
||||
Two different branches can target the same downstream stage:
|
||||
|
||||
```
|
||||
Stage 0: Intake Form
|
||||
branch_rules: [
|
||||
{field: "region", op: "eq", value: "US", target_stage: "US Processing"},
|
||||
{field: "region", op: "eq", value: "EU", target_stage: "EU Processing"}
|
||||
]
|
||||
|
||||
Stage 1: US Processing (ordinal 1)
|
||||
branch_rules: [{field: "*", op: "exists", target_stage: "Final Review"}]
|
||||
(always converge after processing)
|
||||
|
||||
Stage 2: EU Processing (ordinal 2)
|
||||
branch_rules: [{field: "*", op: "exists", target_stage: "Final Review"}]
|
||||
(always converge after processing)
|
||||
|
||||
Stage 3: Final Review (ordinal 3)
|
||||
(both branches land here)
|
||||
```
|
||||
|
||||
No special syntax needed. The routing engine doesn't track "which branch am I on" — it just
|
||||
resolves the target and moves the instance there. The accumulated `stage_data` carries
|
||||
everything downstream stages need to know about what happened upstream.
|
||||
|
||||
### Backward jumps
|
||||
|
||||
Branch rules can also target earlier stages (lower ordinals) for retry/correction loops.
|
||||
The cycle guard (max 10 consecutive automated stages) in `automated.go` prevents infinite
|
||||
loops for automated stages. For human-facing stages, backward jumps are intentional — the
|
||||
human breaks the cycle by submitting different data.
|
||||
|
||||
### Operators
|
||||
|
||||
Full set, inherited from the existing `routing.go` implementation:
|
||||
|
||||
| Op | Description | Example |
|
||||
|----|-------------|---------|
|
||||
| `eq` | Loose equality (string comparison) | `"status" eq "approved"` |
|
||||
| `neq` | Not equal | `"status" neq "rejected"` |
|
||||
| `gt` | Greater than (numeric) | `"amount" gt 10000` |
|
||||
| `lt` | Less than (numeric) | `"amount" lt 100` |
|
||||
| `gte` | Greater or equal | `"score" gte 80` |
|
||||
| `lte` | Less or equal | `"score" lte 20` |
|
||||
| `in` | Value in array | `"category" in ["a","b","c"]` |
|
||||
| `contains` | Substring match | `"notes" contains "urgent"` |
|
||||
| `exists` | Field present in stage_data | `"approval_date" exists` |
|
||||
| `not_exists` | Field absent | `"rejection_reason" not_exists` |
|
||||
@@ -1,111 +0,0 @@
|
||||
# Workflow Engine — Design
|
||||
|
||||
The workflow engine provides multi-stage, form-driven processes with team
|
||||
validation, SLA enforcement, and public entry. Workflows are kernel primitives;
|
||||
workflow **surfaces** (admin UI, public landing pages) are extension packages.
|
||||
|
||||
---
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Workflow Definition
|
||||
|
||||
A workflow is a named process template owned by a team. Each workflow defines an
|
||||
ordered list of **stages** that instances progress through.
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `name` | Human-readable workflow name |
|
||||
| `slug` | URL-safe identifier (unique per scope) |
|
||||
| `scope` | Owning team or org |
|
||||
| `stages` | Ordered list of stage definitions |
|
||||
| `entry_mode` | `internal` (authenticated users) or `public_link` (landing page) |
|
||||
| `sla_hours` | Optional SLA deadline for instance completion |
|
||||
|
||||
### Stage Types
|
||||
|
||||
Each stage has a `mode` that determines how participants interact:
|
||||
|
||||
| Mode | Behavior |
|
||||
|------|----------|
|
||||
| `form_only` | Structured form submission. Stage advances when form is complete. |
|
||||
| `form_chat` | Form plus threaded discussion. Useful for review with comments. |
|
||||
| `review` | Approval/rejection gate. Designated reviewers must sign off. |
|
||||
| `custom` | Delegates entirely to a surface package. Enables extension-driven UIs. |
|
||||
|
||||
Stages declare an `assignee_mode` (individual, team, role-based) and optional
|
||||
form schemas (JSON Schema validated at submission time).
|
||||
|
||||
### Workflow Instances
|
||||
|
||||
An instance is a running execution of a workflow definition. It tracks:
|
||||
|
||||
- Current stage index and overall status (`active`, `completed`, `cancelled`, `stale`)
|
||||
- Per-stage completion records with timestamps and actor IDs
|
||||
- Form data submitted at each stage
|
||||
- Assignment and claim history
|
||||
|
||||
Instances use optimistic locking (`claimed_by` + `claimed_at`) to prevent
|
||||
concurrent stage advancement. A claim expires after a configurable timeout.
|
||||
|
||||
---
|
||||
|
||||
## Multi-Party Validation (Signoff Table)
|
||||
|
||||
The `workflow_signoffs` table enables multi-party approval gates:
|
||||
|
||||
| Column | Purpose |
|
||||
|--------|---------|
|
||||
| `instance_id` | Which instance |
|
||||
| `stage_index` | Which stage requires signoff |
|
||||
| `user_id` | Who signed |
|
||||
| `decision` | `approved` or `rejected` |
|
||||
| `comment` | Optional rationale |
|
||||
| `signed_at` | Timestamp |
|
||||
|
||||
The engine checks signoff requirements before advancing past a `review` stage.
|
||||
Requirements are configurable: unanimous, majority, or N-of-M.
|
||||
|
||||
---
|
||||
|
||||
## SLA Scanner + Staleness Sweep
|
||||
|
||||
Two periodic background jobs maintain workflow health:
|
||||
|
||||
**SLA Scanner** — Runs on a configurable interval. Identifies instances that have
|
||||
exceeded their workflow's `sla_hours` deadline. Fires a `workflow.sla.breached`
|
||||
event (consumed by notification extensions or triggers).
|
||||
|
||||
**Staleness Sweep** — Identifies instances that have been idle (no stage
|
||||
advancement) beyond a configurable threshold. Marks them as `stale` and fires
|
||||
`workflow.instance.stale`. Stale instances can be resumed or cancelled.
|
||||
|
||||
Both jobs are distributed-safe: all cluster nodes run them, but operations are
|
||||
idempotent (UPDATE with WHERE guards).
|
||||
|
||||
---
|
||||
|
||||
## Public Entry
|
||||
|
||||
Workflows with `entry_mode: public_link` are accessible at:
|
||||
|
||||
```
|
||||
/w/:scope/:slug
|
||||
```
|
||||
|
||||
The landing page renders the first stage's form without requiring authentication.
|
||||
On submission, the kernel creates an instance and stores the form data. Subsequent
|
||||
stages may require authentication depending on their assignee configuration.
|
||||
|
||||
Public entry enables use cases like intake forms, support requests, and
|
||||
application submissions where the initiator is external.
|
||||
|
||||
---
|
||||
|
||||
## Extension Points
|
||||
|
||||
- **Surface packages** provide workflow admin UIs and participant views
|
||||
- **Trigger extensions** can react to workflow events (`instance.created`,
|
||||
`stage.advanced`, `sla.breached`, `instance.completed`)
|
||||
- **Custom stage mode** delegates rendering and advancement logic entirely to
|
||||
an extension, enabling arbitrary UIs within a workflow stage
|
||||
@@ -1,290 +0,0 @@
|
||||
# Design: PG-Backed Cluster Registry & Self-Assembling Mesh
|
||||
|
||||
**Status:** Proposed — Pre-MVP / MVP wrap-up
|
||||
**Author:** Jeff
|
||||
**Date:** 2026-03-30
|
||||
**Scope:** Kernel primitive — zero domain awareness
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Armature-core is tightly coupled to PostgreSQL. Scaling horizontally requires instance coordination: peer discovery, health monitoring, ephemeral event routing, and (optionally) leader election. Traditional HA solutions (Raft, etcd, Consul) introduce a second consensus layer on top of PG — doubling operational complexity for a system that already has serializable transactions and LISTEN/NOTIFY.
|
||||
|
||||
## Principle
|
||||
|
||||
PG is already the consensus system. Use it as the sole coordinator for service discovery, health, pub/sub, and cluster state. Zero new infrastructure dependencies.
|
||||
|
||||
---
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Node Registry (Unlogged Table)
|
||||
|
||||
```sql
|
||||
CREATE UNLOGGED TABLE IF NOT EXISTS node_registry (
|
||||
node_id TEXT PRIMARY KEY,
|
||||
endpoint TEXT NOT NULL,
|
||||
seq SERIAL,
|
||||
registered_at TIMESTAMPTZ DEFAULT now(),
|
||||
heartbeat TIMESTAMPTZ DEFAULT now(),
|
||||
stats JSONB DEFAULT '{}'
|
||||
);
|
||||
```
|
||||
|
||||
**Why UNLOGGED:** No WAL overhead, visible to all connections, survives session disconnect. Contents do NOT survive a PG crash — but a PG crash means all nodes are dead anyway. Clean slate on recovery is the correct behavior; all nodes re-register on restart.
|
||||
|
||||
**Why not TEMPORARY:** PG temporary tables are session-scoped and invisible to other connections. Useless for cross-instance coordination.
|
||||
|
||||
### 2. Node Lifecycle
|
||||
|
||||
#### Startup
|
||||
|
||||
```
|
||||
boot → connect PG → register self → read peer list →
|
||||
subscribe LISTEN/NOTIFY channels → open WS to clients → ready
|
||||
```
|
||||
|
||||
```sql
|
||||
-- Self-registration (atomic, idempotent)
|
||||
INSERT INTO node_registry (node_id, endpoint)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (node_id) DO UPDATE
|
||||
SET endpoint = EXCLUDED.endpoint,
|
||||
registered_at = now(),
|
||||
heartbeat = now(),
|
||||
stats = '{}';
|
||||
```
|
||||
|
||||
`node_id` is generated at startup: `hostname + PID` or a UUID. Deterministic IDs enable restart-in-place without orphaned rows.
|
||||
|
||||
#### Heartbeat Tick (every N seconds, e.g., 10s)
|
||||
|
||||
Each node performs two operations per tick:
|
||||
|
||||
```go
|
||||
// 1. Update own heartbeat + stats
|
||||
stats := collectStats() // see §5
|
||||
db.Exec(`UPDATE node_registry SET heartbeat = now(), stats = $2 WHERE node_id = $1`,
|
||||
nodeID, stats)
|
||||
|
||||
// 2. Sweep stale entries (idempotent — safe for concurrent execution)
|
||||
db.Exec(`DELETE FROM node_registry WHERE heartbeat < now() - interval '30 seconds'`)
|
||||
```
|
||||
|
||||
The sweep is the distributed health check. Every node runs it. Multiple nodes deleting the same stale row is a no-op. No ring topology required — the sweep is the safety net that guarantees eventual cleanup regardless of which nodes are alive.
|
||||
|
||||
#### Self-Eviction
|
||||
|
||||
If a node's own heartbeat UPDATE returns 0 rows affected, it has been swept by a peer:
|
||||
|
||||
```go
|
||||
result := db.Exec(`UPDATE node_registry SET heartbeat = now() WHERE node_id = $1`, nodeID)
|
||||
if result.RowsAffected() == 0 {
|
||||
log.Error("evicted from registry, shutting down")
|
||||
os.Exit(1)
|
||||
}
|
||||
```
|
||||
|
||||
Kubernetes restarts the process. On boot it re-registers as a fresh node. The restart loop IS the recovery mechanism.
|
||||
|
||||
### 3. Leaderless by Default
|
||||
|
||||
No `role` column. No primary/replica distinction. All nodes are equal peers. PG is the sole coordinator.
|
||||
|
||||
**If a leader is ever needed** (future use case), it's a small lift:
|
||||
|
||||
```sql
|
||||
ALTER TABLE node_registry ADD COLUMN role TEXT DEFAULT 'peer';
|
||||
|
||||
-- Atomic leader claim: first writer wins
|
||||
UPDATE node_registry SET role = 'primary'
|
||||
WHERE node_id = $1
|
||||
AND NOT EXISTS (SELECT 1 FROM node_registry WHERE role = 'primary');
|
||||
```
|
||||
|
||||
No quorum, no voting, no term numbers. PG serialization handles it. But the current design intentionally avoids this — consistent with the existing pattern where scheduled tasks use first-to-mark-wins execution, not leader assignment.
|
||||
|
||||
### 4. Realtime Event Routing (Two Tiers)
|
||||
|
||||
#### Tier 1: Durable Events (messages, state changes)
|
||||
|
||||
These are PG writes. Fan-out via `LISTEN/NOTIFY`:
|
||||
|
||||
```
|
||||
User A sends message → Instance 1 writes to PG →
|
||||
pg_notify('channel:xyz', '{"type":"message","id":"..."}') →
|
||||
All instances receive → push to local WS clients subscribed to channel:xyz
|
||||
```
|
||||
|
||||
This maps directly to the v0.5.0 `realtime.publish()` Starlark primitive. Kernel implementation is `pg_notify(channel, payload)`.
|
||||
|
||||
#### Tier 2: Ephemeral Events (typing indicators, presence, cursor position)
|
||||
|
||||
These NEVER hit durable storage.
|
||||
|
||||
**Phase 1 (MVP):** Use PG LISTEN/NOTIFY for ephemeral events too.
|
||||
|
||||
```
|
||||
User A types → Instance 1 WS handler →
|
||||
pg_notify('ephemeral:xyz', '{"type":"typing","user":"A"}') →
|
||||
Instance 2 receives → pushes to User B's WS
|
||||
Instance 3 receives → pushes to User C's WS
|
||||
```
|
||||
|
||||
PG NOTIFY payload limit is 8KB. A typing indicator is ~60 bytes. At homelab scale (3 nodes, dozens of users) this is a non-issue. One codepath, one transport, zero new infrastructure.
|
||||
|
||||
**Phase 2 (Post-MVP, if needed):** Direct instance-to-instance mesh for ephemeral events.
|
||||
|
||||
- Peer endpoints are already in the registry
|
||||
- Each node dials peers discovered from the registry on startup and on peer list changes
|
||||
- Ephemeral events route over the mesh; durable events stay on PG NOTIFY
|
||||
- The `realtime.publish()` Starlark API does not change — kernel swaps the underlying transport
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ PG (source of truth) │
|
||||
│ ┌───────────┐ ┌──────────────┐ │
|
||||
│ │ node_ │ │ LISTEN/ │ │
|
||||
│ │ registry │ │ NOTIFY │ │
|
||||
│ └───────────┘ └──────────────┘ │
|
||||
└──────┬──────────────┬────────────┘
|
||||
│ durable │
|
||||
┌────────────┼──────────────┼────────────┐
|
||||
│ │ │ │
|
||||
┌────┴────┐ ┌───┴─────┐ ┌────┴─────┐
|
||||
│ Node 1 │◄─┤ Node 2 ├─►│ Node 3 │
|
||||
│ User A │ │ User B │ │ User C │
|
||||
└─────────┘ └─────────┘ └──────────┘
|
||||
◄──── ephemeral mesh ────►
|
||||
(Phase 2, if needed)
|
||||
```
|
||||
|
||||
**Channel subscription model (Phase 1):** Broadcast and discard. Every node receives every event, checks local WebSocket subscriptions, drops if irrelevant. At 3 nodes this is the correct answer — trivial, no subscription state to sync, fully leaderless.
|
||||
|
||||
### 5. Stats Collection & Admin Dashboard
|
||||
|
||||
Each heartbeat tick publishes runtime stats in the `stats` JSONB column:
|
||||
|
||||
```go
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
|
||||
stats := map[string]any{
|
||||
"goroutines": runtime.NumGoroutine(),
|
||||
"heap_alloc": m.HeapAlloc,
|
||||
"heap_sys": m.HeapSys,
|
||||
"gc_cycles": m.NumGC,
|
||||
"gc_pause_ns": m.PauseNs[(m.NumGC+255)%256],
|
||||
"uptime_sec": time.Since(startTime).Seconds(),
|
||||
"ws_clients": wsHub.Count(),
|
||||
"extensions": sandbox.LoadedCount(),
|
||||
}
|
||||
```
|
||||
|
||||
Admin dashboard API endpoint:
|
||||
|
||||
```sql
|
||||
SELECT node_id, endpoint, registered_at, heartbeat, stats
|
||||
FROM node_registry
|
||||
ORDER BY seq;
|
||||
```
|
||||
|
||||
**ICD envelope:** `{"data": [...]}` — consistent with list endpoint convention.
|
||||
|
||||
The admin dashboard extension renders one card per node. One node = one card. Three nodes = three cards. The extension has zero awareness of clustering — it reads a list and renders it. This is the extensibility proof working as designed.
|
||||
|
||||
Since `stats` is JSONB, future additions (mesh peer latency, extension execution counts, queue depths) require no schema migration. The dashboard extension renders whatever keys are present.
|
||||
|
||||
### 6. Self-Assembling Mesh Properties
|
||||
|
||||
The mesh builds itself from the registry with zero configuration:
|
||||
|
||||
| Event | Behavior |
|
||||
|---|---|
|
||||
| Node starts | Inserts into registry → peers discover it on next heartbeat tick |
|
||||
| Node dies | Heartbeat goes stale → swept by peers → mesh shrinks |
|
||||
| Node restarts | Re-registers → peers discover it → mesh restores |
|
||||
| Scale up (K8s) | New replicas register → mesh grows automatically |
|
||||
| Scale down (K8s) | Terminated nodes go stale → swept → mesh shrinks |
|
||||
| PG crash | All nodes lose connection → all exit → K8s restarts all → clean re-registration |
|
||||
|
||||
No config files listing peers. No seed nodes. No service discovery sidecar. No bootstrap ceremony. The registry table IS the service mesh control plane.
|
||||
|
||||
---
|
||||
|
||||
## What This Enables (Future)
|
||||
|
||||
These are NOT in scope for this work. Listed to validate the design supports them without rearchitecting.
|
||||
|
||||
- **Work distribution:** Primary (if elected) assigns extension execution shards via registry metadata. Replicas poll for assignments. No message queue.
|
||||
- **Realtime routing (v0.5.0):** When a node owns a pub/sub channel, it registers ownership in PG. Other nodes route publishes to the owner. Node dies → sweep clears routes → subscribers reconnect.
|
||||
- **Rolling deploys:** New version registers, old version's heartbeat goes stale, clean handoff with zero coordination protocol.
|
||||
- **Session affinity:** Registry tracks which node holds a user's WS connection. Targeted event delivery instead of broadcast (optimization for scale).
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
### Migration
|
||||
|
||||
Pre-MVP: fold `CREATE UNLOGGED TABLE` into existing schema initialization. No new migration file needed. DB rebuild required (acceptable — no install base).
|
||||
|
||||
### Configuration
|
||||
|
||||
| Setting | Default | Notes |
|
||||
|---|---|---|
|
||||
| `CLUSTER_NODE_ID` | `hostname-PID` | Override for deterministic identity across restarts |
|
||||
| `CLUSTER_HEARTBEAT_INTERVAL` | `10s` | Tick frequency |
|
||||
| `CLUSTER_STALE_THRESHOLD` | `30s` | 3x heartbeat = stale |
|
||||
| `CLUSTER_ENDPOINT` | auto-detect | Advertised address for peer mesh (Phase 2) |
|
||||
|
||||
### Single-Node Behavior
|
||||
|
||||
When only one node is registered, the system behaves identically to pre-cluster armature. The registry has one row. LISTEN/NOTIFY delivers events back to the same instance. No special-casing required.
|
||||
|
||||
### Health Endpoint Integration
|
||||
|
||||
`GET /health` includes cluster status:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "healthy",
|
||||
"node_id": "node-abc-1234",
|
||||
"cluster": {
|
||||
"size": 3,
|
||||
"peers": ["node-def-5678", "node-ghi-9012"],
|
||||
"heartbeat_age_ms": 2340
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Satisfies the v0.6.0 MVP health monitoring requirement.
|
||||
|
||||
---
|
||||
|
||||
## Rejected Alternatives
|
||||
|
||||
| Alternative | Why rejected |
|
||||
|---|---|
|
||||
| etcd / Consul | Second consensus layer on top of PG. Doubles operational complexity for a system already tightly coupled to PG. Violates KISS. |
|
||||
| Redis pub/sub for ephemeral events | Second stateful service. Two failure domains, two connection pools, two things to monitor. PG NOTIFY handles the same job at homelab scale. |
|
||||
| Raft implementation in Go | Massive complexity for a problem PG serializable transactions already solve. |
|
||||
| Ring topology monitoring | Each node watches the one above it. Adjacent failures create blind spots. Sweep-all is simpler and has no edge cases. |
|
||||
| Leader election at startup | Unnecessary. Leaderless design with first-to-mark-wins task execution already works. Leader election is a future option, not a requirement. |
|
||||
|
||||
---
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] `node_registry` unlogged table in schema init
|
||||
- [ ] Node registration on startup
|
||||
- [ ] Heartbeat tick with stats collection and stale sweep
|
||||
- [ ] Self-eviction on 0-rows-affected heartbeat
|
||||
- [ ] PG LISTEN/NOTIFY integration for realtime events
|
||||
- [ ] Admin API endpoint: `GET /api/admin/cluster`
|
||||
- [ ] Admin dashboard extension: cluster node cards
|
||||
- [ ] Health endpoint cluster status
|
||||
- [ ] Configuration via environment variables
|
||||
- [ ] Single-node regression test (no behavioral change)
|
||||
- [ ] Multi-node integration test (Docker Compose, 3 instances)
|
||||
@@ -1,306 +0,0 @@
|
||||
# DESIGN — Native mTLS
|
||||
|
||||
**Version:** v0.6.7
|
||||
**Status:** Implemented
|
||||
**Author:** Jeff / Claude session 2026-03-31
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
The existing `MTLSProxyProvider` assumes a TLS-terminating reverse proxy
|
||||
(Traefik, nginx, Istio) sits in front of the Go binary. Identity arrives
|
||||
via injected HTTP headers (`X-SSL-Client-CN`, etc.). The backend never
|
||||
participates in the TLS handshake.
|
||||
|
||||
A target deployment class — systemd units + podman on bare metal or VMs —
|
||||
has no reverse proxy. All connections must be mTLS end-to-end:
|
||||
|
||||
- **Client → server:** browser/CLI presents a user client cert
|
||||
- **Node → node:** cluster peers mutually authenticate for heartbeat,
|
||||
realtime pub/sub, and registry sync
|
||||
|
||||
The Go binary must terminate TLS itself and extract identity directly
|
||||
from the verified peer certificate.
|
||||
|
||||
---
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Certificate revocation (CRL/OCSP). Deferred — short-lived certs +
|
||||
restart is sufficient pre-1.0.
|
||||
- Automatic cert rotation. Operators restart the process after replacing
|
||||
certs on disk.
|
||||
- Acting as a CA at runtime. Cert issuance is an offline operator task.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### TLS Server Mode
|
||||
|
||||
New config knob `TLS_MODE` with three values:
|
||||
|
||||
| Value | Behavior |
|
||||
|----------|----------------------------------------------------|
|
||||
| `none` | Plain HTTP. Current default. Use behind a proxy. |
|
||||
| `server` | Server-side TLS only. No client cert required. |
|
||||
| `mtls` | Mutual TLS. Client cert required and verified. |
|
||||
|
||||
When `TLS_MODE` is `server` or `mtls`, the binary calls
|
||||
`http.Server.ListenAndServeTLS` with paths from `TLS_CERT` and `TLS_KEY`.
|
||||
|
||||
When `TLS_MODE` is `mtls`, `tls.Config` is built with:
|
||||
|
||||
```go
|
||||
&tls.Config{
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
ClientCAs: loadCACertPool(cfg.TLSCA),
|
||||
MinVersion: tls.VersionTLS13,
|
||||
}
|
||||
```
|
||||
|
||||
TLS 1.3 is the floor. No cipher suite configuration exposed — Go's
|
||||
defaults for 1.3 are non-negotiable and correct.
|
||||
|
||||
### Auth Provider: MTLSNativeProvider
|
||||
|
||||
Completely separate from `MTLSProxyProvider`. No shared code paths for
|
||||
cert extraction. They share only downstream helpers.
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ Shared helpers │
|
||||
│ ParseDN() · FingerprintCert() · ProvisionUser() │
|
||||
└────────────────┬──────────────┬──────────────────┘
|
||||
│ │
|
||||
┌────────────┴───┐ ┌──────┴────────────┐
|
||||
│ MTLSProxy │ │ MTLSNative │
|
||||
│ Provider │ │ Provider │
|
||||
│ │ │ │
|
||||
│ Reads headers: │ │ Reads TLS: │
|
||||
│ X-SSL-Client-* │ │ PeerCertificates │
|
||||
└────────────────┘ └───────────────────┘
|
||||
```
|
||||
|
||||
**MTLSNativeProvider.Authenticate():**
|
||||
|
||||
```go
|
||||
func (p *MTLSNativeProvider) Authenticate(c *gin.Context, s store.Stores) (*Result, error) {
|
||||
if c.Request.TLS == nil || len(c.Request.TLS.PeerCertificates) == 0 {
|
||||
return nil, ErrNoCert
|
||||
}
|
||||
peer := c.Request.TLS.PeerCertificates[0]
|
||||
|
||||
cn := peer.Subject.CommonName // → username
|
||||
dn := peer.Subject.String() // → metadata
|
||||
fp := FingerprintCert(peer) // sha256(DER) → external_id
|
||||
|
||||
return p.resolveOrProvision(c.Request.Context(), s, cn, dn, fp)
|
||||
}
|
||||
```
|
||||
|
||||
`FingerprintCert` computes `sha256(cert.Raw)` hex-encoded. This is the
|
||||
stable identity anchor — certs can be reissued with the same CN but will
|
||||
get a new fingerprint, creating a new user unless the operator explicitly
|
||||
maps them.
|
||||
|
||||
**Why Option B (two providers, not a mode switch):**
|
||||
|
||||
The security properties differ fundamentally. The proxy provider trusts
|
||||
headers — if deployed without a proxy that strips client-injected headers,
|
||||
an attacker can forge identity by sending `X-SSL-Client-CN: admin`. The
|
||||
native provider trusts the TLS stack — identity is cryptographically
|
||||
verified before the HTTP layer runs. Mixing these behind a single
|
||||
code path with a runtime switch invites misconfiguration. Two types,
|
||||
selected at startup by `TLS_MODE`, eliminates the ambiguity.
|
||||
|
||||
### Node-to-Node mTLS
|
||||
|
||||
Each Armature node is both server and client:
|
||||
|
||||
- **Server:** accepts connections from peers and user clients on its
|
||||
listen address.
|
||||
- **Client:** dials peers for cluster registry heartbeat, realtime
|
||||
event forwarding, and (future) distributed task coordination.
|
||||
|
||||
When dialing a peer, the node presents its own cert:
|
||||
|
||||
```go
|
||||
peerTLS := &tls.Config{
|
||||
Certificates: []tls.Certificate{nodeKeypair},
|
||||
RootCAs: caCertPool,
|
||||
MinVersion: tls.VersionTLS13,
|
||||
}
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{TLSClientConfig: peerTLS},
|
||||
}
|
||||
```
|
||||
|
||||
Both sides verify against the same CA. A node whose cert is not signed
|
||||
by the cluster CA cannot join. This replaces any need for shared secrets
|
||||
or bearer tokens in the cluster protocol.
|
||||
|
||||
**Interaction with cluster registry (DESIGN-cluster-registry.md):**
|
||||
|
||||
The existing design uses LISTEN/NOTIFY over PostgreSQL for node
|
||||
discovery and an UNLOGGED `node_registry` table for heartbeat. mTLS
|
||||
does not change the discovery mechanism — it secures the HTTP transport
|
||||
between nodes once they've discovered each other. The heartbeat sweep,
|
||||
self-eviction, and leaderless-by-default properties are orthogonal.
|
||||
|
||||
### Cert Topology
|
||||
|
||||
```
|
||||
cluster-ca.crt / cluster-ca.key ← generated once, lives on operator workstation
|
||||
├── node-1.crt + node-1.key ← SAN: node-1.internal, 10.0.0.1
|
||||
├── node-2.crt + node-2.key ← SAN: node-2.internal, 10.0.0.2
|
||||
├── user-jeff.crt + user-jeff.key ← CN=jeff, client auth only
|
||||
└── user-alice.crt + user-alice.key
|
||||
```
|
||||
|
||||
**Node certs** carry both `ServerAuth` and `ClientAuth` extended key
|
||||
usages. SANs include the node's hostname and IP — required because
|
||||
peers may dial by either.
|
||||
|
||||
**User certs** carry only `ClientAuth`. The CN becomes the username.
|
||||
Email can go in the Subject if desired (parsed by `ParseDN()`).
|
||||
|
||||
The CA private key **never** touches a running node. Nodes receive only:
|
||||
`cluster-ca.crt` (for verifying peers), their own `node-N.crt`, and
|
||||
their own `node-N.key`.
|
||||
|
||||
### Cert Provisioning Tooling
|
||||
|
||||
A shell script (`scripts/armature-ca.sh`) wrapping `openssl` is the
|
||||
KISS path. No new binary, no new dependency. Three commands:
|
||||
|
||||
```
|
||||
armature-ca init
|
||||
→ generates cluster-ca.crt + cluster-ca.key in ./ca/
|
||||
|
||||
armature-ca issue-node --name node-1 --san "node-1.internal,10.0.0.1"
|
||||
→ generates node-1.crt + node-1.key in ./nodes/
|
||||
|
||||
armature-ca issue-user --cn jeff [--email jeff@example.com]
|
||||
→ generates jeff.crt + jeff.key in ./users/
|
||||
```
|
||||
|
||||
The script generates a proper `openssl.cnf` fragment per invocation
|
||||
with the right SANs, EKUs, and validity period (default 365 days for
|
||||
nodes, 90 days for users). All output is PEM.
|
||||
|
||||
If we later want a Go-native tool (for cross-platform or embedding),
|
||||
it's a straightforward port — the `crypto/x509` stdlib does everything
|
||||
openssl does here.
|
||||
|
||||
---
|
||||
|
||||
## Config Surface
|
||||
|
||||
```env
|
||||
# TLS mode — controls whether the binary terminates TLS
|
||||
# none: plain HTTP (default, use behind a proxy)
|
||||
# server: TLS, no client cert required
|
||||
# mtls: mutual TLS, client cert required
|
||||
TLS_MODE=mtls
|
||||
|
||||
# Cert paths (required when TLS_MODE != none)
|
||||
TLS_CERT=/etc/armature/tls/node.crt
|
||||
TLS_KEY=/etc/armature/tls/node.key
|
||||
TLS_CA=/etc/armature/tls/ca.crt
|
||||
|
||||
# Listen address (default :8080 for none, :8443 for tls/mtls)
|
||||
LISTEN_ADDR=:8443
|
||||
|
||||
# Auth mode — when TLS_MODE=mtls, this should be mtls
|
||||
AUTH_MODE=mtls
|
||||
```
|
||||
|
||||
`TLS_MODE` and `AUTH_MODE` are independent knobs:
|
||||
|
||||
- `TLS_MODE=server` + `AUTH_MODE=builtin` = HTTPS with password login
|
||||
- `TLS_MODE=mtls` + `AUTH_MODE=mtls` = full mTLS identity
|
||||
- `TLS_MODE=none` + `AUTH_MODE=mtls` = proxy-terminated mTLS (existing behavior)
|
||||
|
||||
The third combination is the current `MTLSProxyProvider` path. The
|
||||
first is useful for deployments that want encrypted transport but
|
||||
password auth (e.g., single-node with Let's Encrypt).
|
||||
|
||||
---
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
**Unit tests (in-process, no network):**
|
||||
|
||||
Generate an ephemeral CA and certs using `crypto/x509` + `crypto/ecdsa`
|
||||
in `TestMain`. Tests call `MTLSNativeProvider.Authenticate()` with a
|
||||
fabricated `*http.Request` whose `TLS.PeerCertificates` is populated
|
||||
directly.
|
||||
|
||||
- Valid cert → user provisioned, correct CN/fingerprint
|
||||
- No TLS → `ErrNoCert`
|
||||
- Empty PeerCertificates → `ErrNoCert`
|
||||
- Second call with same fingerprint → same user returned (idempotent)
|
||||
- Different CN, same fingerprint → same user (cert reissue scenario)
|
||||
|
||||
**Integration tests (real TLS listener):**
|
||||
|
||||
Spin up `http.Server` with `tls.Config` on localhost. Dial with
|
||||
`http.Client` using test client certs.
|
||||
|
||||
- No client cert → TLS handshake rejected (Go returns it before handler)
|
||||
- Wrong CA → TLS handshake rejected
|
||||
- Valid cert → 200, user created
|
||||
- Expired cert → TLS handshake rejected
|
||||
|
||||
**Node-to-node integration:**
|
||||
|
||||
Two in-process servers with distinct node certs, same CA. Verify:
|
||||
|
||||
- Node A can heartbeat to Node B
|
||||
- Node with wrong-CA cert cannot dial either
|
||||
- Connection refused when cert SANs don't match dial address
|
||||
(if `tls.Config.ServerName` is set — TBD whether we enforce this
|
||||
for internal traffic or rely solely on CA verification)
|
||||
|
||||
---
|
||||
|
||||
## Migration Notes
|
||||
|
||||
No database schema changes. The `users` table already has `auth_source`
|
||||
and `external_id` columns from the v0.24.1 mTLS/OIDC work. The native
|
||||
provider populates them identically to the proxy provider.
|
||||
|
||||
The new code is:
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `server/auth/mtls_native.go` | `MTLSNativeProvider` type |
|
||||
| `server/auth/mtls_helpers.go` | Shared: `ParseDN`, `FingerprintCert`, `resolveOrProvision` |
|
||||
| `server/auth/mtls_native_test.go` | Unit + integration tests |
|
||||
| `server/config/tls.go` | `TLSConfig` struct, loader, validation |
|
||||
| `scripts/armature-ca.sh` | Cert provisioning wrapper |
|
||||
|
||||
`server/auth/mtls.go` (existing) is renamed to `mtls_proxy.go` for
|
||||
clarity. No behavioral changes to the proxy provider.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **SAN enforcement on node-to-node:** Do we verify `ServerName`
|
||||
matches the dialed address, or just verify the cert is CA-signed?
|
||||
Strict SAN checking is more secure but makes IP changes painful.
|
||||
Recommendation: verify CA signature only for internal traffic;
|
||||
SAN checking for client-facing listen.
|
||||
|
||||
2. **Cert rotation without restart:** Not in scope for v0.6.7, but
|
||||
the `tls.Config.GetCertificate` / `GetConfigForClient` callbacks
|
||||
make it straightforward to add later — read cert from disk on each
|
||||
handshake (with caching). Worth noting in the design so we don't
|
||||
paint ourselves into a corner.
|
||||
|
||||
3. **PKCS#12 / combined files:** Some operators prefer `.p12` bundles
|
||||
over separate `.crt`/`.key` files. Low priority but trivial to add
|
||||
via `crypto/pkcs12.Decode`. Defer unless requested.
|
||||
@@ -1,227 +0,0 @@
|
||||
# Distribution Guide
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
docker pull gobha/armature:latest
|
||||
docker run -p 8080:80 \
|
||||
-e ARMATURE_ADMIN_USERNAME=admin \
|
||||
-e ARMATURE_ADMIN_PASSWORD=changeme \
|
||||
gobha/armature:latest
|
||||
```
|
||||
|
||||
On first run, bundled packages are automatically installed — workflows, surfaces, and extensions are ready to use immediately.
|
||||
|
||||
## Bundled Packages
|
||||
|
||||
The production Docker image ships with pre-built packages. A **curated default set** is auto-installed on first boot; additional packages ship in the image and can be opted-in via `BUNDLED_PACKAGES`.
|
||||
|
||||
#### Default Set (auto-installed)
|
||||
|
||||
| Package | Type | Description |
|
||||
|---------|------|-------------|
|
||||
| notes | surface | Markdown notes with graph view |
|
||||
| chat | surface | Real-time chat surface |
|
||||
| chat-core | library | Conversations, messages, read cursors |
|
||||
| mermaid-renderer | extension | Diagram rendering |
|
||||
| schedules | surface | Cron task management UI |
|
||||
|
||||
#### Opt-in (ship in image, require `BUNDLED_PACKAGES` to enable)
|
||||
|
||||
| Package | Type | Description |
|
||||
|---------|------|-------------|
|
||||
| tasks | full | Kanban/list task manager with webhooks |
|
||||
| workflow-chat | extension | Chat integration for workflow stages |
|
||||
| dashboard | surface | Dashboard surface |
|
||||
| workflow-demo | surface | Interactive walkthrough with diagrams |
|
||||
| bug-report-triage | workflow | Public entry, severity routing, SLA timers |
|
||||
| content-approval | workflow | Multi-party signoff example |
|
||||
| employee-onboarding | workflow | Automated provisioning + manager signoff |
|
||||
| editor | surface | Rich markdown editor |
|
||||
| hello-dashboard | surface | Welcome/getting started surface |
|
||||
| team-activity-log | surface | Team activity feed |
|
||||
| webhook-notifier | workflow | HTTP outbound via connections + Starlark |
|
||||
| csv-table | extension | CSV table renderer |
|
||||
| diff-viewer | extension | Diff visualization |
|
||||
| git-board | surface | Git board interface |
|
||||
| gitea-client | library | Gitea API integration library |
|
||||
| js-sandbox | extension | JavaScript sandbox |
|
||||
| katex-renderer | extension | LaTeX rendering |
|
||||
| regex-tester | extension | Regex testing tool |
|
||||
| icd-test-runner | surface | E2E API test suite |
|
||||
| sdk-test-runner | surface | SDK feature test suite |
|
||||
|
||||
### Behavior
|
||||
|
||||
- **First boot**: Curated default packages are installed and enabled automatically.
|
||||
- **Subsequent boots**: No-op — already-installed packages are skipped.
|
||||
- **Admin uninstalls a package**: It stays uninstalled. Bundled packages are never force-reinstalled.
|
||||
- **To re-install**: Delete the package from the database, then restart the container.
|
||||
|
||||
### Selecting Packages (Allowlist)
|
||||
|
||||
Set `BUNDLED_PACKAGES` to control which packages are installed:
|
||||
|
||||
```bash
|
||||
# Install ALL packages (everything in the image)
|
||||
docker run -p 8080:80 \
|
||||
-e BUNDLED_PACKAGES="*" \
|
||||
gobha/armature:latest
|
||||
|
||||
# Install specific packages only
|
||||
docker run -p 8080:80 \
|
||||
-e BUNDLED_PACKAGES="notes,tasks,schedules" \
|
||||
gobha/armature:latest
|
||||
```
|
||||
|
||||
Empty (default) installs the curated default set. Use `*` to install all packages. This is useful for Helm charts where different environments need different packages.
|
||||
|
||||
### Disabling Auto-Install
|
||||
|
||||
Set `SKIP_BUNDLED_PACKAGES=true` to prevent bundled packages from being installed:
|
||||
|
||||
```bash
|
||||
docker run -p 8080:80 \
|
||||
-e SKIP_BUNDLED_PACKAGES=true \
|
||||
gobha/armature:latest
|
||||
```
|
||||
|
||||
### Custom Bundle Directory
|
||||
|
||||
Override the default bundled packages location with `BUNDLED_PACKAGES_DIR`:
|
||||
|
||||
```bash
|
||||
docker run -p 8080:80 \
|
||||
-e BUNDLED_PACKAGES_DIR=/custom/packages \
|
||||
-v /host/packages:/custom/packages \
|
||||
gobha/armature:latest
|
||||
```
|
||||
|
||||
## Builder Image
|
||||
|
||||
The builder image pre-caches Go modules and Node dependencies for faster custom builds.
|
||||
|
||||
```bash
|
||||
docker pull gobha/armature-builder:latest
|
||||
```
|
||||
|
||||
### What It Caches
|
||||
|
||||
- Go module cache (`go mod download` for all server dependencies)
|
||||
- Node modules for the CM6 editor bundle
|
||||
- Vendor library tarballs (marked, DOMPurify, mermaid, KaTeX)
|
||||
- Build tools (zip, Node.js runtime)
|
||||
|
||||
### Using in Custom Builds
|
||||
|
||||
Reference the builder image as a base stage in your Dockerfile:
|
||||
|
||||
```dockerfile
|
||||
FROM gobha/armature-builder:latest AS builder
|
||||
WORKDIR /app
|
||||
COPY server/ .
|
||||
RUN go build -ldflags="-s -w" -o /bin/armature .
|
||||
```
|
||||
|
||||
### Building Locally
|
||||
|
||||
```bash
|
||||
docker build -f Dockerfile.builder -t armature-builder .
|
||||
```
|
||||
|
||||
## Custom Build Guide
|
||||
|
||||
### Adding Custom Packages
|
||||
|
||||
1. Create your package in `packages/your-package/` with a `manifest.json`
|
||||
2. Build all packages: `cd packages && bash build.sh all`
|
||||
3. Build the Docker image: `docker build -t my-armature .`
|
||||
|
||||
The Dockerfile automatically builds all packages in the `packages/` directory and bundles them into the production image.
|
||||
|
||||
### Removing Bundled Packages
|
||||
|
||||
To exclude specific packages from the bundle, either:
|
||||
- Remove them from `packages/` before building
|
||||
- Set `SKIP_BUNDLED_PACKAGES=true` and install packages manually via the admin UI
|
||||
|
||||
### Forking for Custom Builds
|
||||
|
||||
```bash
|
||||
git clone https://github.com/gobha/armature.git
|
||||
cd armature
|
||||
|
||||
# Add/modify packages
|
||||
cp -r my-extension packages/my-extension/
|
||||
|
||||
# Build with builder image for faster compilation
|
||||
docker build -t my-armature .
|
||||
```
|
||||
|
||||
## Production Deployment
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `PORT` | `8080` | Backend API port |
|
||||
| `DB_DRIVER` | (auto) | `postgres` or `sqlite` |
|
||||
| `DATABASE_URL` | | PostgreSQL connection string |
|
||||
| `JWT_SECRET` | `dev-secret-change-me` | **Must change in production** |
|
||||
| `ENCRYPTION_KEY` | | AES-256 key for credential encryption |
|
||||
| `AUTH_MODE` | `builtin` | `builtin`, `mtls`, or `oidc` |
|
||||
| `STORAGE_BACKEND` | (auto) | `pvc` or `s3` |
|
||||
| `STORAGE_PATH` | `/data/storage` | PVC mount point |
|
||||
| `BASE_PATH` | | URL prefix (e.g. `/armature`) |
|
||||
| `SKIP_BUNDLED_PACKAGES` | `false` | Disable auto-install of bundled packages |
|
||||
| `BUNDLED_PACKAGES` | (empty = defaults) | `""` curated defaults, `"*"` all, or comma-separated IDs |
|
||||
| `BUNDLED_PACKAGES_DIR` | `/app/bundled-packages` | Override bundled packages location |
|
||||
| `LOG_FORMAT` | `text` | `text` or `json` |
|
||||
| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` |
|
||||
|
||||
### Database
|
||||
|
||||
PostgreSQL is recommended for production. SQLite is suitable for single-instance evaluation.
|
||||
|
||||
```bash
|
||||
# PostgreSQL (recommended)
|
||||
docker run -p 8080:80 \
|
||||
-e DATABASE_URL="postgres://user:pass@host:5432/armature?sslmode=require" \
|
||||
-e JWT_SECRET="$(openssl rand -hex 32)" \
|
||||
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
|
||||
gobha/armature:latest
|
||||
|
||||
# SQLite (evaluation only)
|
||||
docker run -p 8080:80 \
|
||||
-e DB_DRIVER=sqlite \
|
||||
-v armature-data:/data \
|
||||
gobha/armature:latest
|
||||
```
|
||||
|
||||
### Storage
|
||||
|
||||
Object storage is required for file uploads and package asset extraction.
|
||||
|
||||
```bash
|
||||
# PVC (auto-detected if path is writable)
|
||||
docker run -v armature-storage:/data/storage ...
|
||||
|
||||
# S3-compatible (MinIO, AWS S3, Ceph)
|
||||
docker run \
|
||||
-e STORAGE_BACKEND=s3 \
|
||||
-e S3_BUCKET=armature \
|
||||
-e S3_ENDPOINT=https://minio.corp:9000 \
|
||||
-e S3_ACCESS_KEY=... \
|
||||
-e S3_SECRET_KEY=... \
|
||||
-e S3_FORCE_PATH_STYLE=true \
|
||||
...
|
||||
```
|
||||
|
||||
### Kubernetes
|
||||
|
||||
See the `k8s/` directory for example manifests. Key considerations:
|
||||
|
||||
- Use `POSTGRES_HOST`, `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DB` env vars (assembled into DSN automatically)
|
||||
- Set liveness probe to `/healthz/live`, readiness probe to `/healthz/ready`
|
||||
- Mount a PVC at `/data/storage` for file storage, or configure S3
|
||||
- Set `JWT_SECRET` and `ENCRYPTION_KEY` via Kubernetes Secrets
|
||||
@@ -1,196 +0,0 @@
|
||||
# Extension CSS Contract
|
||||
|
||||
> **Version**: v0.6.13 — Responsive & Spacing
|
||||
|
||||
This document defines the CSS contract between the Armature kernel and extension
|
||||
packages. Extensions **must** follow these rules; the kernel guarantees the listed
|
||||
classes and variables are stable public API.
|
||||
|
||||
---
|
||||
|
||||
## Naming Rule
|
||||
|
||||
All class selectors in extension CSS (`packages/{slug}/css/main.css`) must start
|
||||
with `.ext-{slug}-`. The `{slug}` is the package directory name.
|
||||
|
||||
```css
|
||||
/* Good */
|
||||
.ext-my-app-sidebar { ... }
|
||||
.ext-my-app-card { ... }
|
||||
|
||||
/* Bad — will be rejected by the linter */
|
||||
.sidebar { ... }
|
||||
.my-sidebar { ... }
|
||||
```
|
||||
|
||||
**Compound selectors**: Descendant classes scoped under your `.ext-{slug}` root
|
||||
are allowed to reference kernel classes or state modifiers:
|
||||
|
||||
```css
|
||||
/* Allowed — kernel class scoped under extension namespace */
|
||||
.ext-my-app .sw-btn { margin-top: 8px; }
|
||||
|
||||
/* Allowed — state modifier on an extension element */
|
||||
.ext-my-app-item.active { ... }
|
||||
```
|
||||
|
||||
Run `bash scripts/lint-package-css.sh` to validate. The linter checks that the
|
||||
**first** class selector in every rule starts with `.ext-{slug}`.
|
||||
|
||||
---
|
||||
|
||||
## Stable Kernel Classes
|
||||
|
||||
Extensions may reference these classes in compound selectors. They are part of
|
||||
the public API and will not change without a major version bump.
|
||||
|
||||
### Components (from `sw-primitives.css`)
|
||||
|
||||
| Class pattern | Component |
|
||||
|---------------|-----------|
|
||||
| `.sw-btn`, `.sw-btn--{variant}`, `.sw-btn--{size}` | Buttons |
|
||||
| `.sw-input` | Text inputs |
|
||||
| `.sw-field`, `.sw-field__label`, `.sw-field__hint` | Form fields |
|
||||
| `.sw-dialog`, `.sw-dialog__header`, `.sw-dialog__body`, `.sw-dialog__footer` | Dialogs |
|
||||
| `.sw-toast`, `.sw-toast-container` | Toast notifications |
|
||||
| `.sw-menu`, `.sw-menu-item` | Context menus |
|
||||
| `.sw-tabs`, `.sw-tab-btn` | Tab strips |
|
||||
| `.sw-dropdown` | Custom dropdowns |
|
||||
| `.sw-spinner` | Loading spinners |
|
||||
| `.sw-avatar` | User avatars |
|
||||
| `.sw-drawer` | Slide-out drawers |
|
||||
| `.sw-banner` | Banner bars |
|
||||
| `.sw-tooltip` | Tooltips |
|
||||
|
||||
### Extension Mount
|
||||
|
||||
The extension surface container has a `data-ext` attribute set to the package
|
||||
slug. Use this for scoping if needed:
|
||||
|
||||
```css
|
||||
[data-ext="my-app"] .ext-my-app-sidebar { ... }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stable CSS Variables
|
||||
|
||||
All variables from `variables.css` are public API. Extensions should use these
|
||||
instead of hardcoded colors to respect the user's theme.
|
||||
|
||||
### Colors
|
||||
|
||||
| Variable | Purpose |
|
||||
|----------|---------|
|
||||
| `--bg` | Page background |
|
||||
| `--bg-secondary` | Secondary/darker background |
|
||||
| `--bg-elevated` | Elevated surface background |
|
||||
| `--bg-raised` | Raised card background |
|
||||
| `--bg-surface` | Surface-level background |
|
||||
| `--bg-hover` | Hover state background |
|
||||
| `--bg-active` | Active/pressed state background |
|
||||
| `--bg-code` | Code block background |
|
||||
| `--text` | Primary text color |
|
||||
| `--text-2` | Secondary text color |
|
||||
| `--text-3` | Tertiary/muted text color |
|
||||
| `--text-on-color` | Text on colored backgrounds |
|
||||
| `--accent` | Primary accent color |
|
||||
| `--accent-dim` | Dimmed accent for backgrounds |
|
||||
| `--accent-hover` | Accent hover state |
|
||||
| `--accent-light` | Light accent variant |
|
||||
| `--border` | Default border color |
|
||||
| `--border-light` | Light border variant |
|
||||
| `--border-elevated` | Border for elevated surfaces |
|
||||
| `--danger` | Error/destructive color |
|
||||
| `--danger-dim` | Dimmed danger background |
|
||||
| `--danger-light` | Light danger variant |
|
||||
| `--success` | Success/positive color |
|
||||
| `--success-dim` | Dimmed success background |
|
||||
| `--success-light` | Light success variant |
|
||||
| `--warning` | Warning/caution color |
|
||||
| `--warning-dim` | Dimmed warning background |
|
||||
| `--warning-light` | Light warning variant |
|
||||
| `--purple` | Purple accent |
|
||||
| `--purple-dim` | Dimmed purple background |
|
||||
|
||||
### Spacing
|
||||
|
||||
Use spacing tokens instead of hardcoded values for padding, margin, and gap.
|
||||
For sub-4px values (1px, 2px, 3px) used in borders and fine detail, hardcoded
|
||||
values are acceptable.
|
||||
|
||||
| Variable | Value | Computed |
|
||||
|----------|-------|---------|
|
||||
| `--sp-1` | `0.25rem` | 4px |
|
||||
| `--sp-1h` | `0.375rem` | 6px |
|
||||
| `--sp-2` | `0.5rem` | 8px |
|
||||
| `--sp-2h` | `0.625rem` | 10px |
|
||||
| `--sp-3` | `0.75rem` | 12px |
|
||||
| `--sp-4` | `1rem` | 16px |
|
||||
| `--sp-5` | `1.25rem` | 20px |
|
||||
| `--sp-6` | `1.5rem` | 24px |
|
||||
| `--sp-8` | `2rem` | 32px |
|
||||
| `--sp-10` | `2.5rem` | 40px |
|
||||
| `--sp-12` | `3rem` | 48px |
|
||||
|
||||
Example:
|
||||
|
||||
```css
|
||||
.ext-my-app-card {
|
||||
padding: var(--sp-3) var(--sp-4); /* 12px 16px */
|
||||
gap: var(--sp-2); /* 8px */
|
||||
margin-bottom: var(--sp-4); /* 16px */
|
||||
}
|
||||
```
|
||||
|
||||
### Layout & Typography
|
||||
|
||||
| Variable | Purpose |
|
||||
|----------|---------|
|
||||
| `--font` | Primary font family |
|
||||
| `--mono` | Monospace font family |
|
||||
| `--radius-sm` | Small border-radius (4px) — badges, inline controls |
|
||||
| `--radius` | Default border-radius (8px) — buttons, inputs, cards |
|
||||
| `--radius-lg` | Large border-radius (12px) — modals, dialogs, large cards |
|
||||
| `--transition` | Default transition timing |
|
||||
| `--shadow-lg` | Large elevation shadow |
|
||||
| `--overlay` | Modal overlay color |
|
||||
| `--glass` | Glassmorphism backdrop |
|
||||
| `--input-bg` | Form input background |
|
||||
| `--sidebar-w` | Sidebar width |
|
||||
|
||||
---
|
||||
|
||||
## Responsive Breakpoints
|
||||
|
||||
The kernel uses these standard breakpoints. Extensions should use the same
|
||||
values for consistency.
|
||||
|
||||
| Name | Media Query | Use Case |
|
||||
|------|-------------|----------|
|
||||
| Mobile | `@media (max-width: 768px)` | Phone-sized, single column |
|
||||
| Tablet | `@media (max-width: 1024px)` | Tablet/small laptop, narrower sidebars |
|
||||
| Desktop | Default (no query) | Full layout |
|
||||
|
||||
CSS custom properties cannot be used in `@media` queries — use the pixel
|
||||
values directly.
|
||||
|
||||
---
|
||||
|
||||
## What Is Internal
|
||||
|
||||
Everything not listed above is **internal kernel CSS** and may change between
|
||||
minor versions. Extensions must not depend on:
|
||||
|
||||
- Kernel layout classes (`.admin-*`, `.surface-*`, `.sidebar`, etc.)
|
||||
- Kernel CSS file load order
|
||||
- Specific HTML structure of the shell or topbar
|
||||
- Undocumented CSS variables
|
||||
|
||||
---
|
||||
|
||||
## Enforcement
|
||||
|
||||
The linter script `scripts/lint-package-css.sh` runs against all
|
||||
`packages/*/css/main.css` files. It exits non-zero if any rule's first class
|
||||
selector does not start with `.ext-{slug}`.
|
||||
@@ -1,183 +0,0 @@
|
||||
# Extension Guide
|
||||
|
||||
## Package Types
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `surface` | A routable UI page rendered in the shell viewport |
|
||||
| `extension` | Starlark hooks, tools, API routes, DB tables |
|
||||
| `full` | Both surface and extension combined |
|
||||
| `library` | Shared code imported by other packages via `lib.require()` |
|
||||
| `workflow` | Bundled workflow definition |
|
||||
|
||||
## Tiers
|
||||
|
||||
| Tier | Runs | Capabilities |
|
||||
|------|------|-------------|
|
||||
| `browser` | Client-side JS only | DOM access, SDK hooks, no server-side logic |
|
||||
| `starlark` | Sandboxed server-side | DB, HTTP, notifications, secrets, API routes, realtime |
|
||||
| `sidecar` | Separate container | Full runtime (future) |
|
||||
|
||||
## manifest.json
|
||||
|
||||
Every package has a `manifest.json` at its root. Example for a surface:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-surface",
|
||||
"title": "My Surface",
|
||||
"type": "full",
|
||||
"tier": "starlark",
|
||||
"version": "1.0.0",
|
||||
"description": "A custom surface with server-side logic.",
|
||||
"icon": "🔧",
|
||||
"author": "you",
|
||||
"route": "/s/my-surface",
|
||||
"auth": "authenticated",
|
||||
"permissions": ["db.write"],
|
||||
"api_routes": [
|
||||
{"method": "GET", "path": "/items"},
|
||||
{"method": "POST", "path": "/items"}
|
||||
],
|
||||
"db_tables": {
|
||||
"items": {
|
||||
"columns": {
|
||||
"title": "text",
|
||||
"done": "int"
|
||||
},
|
||||
"indexes": [["title"]]
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"page_size": {
|
||||
"type": "string",
|
||||
"label": "Items Per Page",
|
||||
"description": "Number of items shown per page",
|
||||
"default": "25"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Field Reference
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `id` | yes | Unique kebab-case identifier |
|
||||
| `title` | yes | Display name |
|
||||
| `type` | yes | `surface`, `extension`, `full`, `library`, `workflow` |
|
||||
| `tier` | yes | `browser`, `starlark`, `sidecar` |
|
||||
| `version` | yes | Semver string |
|
||||
| `description` | no | Short description |
|
||||
| `icon` | no | Emoji icon for sidebar/menu |
|
||||
| `route` | surfaces | URL path (e.g., `/s/my-surface`) |
|
||||
| `auth` | no | `authenticated` (default) or `public` |
|
||||
| `permissions` | no | Capabilities requested: `db.write`, `http`, `notifications`, `secrets`, `realtime.publish` |
|
||||
| `api_routes` | no | Array of `{method, path}` for extension HTTP endpoints |
|
||||
| `api_schema` | no | OpenAPI documentation for extension API routes (see below) |
|
||||
| `db_tables` | no | Table definitions (see below) |
|
||||
| `settings` | no | User-configurable settings schema |
|
||||
| `exports` | libraries | Functions exported for other packages |
|
||||
| `hooks` | no | Event bus subscriptions |
|
||||
| `schema_version` | no | Integer for additive schema migrations |
|
||||
|
||||
## db_tables Schema
|
||||
|
||||
Tables are automatically namespaced as `ext_{package_id}_{table_name}`. Column types: `text`, `int`. Every table gets an auto-generated `id` primary key and `created_at` timestamp.
|
||||
|
||||
```json
|
||||
"db_tables": {
|
||||
"notes": {
|
||||
"columns": {
|
||||
"title": "text",
|
||||
"body": "text",
|
||||
"creator_id": "text",
|
||||
"pinned": "int"
|
||||
},
|
||||
"indexes": [
|
||||
["creator_id"],
|
||||
["pinned"]
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## api_schema (OpenAPI Documentation)
|
||||
|
||||
Extensions can optionally declare an `api_schema` array in their manifest to provide rich API documentation. Declared routes appear in Swagger UI at `/api/docs` with parameters, request bodies, and response schemas. Routes without `api_schema` entries still appear as auto-generated stubs.
|
||||
|
||||
```json
|
||||
"api_schema": [
|
||||
{
|
||||
"path": "/items",
|
||||
"method": "GET",
|
||||
"summary": "List items",
|
||||
"description": "Returns paginated items for the current user",
|
||||
"params": {
|
||||
"limit": {"type": "integer", "default": 50, "description": "Max results"},
|
||||
"offset": {"type": "integer", "default": 0}
|
||||
},
|
||||
"response": {
|
||||
"type": "object",
|
||||
"example": {"data": [{"id": "string", "title": "string"}]}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/items",
|
||||
"method": "POST",
|
||||
"summary": "Create item",
|
||||
"body": {
|
||||
"title": {"type": "string", "required": true},
|
||||
"description": {"type": "string"}
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Only `path` and `method` are required. All other fields are optional. Malformed entries are logged and skipped without blocking extension loading.
|
||||
|
||||
## Starlark Sandbox API
|
||||
|
||||
Starlark scripts run server-side with a CPU budget and memory ceiling. Available modules (granted per-permission by admin):
|
||||
|
||||
| Module | Permission | API |
|
||||
|--------|-----------|-----|
|
||||
| `db` | `db.write` | `db.query(table, filters)`, `db.insert(table, row)`, `db.update(table, id, row)`, `db.delete(table, id)` |
|
||||
| `http` | `http` | `http.get(url)`, `http.post(url, body)` -- SSRF-safe, no private IPs by default |
|
||||
| `notifications` | `notifications` | `notifications.send(user_id, title, body)` |
|
||||
| `secrets` | `secrets` | `secrets.get(connection_type)` -- reads from the credential vault |
|
||||
| `api` | (implicit) | Registers HTTP routes at `/s/:slug/api/*path` |
|
||||
| `realtime` | `realtime.publish` | `realtime.publish(channel, event, data)` -- push to WebSocket clients |
|
||||
|
||||
The sandbox cannot spawn goroutines, access the filesystem, or import arbitrary packages.
|
||||
|
||||
## Permissions Model
|
||||
|
||||
Extensions declare required permissions in `manifest.json`. The admin must grant each permission before the extension can use the corresponding module. Permission status is visible in Admin > Packages > Permissions.
|
||||
|
||||
Kernel permissions for users/groups: `extension.use`, `extension.install`, `workflow.create`, `workflow.submit`, `admin.view`, `token.unlimited`.
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
my-package/
|
||||
manifest.json # required
|
||||
js/ # browser-side JavaScript
|
||||
index.js
|
||||
css/ # stylesheets
|
||||
styles.css
|
||||
script.star # Starlark entry point
|
||||
star/ # additional Starlark modules
|
||||
assets/ # static assets
|
||||
migrations/ # schema migration files
|
||||
```
|
||||
|
||||
## Testing Extensions
|
||||
|
||||
1. Build the package: `cd packages && bash build.sh my-package`
|
||||
2. Upload the `.pkg` file via Admin > Packages > Install.
|
||||
3. Grant permissions in Admin > Packages > Permissions.
|
||||
4. Enable the package.
|
||||
5. If it is a surface, navigate to its route (e.g., `/s/my-package`).
|
||||
|
||||
Extension API routes are accessible at `/s/{slug}/api/{path}` and require an authenticated Bearer token.
|
||||
@@ -1,91 +0,0 @@
|
||||
# Getting Started
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker and Docker Compose
|
||||
|
||||
## Running with Docker Compose
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000). Default credentials: `admin` / `admin`.
|
||||
|
||||
Data persists in the `sb_data` named volume. To reset everything:
|
||||
|
||||
```bash
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
## First Boot
|
||||
|
||||
On first start, Armature will:
|
||||
|
||||
1. Run database migrations (SQLite by default in compose).
|
||||
2. Create the admin user from `ARMATURE_ADMIN_USERNAME` / `ARMATURE_ADMIN_PASSWORD` env vars.
|
||||
3. Auto-install the curated default package set (notes, chat-core, dashboard, workflow demos, etc.).
|
||||
|
||||
No manual setup steps are required.
|
||||
|
||||
## Installing Additional Packages
|
||||
|
||||
The Docker image ships with extra packages beyond the default set. To install them:
|
||||
|
||||
- **Via Admin UI**: Go to `/admin` > Packages. Browse, enable, or install packages.
|
||||
- **Via environment variable**: Set `BUNDLED_PACKAGES` before starting:
|
||||
|
||||
```bash
|
||||
# Install all bundled packages
|
||||
BUNDLED_PACKAGES="*" docker compose up --build
|
||||
|
||||
# Install specific extras
|
||||
BUNDLED_PACKAGES="notes,tasks,schedules" docker compose up --build
|
||||
```
|
||||
|
||||
You can also upload `.pkg` archives through the Admin > Packages page.
|
||||
|
||||
## Key URLs
|
||||
|
||||
| URL | Purpose |
|
||||
|-----|---------|
|
||||
| `/` | Redirects to your default surface |
|
||||
| `/admin` | Admin panel (users, packages, settings, teams) |
|
||||
| `/settings` | User settings (profile, preferences, default surface) |
|
||||
| `/welcome` | Welcome page (shown when no surfaces are installed) |
|
||||
| `/api/docs` | Interactive OpenAPI documentation |
|
||||
|
||||
## Key Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `PORT` | `8080` | Backend API port |
|
||||
| `DB_DRIVER` | auto | `postgres` or `sqlite` |
|
||||
| `DATABASE_URL` | | PostgreSQL DSN or SQLite file path |
|
||||
| `JWT_SECRET` | `dev-secret-change-me` | **Change in production** |
|
||||
| `ENCRYPTION_KEY` | | AES-256 key for credential encryption |
|
||||
| `AUTH_MODE` | `builtin` | `builtin`, `mtls`, or `oidc` |
|
||||
| `STORAGE_BACKEND` | auto | `pvc` or `s3` |
|
||||
| `STORAGE_PATH` | `/data/storage` | PVC mount point |
|
||||
| `ARMATURE_ADMIN_USERNAME` | | Bootstrap admin username |
|
||||
| `ARMATURE_ADMIN_PASSWORD` | | Bootstrap admin password |
|
||||
| `BUNDLED_PACKAGES` | (empty) | `""` = curated defaults, `"*"` = all, or comma-separated IDs |
|
||||
| `SKIP_BUNDLED_PACKAGES` | `false` | Disable auto-install entirely |
|
||||
| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` |
|
||||
| `LOG_FORMAT` | `text` | `text` or `json` |
|
||||
|
||||
## From Source
|
||||
|
||||
```bash
|
||||
git clone <repo-url> && cd armature
|
||||
cp server/.env.example server/.env # edit DB credentials
|
||||
cd server && go run .
|
||||
# Backend on http://localhost:8080
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Extension Guide](EXTENSION-GUIDE.md) -- Author your own packages
|
||||
- [API Reference](API-REFERENCE.md) -- REST API overview
|
||||
- [Deployment](DEPLOYMENT.md) -- Production deployment
|
||||
- [Architecture](ARCHITECTURE.md) -- System design
|
||||
@@ -1,130 +0,0 @@
|
||||
# Package Format
|
||||
|
||||
Armature packages are distributed as `.pkg` files -- ZIP archives with a standard internal structure.
|
||||
|
||||
## ZIP Structure
|
||||
|
||||
```
|
||||
my-package.pkg
|
||||
├── manifest.json # required -- package metadata
|
||||
├── js/ # browser-side JavaScript
|
||||
│ └── index.js
|
||||
├── css/ # stylesheets
|
||||
│ └── styles.css
|
||||
├── script.star # Starlark entry point
|
||||
├── star/ # additional Starlark modules
|
||||
├── assets/ # static assets (images, etc.)
|
||||
└── migrations/ # schema migration files
|
||||
```
|
||||
|
||||
Only `manifest.json` is required. All other directories are optional and included only if present in the source.
|
||||
|
||||
## manifest.json Reference
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-package",
|
||||
"title": "My Package",
|
||||
"type": "surface",
|
||||
"tier": "browser",
|
||||
"version": "1.0.0",
|
||||
"description": "What this package does.",
|
||||
"icon": "📦",
|
||||
"author": "your-name",
|
||||
"route": "/s/my-package",
|
||||
"auth": "authenticated",
|
||||
"permissions": [],
|
||||
"api_routes": [],
|
||||
"db_tables": {},
|
||||
"settings": {},
|
||||
"hooks": {},
|
||||
"exports": [],
|
||||
"schema_version": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Required Fields
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `id` | Unique kebab-case identifier |
|
||||
| `title` | Human-readable display name |
|
||||
| `type` | `surface`, `extension`, `full`, `library`, `workflow` |
|
||||
| `tier` | `browser`, `starlark`, `sidecar` |
|
||||
| `version` | Semver version string |
|
||||
|
||||
### Optional Fields
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `description` | Short description |
|
||||
| `icon` | Emoji for sidebar/menu display |
|
||||
| `author` | Package author |
|
||||
| `route` | URL path for surfaces (e.g., `/s/my-package`) |
|
||||
| `auth` | `authenticated` or `public` |
|
||||
| `layout` | Surface layout mode (e.g., `single`) |
|
||||
| `permissions` | Array of required capabilities (`db.write`, `http`, `notifications`, `secrets`, `realtime.publish`) |
|
||||
| `api_routes` | Array of `{"method": "GET", "path": "/items"}` |
|
||||
| `db_tables` | Table definitions with columns and indexes |
|
||||
| `settings` | User-configurable settings with type, label, description, default |
|
||||
| `hooks` | Event bus subscription patterns |
|
||||
| `exports` | Functions exported by library packages |
|
||||
| `schema_version` | Integer for additive schema migrations |
|
||||
|
||||
## Package Lifecycle
|
||||
|
||||
1. **Install**: Upload a `.pkg` file via Admin > Packages or `POST /api/v1/admin/packages/install`. The kernel extracts the archive, creates database tables, and registers routes.
|
||||
|
||||
2. **Enable**: Activate the package so its routes, hooks, and UI become available. `PUT /api/v1/admin/packages/:id/enable`.
|
||||
|
||||
3. **Disable**: Deactivate without removing data. `PUT /api/v1/admin/packages/:id/disable`.
|
||||
|
||||
4. **Update**: Upload a new `.pkg` with a higher semver version. Schema changes must be additive (new columns/tables only). `POST /api/v1/admin/packages/:id/update`.
|
||||
|
||||
5. **Export**: Download the installed package as a `.pkg` archive. `GET /api/v1/admin/packages/:id/export`.
|
||||
|
||||
6. **Delete**: Remove the package and its data. `DELETE /api/v1/admin/packages/:id`.
|
||||
|
||||
## Bundled vs User-Installed
|
||||
|
||||
**Bundled packages** ship inside the Docker image at `/app/bundled-packages`. On first boot, a curated default set is auto-installed. Behavior:
|
||||
|
||||
- First boot: curated defaults are installed and enabled.
|
||||
- Subsequent boots: already-installed packages are skipped.
|
||||
- Admin uninstalls: the package stays uninstalled (never force-reinstalled).
|
||||
- Control via `BUNDLED_PACKAGES` env var: empty = defaults, `"*"` = all, or comma-separated IDs.
|
||||
|
||||
**User-installed packages** are uploaded through the Admin UI or API. They follow the same lifecycle but are not tied to the Docker image.
|
||||
|
||||
## Building Packages
|
||||
|
||||
Packages are built by zipping the standard directories alongside `manifest.json`:
|
||||
|
||||
```bash
|
||||
# Build all packages in the packages/ directory
|
||||
cd packages && bash build.sh
|
||||
|
||||
# Build a single package
|
||||
cd packages && bash build.sh my-package
|
||||
```
|
||||
|
||||
Output goes to `dist/my-package.pkg`.
|
||||
|
||||
### Manual Build
|
||||
|
||||
```bash
|
||||
cd packages/my-package
|
||||
zip -r ../../dist/my-package.pkg manifest.json js/ css/ script.star
|
||||
```
|
||||
|
||||
The build script automatically includes whichever standard directories exist: `js/`, `css/`, `assets/`, `script.star`, `star/`, `migrations/`.
|
||||
|
||||
### Custom Docker Image
|
||||
|
||||
To bundle custom packages into a Docker image:
|
||||
|
||||
1. Place your package in `packages/your-package/` with a `manifest.json`.
|
||||
2. Run `cd packages && bash build.sh all`.
|
||||
3. Build the image: `docker build -t my-armature .`
|
||||
|
||||
The Dockerfile builds all packages and copies them into the bundled packages directory.
|
||||
@@ -1,94 +0,0 @@
|
||||
# Package Registry
|
||||
|
||||
The package registry lets admins browse and install packages from an external
|
||||
JSON index — a lightweight alternative to manually uploading `.pkg` files.
|
||||
|
||||
## Registry JSON Format
|
||||
|
||||
The registry is a static JSON file matching the `RegistryResponse` struct:
|
||||
|
||||
```json
|
||||
{
|
||||
"packages": [
|
||||
{
|
||||
"id": "notes",
|
||||
"title": "Notes",
|
||||
"version": "0.8.0",
|
||||
"description": "Markdown notes with backlinks and graph view",
|
||||
"author": "armature",
|
||||
"type": "extension",
|
||||
"tier": "core",
|
||||
"download_url": "https://cdn.example.com/pkg/notes.pkg",
|
||||
"size": 48200,
|
||||
"updated_at": "2026-03-20T00:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Required Fields
|
||||
|
||||
| Field | Description |
|
||||
|----------------|------------------------------------------------|
|
||||
| `id` | Package identifier (matches `manifest.json`) |
|
||||
| `title` | Display name |
|
||||
| `version` | Semver version string |
|
||||
| `description` | Short description |
|
||||
| `download_url` | HTTPS URL to the `.pkg` file (must be HTTPS) |
|
||||
|
||||
### Optional Fields
|
||||
|
||||
| Field | Description |
|
||||
|--------------|------------------------------------------|
|
||||
| `author` | Package author |
|
||||
| `type` | `extension` or `library` |
|
||||
| `tier` | `core`, `official`, or `community` |
|
||||
| `size` | File size in bytes |
|
||||
| `updated_at` | ISO 8601 timestamp of last update |
|
||||
|
||||
## Configuring the Registry URL
|
||||
|
||||
### Via Admin UI
|
||||
|
||||
Navigate to **Admin > Settings > Package Registry** and enter the registry URL.
|
||||
|
||||
### Via API
|
||||
|
||||
```bash
|
||||
curl -X PUT /api/v1/admin/settings/package_registry \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"value": {"url": "https://cdn.example.com/pkg/registry.json"}}'
|
||||
```
|
||||
|
||||
## Generating a Registry
|
||||
|
||||
Use `scripts/generate-registry.sh` to build a `registry.json` from a
|
||||
directory of `.pkg` files:
|
||||
|
||||
```bash
|
||||
# Default: reads dist/, uses placeholder base URL
|
||||
./scripts/generate-registry.sh
|
||||
|
||||
# Custom directory and base URL
|
||||
./scripts/generate-registry.sh ./my-packages https://cdn.example.com/pkg > registry.json
|
||||
```
|
||||
|
||||
Requirements: `jq`, `unzip`, and `stat` (GNU or BSD).
|
||||
|
||||
## Self-Hosting
|
||||
|
||||
Any HTTPS-capable file server works. Upload your `.pkg` files and the
|
||||
generated `registry.json` to the same directory, then point the admin
|
||||
setting to the `registry.json` URL.
|
||||
|
||||
Example with a static file server:
|
||||
|
||||
```
|
||||
/var/www/packages/
|
||||
registry.json
|
||||
notes.pkg
|
||||
chat.pkg
|
||||
chat-core.pkg
|
||||
```
|
||||
|
||||
The registry is fetched and cached for 5 minutes on each browse request.
|
||||
@@ -1,119 +0,0 @@
|
||||
# Build Your First Browser Extension
|
||||
|
||||
This tutorial walks through building a browser extension that renders custom
|
||||
code blocks, modeled on the CSV Table Viewer that ships with Armature.
|
||||
|
||||
**Prerequisites:** A running Armature instance, a text editor, and `zip`.
|
||||
|
||||
## Step 1: Create the Directory
|
||||
|
||||
```sh
|
||||
mkdir -p my-extension/js
|
||||
```
|
||||
|
||||
## Step 2: Write the Manifest
|
||||
|
||||
Create `my-extension/manifest.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-extension",
|
||||
"title": "My Extension",
|
||||
"version": "0.1.0",
|
||||
"type": "extension",
|
||||
"tier": "browser",
|
||||
"author": "you",
|
||||
"description": "Renders demo code blocks as styled HTML",
|
||||
"permissions": [],
|
||||
"settings": {}
|
||||
}
|
||||
```
|
||||
|
||||
- **id** -- unique identifier, used as the install key
|
||||
- **type** -- `extension` for browser-only packages; `full` or `surface` for
|
||||
packages with backend routes
|
||||
- **tier** -- `browser` for client-side JS; `starlark` for server-side scripting
|
||||
|
||||
## Step 3: Write the Browser Script
|
||||
|
||||
Create `my-extension/js/script.js`. Browser extensions use the IIFE pattern
|
||||
and register with the SDK through `sw.renderers`:
|
||||
|
||||
```js
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function register() {
|
||||
if (!window.sw?.renderers) return;
|
||||
|
||||
sw.renderers.register('demo-block', {
|
||||
type: 'block',
|
||||
priority: 10,
|
||||
match(lang) {
|
||||
return (lang || '').toLowerCase() === 'demo';
|
||||
},
|
||||
render(lang, code, container) {
|
||||
container.innerHTML =
|
||||
'<div style="padding:12px;background:var(--bg-2);' +
|
||||
'border:1px solid var(--border);border-radius:8px">' +
|
||||
'<strong>Demo:</strong> ' + code +
|
||||
'</div>';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (window.sw?._sdk) {
|
||||
register();
|
||||
} else {
|
||||
document.addEventListener('sw:ready', register, { once: true });
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
The IIFE wrapper keeps variables out of global scope. `sw.renderers.register`
|
||||
takes a name and an options object: `type: 'block'` targets fenced code blocks,
|
||||
`match` checks the language tag, and `render` receives the language, raw code,
|
||||
and a container element. The `sw:ready` event fires once the SDK initializes;
|
||||
if already loaded, register immediately. Use CSS variables like `var(--bg-2)`
|
||||
and `var(--border)` to follow the active theme.
|
||||
|
||||
## Step 4: Package It
|
||||
|
||||
```sh
|
||||
cd my-extension
|
||||
zip -r ../my-extension.pkg manifest.json js/
|
||||
```
|
||||
|
||||
The `.pkg` format is a ZIP with `manifest.json` at the root. Optional
|
||||
directories: `js/`, `css/`, `assets/`. If working inside `packages/`, use
|
||||
the build script instead: `bash build.sh my-extension`.
|
||||
|
||||
## Step 5: Install It
|
||||
|
||||
```sh
|
||||
curl -X POST http://localhost:3000/api/v1/admin/packages/install \
|
||||
-H "Authorization: Bearer <token>" \
|
||||
-F "file=@my-extension.pkg"
|
||||
```
|
||||
|
||||
You can also install through the Admin UI under the Packages section.
|
||||
|
||||
## Step 6: Enable and Test
|
||||
|
||||
1. Open the admin panel, navigate to Packages, confirm "My Extension" is enabled.
|
||||
2. Go to any markdown surface (Chat, Notes, etc.).
|
||||
3. Enter a fenced code block with the `demo` language tag.
|
||||
|
||||
You should see styled output instead of a plain code block.
|
||||
|
||||
## Going Further
|
||||
|
||||
- **Add CSS** -- create a `css/` directory; stylesheets are injected automatically.
|
||||
- **Post-renderers** -- register with `type: 'post'` to run after block renderers
|
||||
finish (the Mermaid extension uses this for async SVG rendering).
|
||||
- **Settings** -- declare a `settings` object in the manifest for admin-configurable values.
|
||||
- **Server-side logic** -- set `tier: "starlark"` and add `script.star` for
|
||||
backend API routes and database tables.
|
||||
|
||||
See `PACKAGE-FORMAT.md` for the full manifest spec and `EXTENSION-GUIDE.md`
|
||||
for advanced patterns.
|
||||
@@ -1,227 +0,0 @@
|
||||
# Armature Usability Survey — Automated Checklist
|
||||
|
||||
> **Purpose**: Machine-auditable quality gate for the Armature UI.
|
||||
> Run all scripts first, then walk each section. A FAIL in any section blocks release.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Run these scripts from the project root and save their output:
|
||||
|
||||
```bash
|
||||
bash scripts/generate-ui-inventory.sh > ui-inventory.json
|
||||
bash scripts/check-contrast.sh > contrast-report.txt
|
||||
bash scripts/generate-coverage-matrix.sh > coverage-matrix.md
|
||||
bash scripts/audit-touch-targets.sh > touch-targets-report.txt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Section 1: Viewport Correctness
|
||||
|
||||
**Pass criteria:**
|
||||
- No CSS file uses `100vh` (should be `100%` or `100dvh`)
|
||||
- `.sw-shell` uses `height: 100%`, not `100vh`
|
||||
- All extension surfaces use `height: 100%`
|
||||
- No `transform: scale()` for zoom (should use CSS `zoom`)
|
||||
|
||||
**Files to inspect:**
|
||||
- `src/css/sw-shell.css`
|
||||
- `src/css/layout.css`
|
||||
- `packages/*/css/main.css`
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
grep -rn '100vh' src/css/ packages/*/css/ --include='*.css'
|
||||
grep -rn 'transform.*scale' src/css/ packages/*/css/ --include='*.css'
|
||||
```
|
||||
|
||||
**Result:** PASS if zero matches. FAIL if any `100vh` or `transform: scale()` for layout sizing.
|
||||
|
||||
---
|
||||
|
||||
## Section 2: Banner Integration
|
||||
|
||||
**Pass criteria:**
|
||||
- Banners are in-flow (no `position: fixed` on banner elements)
|
||||
- `--banner-top-height` and `--banner-bottom-height` are defined in `:root`
|
||||
- Shell layout accounts for banner height via CSS variables, not hardcoded px
|
||||
- No surface hardcodes `28px` or other banner height values
|
||||
|
||||
**Files to inspect:**
|
||||
- `src/css/sw-shell.css`
|
||||
- `src/css/variables.css` (`:root` block)
|
||||
- `src/js/sw/shell/app-shell.js`
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
grep -n 'position.*fixed' src/css/sw-shell.css | grep -i banner
|
||||
grep -n '28px' src/css/ -r --include='*.css'
|
||||
grep -n 'banner-top-height\|banner-bottom-height' src/css/variables.css
|
||||
```
|
||||
|
||||
**Result:** PASS if banners are in-flow and height is variable-driven. FAIL if fixed positioning or hardcoded heights.
|
||||
|
||||
---
|
||||
|
||||
## Section 3: Responsive Behavior
|
||||
|
||||
**Pass criteria:**
|
||||
- Kernel CSS uses `768px` (mobile) and `1024px` (tablet) breakpoints
|
||||
- No hardcoded widths that break below 768px (except intentional min-widths on dialogs)
|
||||
- Sidebar collapses on mobile
|
||||
- Extension surfaces adapt to narrow viewports
|
||||
|
||||
**Files to inspect:**
|
||||
- `src/css/layout.css`
|
||||
- `src/css/surfaces.css`
|
||||
- `packages/*/css/main.css`
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
# Verify breakpoints used
|
||||
grep -rn '@media.*max-width' src/css/ --include='*.css' | grep -v '768\|1024'
|
||||
# Check for hardcoded widths
|
||||
grep -rn 'width:.*[0-9]\+px' src/css/layout.css | grep -v 'max-width\|min-width\|--'
|
||||
```
|
||||
|
||||
**Result:** PASS if only 768px and 1024px breakpoints. WARN if other breakpoints exist but are justified. FAIL if layout breaks below 768px.
|
||||
|
||||
---
|
||||
|
||||
## Section 4: Styling Consistency
|
||||
|
||||
**Pass criteria:**
|
||||
- All spacing uses `--sp-*` tokens (no raw px for padding/margin/gap > 3px)
|
||||
- All `border-radius` uses `--radius-sm`, `--radius`, or `--radius-lg`
|
||||
- All `font-family` uses `var(--font)` or `var(--mono)`
|
||||
- No external font CDN imports (`@import url(` or Google Fonts references)
|
||||
- No stale fallback colors (`#b38a4e` or other non-token hex in property values)
|
||||
|
||||
**Files to inspect:**
|
||||
- All `src/css/*.css`
|
||||
- `packages/*/css/main.css`
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
# Raw px spacing (padding/margin/gap > 3px, not inside var())
|
||||
grep -rnE '(padding|margin|gap):\s*[0-9]+(px|rem)' src/css/ packages/*/css/ --include='*.css' | grep -v 'var(--' | grep -v '0px\|1px\|2px\|3px'
|
||||
# Raw border-radius
|
||||
grep -rn 'border-radius:' src/css/ packages/*/css/ --include='*.css' | grep -v 'var(--radius'
|
||||
# External fonts
|
||||
grep -rn '@import url\|fonts.googleapis' src/css/ --include='*.css'
|
||||
# Stale fallback gold color
|
||||
grep -rn '#b38a4e' src/css/ packages/*/css/ --include='*.css'
|
||||
```
|
||||
|
||||
**Result:** PASS if zero non-token values (excluding reset/keyframe contexts). WARN for 1-3 edge cases with justification. FAIL for systematic violations.
|
||||
|
||||
---
|
||||
|
||||
## Section 5: Accessibility — Contrast
|
||||
|
||||
**Pass criteria:**
|
||||
- `contrast-report.txt` shows all PASS for normal text (4.5:1 ratio)
|
||||
- No FAIL results in either dark or light theme
|
||||
|
||||
**Files to inspect:**
|
||||
- `contrast-report.txt` (generated above)
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
grep 'FAIL' contrast-report.txt
|
||||
```
|
||||
|
||||
**Result:** PASS if zero FAIL lines. FAIL if any contrast violation.
|
||||
|
||||
---
|
||||
|
||||
## Section 6: Accessibility — Touch Targets
|
||||
|
||||
**Pass criteria:**
|
||||
- `touch-targets-report.txt` shows zero violations
|
||||
- All close buttons have `min-width: 44px; min-height: 44px` in `@media (max-width: 768px)`
|
||||
- Menu items have `min-height: 44px` on mobile (already done in `sw-primitives.css`)
|
||||
|
||||
**Files to inspect:**
|
||||
- `touch-targets-report.txt` (generated above)
|
||||
- `src/css/sw-primitives.css` — close button rules
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
grep 'FAIL\|MISSING' touch-targets-report.txt
|
||||
```
|
||||
|
||||
**Result:** PASS if zero violations. FAIL if any close button lacks mobile touch target.
|
||||
|
||||
---
|
||||
|
||||
## Section 7: Accessibility — Focus Indicators
|
||||
|
||||
**Pass criteria:**
|
||||
- All interactive primitives have `:focus-visible` styles
|
||||
- No `outline: none` without a replacement focus indicator
|
||||
- Focus ring is visible on both dark and light themes
|
||||
|
||||
**Files to inspect:**
|
||||
- `src/css/sw-primitives.css`
|
||||
- `src/css/primitives.css`
|
||||
- `src/css/variables.css`
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
# Check for focus-visible on key primitives
|
||||
for cls in sw-btn sw-input sw-dropdown__trigger sw-menu__item sw-tabs__tab; do
|
||||
echo -n "$cls: "
|
||||
grep -c "\.${cls}.*:focus-visible\|\.${cls}:focus-visible" src/css/sw-primitives.css src/css/primitives.css 2>/dev/null || echo "0"
|
||||
done
|
||||
# Check for outline:none without replacement
|
||||
grep -n 'outline.*none\|outline.*0' src/css/*.css | grep -v 'focus-visible\|focus-within'
|
||||
```
|
||||
|
||||
**Result:** PASS if all 5 key primitives have `:focus-visible`. WARN if outline:none exists with adequate replacement. FAIL if missing focus indicators.
|
||||
|
||||
---
|
||||
|
||||
## Section 8: Component Uniformity
|
||||
|
||||
**Pass criteria:**
|
||||
- `coverage-matrix.md` shows no deprecated component usage (no ⚠ in the deprecated row)
|
||||
- All surfaces use `sw-*` primitives, not old `.btn-*`, `.toast`, `.popup-menu`
|
||||
|
||||
**Files to inspect:**
|
||||
- `coverage-matrix.md` (generated above)
|
||||
|
||||
**How to check:**
|
||||
```bash
|
||||
grep '⚠' coverage-matrix.md
|
||||
```
|
||||
|
||||
**Result:** PASS if zero ⚠ markers. FAIL if any deprecated component still in use.
|
||||
|
||||
---
|
||||
|
||||
## Scoring
|
||||
|
||||
| Section | Weight | Result |
|
||||
|---------|--------|--------|
|
||||
| 1. Viewport Correctness | Required | |
|
||||
| 2. Banner Integration | Required | |
|
||||
| 3. Responsive Behavior | Required | |
|
||||
| 4. Styling Consistency | Required | |
|
||||
| 5. Contrast | Required | |
|
||||
| 6. Touch Targets | Required | |
|
||||
| 7. Focus Indicators | Required | |
|
||||
| 8. Component Uniformity | Required | |
|
||||
|
||||
**Overall:** PASS requires all sections PASS or WARN. Any FAIL blocks the release.
|
||||
|
||||
---
|
||||
|
||||
## After the Survey
|
||||
|
||||
1. Fix all FAIL items
|
||||
2. Re-run affected scripts to confirm fixes
|
||||
3. Re-run the full survey
|
||||
4. Tag `v0.6.16` only after a clean survey pass
|
||||
@@ -1,11 +1,11 @@
|
||||
# k8s/ingress.yaml
|
||||
# ============================================
|
||||
# Armature Core - Ingress
|
||||
# Switchboard Core - Ingress
|
||||
# ============================================
|
||||
# Path-based routing on a single domain:
|
||||
# armature.DOMAIN/ → production
|
||||
# armature.DOMAIN/test/ → test (main branch)
|
||||
# armature.DOMAIN/dev/ → dev (PR branches)
|
||||
# switchboard.DOMAIN/ → production
|
||||
# switchboard.DOMAIN/test/ → test (main branch)
|
||||
# switchboard.DOMAIN/dev/ → dev (PR branches)
|
||||
#
|
||||
# Each environment deploys its own Ingress resource.
|
||||
# Traefik merges rules for the same host automatically.
|
||||
@@ -18,29 +18,29 @@
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: armature${DEPLOY_SUFFIX}
|
||||
name: switchboard${DEPLOY_SUFFIX}
|
||||
namespace: ${NAMESPACE}
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: "${CERT_ISSUER}"
|
||||
traefik.ingress.kubernetes.io/router.entrypoints: websecure
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
env: ${ENVIRONMENT}
|
||||
spec:
|
||||
ingressClassName: "traefik"
|
||||
tls:
|
||||
- hosts:
|
||||
- ${DEPLOY_HOST}
|
||||
secretName: armature-tls
|
||||
secretName: switchboard-tls
|
||||
rules:
|
||||
- host: "${DEPLOY_HOST}"
|
||||
http:
|
||||
paths:
|
||||
# All traffic → armature (unified image)
|
||||
# All traffic → switchboard (unified image)
|
||||
- path: ${BASE_PATH}/
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: armature${DEPLOY_SUFFIX}
|
||||
name: switchboard${DEPLOY_SUFFIX}
|
||||
port:
|
||||
number: 80
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# k8s/middleware-retry.yaml
|
||||
# ============================================
|
||||
# Armature Core - Traefik Retry Middleware
|
||||
# Switchboard Core - Traefik Retry Middleware
|
||||
# ============================================
|
||||
# Retries failed requests (502, connection reset) once before giving up.
|
||||
# Applies to API + WebSocket paths via the Ingress annotation.
|
||||
@@ -15,10 +15,10 @@
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: Middleware
|
||||
metadata:
|
||||
name: armature-retry${DEPLOY_SUFFIX}
|
||||
name: switchboard-retry${DEPLOY_SUFFIX}
|
||||
namespace: ${NAMESPACE}
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
env: ${ENVIRONMENT}
|
||||
spec:
|
||||
retry:
|
||||
|
||||
@@ -16,7 +16,7 @@ metadata:
|
||||
name: traefik-middleware-manager
|
||||
namespace: ${NAMESPACE}
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
rules:
|
||||
- apiGroups: ["traefik.io"]
|
||||
resources: ["middlewares"]
|
||||
@@ -28,7 +28,7 @@ metadata:
|
||||
name: gitea-runner-traefik-middleware
|
||||
namespace: ${NAMESPACE}
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: gitea-runner-sa
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# k8s/storage-pvc.yaml
|
||||
# ============================================
|
||||
# Armature Core - Storage PVC
|
||||
# Switchboard Core - Storage PVC
|
||||
# ============================================
|
||||
# Persistent storage for file attachments, extraction queue,
|
||||
# and future knowledge base / compaction data.
|
||||
@@ -17,10 +17,10 @@
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: armature-storage${DEPLOY_SUFFIX}
|
||||
name: switchboard-storage${DEPLOY_SUFFIX}
|
||||
namespace: ${NAMESPACE}
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
component: storage
|
||||
env: ${ENVIRONMENT}
|
||||
spec:
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# k8s/armature.yaml
|
||||
# k8s/switchboard.yaml
|
||||
# ============================================
|
||||
# Armature Core - Deployment
|
||||
# Switchboard Core - Deployment
|
||||
# ============================================
|
||||
# Secrets:
|
||||
# armature-db-credentials - POSTGRES_USER, POSTGRES_PASSWORD
|
||||
# armature-admin - username, password, email (optional)
|
||||
# armature-encryption - ENCRYPTION_KEY (required for v0.9.4+)
|
||||
# switchboard-db-credentials - POSTGRES_USER, POSTGRES_PASSWORD
|
||||
# switchboard-admin - username, password, email (optional)
|
||||
# switchboard-encryption - ENCRYPTION_KEY (required for v0.9.4+)
|
||||
#
|
||||
# PVC:
|
||||
# armature-storage - Extraction scratch (always needed)
|
||||
# switchboard-storage - Extraction scratch (always needed)
|
||||
# Requires ReadWriteMany (RWX) — see k8s/storage-pvc.yaml
|
||||
# With S3 backend, PVC is small (extraction status only, not blobs)
|
||||
#
|
||||
@@ -23,32 +23,32 @@
|
||||
# S3_ACCESS_KEY - S3 access key
|
||||
# S3_SECRET_KEY - S3 secret key
|
||||
#
|
||||
# Admin bootstrap: on every pod start, if ARMATURE_ADMIN_* env vars
|
||||
# Admin bootstrap: on every pod start, if SWITCHBOARD_ADMIN_* env vars
|
||||
# are set, the backend upserts an admin user. Change the secret and
|
||||
# restart the pod to reset the admin password.
|
||||
# ============================================
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: armature${DEPLOY_SUFFIX}
|
||||
name: switchboard${DEPLOY_SUFFIX}
|
||||
namespace: ${NAMESPACE}
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
env: ${ENVIRONMENT}
|
||||
spec:
|
||||
replicas: ${REPLICAS}
|
||||
selector:
|
||||
matchLabels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
env: ${ENVIRONMENT}
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
env: ${ENVIRONMENT}
|
||||
spec:
|
||||
containers:
|
||||
- name: armature
|
||||
- name: switchboard
|
||||
image: ${IMAGE}:${IMAGE_TAG}
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
@@ -72,43 +72,43 @@ spec:
|
||||
- name: POSTGRES_USER
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-db-credentials
|
||||
name: switchboard-db-credentials
|
||||
key: POSTGRES_USER
|
||||
- name: POSTGRES_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-db-credentials
|
||||
name: switchboard-db-credentials
|
||||
key: POSTGRES_PASSWORD
|
||||
- name: DATABASE_URL
|
||||
value: "postgres://$(POSTGRES_USER):$(POSTGRES_PASSWORD)@$(POSTGRES_HOST):$(POSTGRES_PORT)/$(POSTGRES_DB)?sslmode=disable"
|
||||
- name: ARMATURE_ADMIN_USERNAME
|
||||
- name: SWITCHBOARD_ADMIN_USERNAME
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-admin
|
||||
name: switchboard-admin
|
||||
key: username
|
||||
optional: true
|
||||
- name: ARMATURE_ADMIN_PASSWORD
|
||||
- name: SWITCHBOARD_ADMIN_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-admin
|
||||
name: switchboard-admin
|
||||
key: password
|
||||
optional: true
|
||||
- name: ARMATURE_ADMIN_EMAIL
|
||||
- name: SWITCHBOARD_ADMIN_EMAIL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-admin
|
||||
name: switchboard-admin
|
||||
key: email
|
||||
optional: true
|
||||
- name: SEED_USERS
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-seed-users
|
||||
name: switchboard-seed-users
|
||||
key: users
|
||||
optional: true
|
||||
- name: ENCRYPTION_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-encryption
|
||||
name: switchboard-encryption
|
||||
key: ENCRYPTION_KEY
|
||||
optional: true
|
||||
# File storage (v0.12.0+)
|
||||
@@ -120,47 +120,41 @@ spec:
|
||||
- name: S3_ENDPOINT
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-s3
|
||||
name: switchboard-s3
|
||||
key: S3_ENDPOINT
|
||||
optional: true
|
||||
- name: S3_BUCKET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-s3
|
||||
name: switchboard-s3
|
||||
key: S3_BUCKET
|
||||
optional: true
|
||||
- name: S3_ACCESS_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-s3
|
||||
name: switchboard-s3
|
||||
key: S3_ACCESS_KEY
|
||||
optional: true
|
||||
- name: S3_SECRET_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-s3
|
||||
name: switchboard-s3
|
||||
key: S3_SECRET_KEY
|
||||
optional: true
|
||||
- name: S3_REGION
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-s3
|
||||
name: switchboard-s3
|
||||
key: S3_REGION
|
||||
optional: true
|
||||
- name: S3_PREFIX
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: armature-s3
|
||||
name: switchboard-s3
|
||||
key: S3_PREFIX
|
||||
optional: true
|
||||
- name: S3_FORCE_PATH_STYLE
|
||||
value: "true"
|
||||
# Bundled packages (v0.3.8)
|
||||
# Dev: install all (empty = all). Test: install all. Prod: skip (nothing bundled needed yet).
|
||||
- name: SKIP_BUNDLED_PACKAGES
|
||||
value: "${SKIP_BUNDLED_PACKAGES}"
|
||||
- name: BUNDLED_PACKAGES
|
||||
value: "${BUNDLED_PACKAGES}"
|
||||
volumeMounts:
|
||||
- name: storage
|
||||
mountPath: /data/storage
|
||||
@@ -191,19 +185,19 @@ spec:
|
||||
volumes:
|
||||
- name: storage
|
||||
persistentVolumeClaim:
|
||||
claimName: armature-storage${DEPLOY_SUFFIX}
|
||||
claimName: switchboard-storage${DEPLOY_SUFFIX}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: armature${DEPLOY_SUFFIX}
|
||||
name: switchboard${DEPLOY_SUFFIX}
|
||||
namespace: ${NAMESPACE}
|
||||
labels:
|
||||
app: armature
|
||||
app: switchboard
|
||||
env: ${ENVIRONMENT}
|
||||
spec:
|
||||
selector:
|
||||
app: armature
|
||||
app: switchboard
|
||||
env: ${ENVIRONMENT}
|
||||
ports:
|
||||
- protocol: TCP
|
||||
@@ -66,7 +66,6 @@ server {
|
||||
location ${BASE_PATH}/team-admin { proxy_pass $backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
|
||||
location ${BASE_PATH}/settings { proxy_pass $backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
|
||||
location ${BASE_PATH}/welcome { proxy_pass $backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
|
||||
location ${BASE_PATH}/docs { proxy_pass $backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
|
||||
location ${BASE_PATH}/w/ { proxy_pass $backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
|
||||
|
||||
# Extension surface page routes → backend
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Packages
|
||||
|
||||
Installable `.pkg` archives for Chat Armature. Each subdirectory is a
|
||||
Installable `.pkg` archives for Chat Switchboard. Each subdirectory is a
|
||||
package — either a surface (routable UI), an extension (hooks/tools/pipes),
|
||||
or both (`full` type).
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"version": "0.1.0",
|
||||
"tier": "browser",
|
||||
"icon": "🐛",
|
||||
"author": "Armature",
|
||||
"author": "Switchboard Core",
|
||||
"description": "Public bug report submission with severity-based routing, team assignment, and SLA timers.",
|
||||
"permissions": [],
|
||||
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
{
|
||||
"id": "chat-core",
|
||||
"title": "Chat Core",
|
||||
"type": "library",
|
||||
"tier": "starlark",
|
||||
"version": "0.2.0",
|
||||
"description": "Core chat library — conversations, messages, participants, read cursors. Usable by other packages via lib.require().",
|
||||
"author": "armature",
|
||||
|
||||
"permissions": ["db.write", "realtime.publish"],
|
||||
|
||||
"exports": [
|
||||
"create", "send", "history",
|
||||
"add_participant", "remove_participant", "mark_read"
|
||||
],
|
||||
|
||||
"api_routes": [
|
||||
{"method": "GET", "path": "/conversations"},
|
||||
{"method": "POST", "path": "/conversations"},
|
||||
{"method": "GET", "path": "/conversations/*"},
|
||||
{"method": "PUT", "path": "/conversations/*"},
|
||||
{"method": "DELETE", "path": "/conversations/*"},
|
||||
{"method": "GET", "path": "/messages/*"},
|
||||
{"method": "POST", "path": "/messages/*"},
|
||||
{"method": "PUT", "path": "/messages/*"},
|
||||
{"method": "DELETE", "path": "/messages/*"},
|
||||
{"method": "GET", "path": "/participants/*"},
|
||||
{"method": "POST", "path": "/participants/*"},
|
||||
{"method": "DELETE", "path": "/participants/*"},
|
||||
{"method": "POST", "path": "/read/*"},
|
||||
{"method": "GET", "path": "/search"},
|
||||
{"method": "GET", "path": "/unread"}
|
||||
],
|
||||
|
||||
"db_tables": {
|
||||
"conversations": {
|
||||
"columns": {
|
||||
"title": "text",
|
||||
"type": "text",
|
||||
"created_by": "text",
|
||||
"updated_at": "text"
|
||||
},
|
||||
"indexes": [["created_by"], ["updated_at"]]
|
||||
},
|
||||
"participants": {
|
||||
"columns": {
|
||||
"conversation_id": "text",
|
||||
"participant_id": "text",
|
||||
"participant_type": "text",
|
||||
"display_name": "text",
|
||||
"role": "text",
|
||||
"joined_at": "text"
|
||||
},
|
||||
"indexes": [
|
||||
["conversation_id"],
|
||||
["participant_id"],
|
||||
["conversation_id", "participant_id"]
|
||||
]
|
||||
},
|
||||
"messages": {
|
||||
"columns": {
|
||||
"conversation_id": "text",
|
||||
"participant_id": "text",
|
||||
"content": "text",
|
||||
"content_type": "text",
|
||||
"edited_at": "text"
|
||||
},
|
||||
"indexes": [["conversation_id"]]
|
||||
},
|
||||
"read_cursors": {
|
||||
"columns": {
|
||||
"conversation_id": "text",
|
||||
"participant_id": "text",
|
||||
"last_read_message_id": "text"
|
||||
},
|
||||
"indexes": [["conversation_id", "participant_id"]]
|
||||
}
|
||||
},
|
||||
|
||||
"schema_version": 1
|
||||
}
|
||||
@@ -1,753 +0,0 @@
|
||||
# Chat Core — Starlark Backend (v0.2.0)
|
||||
#
|
||||
# Library package providing conversations, messages, participants,
|
||||
# and read cursors. Consumable via lib.require("chat-core").
|
||||
#
|
||||
# Entry points:
|
||||
# on_request(req) → REST API routes
|
||||
# Exported globals → create, send, history, add_participant,
|
||||
# remove_participant, mark_read
|
||||
#
|
||||
# Modules: db, json, realtime
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Helpers
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
def _resp(status, data):
|
||||
return {"status": status, "body": json.encode(data), "headers": {"Content-Type": "application/json"}}
|
||||
|
||||
def _str(v):
|
||||
if v == None:
|
||||
return ""
|
||||
return str(v)
|
||||
|
||||
def _int(v):
|
||||
if v == None:
|
||||
return 0
|
||||
s = str(v)
|
||||
if not s:
|
||||
return 0
|
||||
return int(s)
|
||||
|
||||
def _is_participant(conversation_id, user_id):
|
||||
"""Check if user is a participant in the conversation."""
|
||||
rows = db.query("participants", filters={"conversation_id": conversation_id, "participant_id": user_id}, limit=1)
|
||||
return len(rows or []) > 0
|
||||
|
||||
def _get_participant(conversation_id, user_id):
|
||||
"""Get participant record or None."""
|
||||
rows = db.query("participants", filters={"conversation_id": conversation_id, "participant_id": user_id}, limit=1)
|
||||
if rows and len(rows) > 0:
|
||||
return rows[0]
|
||||
return None
|
||||
|
||||
def _is_admin(conversation_id, user_id):
|
||||
"""Check if user has admin role in the conversation."""
|
||||
p = _get_participant(conversation_id, user_id)
|
||||
if p:
|
||||
return _str(p.get("role", "")) == "admin"
|
||||
return False
|
||||
|
||||
def _get_conversation(conversation_id):
|
||||
"""Get conversation by ID or None."""
|
||||
rows = db.query("conversations", filters={"id": conversation_id}, limit=1)
|
||||
if rows and len(rows) > 0:
|
||||
return rows[0]
|
||||
return None
|
||||
|
||||
def _now():
|
||||
"""Current timestamp placeholder — db auto-populates created_at."""
|
||||
return ""
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Exported API (lib.require("chat-core"))
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
def create(title, type="group", participants=None, creator_id="", creator_display_name=""):
|
||||
"""Create a conversation and add initial participants.
|
||||
|
||||
Args:
|
||||
title: conversation title
|
||||
type: "direct" or "group" (default "group")
|
||||
participants: list of dicts with {id, type?, display_name?, role?}
|
||||
creator_id: user ID of the creator (added as admin)
|
||||
creator_display_name: display name of the creator
|
||||
|
||||
Returns:
|
||||
dict with conversation data
|
||||
"""
|
||||
if type not in ("direct", "group"):
|
||||
type = "group"
|
||||
|
||||
conv = db.insert("conversations", {
|
||||
"title": _str(title),
|
||||
"type": type,
|
||||
"created_by": _str(creator_id),
|
||||
"updated_at": "",
|
||||
})
|
||||
cid = conv["id"]
|
||||
|
||||
# Add creator as admin participant
|
||||
# NOTE: display_name is a snapshot captured at creation time.
|
||||
# DEPRECATED v0.6.15 — UI resolves display names from users table via sw.users.resolve().
|
||||
# Column retained for backward compatibility; UI no longer relies on this value for display.
|
||||
if creator_id:
|
||||
db.insert("participants", {
|
||||
"conversation_id": cid,
|
||||
"participant_id": _str(creator_id),
|
||||
"participant_type": "user",
|
||||
"display_name": _str(creator_display_name),
|
||||
"role": "admin",
|
||||
"joined_at": "",
|
||||
})
|
||||
|
||||
# Add initial participants
|
||||
for p in (participants or []):
|
||||
pid = _str(p.get("id", ""))
|
||||
if not pid or pid == _str(creator_id):
|
||||
continue
|
||||
db.insert("participants", {
|
||||
"conversation_id": cid,
|
||||
"participant_id": pid,
|
||||
"participant_type": _str(p.get("type", "user")),
|
||||
"display_name": _str(p.get("display_name", "")), # DEPRECATED v0.6.15 — snapshot only
|
||||
"role": _str(p.get("role", "member")),
|
||||
"joined_at": "",
|
||||
})
|
||||
|
||||
return conv
|
||||
|
||||
|
||||
def send(conversation_id, participant_id, content, content_type="text"):
|
||||
"""Send a message to a conversation.
|
||||
|
||||
Args:
|
||||
conversation_id: target conversation
|
||||
participant_id: sender ID
|
||||
content: message content
|
||||
content_type: "text", "system", or "file" (default "text")
|
||||
|
||||
Returns:
|
||||
dict with message data
|
||||
"""
|
||||
if content_type not in ("text", "system", "file"):
|
||||
content_type = "text"
|
||||
|
||||
msg = db.insert("messages", {
|
||||
"conversation_id": _str(conversation_id),
|
||||
"participant_id": _str(participant_id),
|
||||
"content": _str(content),
|
||||
"content_type": content_type,
|
||||
"edited_at": "",
|
||||
})
|
||||
|
||||
# Update conversation timestamp
|
||||
db.update("conversations", _str(conversation_id), {"updated_at": msg.get("created_at", "")})
|
||||
|
||||
# Publish realtime event
|
||||
realtime.publish(
|
||||
"conversation:" + _str(conversation_id),
|
||||
"message",
|
||||
{
|
||||
"id": msg.get("id", ""),
|
||||
"conversation_id": _str(conversation_id),
|
||||
"participant_id": _str(participant_id),
|
||||
"content": _str(content),
|
||||
"content_type": content_type,
|
||||
"created_at": msg.get("created_at", ""),
|
||||
},
|
||||
)
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
def history(conversation_id, limit=50, cursor=""):
|
||||
"""Get paginated message history for a conversation.
|
||||
|
||||
Args:
|
||||
conversation_id: target conversation
|
||||
limit: max messages to return (1-100, default 50)
|
||||
cursor: created_at value of last message from previous page
|
||||
|
||||
Returns:
|
||||
dict with {messages, has_more, next_cursor}
|
||||
"""
|
||||
lim = _int(limit)
|
||||
if lim < 1 or lim > 100:
|
||||
lim = 50
|
||||
|
||||
filters = {"conversation_id": _str(conversation_id)}
|
||||
before = {}
|
||||
if cursor:
|
||||
before = {"created_at": _str(cursor)}
|
||||
|
||||
rows = db.query("messages", filters=filters, order="-created_at", limit=lim + 1, before=before)
|
||||
rows = rows or []
|
||||
|
||||
has_more = len(rows) > lim
|
||||
if has_more:
|
||||
rows = rows[:lim]
|
||||
|
||||
next_cursor = ""
|
||||
if has_more and rows:
|
||||
next_cursor = _str(rows[-1].get("created_at", ""))
|
||||
|
||||
return {"messages": rows, "has_more": has_more, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
def add_participant(conversation_id, participant_id, participant_type="user", display_name="", role="member"):
|
||||
"""Add a participant to a conversation.
|
||||
|
||||
Returns:
|
||||
dict with participant data
|
||||
"""
|
||||
cid = _str(conversation_id)
|
||||
pid = _str(participant_id)
|
||||
|
||||
# Check if already a participant
|
||||
existing = db.query("participants", filters={"conversation_id": cid, "participant_id": pid}, limit=1)
|
||||
if existing and len(existing) > 0:
|
||||
return existing[0]
|
||||
|
||||
p = db.insert("participants", {
|
||||
"conversation_id": cid,
|
||||
"participant_id": pid,
|
||||
"participant_type": _str(participant_type),
|
||||
"display_name": _str(display_name), # DEPRECATED v0.6.15 — snapshot only
|
||||
"role": _str(role),
|
||||
"joined_at": "",
|
||||
})
|
||||
|
||||
# Publish realtime event
|
||||
realtime.publish(
|
||||
"conversation:" + cid,
|
||||
"participant.added",
|
||||
{
|
||||
"conversation_id": cid,
|
||||
"participant_id": pid,
|
||||
"participant_type": _str(participant_type),
|
||||
"display_name": _str(display_name),
|
||||
"role": _str(role),
|
||||
},
|
||||
)
|
||||
|
||||
# Insert system message
|
||||
send(cid, pid, "joined the conversation", "system")
|
||||
|
||||
return p
|
||||
|
||||
|
||||
def remove_participant(conversation_id, participant_id):
|
||||
"""Remove a participant from a conversation.
|
||||
|
||||
Returns:
|
||||
True on success
|
||||
"""
|
||||
cid = _str(conversation_id)
|
||||
pid = _str(participant_id)
|
||||
|
||||
# Delete participant record
|
||||
rows = db.query("participants", filters={"conversation_id": cid, "participant_id": pid}, limit=1)
|
||||
for r in (rows or []):
|
||||
db.delete("participants", r["id"])
|
||||
|
||||
# Delete read cursor
|
||||
cursors = db.query("read_cursors", filters={"conversation_id": cid, "participant_id": pid}, limit=1)
|
||||
for c in (cursors or []):
|
||||
db.delete("read_cursors", c["id"])
|
||||
|
||||
# Publish realtime event
|
||||
realtime.publish(
|
||||
"conversation:" + cid,
|
||||
"participant.removed",
|
||||
{"conversation_id": cid, "participant_id": pid},
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def mark_read(conversation_id, participant_id, last_read_message_id):
|
||||
"""Update the read cursor for a participant.
|
||||
|
||||
Returns:
|
||||
True on success
|
||||
"""
|
||||
cid = _str(conversation_id)
|
||||
pid = _str(participant_id)
|
||||
mid = _str(last_read_message_id)
|
||||
|
||||
# Delete existing cursor (upsert via delete+insert)
|
||||
existing = db.query("read_cursors", filters={"conversation_id": cid, "participant_id": pid}, limit=1)
|
||||
for r in (existing or []):
|
||||
db.delete("read_cursors", r["id"])
|
||||
|
||||
db.insert("read_cursors", {
|
||||
"conversation_id": cid,
|
||||
"participant_id": pid,
|
||||
"last_read_message_id": mid,
|
||||
})
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# REST API dispatcher
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
def on_request(req):
|
||||
path = req["path"]
|
||||
method = req["method"]
|
||||
user_id = req.get("user_id", "")
|
||||
|
||||
# ── Conversations ──────────────────────────
|
||||
|
||||
# GET /conversations — list user's conversations
|
||||
if method == "GET" and path == "/conversations":
|
||||
return _handle_list_conversations(req, user_id)
|
||||
|
||||
# POST /conversations — create
|
||||
if method == "POST" and path == "/conversations":
|
||||
return _handle_create_conversation(req, user_id)
|
||||
|
||||
# GET /search?q=term — search conversations and messages
|
||||
if method == "GET" and path == "/search":
|
||||
return _handle_search(req, user_id)
|
||||
|
||||
# GET /unread — unread counts
|
||||
if method == "GET" and path == "/unread":
|
||||
return _handle_unread(user_id)
|
||||
|
||||
# GET /conversations/:id
|
||||
if method == "GET" and path.startswith("/conversations/"):
|
||||
cid = path[len("/conversations/"):]
|
||||
return _handle_get_conversation(cid, user_id)
|
||||
|
||||
# PUT /conversations/:id
|
||||
if method == "PUT" and path.startswith("/conversations/"):
|
||||
cid = path[len("/conversations/"):]
|
||||
return _handle_update_conversation(cid, req, user_id)
|
||||
|
||||
# DELETE /conversations/:id
|
||||
if method == "DELETE" and path.startswith("/conversations/"):
|
||||
cid = path[len("/conversations/"):]
|
||||
return _handle_delete_conversation(cid, user_id)
|
||||
|
||||
# ── Messages ───────────────────────────────
|
||||
|
||||
# Routes: /messages/:conversation_id or /messages/:conversation_id/:message_id
|
||||
if path.startswith("/messages/"):
|
||||
remainder = path[len("/messages/"):]
|
||||
parts = remainder.split("/")
|
||||
cid = parts[0]
|
||||
mid = parts[1] if len(parts) > 1 else ""
|
||||
|
||||
if method == "GET" and not mid:
|
||||
return _handle_list_messages(cid, req, user_id)
|
||||
if method == "POST" and not mid:
|
||||
return _handle_send_message(cid, req, user_id)
|
||||
if method == "PUT" and mid:
|
||||
return _handle_edit_message(cid, mid, req, user_id)
|
||||
if method == "DELETE" and mid:
|
||||
return _handle_delete_message(cid, mid, user_id)
|
||||
|
||||
# ── Participants ───────────────────────────
|
||||
|
||||
if path.startswith("/participants/"):
|
||||
remainder = path[len("/participants/"):]
|
||||
parts = remainder.split("/")
|
||||
cid = parts[0]
|
||||
pid = parts[1] if len(parts) > 1 else ""
|
||||
|
||||
if method == "GET" and not pid:
|
||||
return _handle_list_participants(cid, user_id)
|
||||
if method == "POST" and not pid:
|
||||
return _handle_add_participant(cid, req, user_id)
|
||||
if method == "DELETE" and pid:
|
||||
return _handle_remove_participant(cid, pid, user_id)
|
||||
|
||||
# ── Read cursors ──────────────────────────
|
||||
|
||||
if method == "POST" and path.startswith("/read/"):
|
||||
cid = path[len("/read/"):]
|
||||
return _handle_mark_read(cid, req, user_id)
|
||||
|
||||
return _resp(404, {"error": "not found"})
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Conversation handlers
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
def _handle_list_conversations(req, user_id):
|
||||
"""List conversations the user is a participant in."""
|
||||
# Get all conversation IDs for this user
|
||||
my_parts = db.query("participants", filters={"participant_id": user_id}, limit=500)
|
||||
if not my_parts:
|
||||
return _resp(200, {"data": []})
|
||||
|
||||
cids = []
|
||||
for p in my_parts:
|
||||
cids.append(_str(p.get("conversation_id", "")))
|
||||
|
||||
# Fetch conversations and enrich with last message
|
||||
items = []
|
||||
for cid in cids:
|
||||
conv = _get_conversation(cid)
|
||||
if not conv:
|
||||
continue
|
||||
|
||||
# Get last message
|
||||
last_msgs = db.query("messages", filters={"conversation_id": cid}, order="-created_at", limit=1)
|
||||
last_msg = None
|
||||
if last_msgs and len(last_msgs) > 0:
|
||||
last_msg = {
|
||||
"id": last_msgs[0].get("id", ""),
|
||||
"content": _str(last_msgs[0].get("content", "")),
|
||||
"participant_id": _str(last_msgs[0].get("participant_id", "")),
|
||||
"content_type": _str(last_msgs[0].get("content_type", "")),
|
||||
"created_at": _str(last_msgs[0].get("created_at", "")),
|
||||
}
|
||||
|
||||
# Get participant count
|
||||
parts = db.query("participants", filters={"conversation_id": cid}, limit=500)
|
||||
part_count = len(parts or [])
|
||||
|
||||
items.append({
|
||||
"id": conv.get("id", ""),
|
||||
"title": conv.get("title", ""),
|
||||
"type": conv.get("type", ""),
|
||||
"created_by": conv.get("created_by", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"last_message": last_msg,
|
||||
"participant_count": part_count,
|
||||
})
|
||||
|
||||
# Sort by updated_at descending (most recent first)
|
||||
items = sorted(items, key=lambda x: x.get("updated_at", "") or x.get("created_at", ""), reverse=True)
|
||||
|
||||
return _resp(200, {"data": items})
|
||||
|
||||
|
||||
def _handle_create_conversation(req, user_id):
|
||||
"""Create a new conversation."""
|
||||
body = json.decode(req.get("body", "{}"))
|
||||
title = _str(body.get("title", ""))
|
||||
conv_type = _str(body.get("type", "group"))
|
||||
participants_list = body.get("participants", [])
|
||||
creator_name = _str(body.get("creator_display_name", ""))
|
||||
|
||||
conv = create(title, conv_type, participants_list, user_id, creator_name)
|
||||
return _resp(201, conv)
|
||||
|
||||
|
||||
def _handle_get_conversation(cid, user_id):
|
||||
"""Get conversation detail with participants."""
|
||||
if not _is_participant(cid, user_id):
|
||||
return _resp(403, {"error": "not a participant"})
|
||||
|
||||
conv = _get_conversation(cid)
|
||||
if not conv:
|
||||
return _resp(404, {"error": "conversation not found"})
|
||||
|
||||
parts = db.query("participants", filters={"conversation_id": cid}, limit=500)
|
||||
|
||||
return _resp(200, {
|
||||
"id": conv.get("id", ""),
|
||||
"title": conv.get("title", ""),
|
||||
"type": conv.get("type", ""),
|
||||
"created_by": conv.get("created_by", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"participants": parts or [],
|
||||
})
|
||||
|
||||
|
||||
def _handle_update_conversation(cid, req, user_id):
|
||||
"""Update conversation (admin only)."""
|
||||
if not _is_admin(cid, user_id):
|
||||
return _resp(403, {"error": "admin only"})
|
||||
|
||||
body = json.decode(req.get("body", "{}"))
|
||||
patch = {}
|
||||
title = body.get("title", None)
|
||||
if title != None:
|
||||
patch["title"] = _str(title)
|
||||
|
||||
if patch:
|
||||
db.update("conversations", cid, patch)
|
||||
|
||||
conv = _get_conversation(cid)
|
||||
return _resp(200, conv)
|
||||
|
||||
|
||||
def _handle_delete_conversation(cid, user_id):
|
||||
"""Delete conversation and all associated data (admin only)."""
|
||||
if not _is_admin(cid, user_id):
|
||||
return _resp(403, {"error": "admin only"})
|
||||
|
||||
# Cascade delete: messages, participants, read_cursors, then conversation
|
||||
msgs = db.query("messages", filters={"conversation_id": cid}, limit=5000)
|
||||
for m in (msgs or []):
|
||||
db.delete("messages", m["id"])
|
||||
|
||||
parts = db.query("participants", filters={"conversation_id": cid}, limit=500)
|
||||
for p in (parts or []):
|
||||
db.delete("participants", p["id"])
|
||||
|
||||
cursors = db.query("read_cursors", filters={"conversation_id": cid}, limit=500)
|
||||
for c in (cursors or []):
|
||||
db.delete("read_cursors", c["id"])
|
||||
|
||||
db.delete("conversations", cid)
|
||||
return _resp(200, {"ok": True})
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Message handlers
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
def _handle_list_messages(cid, req, user_id):
|
||||
"""Paginated message history."""
|
||||
if not _is_participant(cid, user_id):
|
||||
return _resp(403, {"error": "not a participant"})
|
||||
|
||||
q = req.get("query", {})
|
||||
limit_val = _int(q.get("limit", "50"))
|
||||
cursor = _str(q.get("cursor", ""))
|
||||
|
||||
result = history(cid, limit_val, cursor)
|
||||
return _resp(200, result)
|
||||
|
||||
|
||||
def _handle_send_message(cid, req, user_id):
|
||||
"""Send a message."""
|
||||
if not _is_participant(cid, user_id):
|
||||
return _resp(403, {"error": "not a participant"})
|
||||
|
||||
body = json.decode(req.get("body", "{}"))
|
||||
content = _str(body.get("content", ""))
|
||||
content_type = _str(body.get("content_type", "text"))
|
||||
|
||||
if not content:
|
||||
return _resp(400, {"error": "content required"})
|
||||
|
||||
msg = send(cid, user_id, content, content_type)
|
||||
return _resp(201, msg)
|
||||
|
||||
|
||||
def _handle_edit_message(cid, mid, req, user_id):
|
||||
"""Edit a message (author only)."""
|
||||
if not _is_participant(cid, user_id):
|
||||
return _resp(403, {"error": "not a participant"})
|
||||
|
||||
# Verify ownership
|
||||
msgs = db.query("messages", filters={"id": mid}, limit=1)
|
||||
if not msgs:
|
||||
return _resp(404, {"error": "message not found"})
|
||||
|
||||
msg = msgs[0]
|
||||
if _str(msg.get("participant_id", "")) != user_id:
|
||||
return _resp(403, {"error": "can only edit own messages"})
|
||||
|
||||
body = json.decode(req.get("body", "{}"))
|
||||
content = _str(body.get("content", ""))
|
||||
if not content:
|
||||
return _resp(400, {"error": "content required"})
|
||||
|
||||
# Use created_at of the message as the edited_at marker
|
||||
db.update("messages", mid, {"content": content, "edited_at": msg.get("created_at", "")})
|
||||
|
||||
# Publish edit event
|
||||
realtime.publish(
|
||||
"conversation:" + cid,
|
||||
"message.edited",
|
||||
{"id": mid, "conversation_id": cid, "content": content, "edited_by": user_id},
|
||||
)
|
||||
|
||||
updated = db.query("messages", filters={"id": mid}, limit=1)
|
||||
return _resp(200, updated[0] if updated else {})
|
||||
|
||||
|
||||
def _handle_delete_message(cid, mid, user_id):
|
||||
"""Delete a message (author or admin)."""
|
||||
if not _is_participant(cid, user_id):
|
||||
return _resp(403, {"error": "not a participant"})
|
||||
|
||||
msgs = db.query("messages", filters={"id": mid}, limit=1)
|
||||
if not msgs:
|
||||
return _resp(404, {"error": "message not found"})
|
||||
|
||||
msg = msgs[0]
|
||||
is_author = _str(msg.get("participant_id", "")) == user_id
|
||||
is_conv_admin = _is_admin(cid, user_id)
|
||||
|
||||
if not is_author and not is_conv_admin:
|
||||
return _resp(403, {"error": "can only delete own messages or be admin"})
|
||||
|
||||
db.delete("messages", mid)
|
||||
|
||||
# Publish delete event
|
||||
realtime.publish(
|
||||
"conversation:" + cid,
|
||||
"message.deleted",
|
||||
{"id": mid, "conversation_id": cid, "deleted_by": user_id},
|
||||
)
|
||||
|
||||
return _resp(200, {"ok": True})
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Participant handlers
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
def _handle_list_participants(cid, user_id):
|
||||
"""List participants in a conversation."""
|
||||
if not _is_participant(cid, user_id):
|
||||
return _resp(403, {"error": "not a participant"})
|
||||
|
||||
parts = db.query("participants", filters={"conversation_id": cid}, limit=500)
|
||||
return _resp(200, {"data": parts or []})
|
||||
|
||||
|
||||
def _handle_add_participant(cid, req, user_id):
|
||||
"""Add a participant (admin only)."""
|
||||
if not _is_admin(cid, user_id):
|
||||
return _resp(403, {"error": "admin only"})
|
||||
|
||||
body = json.decode(req.get("body", "{}"))
|
||||
pid = _str(body.get("participant_id", ""))
|
||||
if not pid:
|
||||
return _resp(400, {"error": "participant_id required"})
|
||||
|
||||
ptype = _str(body.get("participant_type", "user"))
|
||||
display_name = _str(body.get("display_name", ""))
|
||||
role = _str(body.get("role", "member"))
|
||||
|
||||
p = add_participant(cid, pid, ptype, display_name, role)
|
||||
return _resp(201, p)
|
||||
|
||||
|
||||
def _handle_remove_participant(cid, pid, user_id):
|
||||
"""Remove a participant (admin only, or self-remove)."""
|
||||
is_self = pid == user_id
|
||||
if not is_self and not _is_admin(cid, user_id):
|
||||
return _resp(403, {"error": "admin only (or remove yourself)"})
|
||||
|
||||
remove_participant(cid, pid)
|
||||
return _resp(200, {"ok": True})
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════
|
||||
# Read cursor handlers
|
||||
# ═══════════════════════════════════════════════
|
||||
|
||||
def _handle_mark_read(cid, req, user_id):
|
||||
"""Mark conversation as read up to a message."""
|
||||
if not _is_participant(cid, user_id):
|
||||
return _resp(403, {"error": "not a participant"})
|
||||
|
||||
body = json.decode(req.get("body", "{}"))
|
||||
mid = _str(body.get("last_read_message_id", ""))
|
||||
if not mid:
|
||||
return _resp(400, {"error": "last_read_message_id required"})
|
||||
|
||||
mark_read(cid, user_id, mid)
|
||||
return _resp(200, {"ok": True})
|
||||
|
||||
|
||||
def _handle_search(req, user_id):
|
||||
"""Search across conversation titles and message content."""
|
||||
q = _str(req.get("query", {}).get("q", ""))
|
||||
if len(q) < 2:
|
||||
return _resp(400, {"error": "query must be at least 2 characters"})
|
||||
|
||||
pattern = "%" + q + "%"
|
||||
|
||||
# Get user's conversation IDs
|
||||
my_parts = db.query("participants", filters={"participant_id": user_id}, limit=500)
|
||||
if not my_parts:
|
||||
return _resp(200, {"conversations": [], "messages": []})
|
||||
|
||||
cid_set = {}
|
||||
for p in my_parts:
|
||||
cid_set[_str(p.get("conversation_id", ""))] = True
|
||||
|
||||
# Search conversations by title
|
||||
matching_convs = db.query("conversations", search_like={"title": pattern}, limit=50)
|
||||
conv_results = []
|
||||
for conv in (matching_convs or []):
|
||||
cid = _str(conv.get("id", ""))
|
||||
if cid in cid_set:
|
||||
conv_results.append({
|
||||
"id": cid,
|
||||
"title": conv.get("title", ""),
|
||||
"type": conv.get("type", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
})
|
||||
|
||||
# Search messages in user's conversations
|
||||
msg_results = []
|
||||
for cid in cid_set:
|
||||
if not cid:
|
||||
continue
|
||||
msgs = db.query("messages", filters={"conversation_id": cid}, search_like={"content": pattern}, order="-created_at", limit=5)
|
||||
for m in (msgs or []):
|
||||
msg_results.append({
|
||||
"id": m.get("id", ""),
|
||||
"conversation_id": cid,
|
||||
"participant_id": m.get("participant_id", ""),
|
||||
"content": _str(m.get("content", "")),
|
||||
"content_type": _str(m.get("content_type", "")),
|
||||
"created_at": _str(m.get("created_at", "")),
|
||||
})
|
||||
|
||||
# Sort messages by created_at descending, limit to 50
|
||||
msg_results = sorted(msg_results, key=lambda x: x.get("created_at", ""), reverse=True)[:50]
|
||||
|
||||
return _resp(200, {"conversations": conv_results, "messages": msg_results})
|
||||
|
||||
|
||||
def _handle_unread(user_id):
|
||||
"""Get unread counts for all user's conversations."""
|
||||
my_parts = db.query("participants", filters={"participant_id": user_id}, limit=500)
|
||||
if not my_parts:
|
||||
return _resp(200, {"data": {}})
|
||||
|
||||
counts = {}
|
||||
for p in my_parts:
|
||||
cid = _str(p.get("conversation_id", ""))
|
||||
if not cid:
|
||||
continue
|
||||
|
||||
# Get read cursor
|
||||
cursors = db.query("read_cursors", filters={"conversation_id": cid, "participant_id": user_id}, limit=1)
|
||||
|
||||
if cursors and len(cursors) > 0:
|
||||
last_read_id = _str(cursors[0].get("last_read_message_id", ""))
|
||||
if last_read_id:
|
||||
# Get the created_at of the last read message
|
||||
last_read_msgs = db.query("messages", filters={"id": last_read_id}, limit=1)
|
||||
if last_read_msgs and len(last_read_msgs) > 0:
|
||||
last_read_at = _str(last_read_msgs[0].get("created_at", ""))
|
||||
# Count messages after the read cursor
|
||||
unread = db.query("messages", filters={"conversation_id": cid}, after={"created_at": last_read_at}, limit=1000)
|
||||
counts[cid] = len(unread or [])
|
||||
else:
|
||||
# Last read message was deleted — count all
|
||||
all_msgs = db.query("messages", filters={"conversation_id": cid}, limit=1000)
|
||||
counts[cid] = len(all_msgs or [])
|
||||
else:
|
||||
# No cursor value — all messages are unread
|
||||
all_msgs = db.query("messages", filters={"conversation_id": cid}, limit=1000)
|
||||
counts[cid] = len(all_msgs or [])
|
||||
else:
|
||||
# No cursor at all — all messages are unread
|
||||
all_msgs = db.query("messages", filters={"conversation_id": cid}, limit=1000)
|
||||
counts[cid] = len(all_msgs or [])
|
||||
|
||||
return _resp(200, {"data": counts})
|
||||
@@ -1,616 +0,0 @@
|
||||
/* ═══════════════════════════════════════════
|
||||
Chat Surface — Styles (v0.2.0)
|
||||
Uses variables.css theme tokens:
|
||||
--bg, --bg-surface, --bg-raised, --bg-hover, --bg-secondary
|
||||
--text, --text-2, --text-3
|
||||
--accent, --accent-dim, --border, --border-light
|
||||
--input-bg, --danger, --danger-bg, --success
|
||||
═══════════════════════════════════════════ */
|
||||
|
||||
/* ── Layout ─────────────────────────────── */
|
||||
|
||||
.ext-chat-app {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ext-chat-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.ext-chat-body {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.ext-chat-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ── Topbar extras ──────────────────────── */
|
||||
|
||||
.ext-chat-topbar__thread-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
margin-right: var(--sp-2);
|
||||
color: var(--text-2);
|
||||
}
|
||||
|
||||
/* ── Sidebar ────────────────────────────── */
|
||||
|
||||
.ext-chat-sidebar {
|
||||
width: 280px;
|
||||
min-width: 280px;
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__empty {
|
||||
padding: var(--sp-6) var(--sp-4);
|
||||
text-align: center;
|
||||
color: var(--text-3);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item {
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
cursor: pointer;
|
||||
border-bottom: 1px solid var(--border-light);
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item--active {
|
||||
background: var(--accent-dim);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item-title {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
flex: 1;
|
||||
margin-right: var(--sp-2);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item-time {
|
||||
font-size: 11px;
|
||||
color: var(--text-3);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item-bottom {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item-preview {
|
||||
font-size: 12px;
|
||||
color: var(--text-2);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__badge {
|
||||
background: var(--accent);
|
||||
color: var(--text-on-color);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 9px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 5px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ── Sidebar Search ────────────────────── */
|
||||
|
||||
.ext-chat-sidebar__search {
|
||||
position: relative;
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
border-bottom: 1px solid var(--border-light);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__search-input {
|
||||
width: 100%;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-2) var(--sp-6) var(--sp-2) var(--sp-3);
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
background: var(--input-bg);
|
||||
color: var(--text);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__search-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__search-clear {
|
||||
position: absolute;
|
||||
right: 22px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-3);
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
padding: 0 var(--sp-1);
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__search-clear:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__search-results {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__search-section {
|
||||
padding: var(--sp-2) var(--sp-4) var(--sp-1);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__search-loading {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: var(--sp-4);
|
||||
}
|
||||
|
||||
.ext-chat-sidebar__item--search-msg .ext-chat-sidebar__item-preview {
|
||||
font-size: 13px;
|
||||
white-space: normal;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ── Message Thread ─────────────────────── */
|
||||
|
||||
.ext-chat-thread {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.ext-chat-thread--empty {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
.ext-chat-thread__messages {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-4);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-1);
|
||||
}
|
||||
|
||||
.ext-chat-thread__loading {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: var(--sp-6);
|
||||
}
|
||||
|
||||
.ext-chat-thread__loading-more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: var(--sp-2);
|
||||
}
|
||||
|
||||
.ext-chat-thread__load-more {
|
||||
align-self: center;
|
||||
background: none;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-1) var(--sp-3);
|
||||
font-size: 12px;
|
||||
color: var(--text-2);
|
||||
cursor: pointer;
|
||||
margin-bottom: var(--sp-2);
|
||||
}
|
||||
|
||||
.ext-chat-thread__load-more:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-chat-thread__typing {
|
||||
padding: var(--sp-1) var(--sp-4) var(--sp-2);
|
||||
font-size: 12px;
|
||||
color: var(--text-3);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* ── Message Bubble ─────────────────────── */
|
||||
|
||||
.ext-chat-msg {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-1) 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ext-chat-msg--own {
|
||||
flex-direction: row-reverse;
|
||||
}
|
||||
|
||||
.ext-chat-msg--system {
|
||||
justify-content: center;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.ext-chat-msg--system span {
|
||||
font-size: 12px;
|
||||
color: var(--text-3);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.ext-chat-msg--deleted {
|
||||
justify-content: center;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.ext-chat-msg--deleted em {
|
||||
font-size: 12px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
.ext-chat-msg__body {
|
||||
max-width: 65%;
|
||||
background: var(--bg-raised);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
}
|
||||
|
||||
.ext-chat-msg--own .ext-chat-msg__body {
|
||||
background: var(--accent);
|
||||
color: var(--text-on-color);
|
||||
}
|
||||
|
||||
.ext-chat-msg__name {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--text-2);
|
||||
display: block;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.ext-chat-msg__content {
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.ext-chat-msg__meta {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
align-items: center;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.ext-chat-msg__time {
|
||||
font-size: 10px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
.ext-chat-msg--own .ext-chat-msg__time {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
.ext-chat-msg__edited {
|
||||
font-size: 10px;
|
||||
color: var(--text-3);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.ext-chat-msg--own .ext-chat-msg__edited {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
/* ── Message Actions ────────────────────── */
|
||||
|
||||
.ext-chat-msg__actions {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-lg);
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.ext-chat-msg--own .ext-chat-msg__actions {
|
||||
right: auto;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.ext-chat-msg__action {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
color: var(--text-2);
|
||||
}
|
||||
|
||||
.ext-chat-msg__action:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-chat-msg__action--danger:hover {
|
||||
background: var(--danger-bg);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
/* ── Message Edit ───────────────────────── */
|
||||
|
||||
.ext-chat-msg__edit {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.ext-chat-msg__edit-input {
|
||||
width: 100%;
|
||||
min-width: 200px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-2) var(--sp-2);
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
resize: vertical;
|
||||
background: var(--input-bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ext-chat-msg__edit-actions {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* ── Compose Bar ────────────────────────── */
|
||||
|
||||
.ext-chat-compose {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.ext-chat-compose__input {
|
||||
flex: 1;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
resize: none;
|
||||
line-height: 1.4;
|
||||
max-height: 160px;
|
||||
background: var(--input-bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ext-chat-compose__input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 2px var(--accent-dim);
|
||||
}
|
||||
|
||||
/* ── Participant Sidebar ────────────────── */
|
||||
|
||||
.ext-chat-participants {
|
||||
width: 240px;
|
||||
min-width: 240px;
|
||||
border-left: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
|
||||
.ext-chat-participants__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.ext-chat-participants__list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-2) 0;
|
||||
}
|
||||
|
||||
.ext-chat-participants__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
}
|
||||
|
||||
.ext-chat-participants__name {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.ext-chat-participants__badge {
|
||||
font-size: 10px;
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
margin-left: var(--sp-1);
|
||||
}
|
||||
|
||||
.ext-chat-participants__status {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-3);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ext-chat-participants__status--online {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.ext-chat-participants__remove {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-3);
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
padding: 0 var(--sp-1);
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.ext-chat-participants__remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
/* ── New Conversation Dialog ────────────── */
|
||||
|
||||
.ext-chat-new {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 320px;
|
||||
}
|
||||
|
||||
.ext-chat-new__type {
|
||||
display: flex;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
.ext-chat-new__type label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ext-chat-new__title {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
background: var(--input-bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ext-chat-new__selected {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.ext-chat-new__chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
background: var(--accent-dim);
|
||||
color: var(--accent);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
padding: 3px var(--sp-2);
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
|
||||
.ext-chat-new__chip button {
|
||||
background: none;
|
||||
border: none;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* ── Dialog UserPicker overflow fix ─────── */
|
||||
/* Allow the autocomplete dropdown to overflow the dialog body.
|
||||
Applies to both New Conversation and Add Participant dialogs. */
|
||||
|
||||
[data-ext="chat"] .sw-dialog__body:has(.sw-user-picker) {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-ext="chat"] .sw-dialog:has(.sw-user-picker) {
|
||||
overflow: visible;
|
||||
}
|
||||
@@ -1,879 +0,0 @@
|
||||
/**
|
||||
* Chat — Surface Entry Point (v0.2.0)
|
||||
*
|
||||
* Messaging surface built on chat-core library:
|
||||
* sw.api.ext('chat-core') — conversation/message CRUD
|
||||
* sw.api.ext('chat') — typing indicators
|
||||
* sw.realtime — live events
|
||||
* sw.ui.* — primitive components
|
||||
* sw.shell.Topbar — navigation bar
|
||||
*/
|
||||
(async function () {
|
||||
'use strict';
|
||||
|
||||
var mount = document.getElementById('extension-mount');
|
||||
if (!mount) return;
|
||||
|
||||
var base = window.__BASE__ || '';
|
||||
var ver = window.__VERSION__ || '0';
|
||||
|
||||
// ── Boot SDK ───────────────────────────────
|
||||
try {
|
||||
if (!window.preact) {
|
||||
var { h, render } = await import(base + '/js/sw/vendor/preact.module.js');
|
||||
var hooksModule = await import(base + '/js/sw/vendor/hooks.module.js');
|
||||
var htmModule = await import(base + '/js/sw/vendor/htm.module.js');
|
||||
window.preact = { h, render };
|
||||
window.hooks = hooksModule;
|
||||
window.html = htmModule.default.bind(h);
|
||||
}
|
||||
var sdk = await import(base + '/js/sw/sdk/index.js?v=' + ver);
|
||||
await sdk.boot();
|
||||
} catch (e) {
|
||||
mount.innerHTML = '<p style="color:var(--danger);padding:24px;">SDK boot failed: ' + e.message + '</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
var { html } = window;
|
||||
var { useState, useEffect, useCallback, useRef, useMemo } = hooks;
|
||||
var { render } = preact;
|
||||
|
||||
// ── SDK modules ────────────────────────────
|
||||
var api = sw.api.ext('chat-core');
|
||||
var chatApi = sw.api.ext('chat');
|
||||
var { Button, Spinner, Avatar, Dialog, Tabs } = sw.ui;
|
||||
var Topbar = sw.shell.Topbar;
|
||||
|
||||
// Import UserPicker directly (not in sw.ui index)
|
||||
var { UserPicker } = await import(base + '/js/sw/primitives/user-picker.js?v=' + ver);
|
||||
|
||||
// ── Helpers ────────────────────────────────
|
||||
var _timers = {};
|
||||
function debounce(key, fn, ms) {
|
||||
clearTimeout(_timers[key]);
|
||||
_timers[key] = setTimeout(fn, ms);
|
||||
}
|
||||
|
||||
function timeAgo(ts) {
|
||||
if (!ts) return '';
|
||||
var d = new Date(ts);
|
||||
var now = Date.now();
|
||||
var diff = Math.floor((now - d.getTime()) / 1000);
|
||||
if (diff < 60) return 'now';
|
||||
if (diff < 3600) return Math.floor(diff / 60) + 'm';
|
||||
if (diff < 86400) return Math.floor(diff / 3600) + 'h';
|
||||
if (diff < 604800) return Math.floor(diff / 86400) + 'd';
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
function truncate(str, len) {
|
||||
if (!str) return '';
|
||||
return str.length > len ? str.slice(0, len) + '\u2026' : str;
|
||||
}
|
||||
|
||||
function currentUserId() {
|
||||
return sw.auth?.user?.id || '';
|
||||
}
|
||||
|
||||
function currentDisplayName() {
|
||||
return sw.auth?.user?.display_name || sw.auth?.user?.username || '';
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// ConversationList — left sidebar
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
function ConversationList({ selected, onSelect, onNew, conversations, unread }) {
|
||||
var [searchQuery, setSearchQuery] = useState('');
|
||||
var [searchResults, setSearchResults] = useState(null);
|
||||
var [searching, setSearching] = useState(false);
|
||||
|
||||
function handleSearchInput(e) {
|
||||
var q = e.target.value;
|
||||
setSearchQuery(q);
|
||||
if (q.length < 2) {
|
||||
setSearchResults(null);
|
||||
setSearching(false);
|
||||
return;
|
||||
}
|
||||
debounce('search', () => {
|
||||
setSearching(true);
|
||||
api.get('/search?q=' + encodeURIComponent(q)).then(res => {
|
||||
setSearchResults(res || { conversations: [], messages: [] });
|
||||
setSearching(false);
|
||||
}).catch(() => { setSearching(false); });
|
||||
}, 300);
|
||||
}
|
||||
|
||||
function clearSearch() {
|
||||
setSearchQuery('');
|
||||
setSearchResults(null);
|
||||
setSearching(false);
|
||||
}
|
||||
|
||||
function selectFromSearch(cid) {
|
||||
clearSearch();
|
||||
onSelect(cid);
|
||||
}
|
||||
|
||||
// Render search results
|
||||
var showSearch = searchResults !== null;
|
||||
var sConvs = showSearch ? (searchResults.conversations || []) : [];
|
||||
var sMsgs = showSearch ? (searchResults.messages || []) : [];
|
||||
|
||||
return html`
|
||||
<div class="ext-chat-sidebar">
|
||||
<div class="ext-chat-sidebar__header">
|
||||
<span class="ext-chat-sidebar__title">Conversations</span>
|
||||
<${Button} size="sm" onClick=${onNew}>New<//>
|
||||
</div>
|
||||
<div class="ext-chat-sidebar__search">
|
||||
<input class="ext-chat-sidebar__search-input"
|
||||
type="text"
|
||||
value=${searchQuery}
|
||||
placeholder="Search\u2026"
|
||||
onInput=${handleSearchInput} />
|
||||
${searchQuery && html`
|
||||
<button class="ext-chat-sidebar__search-clear" onClick=${clearSearch}>\u00d7</button>`}
|
||||
</div>
|
||||
${showSearch ? html`
|
||||
<div class="ext-chat-sidebar__search-results">
|
||||
${searching && html`<div class="ext-chat-sidebar__search-loading"><${Spinner} size="sm" /></div>`}
|
||||
${!searching && sConvs.length === 0 && sMsgs.length === 0 && html`
|
||||
<div class="ext-chat-sidebar__empty">No results</div>`}
|
||||
${sConvs.length > 0 && html`
|
||||
<div class="ext-chat-sidebar__search-section">Conversations</div>
|
||||
${sConvs.map(c => html`
|
||||
<div key=${c.id} class="ext-chat-sidebar__item" onClick=${() => selectFromSearch(c.id)}>
|
||||
<div class="ext-chat-sidebar__item-top">
|
||||
<span class="ext-chat-sidebar__item-title">${c.title || 'Untitled'}</span>
|
||||
<span class="ext-chat-sidebar__item-time">${timeAgo(c.updated_at || c.created_at)}</span>
|
||||
</div>
|
||||
</div>`)}`}
|
||||
${sMsgs.length > 0 && html`
|
||||
<div class="ext-chat-sidebar__search-section">Messages</div>
|
||||
${sMsgs.map(m => html`
|
||||
<div key=${m.id} class="ext-chat-sidebar__item ext-chat-sidebar__item--search-msg" onClick=${() => selectFromSearch(m.conversation_id)}>
|
||||
<div class="ext-chat-sidebar__item-top">
|
||||
<span class="ext-chat-sidebar__item-preview">${truncate(m.content, 80)}</span>
|
||||
</div>
|
||||
<div class="ext-chat-sidebar__item-bottom">
|
||||
<span class="ext-chat-sidebar__item-time">${timeAgo(m.created_at)}</span>
|
||||
</div>
|
||||
</div>`)}`}
|
||||
</div>
|
||||
` : html`
|
||||
<div class="ext-chat-sidebar__list">
|
||||
${conversations.length === 0 && html`
|
||||
<div class="ext-chat-sidebar__empty">No conversations yet</div>`}
|
||||
${conversations.map(c => html`
|
||||
<div key=${c.id}
|
||||
class=${'ext-chat-sidebar__item' + (selected === c.id ? ' ext-chat-sidebar__item--active' : '')}
|
||||
onClick=${() => onSelect(c.id)}>
|
||||
<div class="ext-chat-sidebar__item-top">
|
||||
<span class="ext-chat-sidebar__item-title">${c.title || 'Untitled'}</span>
|
||||
<span class="ext-chat-sidebar__item-time">${timeAgo(c.updated_at || c.created_at)}</span>
|
||||
</div>
|
||||
<div class="ext-chat-sidebar__item-bottom">
|
||||
<span class="ext-chat-sidebar__item-preview">
|
||||
${c.last_message
|
||||
? truncate(c.last_message.content_type === 'system'
|
||||
? '\u2022 ' + c.last_message.content
|
||||
: c.last_message.content, 60)
|
||||
: 'No messages yet'}
|
||||
</span>
|
||||
${(unread[c.id] || 0) > 0 && html`
|
||||
<span class="ext-chat-sidebar__badge">${unread[c.id]}</span>`}
|
||||
</div>
|
||||
</div>`)}
|
||||
</div>
|
||||
`}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// MessageBubble — single message
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
function MessageBubble({ msg, isOwn, onEdit, onDelete }) {
|
||||
var [editing, setEditing] = useState(false);
|
||||
var [editText, setEditText] = useState('');
|
||||
var [hover, setHover] = useState(false);
|
||||
|
||||
if (msg._deleted) {
|
||||
return html`
|
||||
<div class="ext-chat-msg ext-chat-msg--deleted">
|
||||
<em>This message was deleted</em>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
if (msg.content_type === 'system') {
|
||||
return html`
|
||||
<div class="ext-chat-msg ext-chat-msg--system">
|
||||
<span>${msg.content}</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function startEdit() {
|
||||
setEditText(msg.content);
|
||||
setEditing(true);
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
setEditing(false);
|
||||
setEditText('');
|
||||
}
|
||||
|
||||
function saveEdit() {
|
||||
if (editText.trim() && editText !== msg.content) {
|
||||
onEdit(msg.id, editText.trim());
|
||||
}
|
||||
setEditing(false);
|
||||
}
|
||||
|
||||
function onEditKeyDown(e) {
|
||||
if (e.key === 'Escape') cancelEdit();
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); saveEdit(); }
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class=${'ext-chat-msg' + (isOwn ? ' ext-chat-msg--own' : '')}
|
||||
onMouseEnter=${() => setHover(true)}
|
||||
onMouseLeave=${() => setHover(false)}>
|
||||
${!isOwn && html`
|
||||
<${Avatar} name=${msg._display_name || 'Unknown'} size="sm" />`}
|
||||
<div class="ext-chat-msg__body">
|
||||
${!isOwn && html`<span class="ext-chat-msg__name">${msg._display_name || 'Unknown'}</span>`}
|
||||
${editing ? html`
|
||||
<div class="ext-chat-msg__edit">
|
||||
<textarea class="ext-chat-msg__edit-input"
|
||||
value=${editText}
|
||||
onInput=${e => setEditText(e.target.value)}
|
||||
onKeyDown=${onEditKeyDown}
|
||||
rows="2" />
|
||||
<div class="ext-chat-msg__edit-actions">
|
||||
<${Button} size="sm" variant="secondary" onClick=${cancelEdit}>Cancel<//>
|
||||
<${Button} size="sm" onClick=${saveEdit}>Save<//>
|
||||
</div>
|
||||
</div>
|
||||
` : msg.content_type === 'markdown' && sw?.markdown?.ready ? html`
|
||||
<div class="ext-chat-msg__content" dangerouslySetInnerHTML=${{ __html: sw.markdown.renderSync(msg.content, { sanitize: true }) }} />` : html`
|
||||
<div class="ext-chat-msg__content">${msg.content}</div>`}
|
||||
<div class="ext-chat-msg__meta">
|
||||
<span class="ext-chat-msg__time">${timeAgo(msg.created_at)}</span>
|
||||
${msg.edited_at && html`<span class="ext-chat-msg__edited">(edited)</span>`}
|
||||
</div>
|
||||
</div>
|
||||
${hover && isOwn && !editing && html`
|
||||
<div class="ext-chat-msg__actions">
|
||||
<button class="ext-chat-msg__action" onClick=${startEdit} title="Edit">✎</button>
|
||||
<button class="ext-chat-msg__action ext-chat-msg__action--danger" onClick=${() => onDelete(msg.id)} title="Delete">🗑</button>
|
||||
</div>`}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// MessageThread — center pane
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
function MessageThread({ conversationId, participants }) {
|
||||
var [messages, setMessages] = useState([]);
|
||||
var [loading, setLoading] = useState(false);
|
||||
var [hasMore, setHasMore] = useState(false);
|
||||
var [nextCursor, setNextCursor] = useState('');
|
||||
var [typingUsers, setTypingUsers] = useState({});
|
||||
var [resolvedNames, setResolvedNames] = useState({});
|
||||
var bottomRef = useRef(null);
|
||||
var listRef = useRef(null);
|
||||
var userId = currentUserId();
|
||||
|
||||
// Resolve participant display names from users table (not snapshot)
|
||||
useEffect(() => {
|
||||
var ids = (participants || []).map(p => p.participant_id).filter(Boolean);
|
||||
if (ids.length === 0) return;
|
||||
sw.users.resolveMany(ids).then(map => {
|
||||
var names = {};
|
||||
map.forEach((user, id) => { names[id] = sw.users.displayName(user); });
|
||||
setResolvedNames(names);
|
||||
});
|
||||
}, [participants]);
|
||||
|
||||
// Build participant lookup from resolved names
|
||||
var partMap = useMemo(() => {
|
||||
var m = {};
|
||||
(participants || []).forEach(p => { m[p.participant_id] = resolvedNames[p.participant_id] || p.display_name || 'Unknown'; });
|
||||
return m;
|
||||
}, [participants, resolvedNames]);
|
||||
|
||||
// Enrich messages with display names
|
||||
function enrichMessages(msgs) {
|
||||
return msgs.map(m => ({ ...m, _display_name: partMap[m.participant_id] || 'Unknown' }));
|
||||
}
|
||||
|
||||
// Load initial messages
|
||||
useEffect(() => {
|
||||
if (!conversationId) { setMessages([]); return; }
|
||||
setLoading(true);
|
||||
setMessages([]);
|
||||
setNextCursor('');
|
||||
setHasMore(false);
|
||||
api.get('/messages/' + conversationId + '?limit=50').then(res => {
|
||||
var data = res || {};
|
||||
var msgs = (data.messages || []).reverse();
|
||||
setMessages(enrichMessages(msgs));
|
||||
setHasMore(!!data.has_more);
|
||||
setNextCursor(data.next_cursor || '');
|
||||
setLoading(false);
|
||||
setTimeout(() => scrollToBottom(), 50);
|
||||
}).catch(() => setLoading(false));
|
||||
}, [conversationId, partMap]);
|
||||
|
||||
// Load older messages (preserves scroll position)
|
||||
function loadMore() {
|
||||
if (!hasMore || !nextCursor || loading) return;
|
||||
var el = listRef.current;
|
||||
var prevHeight = el ? el.scrollHeight : 0;
|
||||
setLoading(true);
|
||||
api.get('/messages/' + conversationId + '?limit=50&cursor=' + encodeURIComponent(nextCursor)).then(res => {
|
||||
var data = res || {};
|
||||
var older = (data.messages || []).reverse();
|
||||
setMessages(prev => [...enrichMessages(older), ...prev]);
|
||||
setHasMore(!!data.has_more);
|
||||
setNextCursor(data.next_cursor || '');
|
||||
setLoading(false);
|
||||
// Restore scroll position after prepending older messages
|
||||
requestAnimationFrame(() => {
|
||||
if (el) el.scrollTop = el.scrollHeight - prevHeight;
|
||||
});
|
||||
}).catch(() => setLoading(false));
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
if (bottomRef.current) bottomRef.current.scrollIntoView({ behavior: 'auto' });
|
||||
}
|
||||
|
||||
// Scroll listener for load-more
|
||||
useEffect(() => {
|
||||
var el = listRef.current;
|
||||
if (!el) return;
|
||||
function onScroll() {
|
||||
if (el.scrollTop < 80 && hasMore && !loading) loadMore();
|
||||
}
|
||||
el.addEventListener('scroll', onScroll);
|
||||
return () => el.removeEventListener('scroll', onScroll);
|
||||
}, [hasMore, loading, nextCursor, conversationId]);
|
||||
|
||||
// Realtime: new messages, edits, deletes
|
||||
useEffect(() => {
|
||||
if (!conversationId) return;
|
||||
var channel = 'conversation:' + conversationId;
|
||||
|
||||
var unsubs = [
|
||||
sw.realtime.subscribe(channel, 'message', (payload) => {
|
||||
var msg = { ...payload, _display_name: partMap[payload.participant_id] || 'Unknown' };
|
||||
setMessages(prev => [...prev, msg]);
|
||||
setTimeout(() => scrollToBottom(), 50);
|
||||
// Auto mark read if from someone else
|
||||
if (payload.participant_id !== userId && payload.id) {
|
||||
api.post('/read/' + conversationId, { last_read_message_id: payload.id }).catch(() => {});
|
||||
}
|
||||
}),
|
||||
sw.realtime.subscribe(channel, 'message.edited', (payload) => {
|
||||
setMessages(prev => prev.map(m =>
|
||||
m.id === payload.id ? { ...m, content: payload.content, edited_at: 'true' } : m
|
||||
));
|
||||
}),
|
||||
sw.realtime.subscribe(channel, 'message.deleted', (payload) => {
|
||||
setMessages(prev => prev.map(m =>
|
||||
m.id === payload.id ? { ...m, _deleted: true, content: '' } : m
|
||||
));
|
||||
}),
|
||||
];
|
||||
|
||||
// Typing indicators
|
||||
var typingTimers = {};
|
||||
unsubs.push(sw.realtime.subscribe(channel, 'typing', (payload) => {
|
||||
var pid = payload.participant_id;
|
||||
if (pid === userId) return;
|
||||
var typingName = resolvedNames[pid] || payload.display_name || 'Someone';
|
||||
setTypingUsers(prev => ({ ...prev, [pid]: typingName }));
|
||||
clearTimeout(typingTimers[pid]);
|
||||
typingTimers[pid] = setTimeout(() => {
|
||||
setTypingUsers(prev => {
|
||||
var next = { ...prev };
|
||||
delete next[pid];
|
||||
return next;
|
||||
});
|
||||
}, 4000);
|
||||
}));
|
||||
|
||||
return () => {
|
||||
unsubs.forEach(fn => fn());
|
||||
Object.values(typingTimers).forEach(clearTimeout);
|
||||
setTypingUsers({});
|
||||
};
|
||||
}, [conversationId, partMap, userId]);
|
||||
|
||||
// Mark read on first load
|
||||
useEffect(() => {
|
||||
if (!conversationId || messages.length === 0) return;
|
||||
var last = messages[messages.length - 1];
|
||||
if (last && last.id) {
|
||||
api.post('/read/' + conversationId, { last_read_message_id: last.id }).catch(() => {});
|
||||
}
|
||||
}, [conversationId, messages.length > 0]);
|
||||
|
||||
// Edit message
|
||||
function handleEdit(msgId, newContent) {
|
||||
api.put('/messages/' + conversationId + '/' + msgId, { content: newContent }).then(() => {
|
||||
setMessages(prev => prev.map(m =>
|
||||
m.id === msgId ? { ...m, content: newContent, edited_at: 'true' } : m
|
||||
));
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
// Delete message
|
||||
async function handleDelete(msgId) {
|
||||
var ok = await sw.ui.confirm('Delete this message?', { destructive: true });
|
||||
if (!ok) return;
|
||||
api.del('/messages/' + conversationId + '/' + msgId).then(() => {
|
||||
setMessages(prev => prev.map(m =>
|
||||
m.id === msgId ? { ...m, _deleted: true, content: '' } : m
|
||||
));
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
// Typing indicator text
|
||||
var typingNames = Object.values(typingUsers);
|
||||
var typingText = '';
|
||||
if (typingNames.length === 1) typingText = typingNames[0] + ' is typing\u2026';
|
||||
else if (typingNames.length === 2) typingText = typingNames.join(' and ') + ' are typing\u2026';
|
||||
else if (typingNames.length > 2) typingText = 'Several people are typing\u2026';
|
||||
|
||||
if (!conversationId) {
|
||||
return html`
|
||||
<div class="ext-chat-thread chat-thread--empty">
|
||||
<p>Select a conversation or start a new one</p>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="ext-chat-thread">
|
||||
<div class="ext-chat-thread__messages" ref=${listRef}>
|
||||
${loading && messages.length === 0 && html`<div class="ext-chat-thread__loading"><${Spinner} /></div>`}
|
||||
${loading && messages.length > 0 && html`<div class="ext-chat-thread__loading-more"><${Spinner} size="sm" /></div>`}
|
||||
${hasMore && !loading && html`
|
||||
<button class="ext-chat-thread__load-more" onClick=${loadMore}>
|
||||
Load older messages
|
||||
</button>`}
|
||||
${messages.map(m => html`
|
||||
<${MessageBubble}
|
||||
key=${m.id}
|
||||
msg=${m}
|
||||
isOwn=${m.participant_id === userId}
|
||||
onEdit=${handleEdit}
|
||||
onDelete=${handleDelete}
|
||||
/>`)}
|
||||
<div ref=${bottomRef} />
|
||||
</div>
|
||||
${typingText && html`<div class="ext-chat-thread__typing">${typingText}</div>`}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// ComposeBar — message input
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
function ComposeBar({ conversationId }) {
|
||||
var [text, setText] = useState('');
|
||||
var [sending, setSending] = useState(false);
|
||||
var textareaRef = useRef(null);
|
||||
|
||||
// Reset on conversation change
|
||||
useEffect(() => { setText(''); }, [conversationId]);
|
||||
|
||||
// Auto-focus
|
||||
useEffect(() => {
|
||||
if (textareaRef.current) textareaRef.current.focus();
|
||||
}, [conversationId]);
|
||||
|
||||
// Auto-resize
|
||||
function autoResize(el) {
|
||||
if (!el) return;
|
||||
el.style.height = 'auto';
|
||||
el.style.height = Math.min(el.scrollHeight, 160) + 'px';
|
||||
}
|
||||
|
||||
function handleInput(e) {
|
||||
setText(e.target.value);
|
||||
autoResize(e.target);
|
||||
// Typing indicator (debounced)
|
||||
debounce('typing', () => {
|
||||
chatApi.post('/typing/' + conversationId, {
|
||||
display_name: currentDisplayName(),
|
||||
}).catch(() => {});
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
async function handleSend() {
|
||||
var content = text.trim();
|
||||
if (!content || sending) return;
|
||||
setSending(true);
|
||||
try {
|
||||
await api.post('/messages/' + conversationId, { content: content, content_type: 'text' });
|
||||
setText('');
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto';
|
||||
textareaRef.current.focus();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[chat] send failed:', e);
|
||||
}
|
||||
setSending(false);
|
||||
}
|
||||
|
||||
function onKeyDown(e) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
}
|
||||
|
||||
if (!conversationId) return null;
|
||||
|
||||
return html`
|
||||
<div class="ext-chat-compose">
|
||||
<textarea class="ext-chat-compose__input"
|
||||
ref=${textareaRef}
|
||||
value=${text}
|
||||
placeholder="Type a message\u2026"
|
||||
rows="1"
|
||||
onInput=${handleInput}
|
||||
onKeyDown=${onKeyDown} />
|
||||
<${Button} onClick=${handleSend} disabled=${!text.trim() || sending}>Send<//>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// ParticipantSidebar — right panel
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
function ParticipantSidebar({ conversationId, participants, onRefresh, isAdmin }) {
|
||||
var [addOpen, setAddOpen] = useState(false);
|
||||
var [presence, setPresence] = useState({});
|
||||
var [resolvedNames, setResolvedNames] = useState({});
|
||||
|
||||
// Resolve display names from users table
|
||||
useEffect(() => {
|
||||
var ids = (participants || []).map(p => p.participant_id).filter(Boolean);
|
||||
if (ids.length === 0) return;
|
||||
sw.users.resolveMany(ids).then(map => {
|
||||
var names = {};
|
||||
map.forEach((user, id) => { names[id] = sw.users.displayName(user); });
|
||||
setResolvedNames(names);
|
||||
});
|
||||
}, [participants]);
|
||||
|
||||
// Query presence
|
||||
useEffect(() => {
|
||||
if (!participants || participants.length === 0) return;
|
||||
var ids = participants.map(p => p.participant_id).join(',');
|
||||
sw.api.get('/api/v1/presence?users=' + ids).then(res => {
|
||||
setPresence(res || {});
|
||||
}).catch(() => {});
|
||||
}, [participants]);
|
||||
|
||||
async function addUser(user) {
|
||||
setAddOpen(false);
|
||||
await api.post('/participants/' + conversationId, {
|
||||
participant_id: user.id,
|
||||
display_name: user.display_name || user.username,
|
||||
}).catch(() => {});
|
||||
onRefresh();
|
||||
}
|
||||
|
||||
async function removeUser(pid) {
|
||||
var ok = await sw.ui.confirm('Remove this participant?', { destructive: true });
|
||||
if (!ok) return;
|
||||
await api.del('/participants/' + conversationId + '/' + pid).catch(() => {});
|
||||
onRefresh();
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="ext-chat-participants">
|
||||
<div class="ext-chat-participants__header">
|
||||
<span>Participants (${(participants || []).length})</span>
|
||||
${isAdmin && html`<${Button} size="sm" onClick=${() => setAddOpen(true)}>Add<//>` }
|
||||
</div>
|
||||
<div class="ext-chat-participants__list">
|
||||
${(participants || []).map(p => html`
|
||||
<div key=${p.participant_id} class="ext-chat-participants__item">
|
||||
<${Avatar} name=${resolvedNames[p.participant_id] || p.display_name || 'Unknown'} size="sm" />
|
||||
<span class="ext-chat-participants__name">
|
||||
${resolvedNames[p.participant_id] || p.display_name || 'Unknown'}
|
||||
${p.role === 'admin' && html`<span class="ext-chat-participants__badge">admin</span>`}
|
||||
</span>
|
||||
<span class=${'chat-participants__status' + (presence[p.participant_id] ? ' ext-chat-participants__status--online' : '')} />
|
||||
${isAdmin && p.participant_id !== currentUserId() && html`
|
||||
<button class="ext-chat-participants__remove" onClick=${() => removeUser(p.participant_id)} title="Remove">\u00d7</button>`}
|
||||
</div>`)}
|
||||
</div>
|
||||
|
||||
<${Dialog} open=${addOpen} title="Add Participant" onClose=${() => setAddOpen(false)}>
|
||||
<${UserPicker} onSelect=${addUser} placeholder="Search users\u2026" autoFocus />
|
||||
<//>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// NewConversationDialog
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
function NewConversationDialog({ open, onClose, onCreated }) {
|
||||
var [type, setType] = useState('group');
|
||||
var [title, setTitle] = useState('');
|
||||
var [selected, setSelected] = useState([]);
|
||||
var [creating, setCreating] = useState(false);
|
||||
|
||||
function reset() {
|
||||
setType('group');
|
||||
setTitle('');
|
||||
setSelected([]);
|
||||
setCreating(false);
|
||||
}
|
||||
|
||||
function addUser(user) {
|
||||
// Avoid duplicates
|
||||
if (selected.find(u => u.id === user.id)) return;
|
||||
// For DM, only allow one user
|
||||
if (type === 'direct' && selected.length >= 1) {
|
||||
setSelected([user]);
|
||||
return;
|
||||
}
|
||||
setSelected(prev => [...prev, user]);
|
||||
}
|
||||
|
||||
function removeSelected(id) {
|
||||
setSelected(prev => prev.filter(u => u.id !== id));
|
||||
}
|
||||
|
||||
async function handleCreate() {
|
||||
if (selected.length === 0) return;
|
||||
setCreating(true);
|
||||
try {
|
||||
var convTitle = type === 'direct'
|
||||
? ''
|
||||
: (title.trim() || selected.map(u => u.display_name || u.username).join(', '));
|
||||
var participants = selected.map(u => ({
|
||||
id: u.id,
|
||||
display_name: u.display_name || u.username,
|
||||
}));
|
||||
var res = await api.post('/conversations', {
|
||||
title: convTitle,
|
||||
type: type,
|
||||
participants: participants,
|
||||
creator_display_name: currentDisplayName(),
|
||||
});
|
||||
reset();
|
||||
onClose();
|
||||
onCreated(res.id || res.data?.id);
|
||||
} catch (e) {
|
||||
console.error('[chat] create failed:', e);
|
||||
}
|
||||
setCreating(false);
|
||||
}
|
||||
|
||||
var actions = [
|
||||
{ label: 'Cancel', variant: 'secondary', onClick: () => { reset(); onClose(); } },
|
||||
{ label: 'Create', variant: 'primary', onClick: handleCreate, disabled: creating || selected.length === 0 },
|
||||
];
|
||||
|
||||
return html`
|
||||
<${Dialog} open=${open} title="New Conversation" onClose=${() => { reset(); onClose(); }} actions=${actions}>
|
||||
<div class="ext-chat-new">
|
||||
<div class="ext-chat-new__type">
|
||||
<label>
|
||||
<input type="radio" name="convType" value="group"
|
||||
checked=${type === 'group'} onChange=${() => { setType('group'); setSelected([]); }} />
|
||||
Group
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" name="convType" value="direct"
|
||||
checked=${type === 'direct'} onChange=${() => { setType('direct'); setSelected([]); }} />
|
||||
Direct Message
|
||||
</label>
|
||||
</div>
|
||||
${type === 'group' && html`
|
||||
<input class="ext-chat-new__title" type="text" value=${title}
|
||||
placeholder="Conversation title (optional)"
|
||||
onInput=${e => setTitle(e.target.value)} />`}
|
||||
<${UserPicker} onSelect=${addUser} placeholder=${type === 'direct' ? 'Search for a user\u2026' : 'Add participants\u2026'} />
|
||||
${selected.length > 0 && html`
|
||||
<div class="ext-chat-new__selected">
|
||||
${selected.map(u => html`
|
||||
<span key=${u.id} class="ext-chat-new__chip">
|
||||
${u.display_name || u.username}
|
||||
<button onClick=${() => removeSelected(u.id)}>\u00d7</button>
|
||||
</span>`)}
|
||||
</div>`}
|
||||
</div>
|
||||
<//>`;
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// ChatApp — root component
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
function ChatApp() {
|
||||
var [conversations, setConversations] = useState([]);
|
||||
var [unread, setUnread] = useState({});
|
||||
var [selectedId, setSelectedId] = useState(null);
|
||||
var [participants, setParticipants] = useState([]);
|
||||
var [showParticipants, setShowParticipants] = useState(false);
|
||||
var [showNew, setShowNew] = useState(false);
|
||||
var [loading, setLoading] = useState(true);
|
||||
var userId = currentUserId();
|
||||
|
||||
// Load conversations
|
||||
// Note: SDK auto-unwraps {data: [...]} envelopes → res is the array directly
|
||||
function loadConversations() {
|
||||
return api.get('/conversations').then(res => {
|
||||
setConversations(Array.isArray(res) ? res : (res && res.data) || []);
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
// Load unread
|
||||
// Note: SDK returns {data: {id: count}} — NOT auto-unwrapped (data is object, not array)
|
||||
function loadUnread() {
|
||||
return api.get('/unread').then(res => {
|
||||
setUnread((res && res.data) || (typeof res === 'object' && !Array.isArray(res) ? res : {}));
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
// Initial load
|
||||
useEffect(() => {
|
||||
Promise.all([loadConversations(), loadUnread()]).then(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
// Load participants when conversation changes
|
||||
useEffect(() => {
|
||||
if (!selectedId) { setParticipants([]); return; }
|
||||
api.get('/participants/' + selectedId).then(res => {
|
||||
setParticipants(Array.isArray(res) ? res : (res && res.data) || []);
|
||||
}).catch(() => {});
|
||||
}, [selectedId]);
|
||||
|
||||
// Realtime: refresh conversation list on activity
|
||||
useEffect(() => {
|
||||
// Subscribe to all active conversations
|
||||
var unsubs = [];
|
||||
conversations.forEach(c => {
|
||||
unsubs.push(sw.realtime.subscribe('conversation:' + c.id, 'message', () => {
|
||||
loadConversations();
|
||||
loadUnread();
|
||||
}));
|
||||
unsubs.push(sw.realtime.subscribe('conversation:' + c.id, 'participant.added', () => {
|
||||
loadConversations();
|
||||
if (c.id === selectedId) {
|
||||
api.get('/participants/' + selectedId).then(res => {
|
||||
setParticipants(Array.isArray(res) ? res : (res && res.data) || []);
|
||||
}).catch(() => {});
|
||||
}
|
||||
}));
|
||||
unsubs.push(sw.realtime.subscribe('conversation:' + c.id, 'participant.removed', () => {
|
||||
loadConversations();
|
||||
if (c.id === selectedId) {
|
||||
api.get('/participants/' + selectedId).then(res => {
|
||||
setParticipants(Array.isArray(res) ? res : (res && res.data) || []);
|
||||
}).catch(() => {});
|
||||
}
|
||||
}));
|
||||
});
|
||||
return () => unsubs.forEach(fn => fn());
|
||||
}, [conversations.map(c => c.id).join(','), selectedId]);
|
||||
|
||||
// Select conversation
|
||||
function selectConversation(id) {
|
||||
setSelectedId(id);
|
||||
setShowParticipants(false);
|
||||
// Mark read
|
||||
setUnread(prev => { var next = { ...prev }; delete next[id]; return next; });
|
||||
}
|
||||
|
||||
// After creating a new conversation
|
||||
function onCreated(id) {
|
||||
loadConversations().then(() => {
|
||||
if (id) setSelectedId(id);
|
||||
});
|
||||
}
|
||||
|
||||
// Is current user admin in selected conversation?
|
||||
var isAdmin = useMemo(() => {
|
||||
return participants.some(p => p.participant_id === userId && p.role === 'admin');
|
||||
}, [participants, userId]);
|
||||
|
||||
// Refresh participants
|
||||
function refreshParticipants() {
|
||||
if (!selectedId) return;
|
||||
api.get('/participants/' + selectedId).then(res => {
|
||||
setParticipants(Array.isArray(res) ? res : (res && res.data) || []);
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
// Conversation title for topbar
|
||||
var selectedConv = conversations.find(c => c.id === selectedId);
|
||||
var threadTitle = selectedConv ? (selectedConv.title || 'Direct Message') : '';
|
||||
|
||||
if (loading) {
|
||||
return html`<div class="ext-chat-loading"><${Spinner} /></div>`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="ext-chat-app">
|
||||
<${Topbar} title="Chat">
|
||||
${selectedId && html`
|
||||
<span class="ext-chat-topbar__thread-title">${threadTitle}</span>
|
||||
<${Button} size="sm" variant="secondary"
|
||||
onClick=${() => setShowParticipants(!showParticipants)}>
|
||||
${showParticipants ? 'Hide' : 'People'}
|
||||
<//>`}
|
||||
<//>
|
||||
<div class="ext-chat-body">
|
||||
<${ConversationList}
|
||||
selected=${selectedId}
|
||||
onSelect=${selectConversation}
|
||||
onNew=${() => setShowNew(true)}
|
||||
conversations=${conversations}
|
||||
unread=${unread} />
|
||||
<div class="ext-chat-main">
|
||||
<${MessageThread}
|
||||
conversationId=${selectedId}
|
||||
participants=${participants} />
|
||||
<${ComposeBar} conversationId=${selectedId} />
|
||||
</div>
|
||||
${showParticipants && selectedId && html`
|
||||
<${ParticipantSidebar}
|
||||
conversationId=${selectedId}
|
||||
participants=${participants}
|
||||
onRefresh=${refreshParticipants}
|
||||
isAdmin=${isAdmin} />`}
|
||||
</div>
|
||||
<${NewConversationDialog}
|
||||
open=${showNew}
|
||||
onClose=${() => setShowNew(false)}
|
||||
onCreated=${onCreated} />
|
||||
</div>`;
|
||||
}
|
||||
|
||||
|
||||
// ── Mount ──────────────────────────────────
|
||||
render(html`<${ChatApp} />`, mount);
|
||||
|
||||
})();
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"id": "chat",
|
||||
"title": "Chat",
|
||||
"type": "full",
|
||||
"tier": "starlark",
|
||||
"route": "/s/chat",
|
||||
"auth": "authenticated",
|
||||
"layout": "single",
|
||||
"version": "0.2.0",
|
||||
"icon": "\ud83d\udcac",
|
||||
"description": "Chat surface — conversations, messaging, typing indicators, read receipts.",
|
||||
"author": "armature",
|
||||
|
||||
"permissions": ["db.write", "realtime.publish"],
|
||||
|
||||
"depends": ["chat-core"],
|
||||
|
||||
"api_routes": [
|
||||
{"method": "POST", "path": "/typing/*"}
|
||||
],
|
||||
|
||||
"settings": {
|
||||
"enter_to_send": {
|
||||
"type": "boolean",
|
||||
"label": "Enter to Send",
|
||||
"description": "Press Enter to send messages (Shift+Enter for newline). When off, Enter inserts a newline.",
|
||||
"default": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
# Chat Surface — Starlark Backend (v0.1.0)
|
||||
#
|
||||
# Thin surface layer on top of chat-core library.
|
||||
# Only handles typing indicator broadcast — all CRUD is
|
||||
# delegated to chat-core's own API routes.
|
||||
#
|
||||
# Modules: json, realtime
|
||||
|
||||
def _resp(status, data):
|
||||
return {"status": status, "body": json.encode(data), "headers": {"Content-Type": "application/json"}}
|
||||
|
||||
|
||||
def on_request(req):
|
||||
path = req["path"]
|
||||
method = req["method"]
|
||||
user_id = req.get("user_id", "")
|
||||
|
||||
# POST /typing/:conversation_id — broadcast typing indicator
|
||||
if method == "POST" and path.startswith("/typing/"):
|
||||
cid = path[len("/typing/"):]
|
||||
if not cid:
|
||||
return _resp(400, {"error": "conversation_id required"})
|
||||
|
||||
body = json.decode(req.get("body", "{}"))
|
||||
display_name = str(body.get("display_name", ""))
|
||||
|
||||
realtime.publish(
|
||||
"conversation:" + cid,
|
||||
"typing",
|
||||
{
|
||||
"participant_id": user_id,
|
||||
"display_name": display_name,
|
||||
"conversation_id": cid,
|
||||
},
|
||||
)
|
||||
|
||||
return _resp(200, {"ok": True})
|
||||
|
||||
return _resp(404, {"error": "not found"})
|
||||
@@ -5,7 +5,7 @@
|
||||
"version": "0.1.0",
|
||||
"tier": "browser",
|
||||
"icon": "📝",
|
||||
"author": "Armature",
|
||||
"author": "Switchboard Core",
|
||||
"description": "Multi-party content review with quorum signoff and revision cycle.",
|
||||
"permissions": [],
|
||||
|
||||
|
||||
@@ -3,68 +3,71 @@
|
||||
// ==========================================
|
||||
// Renders ```csv and ```tsv code blocks as sortable HTML tables.
|
||||
// No external dependencies.
|
||||
//
|
||||
// Registers with sw.renderers via the sw:ready event.
|
||||
// ==========================================
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
Extensions.register({
|
||||
id: 'csv-table',
|
||||
|
||||
function _escapeHtml(str) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
}
|
||||
async init(ctx) {
|
||||
const self = this;
|
||||
|
||||
function _parseCSV(text, delimiter) {
|
||||
const rows = [];
|
||||
let row = [];
|
||||
let field = '';
|
||||
let inQuotes = false;
|
||||
let i = 0;
|
||||
// ── Inject styles ──
|
||||
this._injectStyles();
|
||||
|
||||
while (i < text.length) {
|
||||
const ch = text[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (i + 1 < text.length && text[i + 1] === '"') {
|
||||
field += '"'; i += 2;
|
||||
} else {
|
||||
inQuotes = false; i++;
|
||||
}
|
||||
} else {
|
||||
field += ch; i++;
|
||||
}
|
||||
} else {
|
||||
if (ch === '"' && field === '') {
|
||||
inQuotes = true; i++;
|
||||
} else if (ch === delimiter) {
|
||||
row.push(field.trim()); field = ''; i++;
|
||||
} else if (ch === '\n' || (ch === '\r' && text[i + 1] === '\n')) {
|
||||
row.push(field.trim());
|
||||
if (row.some(cell => cell !== '')) rows.push(row);
|
||||
row = []; field = '';
|
||||
i += (ch === '\r') ? 2 : 1;
|
||||
} else {
|
||||
field += ch; i++;
|
||||
ctx.renderers.register('csv-block', {
|
||||
type: 'block',
|
||||
priority: 10,
|
||||
match(lang) {
|
||||
const l = (lang || '').toLowerCase();
|
||||
return l === 'csv' || l === 'tsv';
|
||||
},
|
||||
render(lang, code, container) {
|
||||
const delimiter = lang.toLowerCase() === 'tsv' ? '\t' : ',';
|
||||
const rows = self._parseCSV(code.trim(), delimiter);
|
||||
|
||||
if (rows.length === 0) {
|
||||
container.innerHTML = '<div class="csv-empty">No data</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = rows[0];
|
||||
const data = rows.slice(1);
|
||||
const tableId = 'csv-' + Math.random().toString(36).slice(2, 9);
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="csv-table-block ext-rendered" data-csv-id="${tableId}">
|
||||
<div class="csv-toolbar">
|
||||
<span class="csv-info">${data.length} row${data.length !== 1 ? 's' : ''} × ${headers.length} col${headers.length !== 1 ? 's' : ''}</span>
|
||||
<button class="csv-copy-btn" title="Copy as CSV">📋 Copy</button>
|
||||
</div>
|
||||
<div class="csv-table-scroll">
|
||||
<table class="csv-table">
|
||||
<thead>
|
||||
<tr>${headers.map((h, i) => `<th data-col="${i}" title="Click to sort">${self._escapeHtml(h)}<span class="csv-sort-icon"></span></th>`).join('')}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${data.map(row => `<tr>${row.map(cell => `<td>${self._escapeHtml(cell)}</td>`).join('')}</tr>`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<details class="csv-source">
|
||||
<summary>📄 View raw</summary>
|
||||
<pre><code>${self._escapeHtml(code.trim())}</code></pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Attach sort handlers + copy
|
||||
self._attachHandlers(container, tableId, code.trim());
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
row.push(field.trim());
|
||||
if (row.some(cell => cell !== '')) rows.push(row);
|
||||
|
||||
if (rows.length > 0) {
|
||||
const maxCols = Math.max(...rows.map(r => r.length));
|
||||
rows.forEach(r => { while (r.length < maxCols) r.push(''); });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function _attachHandlers(container, tableId, rawCSV) {
|
||||
_attachHandlers(container, tableId, rawCSV) {
|
||||
const block = container.querySelector(`[data-csv-id="${tableId}"]`);
|
||||
if (!block) return;
|
||||
|
||||
// ── Column sorting ──
|
||||
const ths = block.querySelectorAll('th[data-col]');
|
||||
let sortCol = -1;
|
||||
let sortAsc = true;
|
||||
@@ -73,50 +76,129 @@
|
||||
th.style.cursor = 'pointer';
|
||||
th.addEventListener('click', () => {
|
||||
const col = parseInt(th.dataset.col, 10);
|
||||
if (sortCol === col) { sortAsc = !sortAsc; }
|
||||
else { sortCol = col; sortAsc = true; }
|
||||
if (sortCol === col) {
|
||||
sortAsc = !sortAsc;
|
||||
} else {
|
||||
sortCol = col;
|
||||
sortAsc = true;
|
||||
}
|
||||
|
||||
const tbody = block.querySelector('tbody');
|
||||
const rows = Array.from(tbody.querySelectorAll('tr'));
|
||||
|
||||
rows.sort((a, b) => {
|
||||
const cellA = (a.children[col]?.textContent || '').trim();
|
||||
const cellB = (b.children[col]?.textContent || '').trim();
|
||||
const numA = parseFloat(cellA);
|
||||
const numB = parseFloat(cellB);
|
||||
if (!isNaN(numA) && !isNaN(numB))
|
||||
|
||||
// Numeric sort if both are numbers
|
||||
if (!isNaN(numA) && !isNaN(numB)) {
|
||||
return sortAsc ? numA - numB : numB - numA;
|
||||
}
|
||||
// String sort
|
||||
const cmp = cellA.localeCompare(cellB, undefined, { numeric: true, sensitivity: 'base' });
|
||||
return sortAsc ? cmp : -cmp;
|
||||
});
|
||||
|
||||
rows.forEach(row => tbody.appendChild(row));
|
||||
|
||||
// Update sort icons
|
||||
ths.forEach(h => {
|
||||
const icon = h.querySelector('.csv-sort-icon');
|
||||
if (icon) {
|
||||
const hCol = parseInt(h.dataset.col, 10);
|
||||
icon.textContent = hCol === sortCol ? (sortAsc ? ' \u25b2' : ' \u25bc') : '';
|
||||
icon.textContent = hCol === sortCol ? (sortAsc ? ' ▲' : ' ▼') : '';
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── Copy button ──
|
||||
const copyBtn = block.querySelector('.csv-copy-btn');
|
||||
if (copyBtn) {
|
||||
copyBtn.addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(rawCSV).then(() => {
|
||||
copyBtn.textContent = '\u2713 Copied';
|
||||
setTimeout(() => { copyBtn.textContent = '\ud83d\udccb Copy'; }, 1500);
|
||||
copyBtn.textContent = '✓ Copied';
|
||||
setTimeout(() => { copyBtn.textContent = '📋 Copy'; }, 1500);
|
||||
}).catch(() => {
|
||||
copyBtn.textContent = '\u2717 Failed';
|
||||
setTimeout(() => { copyBtn.textContent = '\ud83d\udccb Copy'; }, 1500);
|
||||
copyBtn.textContent = '✗ Failed';
|
||||
setTimeout(() => { copyBtn.textContent = '📋 Copy'; }, 1500);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// ── Styles ──────────────────────────────
|
||||
/**
|
||||
* Simple CSV parser that handles quoted fields.
|
||||
*/
|
||||
_parseCSV(text, delimiter) {
|
||||
const rows = [];
|
||||
let row = [];
|
||||
let field = '';
|
||||
let inQuotes = false;
|
||||
let i = 0;
|
||||
|
||||
function _injectStyles() {
|
||||
while (i < text.length) {
|
||||
const ch = text[i];
|
||||
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
// Peek ahead: escaped quote or end of quoted field
|
||||
if (i + 1 < text.length && text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i += 2;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
field += ch;
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
if (ch === '"' && field === '') {
|
||||
inQuotes = true;
|
||||
i++;
|
||||
} else if (ch === delimiter) {
|
||||
row.push(field.trim());
|
||||
field = '';
|
||||
i++;
|
||||
} else if (ch === '\n' || (ch === '\r' && text[i + 1] === '\n')) {
|
||||
row.push(field.trim());
|
||||
if (row.some(cell => cell !== '')) rows.push(row);
|
||||
row = [];
|
||||
field = '';
|
||||
i += (ch === '\r') ? 2 : 1;
|
||||
} else {
|
||||
field += ch;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Last field/row
|
||||
row.push(field.trim());
|
||||
if (row.some(cell => cell !== '')) rows.push(row);
|
||||
|
||||
// Normalize: pad short rows to header length
|
||||
if (rows.length > 0) {
|
||||
const maxCols = Math.max(...rows.map(r => r.length));
|
||||
rows.forEach(r => {
|
||||
while (r.length < maxCols) r.push('');
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
},
|
||||
|
||||
_escapeHtml(str) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
},
|
||||
|
||||
_injectStyles() {
|
||||
if (document.getElementById('ext-style-csv-table')) return;
|
||||
const style = document.createElement('style');
|
||||
style.id = 'ext-style-csv-table';
|
||||
@@ -164,66 +246,9 @@
|
||||
}
|
||||
.csv-empty { padding: 16px; text-align: center; color: var(--text-3); }`;
|
||||
document.head.appendChild(style);
|
||||
},
|
||||
|
||||
destroy() {
|
||||
document.getElementById('ext-style-csv-table')?.remove();
|
||||
}
|
||||
|
||||
// ── Registration ────────────────────────
|
||||
|
||||
function register() {
|
||||
if (!window.sw?.renderers) return;
|
||||
|
||||
_injectStyles();
|
||||
|
||||
sw.renderers.register('csv-block', {
|
||||
type: 'block',
|
||||
priority: 10,
|
||||
match(lang) {
|
||||
const l = (lang || '').toLowerCase();
|
||||
return l === 'csv' || l === 'tsv';
|
||||
},
|
||||
render(lang, code, container) {
|
||||
const delimiter = lang.toLowerCase() === 'tsv' ? '\t' : ',';
|
||||
const rows = _parseCSV(code.trim(), delimiter);
|
||||
|
||||
if (rows.length === 0) {
|
||||
container.innerHTML = '<div class="csv-empty">No data</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = rows[0];
|
||||
const data = rows.slice(1);
|
||||
const tableId = 'csv-' + Math.random().toString(36).slice(2, 9);
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="csv-table-block ext-rendered" data-csv-id="${tableId}">
|
||||
<div class="csv-toolbar">
|
||||
<span class="csv-info">${data.length} row${data.length !== 1 ? 's' : ''} \u00d7 ${headers.length} col${headers.length !== 1 ? 's' : ''}</span>
|
||||
<button class="csv-copy-btn" title="Copy as CSV">\ud83d\udccb Copy</button>
|
||||
</div>
|
||||
<div class="csv-table-scroll">
|
||||
<table class="csv-table">
|
||||
<thead>
|
||||
<tr>${headers.map((h, i) => `<th data-col="${i}" title="Click to sort">${_escapeHtml(h)}<span class="csv-sort-icon"></span></th>`).join('')}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${data.map(row => `<tr>${row.map(cell => `<td>${_escapeHtml(cell)}</td>`).join('')}</tr>`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<details class="csv-source">
|
||||
<summary>\ud83d\udcc4 View raw</summary>
|
||||
<pre><code>${_escapeHtml(code.trim())}</code></pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
|
||||
_attachHandlers(container, tableId, code.trim());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (window.sw?._sdk) {
|
||||
register();
|
||||
} else {
|
||||
document.addEventListener('sw:ready', register, { once: true });
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
"version": "1.0.0",
|
||||
"type": "extension",
|
||||
"tier": "browser",
|
||||
"author": "armature",
|
||||
"author": "switchboard",
|
||||
"description": "Renders ```csv code blocks as sortable, interactive HTML tables",
|
||||
"requires": [],
|
||||
"requires": ["chat"],
|
||||
"permissions": [],
|
||||
"tools": [],
|
||||
"surfaces": [],
|
||||
|
||||
@@ -6,63 +6,63 @@
|
||||
All SDK components style themselves.
|
||||
========================================== */
|
||||
|
||||
.ext-dashboard {
|
||||
.surface-dashboard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ── Topbar ──────────────────────────────── */
|
||||
|
||||
.ext-dashboard-topbar {
|
||||
.dashboard-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
padding: 0 var(--sp-4);
|
||||
gap: 12px;
|
||||
padding: 0 16px;
|
||||
height: 44px;
|
||||
flex-shrink: 0;
|
||||
background: var(--bg-secondary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.ext-dashboard-topbar-back {
|
||||
.dashboard-topbar-back {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
gap: 4px;
|
||||
color: var(--text-2);
|
||||
text-decoration: none;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
padding: 4px 8px;
|
||||
border-radius: var(--radius);
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
.ext-dashboard-topbar-back:hover {
|
||||
.dashboard-topbar-back:hover {
|
||||
color: var(--text);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-dashboard-topbar-title {
|
||||
.dashboard-topbar-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ext-dashboard-topbar-sep {
|
||||
.dashboard-topbar-sep {
|
||||
width: 1px;
|
||||
height: 18px;
|
||||
background: var(--border);
|
||||
}
|
||||
|
||||
.ext-dashboard-topbar-spacer {
|
||||
.dashboard-topbar-spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ── Body ────────────────────────────────── */
|
||||
|
||||
.ext-dashboard-body {
|
||||
.dashboard-body {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -70,7 +70,7 @@
|
||||
|
||||
/* ── Sidebar ─────────────────────────────── */
|
||||
|
||||
.ext-dashboard-sidebar {
|
||||
.dashboard-sidebar {
|
||||
width: 300px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
@@ -81,34 +81,34 @@
|
||||
|
||||
/* ── Main Content ────────────────────────── */
|
||||
|
||||
.ext-dashboard-main {
|
||||
.dashboard-main {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-5);
|
||||
padding: 20px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ext-dashboard-greeting {
|
||||
.dashboard-greeting {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
margin-bottom: var(--sp-1);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.ext-dashboard-subtitle {
|
||||
.dashboard-subtitle {
|
||||
font-size: 13px;
|
||||
color: var(--text-3);
|
||||
margin-bottom: var(--sp-5);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.ext-dashboard-filter-bar {
|
||||
.dashboard-filter-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
margin-bottom: var(--sp-4);
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.ext-dashboard-filter-label {
|
||||
.dashboard-filter-label {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-2);
|
||||
@@ -118,34 +118,34 @@
|
||||
|
||||
/* ── Cards Grid ──────────────────────────── */
|
||||
|
||||
.ext-dashboard-cards {
|
||||
.dashboard-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: var(--sp-3);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.ext-dashboard-card {
|
||||
.dashboard-card {
|
||||
background: var(--bg-raised);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--sp-4);
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
gap: 8px;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
|
||||
.ext-dashboard-card:hover {
|
||||
.dashboard-card:hover {
|
||||
border-color: var(--border-elevated);
|
||||
}
|
||||
|
||||
.ext-dashboard-card-header {
|
||||
.dashboard-card-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ext-dashboard-card-title {
|
||||
.dashboard-card-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
@@ -155,43 +155,43 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ext-dashboard-card-meta {
|
||||
.dashboard-card-meta {
|
||||
font-size: 11px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
.ext-dashboard-card-desc {
|
||||
.dashboard-card-desc {
|
||||
font-size: 12px;
|
||||
color: var(--text-2);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.ext-dashboard-card-actions {
|
||||
.dashboard-card-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: var(--sp-1);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.ext-dashboard-empty {
|
||||
.dashboard-empty {
|
||||
text-align: center;
|
||||
color: var(--text-3);
|
||||
font-size: 13px;
|
||||
padding: var(--sp-10) var(--sp-5);
|
||||
padding: 40px 20px;
|
||||
}
|
||||
|
||||
/* ── Admin Section ───────────────────────── */
|
||||
|
||||
.ext-dashboard-admin-section {
|
||||
margin-top: var(--sp-6);
|
||||
padding-top: var(--sp-4);
|
||||
.dashboard-admin-section {
|
||||
margin-top: 24px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.ext-dashboard-section-title {
|
||||
.dashboard-section-title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-2);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-bottom: var(--sp-3);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// ==========================================
|
||||
// Armature — Dashboard Package (v0.31.1)
|
||||
// Switchboard Core — Dashboard Package (v0.31.1)
|
||||
// ==========================================
|
||||
// SDK Exercise Surface. Exercises every sw.* primitive with ZERO
|
||||
// component CSS overrides. All styling comes from the SDK itself.
|
||||
@@ -28,7 +28,7 @@
|
||||
if (!mount) return;
|
||||
|
||||
const surface = document.createElement('div');
|
||||
surface.className = 'ext-dashboard';
|
||||
surface.className = 'surface-dashboard';
|
||||
surface.id = 'dashboardSurface';
|
||||
mount.appendChild(surface);
|
||||
|
||||
@@ -41,12 +41,12 @@
|
||||
|
||||
// ── Body ──
|
||||
const body = document.createElement('div');
|
||||
body.className = 'ext-dashboard-body';
|
||||
body.className = 'dashboard-body';
|
||||
surface.appendChild(body);
|
||||
|
||||
// ── Sidebar (tabs: activity + notes) ──
|
||||
const sidebar = document.createElement('div');
|
||||
sidebar.className = 'ext-dashboard-sidebar';
|
||||
sidebar.className = 'dashboard-sidebar';
|
||||
body.appendChild(sidebar);
|
||||
|
||||
// sw.tabs — two tabs
|
||||
@@ -83,14 +83,14 @@
|
||||
|
||||
// ── Main content area ──
|
||||
const main = document.createElement('div');
|
||||
main.className = 'ext-dashboard-main';
|
||||
main.className = 'dashboard-main';
|
||||
body.appendChild(main);
|
||||
|
||||
_buildMainContent(main);
|
||||
|
||||
// ── Theme reactivity ──
|
||||
sw.theme.on('change', function (resolved) {
|
||||
const cards = main.querySelectorAll('.ext-dashboard-card');
|
||||
const cards = main.querySelectorAll('.dashboard-card');
|
||||
cards.forEach(function (c) {
|
||||
c.style.borderColor = ''; // reset to CSS default for new theme
|
||||
});
|
||||
@@ -98,7 +98,7 @@
|
||||
|
||||
// ── Cross-component events ──
|
||||
sw.on('dashboard.filter.changed', function (payload) {
|
||||
_loadChannels(main.querySelector('.ext-dashboard-cards'), payload.value);
|
||||
_loadChannels(main.querySelector('.dashboard-cards'), payload.value);
|
||||
});
|
||||
|
||||
console.log('[DashboardPkg] Mounted');
|
||||
@@ -108,15 +108,15 @@
|
||||
|
||||
function _buildTopbar() {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'ext-dashboard-topbar';
|
||||
el.className = 'dashboard-topbar';
|
||||
el.innerHTML =
|
||||
'<a href="' + esc(base) + '/" class="ext-dashboard-topbar-back" title="Back to chat">' +
|
||||
'<a href="' + esc(base) + '/" class="dashboard-topbar-back" title="Back to chat">' +
|
||||
'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>' +
|
||||
'Back' +
|
||||
'</a>' +
|
||||
'<div class="ext-dashboard-topbar-sep"></div>' +
|
||||
'<span class="ext-dashboard-topbar-title">Dashboard</span>' +
|
||||
'<div class="ext-dashboard-topbar-spacer"></div>';
|
||||
'<div class="dashboard-topbar-sep"></div>' +
|
||||
'<span class="dashboard-topbar-title">Dashboard</span>' +
|
||||
'<div class="dashboard-topbar-spacer"></div>';
|
||||
|
||||
// sw.toolbar — action buttons
|
||||
const toolbarItems = [
|
||||
@@ -125,7 +125,7 @@
|
||||
icon: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>',
|
||||
title: 'Refresh',
|
||||
onClick: function () {
|
||||
const cards = document.querySelector('.ext-dashboard-cards');
|
||||
const cards = document.querySelector('.dashboard-cards');
|
||||
if (cards) _loadChannels(cards, _currentFilter);
|
||||
sw.toast('Refreshed', 'success');
|
||||
},
|
||||
@@ -155,22 +155,22 @@
|
||||
// sw.user — greeting
|
||||
const user = sw.user;
|
||||
const greeting = document.createElement('div');
|
||||
greeting.className = 'ext-dashboard-greeting';
|
||||
greeting.textContent = 'Welcome back' + (user ? ', ' + (user.display_name || user.username || 'Unknown') : '');
|
||||
greeting.className = 'dashboard-greeting';
|
||||
greeting.textContent = 'Welcome back' + (user ? ', ' + (user.display_name || user.username) : '');
|
||||
main.appendChild(greeting);
|
||||
|
||||
const subtitle = document.createElement('div');
|
||||
subtitle.className = 'ext-dashboard-subtitle';
|
||||
subtitle.className = 'dashboard-subtitle';
|
||||
subtitle.textContent = 'Your recent conversations' + (sw.isAdmin ? ' \u00b7 Admin' : '');
|
||||
main.appendChild(subtitle);
|
||||
|
||||
// ── Filter bar ──
|
||||
const filterBar = document.createElement('div');
|
||||
filterBar.className = 'ext-dashboard-filter-bar';
|
||||
filterBar.className = 'dashboard-filter-bar';
|
||||
main.appendChild(filterBar);
|
||||
|
||||
const filterLabel = document.createElement('span');
|
||||
filterLabel.className = 'ext-dashboard-filter-label';
|
||||
filterLabel.className = 'dashboard-filter-label';
|
||||
filterLabel.textContent = 'Filter';
|
||||
filterBar.appendChild(filterLabel);
|
||||
|
||||
@@ -192,7 +192,7 @@
|
||||
|
||||
// ── Cards ──
|
||||
const cards = document.createElement('div');
|
||||
cards.className = 'ext-dashboard-cards';
|
||||
cards.className = 'dashboard-cards';
|
||||
main.appendChild(cards);
|
||||
|
||||
_loadChannels(cards, '');
|
||||
@@ -200,16 +200,16 @@
|
||||
// ── Admin section (sw.isAdmin) ──
|
||||
if (sw.isAdmin) {
|
||||
const adminSection = document.createElement('div');
|
||||
adminSection.className = 'ext-dashboard-admin-section';
|
||||
adminSection.className = 'dashboard-admin-section';
|
||||
main.appendChild(adminSection);
|
||||
|
||||
const sectionTitle = document.createElement('div');
|
||||
sectionTitle.className = 'ext-dashboard-section-title';
|
||||
sectionTitle.className = 'dashboard-section-title';
|
||||
sectionTitle.textContent = 'Administration';
|
||||
adminSection.appendChild(sectionTitle);
|
||||
|
||||
const adminCards = document.createElement('div');
|
||||
adminCards.className = 'ext-dashboard-cards';
|
||||
adminCards.className = 'dashboard-cards';
|
||||
adminSection.appendChild(adminCards);
|
||||
|
||||
_loadAdminCards(adminCards);
|
||||
@@ -220,7 +220,7 @@
|
||||
|
||||
async function _loadChannels(container, typeFilter) {
|
||||
if (!container) return;
|
||||
container.innerHTML = '<div class="ext-dashboard-empty">Loading\u2026</div>';
|
||||
container.innerHTML = '<div class="dashboard-empty">Loading\u2026</div>';
|
||||
|
||||
try {
|
||||
// sw.api — real API call
|
||||
@@ -231,7 +231,7 @@
|
||||
|
||||
container.innerHTML = '';
|
||||
if (!channels.length) {
|
||||
container.innerHTML = '<div class="ext-dashboard-empty">No channels found</div>';
|
||||
container.innerHTML = '<div class="dashboard-empty">No channels found</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -239,31 +239,31 @@
|
||||
container.appendChild(_buildChannelCard(ch));
|
||||
});
|
||||
} catch (e) {
|
||||
container.innerHTML = '<div class="ext-dashboard-empty">Failed to load: ' + (typeof esc === 'function' ? esc(e.message) : e.message) + '</div>';
|
||||
container.innerHTML = '<div class="dashboard-empty">Failed to load: ' + (typeof esc === 'function' ? esc(e.message) : e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function _buildChannelCard(ch) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'ext-dashboard-card';
|
||||
card.className = 'dashboard-card';
|
||||
|
||||
const header = document.createElement('div');
|
||||
header.className = 'ext-dashboard-card-header';
|
||||
header.className = 'dashboard-card-header';
|
||||
card.appendChild(header);
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'ext-dashboard-card-title';
|
||||
title.className = 'dashboard-card-title';
|
||||
title.textContent = ch.title || ch.name || 'Untitled';
|
||||
header.appendChild(title);
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'ext-dashboard-card-meta';
|
||||
meta.className = 'dashboard-card-meta';
|
||||
meta.textContent = ch.type || '';
|
||||
card.appendChild(meta);
|
||||
|
||||
if (ch.description) {
|
||||
const desc = document.createElement('div');
|
||||
desc.className = 'ext-dashboard-card-desc';
|
||||
desc.className = 'dashboard-card-desc';
|
||||
desc.textContent = ch.description.slice(0, 120);
|
||||
card.appendChild(desc);
|
||||
}
|
||||
@@ -271,14 +271,14 @@
|
||||
const updated = ch.updated_at || ch.created_at;
|
||||
if (updated) {
|
||||
const date = document.createElement('div');
|
||||
date.className = 'ext-dashboard-card-meta';
|
||||
date.className = 'dashboard-card-meta';
|
||||
date.textContent = new Date(updated).toLocaleDateString();
|
||||
card.appendChild(date);
|
||||
}
|
||||
|
||||
// ── Card action menu ──
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'ext-dashboard-card-actions';
|
||||
actions.className = 'dashboard-card-actions';
|
||||
card.appendChild(actions);
|
||||
|
||||
const menuBtn = document.createElement('button');
|
||||
@@ -343,8 +343,8 @@
|
||||
(ch.description ? '<div style="font-size:12px;color:var(--text-2);margin-bottom:8px;"><strong>Description:</strong> ' + (typeof esc === 'function' ? esc(ch.description) : ch.description) + '</div>' : '') +
|
||||
(ch.created_at ? '<div style="font-size:12px;color:var(--text-3);margin-bottom:16px;">Created: ' + new Date(ch.created_at).toLocaleString() + '</div>' : '') +
|
||||
'<div style="display:flex;justify-content:flex-end;gap:8px;">' +
|
||||
'<button class="sw-btn sw-btn--secondary sw-btn--sm" id="dashDetailClose">Close</button>' +
|
||||
'<button class="sw-btn sw-btn--primary sw-btn--sm" id="dashDetailOpen">Open Chat</button>' +
|
||||
'<button class="btn-small" id="dashDetailClose">Close</button>' +
|
||||
'<button class="btn-small btn-primary" id="dashDetailOpen">Open Chat</button>' +
|
||||
'</div>';
|
||||
|
||||
modal.appendChild(box);
|
||||
@@ -372,7 +372,7 @@
|
||||
// sw.toast — success feedback
|
||||
sw.toast('Channel deleted', 'success');
|
||||
// Refresh cards
|
||||
const cards = document.querySelector('.ext-dashboard-cards');
|
||||
const cards = document.querySelector('.dashboard-cards');
|
||||
if (cards) _loadChannels(cards, _currentFilter);
|
||||
} catch (e) {
|
||||
// sw.toast — error feedback
|
||||
@@ -390,21 +390,21 @@
|
||||
container.innerHTML = '';
|
||||
packages.forEach(function (pkg) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'ext-dashboard-card';
|
||||
card.className = 'dashboard-card';
|
||||
card.innerHTML =
|
||||
'<div class="ext-dashboard-card-header">' +
|
||||
'<div class="ext-dashboard-card-title">' + (typeof esc === 'function' ? esc(pkg.title || pkg.id) : (pkg.title || pkg.id)) + '</div>' +
|
||||
'<div class="dashboard-card-header">' +
|
||||
'<div class="dashboard-card-title">' + (typeof esc === 'function' ? esc(pkg.title || pkg.id) : (pkg.title || pkg.id)) + '</div>' +
|
||||
'</div>' +
|
||||
'<div class="ext-dashboard-card-meta">' + (typeof esc === 'function' ? esc(pkg.type || '') : (pkg.type || '')) + ' \u00b7 ' + (typeof esc === 'function' ? esc(pkg.tier || '') : (pkg.tier || '')) + '</div>' +
|
||||
'<div class="ext-dashboard-card-desc">' + (typeof esc === 'function' ? esc(pkg.description || '') : (pkg.description || '')) + '</div>';
|
||||
'<div class="dashboard-card-meta">' + (typeof esc === 'function' ? esc(pkg.type || '') : (pkg.type || '')) + ' \u00b7 ' + (typeof esc === 'function' ? esc(pkg.tier || '') : (pkg.tier || '')) + '</div>' +
|
||||
'<div class="dashboard-card-desc">' + (typeof esc === 'function' ? esc(pkg.description || '') : (pkg.description || '')) + '</div>';
|
||||
container.appendChild(card);
|
||||
});
|
||||
|
||||
if (!packages.length) {
|
||||
container.innerHTML = '<div class="ext-dashboard-empty">No packages installed</div>';
|
||||
container.innerHTML = '<div class="dashboard-empty">No packages installed</div>';
|
||||
}
|
||||
} catch (_) {
|
||||
container.innerHTML = '<div class="ext-dashboard-empty">Failed to load packages</div>';
|
||||
container.innerHTML = '<div class="dashboard-empty">Failed to load packages</div>';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"type": "full",
|
||||
"version": "0.31.1",
|
||||
"tier": "browser",
|
||||
"author": "Armature",
|
||||
"author": "Switchboard Core",
|
||||
"icon": "📊",
|
||||
"description": "Project dashboard exercising all SDK primitives (requires legacy sw.* SDK — dormant until rewritten)",
|
||||
"requires": ["legacy-sdk"],
|
||||
|
||||
@@ -4,22 +4,106 @@
|
||||
// Renders ```diff code blocks with syntax-highlighted
|
||||
// additions, deletions, hunk headers, and context lines.
|
||||
// No external dependencies.
|
||||
//
|
||||
// Registers with sw.renderers via the sw:ready event.
|
||||
// ==========================================
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
Extensions.register({
|
||||
id: 'diff-viewer',
|
||||
|
||||
function _escapeHtml(str) {
|
||||
async init(ctx) {
|
||||
const self = this;
|
||||
|
||||
// ── Inject styles ──
|
||||
this._injectStyles();
|
||||
|
||||
ctx.renderers.register('diff-block', {
|
||||
type: 'block',
|
||||
priority: 10,
|
||||
pattern: 'diff',
|
||||
render(lang, code, container) {
|
||||
const lines = code.split('\n');
|
||||
let stats = { added: 0, removed: 0 };
|
||||
let currentFile = '';
|
||||
|
||||
const rendered = lines.map(line => {
|
||||
const escaped = self._escapeHtml(line);
|
||||
|
||||
// File headers
|
||||
if (line.startsWith('--- ') || line.startsWith('+++ ')) {
|
||||
if (line.startsWith('+++ ')) {
|
||||
currentFile = line.slice(4).trim();
|
||||
}
|
||||
return `<div class="diff-line diff-file-header">${escaped}</div>`;
|
||||
}
|
||||
|
||||
// Hunk headers
|
||||
if (line.startsWith('@@')) {
|
||||
const hunkMatch = line.match(/^@@\s*-(\d+)(?:,\d+)?\s*\+(\d+)(?:,\d+)?\s*@@\s*(.*)/);
|
||||
const context = hunkMatch ? hunkMatch[3] : '';
|
||||
return `<div class="diff-line diff-hunk">${escaped}</div>`;
|
||||
}
|
||||
|
||||
// Additions
|
||||
if (line.startsWith('+')) {
|
||||
stats.added++;
|
||||
return `<div class="diff-line diff-add"><span class="diff-indicator">+</span>${self._escapeHtml(line.slice(1))}</div>`;
|
||||
}
|
||||
|
||||
// Deletions
|
||||
if (line.startsWith('-')) {
|
||||
stats.removed++;
|
||||
return `<div class="diff-line diff-del"><span class="diff-indicator">-</span>${self._escapeHtml(line.slice(1))}</div>`;
|
||||
}
|
||||
|
||||
// Context (lines starting with space or no prefix)
|
||||
if (line.startsWith(' ')) {
|
||||
return `<div class="diff-line diff-ctx"><span class="diff-indicator"> </span>${self._escapeHtml(line.slice(1))}</div>`;
|
||||
}
|
||||
|
||||
// Other (commit info, etc)
|
||||
return `<div class="diff-line diff-meta">${escaped}</div>`;
|
||||
}).join('');
|
||||
|
||||
const fileLabel = currentFile ? `<span class="diff-filename" title="${self._escapeHtml(currentFile)}">${self._escapeHtml(currentFile)}</span>` : '';
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="diff-block ext-rendered">
|
||||
<div class="diff-toolbar">
|
||||
${fileLabel}
|
||||
<span class="diff-stats">
|
||||
<span class="diff-stat-add">+${stats.added}</span>
|
||||
<span class="diff-stat-del">-${stats.removed}</span>
|
||||
</span>
|
||||
<button class="diff-copy-btn" title="Copy diff">📋 Copy</button>
|
||||
</div>
|
||||
<div class="diff-content">${rendered}</div>
|
||||
<details class="diff-source-toggle">
|
||||
<summary>📝 View raw</summary>
|
||||
<pre><code>${self._escapeHtml(code)}</code></pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Copy handler
|
||||
const copyBtn = container.querySelector('.diff-copy-btn');
|
||||
if (copyBtn) {
|
||||
copyBtn.addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
copyBtn.textContent = '✓ Copied';
|
||||
setTimeout(() => { copyBtn.textContent = '📋 Copy'; }, 1500);
|
||||
}).catch(() => {});
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
_escapeHtml(str) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
}
|
||||
},
|
||||
|
||||
// ── Styles ──────────────────────────────
|
||||
|
||||
function _injectStyles() {
|
||||
_injectStyles() {
|
||||
if (document.getElementById('ext-style-diff-viewer')) return;
|
||||
const style = document.createElement('style');
|
||||
style.id = 'ext-style-diff-viewer';
|
||||
@@ -74,86 +158,9 @@
|
||||
max-height: 200px; overflow: auto;
|
||||
}`;
|
||||
document.head.appendChild(style);
|
||||
},
|
||||
|
||||
destroy() {
|
||||
document.getElementById('ext-style-diff-viewer')?.remove();
|
||||
}
|
||||
|
||||
// ── Registration ────────────────────────
|
||||
|
||||
function register() {
|
||||
if (!window.sw?.renderers) return;
|
||||
|
||||
_injectStyles();
|
||||
|
||||
sw.renderers.register('diff-block', {
|
||||
type: 'block',
|
||||
priority: 10,
|
||||
pattern: 'diff',
|
||||
render(lang, code, container) {
|
||||
const lines = code.split('\n');
|
||||
let stats = { added: 0, removed: 0 };
|
||||
let currentFile = '';
|
||||
|
||||
const rendered = lines.map(line => {
|
||||
const escaped = _escapeHtml(line);
|
||||
|
||||
if (line.startsWith('--- ') || line.startsWith('+++ ')) {
|
||||
if (line.startsWith('+++ ')) currentFile = line.slice(4).trim();
|
||||
return `<div class="diff-line diff-file-header">${escaped}</div>`;
|
||||
}
|
||||
if (line.startsWith('@@')) {
|
||||
return `<div class="diff-line diff-hunk">${escaped}</div>`;
|
||||
}
|
||||
if (line.startsWith('+')) {
|
||||
stats.added++;
|
||||
return `<div class="diff-line diff-add"><span class="diff-indicator">+</span>${_escapeHtml(line.slice(1))}</div>`;
|
||||
}
|
||||
if (line.startsWith('-')) {
|
||||
stats.removed++;
|
||||
return `<div class="diff-line diff-del"><span class="diff-indicator">-</span>${_escapeHtml(line.slice(1))}</div>`;
|
||||
}
|
||||
if (line.startsWith(' ')) {
|
||||
return `<div class="diff-line diff-ctx"><span class="diff-indicator"> </span>${_escapeHtml(line.slice(1))}</div>`;
|
||||
}
|
||||
return `<div class="diff-line diff-meta">${escaped}</div>`;
|
||||
}).join('');
|
||||
|
||||
const fileLabel = currentFile
|
||||
? `<span class="diff-filename" title="${_escapeHtml(currentFile)}">${_escapeHtml(currentFile)}</span>`
|
||||
: '';
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="diff-block ext-rendered">
|
||||
<div class="diff-toolbar">
|
||||
${fileLabel}
|
||||
<span class="diff-stats">
|
||||
<span class="diff-stat-add">+${stats.added}</span>
|
||||
<span class="diff-stat-del">-${stats.removed}</span>
|
||||
</span>
|
||||
<button class="diff-copy-btn" title="Copy diff">\ud83d\udccb Copy</button>
|
||||
</div>
|
||||
<div class="diff-content">${rendered}</div>
|
||||
<details class="diff-source-toggle">
|
||||
<summary>\ud83d\udcdd View raw</summary>
|
||||
<pre><code>${_escapeHtml(code)}</code></pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const copyBtn = container.querySelector('.diff-copy-btn');
|
||||
if (copyBtn) {
|
||||
copyBtn.addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
copyBtn.textContent = '\u2713 Copied';
|
||||
setTimeout(() => { copyBtn.textContent = '\ud83d\udccb Copy'; }, 1500);
|
||||
}).catch(() => {});
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (window.sw?._sdk) {
|
||||
register();
|
||||
} else {
|
||||
document.addEventListener('sw:ready', register, { once: true });
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
"version": "1.0.0",
|
||||
"type": "extension",
|
||||
"tier": "browser",
|
||||
"author": "armature",
|
||||
"author": "switchboard",
|
||||
"description": "Renders ```diff code blocks with syntax-highlighted additions, deletions, and context lines",
|
||||
"requires": [],
|
||||
"requires": ["chat"],
|
||||
"permissions": [],
|
||||
"tools": [],
|
||||
"surfaces": [],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* ==========================================
|
||||
Armature — Editor Surface (v0.25.0)
|
||||
Switchboard Core — Editor Surface (v0.25.0)
|
||||
==========================================
|
||||
Replaces editor-mode.css for the pane-based editor.
|
||||
Covers: topbar, bootstrap, and component-specific
|
||||
@@ -8,166 +8,166 @@
|
||||
|
||||
/* ── Surface Shell ─────────────────────────── */
|
||||
|
||||
.ext-editor {
|
||||
.surface-editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
background: var(--bg, #0e0e10);
|
||||
}
|
||||
|
||||
/* ── Topbar ────────────────────────────────── */
|
||||
|
||||
.ext-editor-topbar {
|
||||
.editor-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding: 0 var(--sp-3);
|
||||
gap: 8px;
|
||||
padding: 0 12px;
|
||||
height: 40px;
|
||||
flex-shrink: 0;
|
||||
background: var(--bg-secondary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-secondary, #151517);
|
||||
border-bottom: 1px solid var(--border, #2a2a2e);
|
||||
font-size: 13px;
|
||||
position: relative;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
.ext-editor-topbar-back {
|
||||
.editor-topbar-back {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
color: var(--text-3);
|
||||
gap: 4px;
|
||||
color: var(--text-3, #777);
|
||||
text-decoration: none;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
.ext-editor-topbar-back:hover {
|
||||
color: var(--text);
|
||||
.editor-topbar-back:hover {
|
||||
color: var(--text, #eee);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-editor-topbar-sep {
|
||||
.editor-topbar-sep {
|
||||
width: 1px;
|
||||
height: 18px;
|
||||
background: var(--border);
|
||||
background: var(--border, #2a2a2e);
|
||||
}
|
||||
|
||||
.ext-editor-topbar-name {
|
||||
.editor-topbar-name {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
color: var(--text, #eee);
|
||||
}
|
||||
|
||||
/* ── Workspace Selector ────────────────────── */
|
||||
|
||||
.ext-editor-ws-selector {
|
||||
.editor-ws-selector {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ext-editor-ws-selector-btn {
|
||||
.editor-ws-selector-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
gap: 6px;
|
||||
background: none;
|
||||
border: 1px solid transparent;
|
||||
color: var(--text);
|
||||
color: var(--text, #eee);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
.ext-editor-ws-selector-btn:hover {
|
||||
border-color: var(--border);
|
||||
.editor-ws-selector-btn:hover {
|
||||
border-color: var(--border, #2a2a2e);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-editor-ws-dropdown {
|
||||
.editor-ws-dropdown {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
margin-top: var(--sp-1);
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
margin-top: 4px;
|
||||
background: var(--bg-secondary, #1a1a1e);
|
||||
border: 1px solid var(--border, #2a2a2e);
|
||||
border-radius: 8px;
|
||||
min-width: 220px;
|
||||
max-height: 320px;
|
||||
overflow-y: auto;
|
||||
z-index: 1000;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
||||
padding: var(--sp-1) 0;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.ext-editor-ws-dropdown.open { display: block; }
|
||||
.editor-ws-dropdown.open { display: block; }
|
||||
|
||||
.ext-editor-ws-list {
|
||||
.editor-ws-list {
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.ext-editor-ws-dropdown-item {
|
||||
.editor-ws-dropdown-item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text);
|
||||
color: var(--text, #eee);
|
||||
font-size: 12px;
|
||||
font-family: inherit;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.ext-editor-ws-dropdown-item:hover {
|
||||
.editor-ws-dropdown-item:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-editor-ws-dropdown-item.active {
|
||||
color: var(--accent);
|
||||
.editor-ws-dropdown-item.active {
|
||||
color: var(--accent, #b38a4e);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ext-editor-ws-dropdown-divider {
|
||||
.editor-ws-dropdown-divider {
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
margin: var(--sp-1) 0;
|
||||
background: var(--border, #2a2a2e);
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.ext-editor-ws-new {
|
||||
.editor-ws-new {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
color: var(--accent);
|
||||
gap: 6px;
|
||||
color: var(--accent, #b38a4e);
|
||||
}
|
||||
|
||||
.ext-editor-topbar-branch {
|
||||
.editor-topbar-branch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
background: var(--purple-dim);
|
||||
padding: 2px var(--sp-2);
|
||||
border-radius: var(--radius-sm);
|
||||
gap: 4px;
|
||||
background: var(--purple-dim, rgba(160, 120, 255, 0.1));
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.ext-editor-topbar-branch-text {
|
||||
.editor-topbar-branch-text {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--purple);
|
||||
color: var(--purple, #a078ff);
|
||||
font-family: var(--mono, 'SF Mono', monospace);
|
||||
}
|
||||
|
||||
/* ── Body ──────────────────────────────────── */
|
||||
|
||||
.ext-editor-body {
|
||||
.editor-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
@@ -175,47 +175,47 @@
|
||||
|
||||
/* ── Bootstrap (no workspace) ──────────────── */
|
||||
|
||||
.ext-editor-bootstrap {
|
||||
.editor-bootstrap {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-card {
|
||||
.editor-bootstrap-card {
|
||||
text-align: center;
|
||||
padding: var(--sp-10);
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 40px;
|
||||
background: var(--bg-secondary, #151517);
|
||||
border: 1px solid var(--border, #2a2a2e);
|
||||
border-radius: 12px;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-input {
|
||||
.editor-bootstrap-input {
|
||||
width: 100%;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text);
|
||||
padding: 8px 12px;
|
||||
background: var(--bg, #0e0e10);
|
||||
border: 1px solid var(--border, #2a2a2e);
|
||||
border-radius: 6px;
|
||||
color: var(--text, #eee);
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
margin-bottom: var(--sp-3);
|
||||
margin-bottom: 12px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-input:focus {
|
||||
border-color: var(--accent);
|
||||
.editor-bootstrap-input:focus {
|
||||
border-color: var(--accent, #b38a4e);
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-btn {
|
||||
.editor-bootstrap-btn {
|
||||
width: 100%;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
background: var(--accent);
|
||||
padding: 10px 16px;
|
||||
background: var(--accent, #b38a4e);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
@@ -223,108 +223,108 @@
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-btn:hover { opacity: 0.9; }
|
||||
.ext-editor-bootstrap-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.editor-bootstrap-btn:hover { opacity: 0.9; }
|
||||
.editor-bootstrap-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
/* Workspace list in bootstrap */
|
||||
.ext-editor-bootstrap-ws-item {
|
||||
.editor-bootstrap-ws-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
padding: var(--sp-3) var(--sp-3);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text);
|
||||
padding: 10px 12px;
|
||||
background: var(--bg, #0e0e10);
|
||||
border: 1px solid var(--border, #2a2a2e);
|
||||
border-radius: 6px;
|
||||
color: var(--text, #eee);
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
margin-bottom: var(--sp-2);
|
||||
margin-bottom: 6px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-ws-item:hover {
|
||||
border-color: var(--accent);
|
||||
.editor-bootstrap-ws-item:hover {
|
||||
border-color: var(--accent, #b38a4e);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-ws-name {
|
||||
.editor-bootstrap-ws-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ext-editor-bootstrap-ws-date {
|
||||
.editor-bootstrap-ws-date {
|
||||
font-size: 11px;
|
||||
color: var(--text-3);
|
||||
color: var(--text-3, #777);
|
||||
}
|
||||
|
||||
/* ── FileTree overrides (in editor context) ── */
|
||||
|
||||
.ext-editor .file-tree {
|
||||
.surface-editor .file-tree {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border, #2a2a2e);
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-header {
|
||||
.surface-editor .file-tree-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 6px;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--border, #2a2a2e);
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-title {
|
||||
.surface-editor .file-tree-title {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--text-2);
|
||||
color: var(--text-2, #999);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.4px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-items {
|
||||
.surface-editor .file-tree-items {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-1) 0;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-row {
|
||||
.surface-editor .file-tree-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
padding: 3px var(--sp-2);
|
||||
gap: 4px;
|
||||
padding: 3px 8px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: var(--text-2);
|
||||
color: var(--text-2, #999);
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-row:hover {
|
||||
.surface-editor .file-tree-row:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-row.active {
|
||||
background: var(--accent-dim);
|
||||
color: var(--text);
|
||||
.surface-editor .file-tree-row.active {
|
||||
background: var(--accent-dim, rgba(179, 138, 78, 0.15));
|
||||
color: var(--text, #eee);
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-arrow {
|
||||
.surface-editor .file-tree-arrow {
|
||||
width: 12px;
|
||||
font-size: 10px;
|
||||
color: var(--text-3);
|
||||
color: var(--text-3, #555);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-icon {
|
||||
.surface-editor .file-tree-icon {
|
||||
font-size: 13px;
|
||||
width: 18px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.ext-editor .file-tree-name {
|
||||
.surface-editor .file-tree-name {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -332,134 +332,134 @@
|
||||
}
|
||||
|
||||
/* Git status indicators */
|
||||
.ext-editor .file-tree-row.git-modified .file-tree-name { color: var(--warning); }
|
||||
.ext-editor .file-tree-row.git-added .file-tree-name { color: var(--success); }
|
||||
.ext-editor .file-tree-row.git-untracked .file-tree-name { color: var(--text-3); font-style: italic; }
|
||||
.ext-editor .file-tree-row.git-deleted .file-tree-name { color: var(--danger); text-decoration: line-through; }
|
||||
.surface-editor .file-tree-row.git-modified .file-tree-name { color: var(--warning, #e5a842); }
|
||||
.surface-editor .file-tree-row.git-added .file-tree-name { color: var(--success, #4caf50); }
|
||||
.surface-editor .file-tree-row.git-untracked .file-tree-name { color: var(--text-3, #555); font-style: italic; }
|
||||
.surface-editor .file-tree-row.git-deleted .file-tree-name { color: var(--danger, #f44336); text-decoration: line-through; }
|
||||
|
||||
/* Context menu */
|
||||
.ext-editor-file-tree-ctx-menu {
|
||||
.file-tree-ctx-menu {
|
||||
position: fixed;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-1) 0;
|
||||
background: var(--bg-secondary, #1a1a1e);
|
||||
border: 1px solid var(--border, #2a2a2e);
|
||||
border-radius: 6px;
|
||||
padding: 4px 0;
|
||||
min-width: 120px;
|
||||
z-index: 1000;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
|
||||
}
|
||||
|
||||
.ext-editor-file-tree-ctx-item {
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
.file-tree-ctx-item {
|
||||
padding: 6px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
color: var(--text, #eee);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ext-editor-file-tree-ctx-item:hover {
|
||||
.file-tree-ctx-item:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
/* ── CodeEditor overrides ──────────────────── */
|
||||
|
||||
.ext-editor .code-editor {
|
||||
.surface-editor .code-editor {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-tabs {
|
||||
.surface-editor .code-editor-tabs {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
background: var(--bg-secondary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-secondary, #151517);
|
||||
border-bottom: 1px solid var(--border, #2a2a2e);
|
||||
height: 32px;
|
||||
overflow-x: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-tabs::-webkit-scrollbar { height: 0; }
|
||||
.surface-editor .code-editor-tabs::-webkit-scrollbar { height: 0; }
|
||||
|
||||
.ext-editor .code-editor-tab {
|
||||
.surface-editor .code-editor-tab {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
padding: 0 var(--sp-3);
|
||||
gap: 4px;
|
||||
padding: 0 12px;
|
||||
height: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--text-3);
|
||||
color: var(--text-3, #777);
|
||||
cursor: pointer;
|
||||
border-right: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border, #2a2a2e);
|
||||
transition: background 0.1s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-tab:hover { background: var(--bg-hover); }
|
||||
.ext-editor .code-editor-tab.active { color: var(--text); background: var(--bg); }
|
||||
.ext-editor .code-editor-tab.modified .code-editor-tab-modified { color: var(--warning); }
|
||||
.surface-editor .code-editor-tab:hover { background: var(--bg-hover); }
|
||||
.surface-editor .code-editor-tab.active { color: var(--text, #eee); background: var(--bg, #0e0e10); }
|
||||
.surface-editor .code-editor-tab.modified .code-editor-tab-modified { color: var(--warning, #e5a842); }
|
||||
|
||||
.ext-editor .code-editor-tab-icon { font-size: 12px; }
|
||||
.ext-editor .code-editor-tab-modified { font-size: 10px; color: var(--text-3); }
|
||||
.surface-editor .code-editor-tab-icon { font-size: 12px; }
|
||||
.surface-editor .code-editor-tab-modified { font-size: 10px; color: var(--text-3); }
|
||||
|
||||
.ext-editor .code-editor-tab-close {
|
||||
.surface-editor .code-editor-tab-close {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-3);
|
||||
color: var(--text-3, #555);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 0 2px;
|
||||
margin-left: var(--sp-1);
|
||||
border-radius: var(--radius-sm);
|
||||
margin-left: 4px;
|
||||
border-radius: 2px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-tab-close:hover {
|
||||
background: var(--danger-dim);
|
||||
color: var(--danger);
|
||||
.surface-editor .code-editor-tab-close:hover {
|
||||
background: var(--danger-dim, rgba(244, 67, 54, 0.15));
|
||||
color: var(--danger, #f44336);
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-content {
|
||||
.surface-editor .code-editor-content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-welcome {
|
||||
.surface-editor .code-editor-welcome {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-cm-wrap {
|
||||
.surface-editor .code-editor-cm-wrap {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-cm-wrap .cm-editor {
|
||||
.surface-editor .code-editor-cm-wrap .cm-editor {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-statusbar {
|
||||
.surface-editor .code-editor-statusbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
padding: 0 var(--sp-3);
|
||||
gap: 16px;
|
||||
padding: 0 12px;
|
||||
height: 24px;
|
||||
flex-shrink: 0;
|
||||
background: var(--bg-secondary);
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-secondary, #151517);
|
||||
border-top: 1px solid var(--border, #2a2a2e);
|
||||
font-size: 11px;
|
||||
color: var(--text-3);
|
||||
color: var(--text-3, #777);
|
||||
font-family: var(--mono, 'SF Mono', monospace);
|
||||
}
|
||||
|
||||
.ext-editor .code-editor-textarea-fallback {
|
||||
.surface-editor .code-editor-textarea-fallback {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
background: var(--bg, #0e0e10);
|
||||
color: var(--text, #eee);
|
||||
border: none;
|
||||
padding: var(--sp-3);
|
||||
padding: 12px;
|
||||
font-family: var(--mono, 'SF Mono', monospace);
|
||||
font-size: 13px;
|
||||
resize: none;
|
||||
@@ -469,18 +469,18 @@
|
||||
|
||||
/* ── Tabbed assist pane overrides ──────────── */
|
||||
|
||||
.ext-editor .pane-tabbed {
|
||||
border-left: 1px solid var(--border);
|
||||
.surface-editor .pane-tabbed {
|
||||
border-left: 1px solid var(--border, #2a2a2e);
|
||||
}
|
||||
|
||||
/* ChatPane in editor tabbed pane */
|
||||
.ext-editor .chat-pane {
|
||||
.surface-editor .chat-pane {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
/* Notes in editor pane */
|
||||
.ext-editor .ext-notes-editor {
|
||||
.surface-editor .note-editor {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
@@ -488,43 +488,43 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ext-editor .ext-notes-editor-list-view {
|
||||
.surface-editor .note-editor-list-view {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ext-editor .ext-notes-list {
|
||||
.surface-editor .notes-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* Compact notes toolbar for narrow pane */
|
||||
.ext-editor .ext-notes-toolbar {
|
||||
.surface-editor .notes-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-1);
|
||||
padding: var(--sp-2) var(--sp-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 4px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border, #2a2a2e);
|
||||
}
|
||||
|
||||
.ext-editor .ext-notes-toolbar .sw-btn--sm {
|
||||
.surface-editor .notes-toolbar .btn-small {
|
||||
font-size: 11px;
|
||||
padding: 3px var(--sp-2);
|
||||
padding: 3px 6px;
|
||||
}
|
||||
|
||||
.ext-editor .ext-notes-search-row {
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
.surface-editor .notes-search-row {
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.ext-editor .ext-notes-filter-row {
|
||||
padding: 2px var(--sp-2) var(--sp-1);
|
||||
.surface-editor .notes-filter-row {
|
||||
padding: 2px 8px 4px;
|
||||
display: flex;
|
||||
gap: var(--sp-1);
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.ext-editor .ext-notes-filter-select {
|
||||
.surface-editor .notes-filter-select {
|
||||
font-size: 11px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// ==========================================
|
||||
// Armature — Editor Package (v0.31.0)
|
||||
// Switchboard Core — Editor Package (v0.31.0)
|
||||
// ==========================================
|
||||
// Installable .pkg that provides the code editor surface.
|
||||
// Mounts into #extension-mount (surface-extension template).
|
||||
@@ -56,7 +56,7 @@
|
||||
|
||||
// Wrap in surface container for CSS scoping
|
||||
const surface = document.createElement('div');
|
||||
surface.className = 'ext-editor';
|
||||
surface.className = 'surface-editor';
|
||||
surface.id = 'editorSurface';
|
||||
mount.appendChild(surface);
|
||||
|
||||
@@ -84,7 +84,7 @@
|
||||
|
||||
// Build body + bootstrap
|
||||
const body = document.createElement('div');
|
||||
body.className = 'ext-editor-body';
|
||||
body.className = 'editor-body';
|
||||
body.id = 'editorBody';
|
||||
surface.appendChild(body);
|
||||
|
||||
@@ -113,32 +113,32 @@
|
||||
|
||||
function _buildTopbar(wsName) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'ext-editor-topbar';
|
||||
el.className = 'editor-topbar';
|
||||
el.id = 'editorTopbar';
|
||||
el.innerHTML =
|
||||
'<a href="' + esc(base) + '/" class="ext-editor-topbar-back" title="Back to chat">' +
|
||||
'<a href="' + esc(base) + '/" class="editor-topbar-back" title="Back to chat">' +
|
||||
'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>' +
|
||||
'Back' +
|
||||
'</a>' +
|
||||
'<div class="ext-editor-topbar-sep"></div>' +
|
||||
'<div class="editor-topbar-sep"></div>' +
|
||||
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color:var(--accent);"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>' +
|
||||
'<div class="ext-editor-ws-selector" id="editorWsSelector">' +
|
||||
'<button class="ext-editor-ws-selector-btn" id="editorWsSelectorBtn">' +
|
||||
'<div class="editor-ws-selector" id="editorWsSelector">' +
|
||||
'<button class="editor-ws-selector-btn" id="editorWsSelectorBtn">' +
|
||||
'<span id="editorWorkspaceName">' + esc(wsName || 'Editor') + '</span>' +
|
||||
'<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>' +
|
||||
'</button>' +
|
||||
'<div class="ext-editor-ws-dropdown" id="editorWsDropdown">' +
|
||||
'<div id="editorWsList" class="ext-editor-ws-list"></div>' +
|
||||
'<div class="ext-editor-ws-dropdown-divider"></div>' +
|
||||
'<button class="ext-editor-ws-dropdown-item ext-editor-ws-new" id="editorWsNewBtn">' +
|
||||
'<div class="editor-ws-dropdown" id="editorWsDropdown">' +
|
||||
'<div id="editorWsList" class="editor-ws-list"></div>' +
|
||||
'<div class="editor-ws-dropdown-divider"></div>' +
|
||||
'<button class="editor-ws-dropdown-item editor-ws-new" id="editorWsNewBtn">' +
|
||||
'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>' +
|
||||
'New Workspace' +
|
||||
'</button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="ext-editor-topbar-branch" id="editorBranchBadge" style="display:none;">' +
|
||||
'<div class="editor-topbar-branch" id="editorBranchBadge" style="display:none;">' +
|
||||
'<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--purple)" stroke-width="2"><circle cx="12" cy="18" r="3"/><circle cx="12" cy="6" r="3"/><line x1="12" y1="9" x2="12" y2="15"/></svg>' +
|
||||
'<span id="editorBranchName" class="ext-editor-topbar-branch-text">main</span>' +
|
||||
'<span id="editorBranchName" class="editor-topbar-branch-text">main</span>' +
|
||||
'</div>' +
|
||||
'<div style="flex:1;"></div>' +
|
||||
'<button class="icon-btn" id="editorRefreshBtn" title="Refresh files">' +
|
||||
@@ -151,11 +151,11 @@
|
||||
|
||||
function _buildBootstrap() {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'ext-editor-bootstrap';
|
||||
el.className = 'editor-bootstrap';
|
||||
el.id = 'editorBootstrap';
|
||||
el.style.display = 'none';
|
||||
el.innerHTML =
|
||||
'<div class="ext-editor-bootstrap-card">' +
|
||||
'<div class="editor-bootstrap-card">' +
|
||||
'<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" stroke-width="1.5" style="opacity:0.6;margin-bottom:12px;">' +
|
||||
'<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>' +
|
||||
'</svg>' +
|
||||
@@ -168,8 +168,8 @@
|
||||
'<span style="font-size:11px;color:var(--text-3);text-transform:uppercase;">or create new</span>' +
|
||||
'<div style="flex:1;height:1px;background:var(--border);"></div>' +
|
||||
'</div>' +
|
||||
'<input type="text" id="editorBootstrapName" class="ext-editor-bootstrap-input" placeholder="Workspace name" value="workspace">' +
|
||||
'<button id="editorBootstrapBtn" class="ext-editor-bootstrap-btn">Create Workspace</button>' +
|
||||
'<input type="text" id="editorBootstrapName" class="editor-bootstrap-input" placeholder="Workspace name" value="workspace">' +
|
||||
'<button id="editorBootstrapBtn" class="editor-bootstrap-btn">Create Workspace</button>' +
|
||||
'</div>';
|
||||
return el;
|
||||
}
|
||||
@@ -218,7 +218,7 @@
|
||||
}
|
||||
workspaces.forEach(ws => {
|
||||
const item = document.createElement('button');
|
||||
item.className = 'ext-editor-ws-dropdown-item' + (ws.id === currentWsId ? ' active' : '');
|
||||
item.className = 'editor-ws-dropdown-item' + (ws.id === currentWsId ? ' active' : '');
|
||||
item.textContent = ws.name || ws.id?.slice(0, 8);
|
||||
item.addEventListener('click', () => { window.location.href = base + '/s/editor?ws=' + ws.id; });
|
||||
listEl.appendChild(item);
|
||||
@@ -243,10 +243,10 @@
|
||||
listEl.innerHTML = '';
|
||||
workspaces.forEach(ws => {
|
||||
const item = document.createElement('button');
|
||||
item.className = 'ext-editor-bootstrap-ws-item';
|
||||
item.className = 'editor-bootstrap-ws-item';
|
||||
item.innerHTML =
|
||||
'<span class="ext-editor-bootstrap-ws-name">' + esc(ws.name || ws.id?.slice(0, 8)) + '</span>' +
|
||||
'<span class="ext-editor-bootstrap-ws-date">' + esc(ws.created_at ? new Date(ws.created_at).toLocaleDateString() : '') + '</span>';
|
||||
'<span class="editor-bootstrap-ws-name">' + esc(ws.name || ws.id?.slice(0, 8)) + '</span>' +
|
||||
'<span class="editor-bootstrap-ws-date">' + esc(ws.created_at ? new Date(ws.created_at).toLocaleDateString() : '') + '</span>';
|
||||
item.addEventListener('click', () => { window.location.href = base + '/s/editor?ws=' + ws.id; });
|
||||
listEl.appendChild(item);
|
||||
});
|
||||
@@ -372,8 +372,8 @@
|
||||
// ── File Operations ─────────────────────────
|
||||
|
||||
async function _deleteFile(wsId, path, fileTree, codeEditor) {
|
||||
const ok = typeof sw !== 'undefined' && sw.confirm
|
||||
? await sw.confirm('Delete ' + path + '?', { destructive: true })
|
||||
const ok = typeof showConfirm === 'function'
|
||||
? await showConfirm('Delete ' + path + '?')
|
||||
: window.confirm('Delete ' + path + '?');
|
||||
if (!ok) return;
|
||||
try {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"type": "full",
|
||||
"version": "0.31.0",
|
||||
"tier": "browser",
|
||||
"author": "Armature",
|
||||
"author": "Switchboard Core",
|
||||
"icon": "✏️",
|
||||
"description": "Code editor with workspace management, file tree, and AI assist (requires legacy sw.* SDK — dormant until rewritten)",
|
||||
"requires": ["legacy-sdk"],
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"version": "0.1.0",
|
||||
"tier": "starlark",
|
||||
"icon": "🏢",
|
||||
"author": "Armature",
|
||||
"author": "Switchboard Core",
|
||||
"description": "Employee onboarding with automated provisioning, manager signoff, and welcome notification.",
|
||||
"permissions": ["db.write", "notifications.send"],
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* Git Board — Surface Styles */
|
||||
|
||||
.ext-git-board-shell {
|
||||
.gb-shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
@@ -9,80 +9,80 @@
|
||||
|
||||
/* ── Header ──────────────────────────────── */
|
||||
|
||||
.ext-git-board-header {
|
||||
.gb-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ext-git-board-header__left,
|
||||
.ext-git-board-header__right {
|
||||
.gb-header__left,
|
||||
.gb-header__right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.ext-git-board-title {
|
||||
.gb-title {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ext-git-board-repo-picker {
|
||||
.gb-repo-picker {
|
||||
background: var(--bg-raised);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text);
|
||||
font-family: var(--mono);
|
||||
font-size: 13px;
|
||||
padding: 5px var(--sp-2);
|
||||
padding: 5px 8px;
|
||||
max-width: 260px;
|
||||
}
|
||||
|
||||
/* ── Connection Setup ─────────────────────── */
|
||||
|
||||
.ext-git-board-setup {
|
||||
.gb-setup {
|
||||
max-width: 480px;
|
||||
margin: 60px auto;
|
||||
text-align: center;
|
||||
padding: 0 var(--sp-4);
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.ext-git-board-setup h2 {
|
||||
.gb-setup h2 {
|
||||
color: var(--text);
|
||||
font-size: 20px;
|
||||
margin: 0 0 var(--sp-2);
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.ext-git-board-setup p {
|
||||
.gb-setup p {
|
||||
color: var(--text-2);
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
margin: 0 0 var(--sp-5);
|
||||
margin: 0 0 20px;
|
||||
}
|
||||
|
||||
|
||||
.ext-git-board-setup__hint {
|
||||
.gb-setup__hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
/* ── Kanban Board ────────────────────────── */
|
||||
|
||||
.ext-git-board-board {
|
||||
.gb-board {
|
||||
display: flex;
|
||||
gap: var(--sp-3);
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
flex: 1;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
}
|
||||
|
||||
.ext-git-board-column {
|
||||
.gb-column {
|
||||
min-width: 260px;
|
||||
max-width: 320px;
|
||||
flex: 1;
|
||||
@@ -94,15 +94,15 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ext-git-board-column__header {
|
||||
.gb-column__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--sp-3) var(--sp-3);
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.ext-git-board-column__title {
|
||||
.gb-column__title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
@@ -110,67 +110,67 @@
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.ext-git-board-column__count {
|
||||
.gb-column__count {
|
||||
background: var(--bg-raised);
|
||||
color: var(--text-2);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
padding: 2px 7px;
|
||||
border-radius: var(--radius-lg);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.ext-git-board-column__cards {
|
||||
.gb-column__cards {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-2);
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* ── Cards ───────────────────────────────── */
|
||||
|
||||
.ext-git-board-card {
|
||||
.gb-card {
|
||||
display: block;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-3);
|
||||
padding: 10px;
|
||||
text-decoration: none;
|
||||
color: var(--text);
|
||||
transition: border-color var(--transition), background var(--transition);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ext-git-board-card:hover {
|
||||
.gb-card:hover {
|
||||
border-color: var(--accent);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-git-board-card--pr {
|
||||
.gb-card--pr {
|
||||
border-left: 3px solid var(--accent);
|
||||
}
|
||||
|
||||
.ext-git-board-card__header {
|
||||
.gb-card__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
margin-bottom: var(--sp-1);
|
||||
gap: 6px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.ext-git-board-card__number {
|
||||
.gb-card__number {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
.ext-git-board-card__assignee {
|
||||
.gb-card__assignee {
|
||||
font-size: 11px;
|
||||
color: var(--accent);
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.ext-git-board-card__branch {
|
||||
.gb-card__branch {
|
||||
font-family: var(--mono);
|
||||
font-size: 11px;
|
||||
color: var(--text-3);
|
||||
@@ -181,54 +181,54 @@
|
||||
max-width: 150px;
|
||||
}
|
||||
|
||||
.ext-git-board-card__title {
|
||||
.gb-card__title {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ext-git-board-card__labels {
|
||||
.gb-card__labels {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-1);
|
||||
margin-top: var(--sp-2);
|
||||
gap: 4px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.ext-git-board-card__labels .ext-git-board-badge {
|
||||
.gb-card__labels .badge {
|
||||
font-size: 10px;
|
||||
padding: 1px var(--sp-2);
|
||||
padding: 1px 6px;
|
||||
}
|
||||
|
||||
.ext-git-board-card__meta {
|
||||
.gb-card__meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: var(--sp-2);
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
/* ── DnD States ─────────────────────────── */
|
||||
|
||||
.ext-git-board-card[draggable="true"] {
|
||||
.gb-card[draggable="true"] {
|
||||
cursor: grab;
|
||||
user-select: none;
|
||||
}
|
||||
.ext-git-board-card[draggable="true"]:active {
|
||||
.gb-card[draggable="true"]:active {
|
||||
cursor: grabbing;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.ext-git-board-column--dragover {
|
||||
.gb-column--dragover {
|
||||
border-color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 6%, var(--bg-surface));
|
||||
}
|
||||
.ext-git-board-column--dragover .ext-git-board-column__header {
|
||||
.gb-column--dragover .gb-column__header {
|
||||
border-bottom-color: var(--accent);
|
||||
}
|
||||
|
||||
/* ── Empty state ─────────────────────────── */
|
||||
|
||||
.ext-git-board-empty {
|
||||
.gb-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -239,7 +239,7 @@
|
||||
|
||||
/* ── Issue Detail Modal ─────────────────── */
|
||||
|
||||
.ext-git-board-modal-overlay {
|
||||
.gb-modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.5);
|
||||
@@ -247,41 +247,40 @@
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding: var(--sp-10) var(--sp-4);
|
||||
padding: 40px 16px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.ext-git-board-modal {
|
||||
.gb-modal {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
width: 100%;
|
||||
max-width: 680px;
|
||||
max-height: calc(100vh - 80px);
|
||||
max-height: calc(100dvh - 80px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
.ext-git-board-modal__header {
|
||||
.gb-modal__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: var(--sp-4) var(--sp-5);
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ext-git-board-modal__title-row {
|
||||
.gb-modal__title-row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--sp-2);
|
||||
gap: 8px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ext-git-board-modal__title {
|
||||
.gb-modal__title {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
@@ -289,59 +288,59 @@
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.ext-git-board-modal__close {
|
||||
.gb-modal__close {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-3);
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
padding: 2px var(--sp-2);
|
||||
padding: 2px 6px;
|
||||
border-radius: var(--radius);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.ext-git-board-modal__close:hover {
|
||||
.gb-modal__close:hover {
|
||||
color: var(--text);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.ext-git-board-modal__body {
|
||||
.gb-modal__body {
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-4) var(--sp-5);
|
||||
padding: 16px 20px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.ext-git-board-modal__meta {
|
||||
.gb-modal__meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: var(--sp-3);
|
||||
margin-bottom: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--text-2);
|
||||
}
|
||||
|
||||
.ext-git-board-modal__date {
|
||||
.gb-modal__date {
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
.ext-git-board-modal__extlink {
|
||||
.gb-modal__extlink {
|
||||
margin-left: auto;
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
font-size: 12px;
|
||||
}
|
||||
.ext-git-board-modal__extlink:hover {
|
||||
.gb-modal__extlink:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.ext-git-board-modal__description {
|
||||
margin-bottom: var(--sp-5);
|
||||
padding-bottom: var(--sp-4);
|
||||
.gb-modal__description {
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.ext-git-board-modal__body-text {
|
||||
.gb-modal__body-text {
|
||||
font-family: var(--font);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
@@ -354,49 +353,49 @@
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.ext-git-board-modal__empty {
|
||||
.gb-modal__empty {
|
||||
color: var(--text-3);
|
||||
font-size: 13px;
|
||||
font-style: italic;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ext-git-board-modal__section-title {
|
||||
.gb-modal__section-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text-2);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
margin: 0 0 var(--sp-3);
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
/* ── Comments ────────────────────────────── */
|
||||
|
||||
.ext-git-board-comment {
|
||||
padding: var(--sp-3) 0;
|
||||
.gb-comment {
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.ext-git-board-comment:last-child {
|
||||
.gb-comment:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.ext-git-board-comment__header {
|
||||
.gb-comment__header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--sp-2);
|
||||
margin-bottom: var(--sp-1);
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.ext-git-board-comment__header strong {
|
||||
.gb-comment__header strong {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.ext-git-board-comment__date {
|
||||
.gb-comment__date {
|
||||
color: var(--text-3);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.ext-git-board-comment__body {
|
||||
.gb-comment__body {
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
@@ -406,13 +405,13 @@
|
||||
|
||||
/* ── Add Comment ─────────────────────────── */
|
||||
|
||||
.ext-git-board-modal__add-comment {
|
||||
margin-top: var(--sp-4);
|
||||
padding-top: var(--sp-4);
|
||||
.gb-modal__add-comment {
|
||||
margin-top: 16px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.ext-git-board-modal__textarea {
|
||||
.gb-modal__textarea {
|
||||
width: 100%;
|
||||
background: var(--bg-raised);
|
||||
border: 1px solid var(--border);
|
||||
@@ -420,31 +419,38 @@
|
||||
color: var(--text);
|
||||
font-family: var(--font);
|
||||
font-size: 13px;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
padding: 8px 10px;
|
||||
resize: vertical;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.ext-git-board-modal__textarea:focus {
|
||||
.gb-modal__textarea:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.ext-git-board-modal__actions {
|
||||
.gb-modal__actions {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
margin-top: var(--sp-2);
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* ── Badge variants ──────────────────────── */
|
||||
|
||||
.ext-git-board-badge--green {
|
||||
.badge--green {
|
||||
background: var(--green);
|
||||
color: #fff;
|
||||
}
|
||||
.ext-git-board-badge--muted {
|
||||
.badge--muted {
|
||||
background: var(--bg-raised);
|
||||
color: var(--text-3);
|
||||
}
|
||||
|
||||
/* git-board danger button override — uses kernel .sw-btn--danger */
|
||||
.btn-danger {
|
||||
background: var(--danger, #e53e3e);
|
||||
color: #fff;
|
||||
border: none;
|
||||
}
|
||||
.btn-danger:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
@@ -160,21 +160,21 @@
|
||||
return html`
|
||||
<div class="user-menu-container" ref=${menuRef}></div>
|
||||
${needsConn ? html`<${ConnectionSetup} />` : html`
|
||||
<div class="ext-git-board-shell">
|
||||
<header class="ext-git-board-header">
|
||||
<div class="ext-git-board-header__left">
|
||||
<h1 class="ext-git-board-title">Git Board</h1>
|
||||
<div class="gb-shell">
|
||||
<header class="gb-header">
|
||||
<div class="gb-header__left">
|
||||
<h1 class="gb-title">Git Board</h1>
|
||||
<${RepoPicker} repos=${repos} owner=${owner} repo=${repo}
|
||||
onSelect=${function (o, r) { setOwner(o); setRepo(r); }} />
|
||||
</div>
|
||||
<div class="ext-git-board-header__right">
|
||||
<button class="sw-btn sw-btn--secondary sw-btn--sm" onClick=${loadBoard} disabled=${loading}>
|
||||
<div class="gb-header__right">
|
||||
<button class="btn-small" onClick=${loadBoard} disabled=${loading}>
|
||||
${loading ? '↻' : 'Refresh'}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
${board ? html`<${Board} data=${board} onDrop=${onDrop} onCardClick=${openModal} />` : html`
|
||||
<div class="ext-git-board-empty">${loading ? 'Loading…' : 'Select a repository'}</div>
|
||||
<div class="gb-empty">${loading ? 'Loading…' : 'Select a repository'}</div>
|
||||
`}
|
||||
</div>
|
||||
`}
|
||||
@@ -186,21 +186,21 @@
|
||||
|
||||
function ConnectionSetup() {
|
||||
return html`
|
||||
<div class="ext-git-board-shell">
|
||||
<header class="ext-git-board-header">
|
||||
<div class="ext-git-board-header__left"><h1 class="ext-git-board-title">Git Board</h1></div>
|
||||
<div class="gb-shell">
|
||||
<header class="gb-header">
|
||||
<div class="gb-header__left"><h1 class="gb-title">Git Board</h1></div>
|
||||
</header>
|
||||
<div class="ext-git-board-setup">
|
||||
<div class="gb-setup">
|
||||
<h2>Connect to Gitea</h2>
|
||||
<p>Git Board requires a Gitea connection to fetch repositories, issues, and pull requests.</p>
|
||||
<p>Ask your admin to add a <strong>Gitea</strong> connection in
|
||||
<strong>Admin → Connections</strong>, or add a personal one in
|
||||
<strong>Settings → Connections</strong>.</p>
|
||||
<button class="sw-btn sw-btn--primary sw-btn--sm"
|
||||
<button class="btn-small btn-primary"
|
||||
onClick=${function () { window.location.href = base + '/settings'; }}>
|
||||
Open Settings
|
||||
</button>
|
||||
<p class="ext-git-board-setup__hint">Connections are managed centrally — no API tokens in extension settings.</p>
|
||||
<p class="gb-setup__hint">Connections are managed centrally — no API tokens in extension settings.</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -211,7 +211,7 @@
|
||||
function RepoPicker({ repos, owner, repo, onSelect }) {
|
||||
var current = owner + '/' + repo;
|
||||
return html`
|
||||
<select class="ext-git-board-repo-picker" value=${current}
|
||||
<select class="gb-repo-picker" value=${current}
|
||||
onChange=${function (e) {
|
||||
var parts = e.target.value.split('/');
|
||||
onSelect(parts[0], parts.slice(1).join('/'));
|
||||
@@ -233,7 +233,7 @@
|
||||
var inProgress = issues.filter(function (i) { return i.state === 'open' && !!i.assignee; });
|
||||
|
||||
return html`
|
||||
<div class="ext-git-board-board">
|
||||
<div class="gb-board">
|
||||
<${Column} id="open" title="Open" count=${openUnassigned.length} onDrop=${onDrop}>
|
||||
${openUnassigned.map(function (i) {
|
||||
return html`<${IssueCard} key=${i.number} issue=${i} onClick=${onCardClick} />`;
|
||||
@@ -268,19 +268,19 @@
|
||||
} : {};
|
||||
|
||||
return html`
|
||||
<div class="ext-git-board-column ${over ? 'ext-git-board-column--dragover' : ''}" ...${handlers}>
|
||||
<div class="ext-git-board-column__header">
|
||||
<span class="ext-git-board-column__title">${title}</span>
|
||||
<span class="ext-git-board-column__count">${count || 0}</span>
|
||||
<div class="gb-column ${over ? 'gb-column--dragover' : ''}" ...${handlers}>
|
||||
<div class="gb-column__header">
|
||||
<span class="gb-column__title">${title}</span>
|
||||
<span class="gb-column__count">${count || 0}</span>
|
||||
</div>
|
||||
<div class="ext-git-board-column__cards">${children}</div>
|
||||
<div class="gb-column__cards">${children}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function IssueCard({ issue, onClick }) {
|
||||
return html`
|
||||
<div class="ext-git-board-card" draggable="true"
|
||||
<div class="gb-card" draggable="true"
|
||||
onDragStart=${function (e) {
|
||||
e.dataTransfer.setData('text/plain', String(issue.number));
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
@@ -289,14 +289,14 @@
|
||||
e.preventDefault();
|
||||
if (onClick) onClick(issue.number);
|
||||
}}>
|
||||
<div class="ext-git-board-card__header">
|
||||
<span class="ext-git-board-card__number">#${issue.number}</span>
|
||||
${issue.assignee && html`<span class="ext-git-board-card__assignee">@${esc(issue.assignee)}</span>`}
|
||||
<div class="gb-card__header">
|
||||
<span class="gb-card__number">#${issue.number}</span>
|
||||
${issue.assignee && html`<span class="gb-card__assignee">@${esc(issue.assignee)}</span>`}
|
||||
</div>
|
||||
<div class="ext-git-board-card__title">${esc(issue.title)}</div>
|
||||
<div class="ext-git-board-card__labels">
|
||||
<div class="gb-card__title">${esc(issue.title)}</div>
|
||||
<div class="gb-card__labels">
|
||||
${(issue.labels || []).map(function (l) {
|
||||
return html`<span key=${l} class="ext-git-board-badge">${esc(l)}</span>`;
|
||||
return html`<span key=${l} class="badge">${esc(l)}</span>`;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
@@ -305,13 +305,13 @@
|
||||
|
||||
function PRCard({ pr }) {
|
||||
return html`
|
||||
<a class="ext-git-board-card ext-git-board-card--pr" href=${pr.html_url} target="_blank" rel="noopener">
|
||||
<div class="ext-git-board-card__header">
|
||||
<span class="ext-git-board-card__number">#${pr.number}</span>
|
||||
<span class="ext-git-board-card__branch">${esc(pr.head)} → ${esc(pr.base)}</span>
|
||||
<a class="gb-card gb-card--pr" href=${pr.html_url} target="_blank" rel="noopener">
|
||||
<div class="gb-card__header">
|
||||
<span class="gb-card__number">#${pr.number}</span>
|
||||
<span class="gb-card__branch">${esc(pr.head)} → ${esc(pr.base)}</span>
|
||||
</div>
|
||||
<div class="ext-git-board-card__title">${esc(pr.title)}</div>
|
||||
<div class="ext-git-board-card__meta">
|
||||
<div class="gb-card__title">${esc(pr.title)}</div>
|
||||
<div class="gb-card__meta">
|
||||
<span>@${esc(pr.user)}</span>
|
||||
<span>${timeAgo(pr.created_at)}</span>
|
||||
</div>
|
||||
@@ -387,73 +387,73 @@
|
||||
}, [issue, owner, repo, number]);
|
||||
|
||||
return html`
|
||||
<div class="ext-git-board-modal-overlay" onClick=${function (e) {
|
||||
if (e.target.classList.contains('ext-git-board-modal-overlay')) onClose(changed);
|
||||
<div class="gb-modal-overlay" onClick=${function (e) {
|
||||
if (e.target.classList.contains('gb-modal-overlay')) onClose(changed);
|
||||
}}>
|
||||
<div class="ext-git-board-modal">
|
||||
<div class="ext-git-board-modal__header">
|
||||
<div class="ext-git-board-modal__title-row">
|
||||
<div class="gb-modal">
|
||||
<div class="gb-modal__header">
|
||||
<div class="gb-modal__title-row">
|
||||
${loading ? 'Loading…' : html`
|
||||
<span class="ext-git-board-card__number">#${number}</span>
|
||||
<h2 class="ext-git-board-modal__title">${esc(issue && issue.title)}</h2>
|
||||
<span class="gb-card__number">#${number}</span>
|
||||
<h2 class="gb-modal__title">${esc(issue && issue.title)}</h2>
|
||||
`}
|
||||
</div>
|
||||
<button class="ext-git-board-modal__close" onClick=${function () { onClose(changed); }}>✕</button>
|
||||
<button class="gb-modal__close" onClick=${function () { onClose(changed); }}>✕</button>
|
||||
</div>
|
||||
|
||||
${!loading && issue && html`
|
||||
<div class="ext-git-board-modal__body" ref=${bodyRef}>
|
||||
<div class="ext-git-board-modal__meta">
|
||||
<span class="ext-git-board-badge ${issue.state === 'open' ? 'ext-git-board-badge--green' : 'ext-git-board-badge--muted'}">${issue.state}</span>
|
||||
${issue.assignee && html`<span class="ext-git-board-card__assignee">@${esc(issue.assignee)}</span>`}
|
||||
${issue.created_at && html`<span class="ext-git-board-modal__date">${new Date(issue.created_at).toLocaleDateString()}</span>`}
|
||||
<div class="gb-modal__body" ref=${bodyRef}>
|
||||
<div class="gb-modal__meta">
|
||||
<span class="badge ${issue.state === 'open' ? 'badge--green' : 'badge--muted'}">${issue.state}</span>
|
||||
${issue.assignee && html`<span class="gb-card__assignee">@${esc(issue.assignee)}</span>`}
|
||||
${issue.created_at && html`<span class="gb-modal__date">${new Date(issue.created_at).toLocaleDateString()}</span>`}
|
||||
<a href=${issue.html_url || '#'} target="_blank" rel="noopener"
|
||||
class="ext-git-board-modal__extlink">Open in Gitea ↗</a>
|
||||
class="gb-modal__extlink">Open in Gitea ↗</a>
|
||||
</div>
|
||||
|
||||
${issue.labels && issue.labels.length > 0 && html`
|
||||
<div class="ext-git-board-card__labels" style="margin-bottom:12px;">
|
||||
${issue.labels.map(function (l) { return html`<span key=${l} class="ext-git-board-badge">${esc(l)}</span>`; })}
|
||||
<div class="gb-card__labels" style="margin-bottom:12px;">
|
||||
${issue.labels.map(function (l) { return html`<span key=${l} class="badge">${esc(l)}</span>`; })}
|
||||
</div>
|
||||
`}
|
||||
|
||||
<div class="ext-git-board-modal__description">
|
||||
${issue.body ? html`<pre class="ext-git-board-modal__body-text">${esc(issue.body)}</pre>`
|
||||
: html`<p class="ext-git-board-modal__empty">No description.</p>`}
|
||||
<div class="gb-modal__description">
|
||||
${issue.body ? html`<pre class="gb-modal__body-text">${esc(issue.body)}</pre>`
|
||||
: html`<p class="gb-modal__empty">No description.</p>`}
|
||||
</div>
|
||||
|
||||
<div class="ext-git-board-modal__comments">
|
||||
<h3 class="ext-git-board-modal__section-title">Comments (${(issue.comments || []).length})</h3>
|
||||
<div class="gb-modal__comments">
|
||||
<h3 class="gb-modal__section-title">Comments (${(issue.comments || []).length})</h3>
|
||||
${(issue.comments || []).length === 0 && html`
|
||||
<p class="ext-git-board-modal__empty">No comments yet.</p>
|
||||
<p class="gb-modal__empty">No comments yet.</p>
|
||||
`}
|
||||
${(issue.comments || []).map(function (c, i) {
|
||||
return html`
|
||||
<div class="ext-git-board-comment" key=${i}>
|
||||
<div class="ext-git-board-comment__header">
|
||||
<div class="gb-comment" key=${i}>
|
||||
<div class="gb-comment__header">
|
||||
<strong>@${esc(c.user)}</strong>
|
||||
<span class="ext-git-board-comment__date">${timeAgo(c.created_at)}</span>
|
||||
<span class="gb-comment__date">${timeAgo(c.created_at)}</span>
|
||||
</div>
|
||||
<div class="ext-git-board-comment__body">${esc(c.body)}</div>
|
||||
<div class="gb-comment__body">${esc(c.body)}</div>
|
||||
</div>
|
||||
`;
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div class="ext-git-board-modal__add-comment">
|
||||
<textarea class="ext-git-board-modal__textarea" rows="3"
|
||||
<div class="gb-modal__add-comment">
|
||||
<textarea class="gb-modal__textarea" rows="3"
|
||||
placeholder="Add a comment…"
|
||||
value=${comment}
|
||||
onInput=${function (e) { setComment(e.target.value); }}
|
||||
onKeyDown=${function (e) {
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) postComment();
|
||||
}} />
|
||||
<div class="ext-git-board-modal__actions">
|
||||
<button class="sw-btn sw-btn--primary sw-btn--sm" disabled=${posting || !comment.trim()}
|
||||
<div class="gb-modal__actions">
|
||||
<button class="btn-small btn-primary" disabled=${posting || !comment.trim()}
|
||||
onClick=${postComment}>
|
||||
${posting ? 'Posting…' : 'Comment'}
|
||||
</button>
|
||||
<button class="sw-btn sw-btn--secondary sw-btn--sm ${issue.state === 'open' ? 'sw-btn sw-btn--danger sw-btn--md' : 'sw-btn sw-btn--secondary sw-btn--md'}"
|
||||
<button class="btn-small ${issue.state === 'open' ? 'btn-danger' : 'btn-secondary'}"
|
||||
onClick=${toggleState}>
|
||||
${issue.state === 'open' ? 'Close Issue' : 'Reopen Issue'}
|
||||
</button>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"version": "0.2.0",
|
||||
"icon": "🔀",
|
||||
"description": "Gitea issue and PR board powered by the gitea-client library. Uses extension connections for authentication.",
|
||||
"author": "armature",
|
||||
"author": "switchboard",
|
||||
|
||||
"permissions": ["connections.read"],
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"tier": "starlark",
|
||||
"version": "1.0.1",
|
||||
"description": "Shared Gitea client — connections, API helpers, optional data caching.",
|
||||
"author": "armature",
|
||||
"author": "switchboard",
|
||||
|
||||
"permissions": ["api.http", "connections.read", "db.read", "db.write"],
|
||||
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
Uses CSS custom properties from the platform theme system (variables.css).
|
||||
See EXTENSION-SURFACES.md for the full property reference. */
|
||||
|
||||
.ext-hello-dashboard { max-width: 720px; margin: 0 auto; padding: var(--sp-10) var(--sp-6); }
|
||||
.ext-hello-dashboard-header { margin-bottom: var(--sp-8); }
|
||||
.ext-hello-dashboard-header h1 { font-size: 28px; font-weight: 700; color: var(--text); margin: 0 0 var(--sp-2) 0; }
|
||||
.ext-hello-dashboard-subtitle { font-size: 14px; color: var(--text-2); margin: 0; }
|
||||
.ext-hello-dashboard-subtitle code,
|
||||
.ext-hello-dashboard-card-value code { background: var(--bg-raised); padding: 2px 6px; border-radius: var(--radius-sm); font-size: 13px; }
|
||||
.ext-hello-dashboard-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: var(--sp-4); margin-bottom: var(--sp-6); }
|
||||
.ext-hello-dashboard-card { background: var(--bg-surface); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: var(--sp-4); }
|
||||
.ext-hello-dashboard-card-title { font-size: 12px; font-weight: 600; color: var(--text-2); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: var(--sp-2); }
|
||||
.ext-hello-dashboard-card-value { font-size: 20px; font-weight: 600; color: var(--text); margin-bottom: var(--sp-1); }
|
||||
.ext-hello-dashboard-card-detail { font-size: 12px; color: var(--text-3); }
|
||||
.ext-hello-dashboard-actions { display: flex; gap: var(--sp-3); margin-bottom: var(--sp-6); }
|
||||
.ext-hello-dashboard-manifest { background: var(--bg-surface); border: 1px solid var(--border); border-radius: var(--radius); padding: var(--sp-4); font-size: 12px; color: var(--text-2); overflow-x: auto; white-space: pre-wrap; font-family: var(--mono); line-height: 1.5; }
|
||||
.hello-dashboard { max-width: 720px; margin: 0 auto; padding: 40px 24px; }
|
||||
.hello-header { margin-bottom: 32px; }
|
||||
.hello-header h1 { font-size: 28px; font-weight: 700; color: var(--text); margin: 0 0 8px 0; }
|
||||
.hello-subtitle { font-size: 14px; color: var(--text-2); margin: 0; }
|
||||
.hello-subtitle code,
|
||||
.hello-card-value code { background: var(--bg-raised); padding: 2px 6px; border-radius: 4px; font-size: 13px; }
|
||||
.hello-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
|
||||
.hello-card { background: var(--bg-surface); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 16px; }
|
||||
.hello-card-title { font-size: 12px; font-weight: 600; color: var(--text-2); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
|
||||
.hello-card-value { font-size: 20px; font-weight: 600; color: var(--text); margin-bottom: 4px; }
|
||||
.hello-card-detail { font-size: 12px; color: var(--text-3); }
|
||||
.hello-actions { display: flex; gap: 12px; margin-bottom: 24px; }
|
||||
.hello-manifest { background: var(--bg-surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; font-size: 12px; color: var(--text-2); overflow-x: auto; white-space: pre-wrap; font-family: var(--mono); line-height: 1.5; }
|
||||
|
||||
@@ -20,12 +20,12 @@
|
||||
var name = user.display_name || user.username || 'World';
|
||||
|
||||
mount.innerHTML =
|
||||
'<div class="ext-hello-dashboard">' +
|
||||
'<div class="ext-hello-dashboard-header">' +
|
||||
'<div class="hello-dashboard">' +
|
||||
'<div class="hello-header">' +
|
||||
'<h1>Hello, ' + esc(name) + '!</h1>' +
|
||||
'<p class="ext-hello-dashboard-subtitle">Extension surface <code>' + esc(manifest.id || 'unknown') + '</code> loaded successfully.</p>' +
|
||||
'<p class="hello-subtitle">Extension surface <code>' + esc(manifest.id || 'unknown') + '</code> loaded successfully.</p>' +
|
||||
'</div>' +
|
||||
'<div class="ext-hello-dashboard-cards">' +
|
||||
'<div class="hello-cards">' +
|
||||
card('Platform Access', (typeof UI !== 'undefined' ? '\u2713 Connected' : '\u2717 Unavailable'),
|
||||
'API, Theme, UI primitives available', 'var(--accent)') +
|
||||
card('Theme', isDark ? '\uD83C\uDF19 Dark' : '\u2600\uFE0F Light',
|
||||
@@ -33,11 +33,11 @@
|
||||
card('Route', '<code>' + esc(manifest.route || '/s/hello-dashboard') + '</code>',
|
||||
'Registered via surface manifest', '') +
|
||||
'</div>' +
|
||||
'<div class="ext-hello-dashboard-actions">' +
|
||||
'<button class="sw-btn sw-btn--primary sw-btn--md" id="helloToast">Show Toast</button>' +
|
||||
'<button class="sw-btn sw-btn--secondary sw-btn--md" id="helloApi">Test API</button>' +
|
||||
'<div class="hello-actions">' +
|
||||
'<button class="btn-primary" id="helloToast">Show Toast</button>' +
|
||||
'<button class="btn-secondary" id="helloApi">Test API</button>' +
|
||||
'</div>' +
|
||||
'<pre class="ext-hello-dashboard-manifest">' + esc(JSON.stringify(manifest, null, 2)) + '</pre>' +
|
||||
'<pre class="hello-manifest">' + esc(JSON.stringify(manifest, null, 2)) + '</pre>' +
|
||||
'</div>';
|
||||
|
||||
// Wire toast button
|
||||
@@ -69,10 +69,10 @@
|
||||
|
||||
function card(title, value, detail, color) {
|
||||
var style = color ? ' style="color:' + color + ';"' : '';
|
||||
return '<div class="ext-hello-dashboard-card">' +
|
||||
'<div class="ext-hello-dashboard-card-title">' + esc(title) + '</div>' +
|
||||
'<div class="ext-hello-dashboard-card-value"' + style + '>' + value + '</div>' +
|
||||
'<div class="ext-hello-dashboard-card-detail">' + esc(detail) + '</div>' +
|
||||
return '<div class="hello-card">' +
|
||||
'<div class="hello-card-title">' + esc(title) + '</div>' +
|
||||
'<div class="hello-card-value"' + style + '>' + value + '</div>' +
|
||||
'<div class="hello-card-detail">' + esc(detail) + '</div>' +
|
||||
'</div>';
|
||||
}
|
||||
|
||||
|
||||
@@ -1,38 +1,74 @@
|
||||
/* ICD Test Runner — Surface Styles */
|
||||
|
||||
.ext-icd-test-runner-root {
|
||||
#extension-mount {
|
||||
font-family: var(--font, 'DM Sans', sans-serif);
|
||||
}
|
||||
|
||||
.ext-icd-test-runner-root h1 {
|
||||
#extension-mount h1 {
|
||||
font-family: var(--font, 'DM Sans', sans-serif);
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
|
||||
.ext-icd-test-runner-root table {
|
||||
#extension-mount table {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.ext-icd-test-runner-root table td,
|
||||
.ext-icd-test-runner-root table th {
|
||||
#extension-mount table td,
|
||||
#extension-mount table th {
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
.ext-icd-test-runner-root table tbody tr:last-child {
|
||||
#extension-mount table tbody tr:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.ext-icd-test-runner-root table tbody tr:hover {
|
||||
#extension-mount table tbody tr:hover {
|
||||
background: var(--bg-hover) !important;
|
||||
}
|
||||
|
||||
/* Buttons — uses kernel sw-btn system, minor overrides for weight */
|
||||
.ext-icd-test-runner-root .sw-btn {
|
||||
/* Buttons — override small padding for our use */
|
||||
#extension-mount .btn-primary,
|
||||
#extension-mount .btn-secondary,
|
||||
#extension-mount .btn-ghost {
|
||||
font-size: 13px;
|
||||
padding: 7px 16px;
|
||||
border-radius: var(--radius, 8px);
|
||||
cursor: pointer;
|
||||
font-family: var(--font, 'DM Sans', sans-serif);
|
||||
font-weight: 600;
|
||||
transition: background var(--transition, 180ms ease), opacity var(--transition, 180ms ease);
|
||||
}
|
||||
|
||||
/* Fallback button styles if platform classes not loaded */
|
||||
#extension-mount button.btn-primary {
|
||||
background: var(--accent, #6c9fff);
|
||||
color: #fff;
|
||||
border: none;
|
||||
}
|
||||
#extension-mount button.btn-primary:hover {
|
||||
opacity: 0.88;
|
||||
}
|
||||
|
||||
#extension-mount button.btn-secondary {
|
||||
background: var(--accent-dim, rgba(108,159,255,0.12));
|
||||
color: var(--accent, #6c9fff);
|
||||
border: none;
|
||||
}
|
||||
#extension-mount button.btn-secondary:hover {
|
||||
background: var(--accent-dim, rgba(108,159,255,0.2));
|
||||
}
|
||||
|
||||
#extension-mount button.btn-ghost {
|
||||
background: transparent;
|
||||
color: var(--text-2, #9898a8);
|
||||
border: 1px solid var(--border, #2e2e35);
|
||||
}
|
||||
#extension-mount button.btn-ghost:hover {
|
||||
background: var(--bg-hover, #2a2a30);
|
||||
}
|
||||
|
||||
/* Status dot animation for running state */
|
||||
@keyframes ext-icd-test-runner-pulse-dot {
|
||||
@keyframes pulse-dot {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.4; }
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
type: 'full',
|
||||
version: '0.31.1',
|
||||
tier: 'browser',
|
||||
author: 'Armature',
|
||||
author: 'Switchboard Core',
|
||||
description: 'Project dashboard exercising all SDK primitives',
|
||||
route: '/s/dashboard',
|
||||
permissions: [],
|
||||
@@ -65,9 +65,9 @@
|
||||
T.assert(d.version === '0.31.1', 'version mismatch');
|
||||
});
|
||||
|
||||
await T.test('crud', 'dashboardPackage', 'dashpkg: GET /admin/packages (dashboard in list)', async function () {
|
||||
var d = await T.apiGet('/admin/packages');
|
||||
T.assertHasKey(d, 'data', '/admin/packages');
|
||||
await T.test('crud', 'dashboardPackage', 'dashpkg: GET /admin/surfaces (dashboard in list)', async function () {
|
||||
var d = await T.apiGet('/admin/surfaces');
|
||||
T.assertHasKey(d, 'data', '/admin/surfaces');
|
||||
var found = d.data.some(function (s) { return s.id === 'dashboard'; });
|
||||
T.assert(found, 'dashboard package should appear in surfaces list');
|
||||
});
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
type: 'full',
|
||||
version: '0.31.0',
|
||||
tier: 'browser',
|
||||
author: 'Armature',
|
||||
author: 'Switchboard Core',
|
||||
description: 'Code editor with workspace management',
|
||||
route: '/s/editor',
|
||||
layout: 'editor',
|
||||
@@ -68,9 +68,9 @@
|
||||
T.assert(d.version === '0.31.0', 'version mismatch');
|
||||
});
|
||||
|
||||
await T.test('crud', 'editorPackage', 'edpkg: GET /admin/packages (editor in list)', async function () {
|
||||
var d = await T.apiGet('/admin/packages');
|
||||
T.assertHasKey(d, 'data', '/admin/packages');
|
||||
await T.test('crud', 'editorPackage', 'edpkg: GET /admin/surfaces (editor in list)', async function () {
|
||||
var d = await T.apiGet('/admin/surfaces');
|
||||
T.assertHasKey(d, 'data', '/admin/surfaces');
|
||||
var found = d.data.some(function (s) { return s.id === 'editor'; });
|
||||
T.assert(found, 'editor package should appear in surfaces list');
|
||||
});
|
||||
@@ -78,7 +78,7 @@
|
||||
await T.test('crud', 'editorPackage', 'edpkg: core /editor removed (404)', async function () {
|
||||
// The old /editor route should no longer exist — it was removed in CS1.
|
||||
// We test by checking the surfaces list for a core editor entry.
|
||||
var d = await T.apiGet('/admin/packages');
|
||||
var d = await T.apiGet('/admin/surfaces');
|
||||
var surfaces = d.data || [];
|
||||
var coreEditor = surfaces.find(function (s) { return s.id === 'editor' && s.source === 'core'; });
|
||||
T.assert(!coreEditor, 'no core editor surface should exist — editor is now a package');
|
||||
@@ -139,7 +139,7 @@
|
||||
|
||||
await T.test('crud', 'editorPackage', 'edpkg: editor in extension nav items', async function () {
|
||||
// When installed, editor should appear in the surfaces list as an extension surface
|
||||
var d = await T.apiGet('/admin/packages');
|
||||
var d = await T.apiGet('/admin/surfaces');
|
||||
var surfaces = d.data || [];
|
||||
var editorSurface = surfaces.find(function (s) { return s.id === 'editor'; });
|
||||
T.assert(editorSurface, 'editor should be in surfaces list');
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
var resp = await fetch(T.base + '/metrics');
|
||||
T.assert(resp.ok, 'expected 200 from /metrics, got ' + resp.status);
|
||||
var text = await resp.text();
|
||||
T.assert(text.indexOf('armature_http_requests_total') !== -1, 'expected armature_http_requests_total in /metrics');
|
||||
T.assert(text.indexOf('armature_http_request_duration_seconds') !== -1, 'expected armature_http_request_duration_seconds in /metrics');
|
||||
T.assert(text.indexOf('armature_websocket_connections') !== -1, 'expected armature_websocket_connections in /metrics');
|
||||
T.assert(text.indexOf('switchboard_http_requests_total') !== -1, 'expected switchboard_http_requests_total in /metrics');
|
||||
T.assert(text.indexOf('switchboard_http_request_duration_seconds') !== -1, 'expected switchboard_http_request_duration_seconds in /metrics');
|
||||
T.assert(text.indexOf('switchboard_websocket_connections') !== -1, 'expected switchboard_websocket_connections in /metrics');
|
||||
});
|
||||
|
||||
// -- GET /api/docs (Swagger UI) --
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
var surfaceId = null;
|
||||
|
||||
await T.test('crud', 'surfaces', 'POST /admin/packages/install (happy path)', async function () {
|
||||
await T.test('crud', 'surfaces', 'POST /admin/surfaces/install (happy path)', async function () {
|
||||
surfaceId = 'icd-test-' + Date.now();
|
||||
var manifest = JSON.stringify({
|
||||
id: surfaceId,
|
||||
@@ -28,32 +28,32 @@
|
||||
route: '/s/' + surfaceId
|
||||
});
|
||||
var zipBlob = buildTestZip({ 'manifest.json': manifest });
|
||||
await T.apiUpload('/admin/packages/install', zipBlob, surfaceId + '.surface');
|
||||
await T.apiUpload('/admin/surfaces/install', zipBlob, surfaceId + '.surface');
|
||||
|
||||
// Verify it exists
|
||||
var d = await T.apiGet('/admin/packages/' + surfaceId);
|
||||
var d = await T.apiGet('/admin/surfaces/' + surfaceId);
|
||||
T.assert(d.id === surfaceId, 'installed surface id mismatch');
|
||||
T.assert(d.title === 'ICD Test Surface', 'title mismatch');
|
||||
T.registerCleanup(async function () {
|
||||
if (surfaceId) {
|
||||
var token = await T.getAuthToken();
|
||||
return T.authFetch(token, 'DELETE', '/admin/packages/' + surfaceId);
|
||||
return T.authFetch(token, 'DELETE', '/admin/surfaces/' + surfaceId);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (surfaceId) {
|
||||
await T.test('crud', 'surfaces', 'GET /admin/packages/:id (read)', async function () {
|
||||
var d = await T.apiGet('/admin/packages/' + surfaceId);
|
||||
await T.test('crud', 'surfaces', 'GET /admin/surfaces/:id (read)', async function () {
|
||||
var d = await T.apiGet('/admin/surfaces/' + surfaceId);
|
||||
T.assertShape(d, T.S.surfaceAdmin, 'surface detail');
|
||||
T.assert(d.id === surfaceId, 'id mismatch');
|
||||
T.assert(d.source === 'extension', 'source should be extension');
|
||||
T.assert(d.enabled === true, 'newly installed surface should be enabled');
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'GET /admin/packages (list includes new)', async function () {
|
||||
var d = await T.apiGet('/admin/packages');
|
||||
T.assertHasKey(d, 'data', '/admin/packages');
|
||||
await T.test('crud', 'surfaces', 'GET /admin/surfaces (list includes new)', async function () {
|
||||
var d = await T.apiGet('/admin/surfaces');
|
||||
T.assertHasKey(d, 'data', '/admin/surfaces');
|
||||
var found = d.data.some(function (s) { return s.id === surfaceId; });
|
||||
T.assert(found, 'installed surface should appear in admin list');
|
||||
});
|
||||
@@ -70,9 +70,9 @@
|
||||
T.assert(entry.enabled === undefined, 'nav entry should NOT have enabled');
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/packages/:id/disable', async function () {
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/surfaces/:id/disable', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'PUT',
|
||||
'/admin/packages/' + surfaceId + '/disable');
|
||||
'/admin/surfaces/' + surfaceId + '/disable');
|
||||
T.assertStatus(d, 200, 'disable');
|
||||
T.assert(d.enabled === false, 'should report disabled');
|
||||
});
|
||||
@@ -83,16 +83,16 @@
|
||||
T.assert(!found, 'disabled surface should NOT appear in user nav list');
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'GET /admin/packages (disabled still in admin)', async function () {
|
||||
var d = await T.apiGet('/admin/packages');
|
||||
await T.test('crud', 'surfaces', 'GET /admin/surfaces (disabled still in admin)', async function () {
|
||||
var d = await T.apiGet('/admin/surfaces');
|
||||
var entry = d.data.find(function (s) { return s.id === surfaceId; });
|
||||
T.assert(entry, 'disabled surface should still appear in admin list');
|
||||
T.assert(entry.enabled === false, 'should show as disabled in admin list');
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/packages/:id/enable', async function () {
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/surfaces/:id/enable', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'PUT',
|
||||
'/admin/packages/' + surfaceId + '/enable');
|
||||
'/admin/surfaces/' + surfaceId + '/enable');
|
||||
T.assertStatus(d, 200, 'enable');
|
||||
T.assert(d.enabled === true, 'should report enabled');
|
||||
});
|
||||
@@ -103,53 +103,53 @@
|
||||
T.assert(found, 're-enabled surface should appear in user nav list');
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/packages/chat/disable (reject → 400)', async function () {
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/surfaces/chat/disable (reject → 400)', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'PUT',
|
||||
'/admin/packages/chat/disable');
|
||||
'/admin/surfaces/chat/disable');
|
||||
T.assert(d._status === 400, 'disabling chat should return 400, got ' + d._status);
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/packages/admin/disable (reject → 400)', async function () {
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/surfaces/admin/disable (reject → 400)', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'PUT',
|
||||
'/admin/packages/admin/disable');
|
||||
'/admin/surfaces/admin/disable');
|
||||
T.assert(d._status === 400, 'disabling admin should return 400, got ' + d._status);
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'DELETE /admin/packages/chat (core reject → 400)', async function () {
|
||||
await T.test('crud', 'surfaces', 'DELETE /admin/surfaces/chat (core reject → 400)', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'DELETE',
|
||||
'/admin/packages/chat');
|
||||
'/admin/surfaces/chat');
|
||||
T.assert(d._status === 400, 'deleting core surface should return 400, got ' + d._status);
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'GET /admin/packages/:id (not found → 404)', async function () {
|
||||
await T.test('crud', 'surfaces', 'GET /admin/surfaces/:id (not found → 404)', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'GET',
|
||||
'/admin/packages/nonexistent-surface-id');
|
||||
'/admin/surfaces/nonexistent-surface-id');
|
||||
T.assert(d._status === 404, 'nonexistent should return 404, got ' + d._status);
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/packages/nonexistent/disable (404)', async function () {
|
||||
await T.test('crud', 'surfaces', 'PUT /admin/surfaces/nonexistent/disable (404)', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'PUT',
|
||||
'/admin/packages/nonexistent-surface-id/disable');
|
||||
'/admin/surfaces/nonexistent-surface-id/disable');
|
||||
T.assert(d._status === 404, 'disable nonexistent should return 404, got ' + d._status);
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'POST /admin/packages/install (missing manifest → 400)', async function () {
|
||||
await T.test('crud', 'surfaces', 'POST /admin/surfaces/install (missing manifest → 400)', async function () {
|
||||
var zipBlob = buildTestZip({ 'readme.txt': 'no manifest here' });
|
||||
var d;
|
||||
try {
|
||||
d = await T.apiUpload('/admin/packages/install', zipBlob, 'bad.surface');
|
||||
d = await T.apiUpload('/admin/surfaces/install', zipBlob, 'bad.surface');
|
||||
T.assert(false, 'should have thrown');
|
||||
} catch (e) {
|
||||
T.assert(e.message.indexOf('400') !== -1, 'missing manifest should 400: ' + e.message);
|
||||
}
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'POST /admin/packages/install (core conflict → 409)', async function () {
|
||||
await T.test('crud', 'surfaces', 'POST /admin/surfaces/install (core conflict → 409)', async function () {
|
||||
var manifest = JSON.stringify({ id: 'chat', title: 'Evil Chat', route: '/s/chat' });
|
||||
var zipBlob = buildTestZip({ 'manifest.json': manifest });
|
||||
var d;
|
||||
try {
|
||||
d = await T.apiUpload('/admin/packages/install', zipBlob, 'chat.surface');
|
||||
d = await T.apiUpload('/admin/surfaces/install', zipBlob, 'chat.surface');
|
||||
// If no throw, check status manually
|
||||
T.assert(false, 'overwriting core surface should have thrown');
|
||||
} catch (e) {
|
||||
@@ -157,10 +157,10 @@
|
||||
}
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'POST /admin/packages/install (reseed preserves enabled)', async function () {
|
||||
await T.test('crud', 'surfaces', 'POST /admin/surfaces/install (reseed preserves enabled)', async function () {
|
||||
// Surface was re-enabled above. Disable it, then re-install.
|
||||
await T.authFetch(await T.getAuthToken(), 'PUT',
|
||||
'/admin/packages/' + surfaceId + '/disable');
|
||||
'/admin/surfaces/' + surfaceId + '/disable');
|
||||
|
||||
// Re-install same ID
|
||||
var manifest = JSON.stringify({
|
||||
@@ -169,33 +169,33 @@
|
||||
route: '/s/' + surfaceId
|
||||
});
|
||||
var zipBlob = buildTestZip({ 'manifest.json': manifest });
|
||||
await T.apiUpload('/admin/packages/install', zipBlob, surfaceId + '.surface');
|
||||
await T.apiUpload('/admin/surfaces/install', zipBlob, surfaceId + '.surface');
|
||||
|
||||
// Verify title updated but enabled preserved as false
|
||||
var d = await T.apiGet('/admin/packages/' + surfaceId);
|
||||
var d = await T.apiGet('/admin/surfaces/' + surfaceId);
|
||||
T.assert(d.title === 'ICD Test Surface v2', 'title should be updated after reseed');
|
||||
T.assert(d.enabled === false, 'enabled should be preserved as false after reseed');
|
||||
|
||||
// Re-enable for cleanup
|
||||
await T.authFetch(await T.getAuthToken(), 'PUT',
|
||||
'/admin/packages/' + surfaceId + '/enable');
|
||||
'/admin/surfaces/' + surfaceId + '/enable');
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'DELETE /admin/packages/:id', async function () {
|
||||
await T.test('crud', 'surfaces', 'DELETE /admin/surfaces/:id', async function () {
|
||||
var token = await T.getAuthToken();
|
||||
var d = await T.authFetch(token, 'DELETE', '/admin/packages/' + surfaceId);
|
||||
var d = await T.authFetch(token, 'DELETE', '/admin/surfaces/' + surfaceId);
|
||||
T.assertStatus(d, 200, 'delete');
|
||||
T.assert(d.deleted === true, 'should report deleted');
|
||||
|
||||
// Verify gone
|
||||
var check = await T.authFetch(token, 'GET', '/admin/packages/' + surfaceId);
|
||||
var check = await T.authFetch(token, 'GET', '/admin/surfaces/' + surfaceId);
|
||||
T.assert(check._status === 404, 'deleted surface should 404 on get');
|
||||
surfaceId = null;
|
||||
});
|
||||
|
||||
await T.test('crud', 'surfaces', 'DELETE /admin/packages/nonexistent (404)', async function () {
|
||||
await T.test('crud', 'surfaces', 'DELETE /admin/surfaces/nonexistent (404)', async function () {
|
||||
var d = await T.authFetch(await T.getAuthToken(), 'DELETE',
|
||||
'/admin/packages/nonexistent-surface-id');
|
||||
'/admin/surfaces/nonexistent-surface-id');
|
||||
T.assert(d._status === 404, 'delete nonexistent should return 404, got ' + d._status);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -227,7 +227,7 @@
|
||||
};
|
||||
|
||||
// ─── API Wrappers ───────────────────────────────────────────
|
||||
// Raw fetch — kernel provides no global API wrappers; extensions use fetch directly.
|
||||
// v0.37.14: raw fetch — old API._* globals removed in scorched earth.
|
||||
|
||||
async function _fetchJSON(method, path, body) {
|
||||
var token = await T.getAuthToken();
|
||||
@@ -270,7 +270,7 @@
|
||||
|
||||
function getAuthTokenFromStorage() {
|
||||
var env = (T.base || '').replace(/^\//, '') || 'default';
|
||||
var keys = ['arm_auth_' + env, 'arm_auth', 'arm_token'];
|
||||
var keys = ['sb_auth_' + env, 'sb_auth', 'sb_token'];
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
try {
|
||||
var raw = localStorage.getItem(keys[i]);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
* 8. tier-security.js — Adversarial red-team tests (auth, cross-tenant, input validation)
|
||||
* 9. tier-providers.js — Three-tier provider CRUD + live completions
|
||||
* 10. tier-packaging.js — Extension permission lifecycle + secrets (v0.29.0)
|
||||
* 11. tier-sdk.js — Armature SDK contract tests
|
||||
* 11. tier-sdk.js — Switchboard SDK contract tests
|
||||
* 12. ui.js — Render functions, export, provider setup panel
|
||||
* 11. (this file) — Boot
|
||||
*/
|
||||
@@ -24,7 +24,6 @@
|
||||
|
||||
var mount = document.getElementById('extension-mount');
|
||||
if (!mount) return;
|
||||
mount.classList.add('ext-icd-test-runner-root');
|
||||
|
||||
// ─── Boot Preact SDK (v0.37.14) ───────────────────────────
|
||||
// Extension surfaces don't load Preact vendors or the SDK.
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
var adminGets = [
|
||||
'/admin/stats', '/admin/users', '/admin/settings',
|
||||
'/admin/configs', '/admin/models', '/admin/personas',
|
||||
'/admin/teams', '/admin/groups', '/admin/packages',
|
||||
'/admin/teams', '/admin/groups', '/admin/surfaces',
|
||||
'/admin/providers/health', '/admin/routing/policies',
|
||||
'/admin/permissions', '/admin/roles', '/admin/vault/status',
|
||||
'/admin/storage/status', '/admin/audit', '/admin/pricing',
|
||||
@@ -72,8 +72,8 @@
|
||||
'expected 403/401, got ' + d._status);
|
||||
});
|
||||
|
||||
await T.test('authz', 'admin-deny', 'user → POST /admin/packages/install (expect 403)', async function () {
|
||||
var d = await T.authFetch(testUser.token, 'POST', '/admin/packages/install', {});
|
||||
await T.test('authz', 'admin-deny', 'user → POST /admin/surfaces/install (expect 403)', async function () {
|
||||
var d = await T.authFetch(testUser.token, 'POST', '/admin/surfaces/install', {});
|
||||
T.assert(d._status === 403 || d._status === 401 || d._status === 400,
|
||||
'expected 403/401/400, got ' + d._status);
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Validates Preact SDK (sw/sdk/index.js) contract: boot, identity,
|
||||
* REST client, events, theme, pipe registration, execution ordering,
|
||||
* scoping, halt semantics, error isolation, introspection.
|
||||
* v0.37.14: Updated from Armature.init() to boot() API.
|
||||
* v0.37.14: Updated from Switchboard.init() to boot() API.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
@@ -337,7 +337,7 @@
|
||||
await T.test('sdk', 'pipe-render', 'Render filter modifies DOM', async function () {
|
||||
sw.pipe.render(1, function (ctx) {
|
||||
if (ctx.element.dataset.sdkRenderTest) {
|
||||
ctx.element.classList.add('ext-icd-test-runner-sdk-render-modified');
|
||||
ctx.element.classList.add('sdk-render-modified');
|
||||
}
|
||||
return ctx;
|
||||
}, { source: '_test-render-dom' });
|
||||
@@ -348,7 +348,7 @@
|
||||
element: el, message: null,
|
||||
channel: { id: 'fake', type: 'direct' }
|
||||
});
|
||||
T.assert(el.classList.contains('ext-icd-test-runner-sdk-render-modified'), 'element should have class');
|
||||
T.assert(el.classList.contains('sdk-render-modified'), 'element should have class');
|
||||
});
|
||||
|
||||
await T.test('sdk', 'pipe-render', 'Priority ordering in render chain', async function () {
|
||||
|
||||
@@ -543,7 +543,7 @@
|
||||
await T.test('security', 'input-validation', '[P0] path traversal in surface archive', async function () {
|
||||
var blob = new Blob([JSON.stringify({ id: '../../../etc/evil', title: 'Path Traversal Test' })], { type: 'application/json' });
|
||||
try {
|
||||
var d = await T.apiUpload('/admin/packages/install', blob, 'evil.surface');
|
||||
var d = await T.apiUpload('/admin/surfaces/install', blob, 'evil.surface');
|
||||
T.assert(d._status === 400 || d._status === 409,
|
||||
'path traversal surface accepted! got ' + d._status);
|
||||
} catch (e) {
|
||||
@@ -644,8 +644,8 @@
|
||||
assertDenied(d._status, 'CRITICAL: team admin can delete users');
|
||||
});
|
||||
|
||||
await T.test('security', 'escalation', '[P0] teamAdmin → POST /admin/packages/install', async function () {
|
||||
var d = await T.authFetch(teamAdmin.token, 'POST', '/admin/packages/install', {});
|
||||
await T.test('security', 'escalation', '[P0] teamAdmin → POST /admin/surfaces/install', async function () {
|
||||
var d = await T.authFetch(teamAdmin.token, 'POST', '/admin/surfaces/install', {});
|
||||
if (d._status === 400) return; // bad upload format, not a security issue
|
||||
assertDenied(d._status, 'team admin can install surfaces');
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user