Files
openwork/scripts/features-sync.mjs
T
ben 94359f1439 feat(features): roll out features by deployment and organization, with a kill switch (#5702)
* feat(den): declare features once in a registry stored per organization

Adds packages/types/src/den/features.ts as the single place a feature is
declared. Each entry decides, separately for OpenWork Cloud and self-hosted,
whether the feature exists (unavailable / off / on) or is controlled per
organization by platform admins, with a default.

- Storage moves from organization.metadata.capabilities to a new
  organization_feature table (migration 0129 copies existing overrides and
  the old Connect aliases). Better Auth never writes it, so creating an
  organization can no longer turn features on; metadata.capabilities is
  stripped at creation and no longer sent to members. Writes are mirrored
  into metadata for one release so a rollback keeps working.
- den-api reads features only through features.ts (getOrganizationFeatures,
  organizationFeatureEnabled, requireFeature). The three hand-written
  capability helper modules are deleted.
- DEN_DEPLOYMENT (default self_hosted) and DEN_FEATURE_* locks, rendered
  from a generated Helm config.features block with a values schema. A lock
  outranks a stored override.
- /admin schemas and the Den admin panel are generated from the registry,
  with Default / override / locked states and "Use default".
- GET /v1/org adds features; capabilities stays frozen for published clients.
- pnpm features:sync / features:check plus a CI job keep the chart in step
  and reject new DEN_*_ENABLED switches or metadata.capabilities reads.
- add-a-feature skill and an AGENTS.md line: flag first, before feature code.

No behavior change: every existing feature keeps its current default and
stays platform-controlled on both deployments.

* refactor(features): move the registry into its own @openwork/features package

The registry and resolver were runtime logic living in @openwork/types.
They now live in packages/features:

- src/registry.ts: the one file you edit to declare a feature
- src/resolve.ts: precedence rules, env parsing, key schema (pure, no I/O)
- src/resolve.test.ts: node:test coverage of the precedence rules, env
  parsing, key schema and DEN_FEATURE_* names, run in features-check CI

Files import each other through package self-references, so the TypeScript
source runs as-is under Node (verified in the node:22 production image) and
typechecks in every consumer without a build step.

Also adds the package to the den, gateway and den-web Docker images and to
the den-contract CI path filters, and pins azure/setup-helm to a commit SHA
(Warden finding).

* ci(features): check that Dockerfiles copy every workspace package they need

The den, gateway, den-web and den-gateway images copy workspace packages one
by one for layer caching, and only publish-ee-images builds them, so a missed
COPY line surfaced at release time. scripts/check-docker-workspace-packages.mjs
reads the manifests and Dockerfiles (about 10 ms) and fails when a copied
package.json depends on a workspace package whose package.json is not copied
(pnpm install fails) or a copied source folder imports one at runtime that is
not copied. It runs inside pnpm features:check, and the workflow now also
triggers on Dockerfile, workspace and package.json changes.

* ci(features): name the exact setup-helm version in its pin comment

* feat(features): roll features out by deployment, percentage, organization and kill switch

A feature is no longer "per organization". Each registry entry declares only
what is fixed in code: its subject (organization, or person so signed-out
desktop users are included), the deployments it exists on, and its starting
percentage. Everything else is runtime state, resolved by one function in
@openwork/features, in this order: not part of this deployment, kill switch,
operator lock (DEN_FEATURE_*), organization override, percentage of the
subject (stable FNV-1a bucket; raising it only adds subjects).

- feature_rollout table (migration 0129 now creates it alongside
  organization_feature) holds percentage and kill switch per feature.
- /admin › Features page and GET/PUT /v1/admin/features change them without
  a deploy; organization rows show why a feature is on or off.
- Admin MCP tools den_list_features and den_set_feature_rollout.
- Public GET /v1/features/rollouts for clients that resolve person features
  themselves, including signed-out desktops.
- /v1/org resolves person features for the signed-in member.
- The nine existing features keep today's behaviour: organization subject,
  starting at 100% (install links, Connect) or 0% (the rest).
- Skill, AGENTS.md, Helm comments and README describe the one model;
  features:check asks for a decision on rollouts older than six months
  unless marked permanent.

* refactor(features): drop percentage rollouts; on or off for everyone, per organization, or killed

Removes percentage rollouts and the organization/person subject they needed.
A feature is now rolled out by deployment (fixed in code), on or off for
everyone (/admin, starting from the registry default), per-organization
overrides, operator locks, and the kill switch. feature_rollout stores
enabled and killed; GET /v1/features gives people without an organization
the deployment-wide answer.
2026-10-06 07:38:34 -07:00

248 lines
11 KiB
JavaScript

#!/usr/bin/env node
// Keeps everything derived from the feature registry in step with it.
//
// pnpm features:sync regenerate the Helm chart's feature block, values
// schema and README table from
// packages/features/src/registry.ts
// pnpm features:check fail if those files are stale, if the chart renders
// different DEN_FEATURE_* names than den-api reads, if
// a Dockerfile misses a workspace package its service
// needs, or if code bypasses the registry (see below)
//
// Read .opencode/skills/add-a-feature/SKILL.md before adding a feature.
import { execFileSync } from "node:child_process"
import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
import {
FEATURES,
FEATURE_KEYS,
featureAvailableOn,
featureLockEnvName,
} from "../packages/features/src/index.ts"
import { checkDockerWorkspacePackages } from "./check-docker-workspace-packages.mjs"
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
const chartDir = path.join(root, "packaging/helm/openwork-ee")
const valuesPath = path.join(chartDir, "values.yaml")
const schemaPath = path.join(chartDir, "values.schema.json")
const readmePath = path.join(chartDir, "README.md")
const check = process.argv.includes("--check")
const BEGIN = "# BEGIN GENERATED features (pnpm features:sync; source: packages/features/src/registry.ts)"
const END = "# END GENERATED features"
const README_BEGIN = "<!-- BEGIN GENERATED features (pnpm features:sync) -->"
const README_END = "<!-- END GENERATED features -->"
/** Keys an operator can lock: every feature that exists on at least one deployment. */
const helmKeys = FEATURE_KEYS.filter((key) => featureAvailableOn(key, "self_hosted") || featureAvailableOn(key, "cloud"))
function defaultLabel(key) {
const scope = featureAvailableOn(key, "self_hosted") ? "" : " (cloud only)"
return `default ${FEATURES[key].default ? "on" : "off"}${scope}`
}
function valuesBlock() {
const width = Math.max(...helmKeys.map((key) => key.length)) + 5
const lines = [
` ${BEGIN}`,
" # Operator locks for this install. Each key renders DEN_FEATURE_<KEY>.",
" # \"\" follow /admin: on or off for everyone, plus per-organization overrides",
" # \"true\" on for everyone; /admin shows \"Set by deployment config\"",
" # \"false\" off for everyone; /admin shows \"Set by deployment config\"",
" # The /admin kill switch still turns a feature off, even when locked on.",
" features:",
...helmKeys.map((key) => ` ${`${key}: ""`.padEnd(width)}# ${defaultLabel(key)} · ${FEATURES[key].description}`),
` ${END}`,
]
return lines.join("\n")
}
function renderValues(current) {
const start = current.indexOf(` ${BEGIN}`)
const end = current.indexOf(` ${END}`)
if (start === -1 || end === -1) {
throw new Error(`${path.relative(root, valuesPath)} is missing the generated features markers.`)
}
return current.slice(0, start) + valuesBlock() + current.slice(end + ` ${END}`.length)
}
function renderSchema() {
const schema = {
$schema: "http://json-schema.org/draft-07/schema#",
$comment: "Generated by pnpm features:sync from packages/features/src/registry.ts. Only config.deployment and config.features are constrained.",
type: "object",
properties: {
config: {
type: "object",
properties: {
deployment: {
type: "string",
enum: ["cloud", "self_hosted"],
description: "Which product this install is. Only OpenWork Cloud sets \"cloud\". Renders DEN_DEPLOYMENT.",
},
features: {
type: "object",
additionalProperties: false,
properties: Object.fromEntries(helmKeys.map((key) => [key, {
// --set turns "true" into a boolean, so accept both spellings.
enum: ["", "true", "false", true, false],
description: `${FEATURES[key].label}: ${FEATURES[key].description} Renders ${featureLockEnvName(key)}.`,
}])),
},
},
},
},
}
return `${JSON.stringify(schema, null, 2)}\n`
}
function renderReadme(current) {
const start = current.indexOf(README_BEGIN)
const end = current.indexOf(README_END)
if (start === -1 || end === -1) {
throw new Error(`${path.relative(root, readmePath)} is missing the generated features markers.`)
}
const rows = helmKeys.map((key) => `| \`${key}\` | \`${featureLockEnvName(key)}\` | ${defaultLabel(key)} | ${FEATURES[key].description} |`)
const table = [
README_BEGIN,
"| `config.features.*` | Environment variable | Default | What it does |",
"| --- | --- | --- | --- |",
...rows,
README_END,
].join("\n")
return current.slice(0, start) + table + current.slice(end + README_END.length)
}
const problems = []
function compareOrWrite(filePath, next) {
const current = readFileSync(filePath, "utf8").toString()
if (current === next) return
if (check) problems.push(`${path.relative(root, filePath)} is out of date. Run \`pnpm features:sync\` and commit the result.`)
else writeFileSync(filePath, next)
}
compareOrWrite(valuesPath, renderValues(readFileSync(valuesPath, "utf8")))
compareOrWrite(readmePath, renderReadme(readFileSync(readmePath, "utf8")))
let schemaCurrent = ""
try {
schemaCurrent = readFileSync(schemaPath, "utf8")
} catch {
schemaCurrent = ""
}
if (schemaCurrent !== renderSchema()) {
if (check) problems.push(`${path.relative(root, schemaPath)} is out of date. Run \`pnpm features:sync\` and commit the result.`)
else writeFileSync(schemaPath, renderSchema())
}
if (check) {
// Registry rules.
const now = new Date()
for (const key of FEATURE_KEYS) {
const definition = FEATURES[key]
if (!/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*$/.test(key)) {
problems.push(`Feature key "${key}" must be lowerCamelCase with no consecutive capitals (it becomes ${featureLockEnvName(key)}).`)
}
if (!definition.label.trim() || !definition.description.trim()) problems.push(`Feature "${key}" needs a label and a description.`)
const since = /^(\d{4})-(\d{2})$/.exec(definition.since)
if (!since) {
problems.push(`Feature "${key}" since must be "YYYY-MM".`)
continue
}
if (definition.deployments.length === 0) problems.push(`Feature "${key}" must exist on at least one deployment.`)
const ageMonths = (now.getUTCFullYear() - Number(since[1])) * 12 + (now.getUTCMonth() + 1 - Number(since[2]))
if (!definition.permanent && ageMonths > 6) {
problems.push(`Feature "${key}" has been a rollout since ${definition.since}. Finish it and delete the flag and its checks, or mark it permanent: true if the switch is part of the product (see .opencode/skills/add-a-feature).`)
}
}
// The chart must render exactly the variable names den-api reads.
let helmAvailable = true
try {
execFileSync("helm", ["version", "--short"], { stdio: "ignore" })
} catch {
helmAvailable = false
}
const chartStale = problems.some((problem) => problem.includes("out of date"))
if (helmAvailable && !chartStale) {
const setArgs = helmKeys.flatMap((key) => ["--set-string", `config.features.${key}=true`])
let rendered = ""
try {
rendered = execFileSync("helm", ["template", "features-check", chartDir, "--show-only", "templates/configmap.yaml", ...setArgs], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] })
} catch (error) {
const stderr = error && typeof error === "object" && "stderr" in error ? String(error.stderr) : String(error)
problems.push(`helm template failed with every feature key set: ${stderr.trim()}`)
}
const renderedNames = new Set([...rendered.matchAll(/^\s+(DEN_FEATURE_[A-Z0-9_]+):/gm)].map((match) => match[1]))
for (const key of helmKeys) {
if (!renderedNames.has(featureLockEnvName(key))) {
problems.push(`Helm renders no ${featureLockEnvName(key)} for config.features.${key}; den-api would never see it.`)
}
}
for (const name of renderedNames) {
if (!helmKeys.some((key) => featureLockEnvName(key) === name)) problems.push(`Helm renders ${name}, which den-api does not read.`)
}
if (!/^\s+DEN_DEPLOYMENT: "self_hosted"$/m.test(rendered)) problems.push("Helm must render DEN_DEPLOYMENT, defaulting to self_hosted.")
} else if (!helmAvailable) {
console.warn("[features] helm is not installed; skipped the chart render check.")
}
// Images that copy workspace packages one by one must copy every one they need.
problems.push(...checkDockerWorkspacePackages(root))
// No new deployment-wide feature switches: declare a feature instead.
const allowedEnableFlags = new Set([
"DEN_APP_MCP_SERVERS_ENABLED", "DEN_AUDIT_CAPTURE_ENABLED", "DEN_AUDIT_SELF_HOSTED_ENABLED", "DEN_AUDIT_VISIBILITY_ENABLED",
"DEN_AUTOMATIONS_ENABLED", "DEN_AUTOMATIONS_RUNTIME_ENABLED", "DEN_BOTID_PROTECTION_ENABLED", "DEN_DASHBOARDS_ENABLED",
"DEN_GENERATED_ARTIFACT_VIEWS_ENABLED", "DEN_OPENWORK_WEB_ENABLED", "DEN_PASSWORD_BREACH_SCREENING_ENABLED",
"DEN_PLAN_GATING_ENABLED", "DEN_SLACK_ASSISTANT_WORKER_ENABLED",
])
function* sourceFiles(dir) {
for (const entry of readdirSync(dir)) {
if (entry === "node_modules" || entry === "dist" || entry === ".next" || entry === "drizzle" || entry === "gen") continue
const full = path.join(dir, entry)
if (statSync(full).isDirectory()) yield* sourceFiles(full)
else if (/\.(ts|tsx|mjs)$/.test(entry)) yield full
}
}
// Feature overrides live in the organization_feature table; only the store
// (and the one-release rollback copy) may touch metadata.capabilities.
const metadataCapabilitiesAllowed = new Set([
"ee/packages/den-db/src/organization-features.ts",
"ee/apps/den-api/src/orgs.ts",
])
for (const dir of ["ee/apps/den-api/src", "ee/apps/den-web/app", "ee/apps/den-web/components", "ee/apps/gateway/src", "ee/packages", "apps/app/src", "apps/server/src"]) {
const absolute = path.join(root, dir)
try {
statSync(absolute)
} catch {
continue
}
for (const file of sourceFiles(absolute)) {
const relative = path.relative(root, file)
const text = readFileSync(file, "utf8")
if (relative.startsWith("ee/apps/den-api/src")) {
for (const match of text.matchAll(/\bDEN_[A-Z0-9_]+_ENABLED\b/g)) {
if (!allowedEnableFlags.has(match[0])) {
problems.push(`${relative}: new switch ${match[0]}. Declare a feature in packages/features/src/registry.ts instead (see .opencode/skills/add-a-feature).`)
}
}
}
if (!metadataCapabilitiesAllowed.has(relative) && /metadata\)?\??\.capabilities\b|\$\.capabilities/.test(text)) {
problems.push(`${relative}: reads organization metadata.capabilities. Use getOrganizationFeatures() / orgFeatureEnabled() instead.`)
}
}
}
}
if (problems.length > 0) {
for (const problem of [...new Set(problems)]) console.error(`[features] ${problem}`)
process.exit(1)
}
console.log(check ? "[features] Registry, Helm chart and guard rules are in sync." : "[features] Helm chart files regenerated.")