diff --git a/Dockerfile b/Dockerfile index 86bd34e..1daec97 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,6 +42,10 @@ RUN ./node_modules/.bin/esbuild scripts/send-rule-follow-up.ts \ --bundle --platform=node --format=cjs \ --outfile=follow-up-mail.bundle.cjs \ --external:@prisma/client +RUN ./node_modules/.bin/esbuild scripts/seed-team-rule.ts \ + --bundle --platform=node --format=cjs \ + --outfile=team-rule.bundle.cjs \ + --external:@prisma/client FROM base AS runner # openssl: Prisma engines. gosu: privilege drop in start.sh after chown. @@ -58,6 +62,7 @@ COPY --from=builder --chown=node:node /app/.next/static ./.next/static COPY --from=builder --chown=node:node /app/prisma ./prisma COPY --from=builder --chown=node:node /app/prune-expired.bundle.cjs ./prune-expired.bundle.cjs COPY --from=builder --chown=node:node /app/follow-up-mail.bundle.cjs ./follow-up-mail.bundle.cjs +COPY --from=builder --chown=node:node /app/team-rule.bundle.cjs ./team-rule.bundle.cjs # Facet/template seed JSON — NOT under /app/data (localstorage mount overlays that). COPY --from=builder --chown=node:node /app/data ./seed-data ENV SEED_DATA_DIR=/app/seed-data diff --git a/docs/guides/ops-backend-deploy.md b/docs/guides/ops-backend-deploy.md index 5b8e40b..f9703f9 100644 --- a/docs/guides/ops-backend-deploy.md +++ b/docs/guides/ops-backend-deploy.md @@ -321,8 +321,8 @@ the base image's `node` user (uid 1000), installs `gosu` for the privilege drop, and symlinks `.next/cache → /tmp/next-cache` so Next.js ISR works on Cloudron's read-only rootfs. `start.sh` runs as root to chown `/app/data` (localstorage mount), then drops to -`node:node`, applies `prisma migrate deploy`, and execs the Next.js -standalone server. +`node:node`, applies `prisma migrate deploy`, writes the adopted team +Rule, and execs the Next.js standalone server. ### One-time setup (per operator) @@ -438,7 +438,8 @@ production env vars, and verify the vertical slice before apex cutover already installed.) Cloudron provisions **postgresql**, **sendmail**, and **localstorage** addons from the manifest, pulls the image (no registry credentials needed), and starts the container. `scripts/start.sh` chowns - `/app/data`, runs `prisma migrate deploy`, then execs the Next.js server. + `/app/data`, runs `prisma migrate deploy`, writes the adopted team Rule, + then execs the Next.js server. 4. **Set manual env vars** (Cloudron does not inject these): ```bash cloudron env set --app staging.communityrule.info \ diff --git a/docs/guides/ops-runbook.md b/docs/guides/ops-runbook.md index befc281..28f3443 100644 --- a/docs/guides/ops-runbook.md +++ b/docs/guides/ops-runbook.md @@ -94,7 +94,8 @@ credentials on the host), restarts the container, and runs 1. `chown`s `/app/data` (localstorage mount), 2. runs **`prisma migrate deploy`**, -3. execs the Next.js standalone server. +3. writes the adopted team Rule (document and visibility together), +4. execs the Next.js standalone server. Watch the app **Logs** tab in the Cloudron dashboard for a clean migration and `Listening on port 3000`. @@ -121,7 +122,9 @@ deploying a new image. See [`backend-roadmap.md` §8](backend-roadmap.md#8-prism ### 3.4 Seed data (not every deploy) Template + facet seed (`MethodFacet` rows for create-flow “Recommended” tags) -is **not** applied at boot. Run once per environment after first install, or +is **not** applied at boot. The adopted team Rule is the exception: container +start writes that one row so the public catalog does not keep the old draft +body. Run the template seed once per environment after first install, or when recommendations return all-zero scores: ```bash diff --git a/lib/create/teamRule.ts b/lib/create/teamRule.ts new file mode 100644 index 0000000..571673f --- /dev/null +++ b/lib/create/teamRule.ts @@ -0,0 +1,124 @@ +import type { CreateFlowState } from "../../app/(app)/create/types"; +import { + conflictManagementPresetFor, + decisionApproachPresetFor, +} from "./finalReviewChipPresets"; +import { buildPublishPayload } from "./buildPublishPayload"; + +/** Staging still lists the September draft under this title. */ +export const TEAM_RULE_DRAFT_TITLE = "The CommunityRule Project"; + +export const TEAM_RULE_TITLE = "CommunityRule Creative Team"; + +const TEAM_RULE_SUMMARY = + "We build and maintain CommunityRule for the communities that use it. It is free for every community that wants to write down how it decides."; + +/** Core-value catalog ids, Home hero order. */ +const TEAM_RULE_VALUE_IDS = [ + "transparency", + "forkability", + "documentation", + "maintenance", + "voluntarism", +] as const; + +const TEAM_RULE_COMMUNICATION_IDS = [ + "github-gitlab", + "matrix-element", + "email-distribution-list", + "how-we-run-meetings", +] as const; + +const TEAM_RULE_MEMBERSHIP_IDS = [ + "join-by-contributing", + "companions", +] as const; + +const TEAM_RULE_DECISION_IDS = [ + "consensus-decision-making", + "lazy-consensus", + "do-ocracy", + "changing-this-rule", +] as const; + +const TEAM_RULE_CONFLICT_IDS = [ + "conflict-ladder", + "hearing-panel", + "restorative-practices", +] as const; + +const VALUE_LABELS: Record<(typeof TEAM_RULE_VALUE_IDS)[number], string> = { + transparency: "Transparency", + forkability: "Forkability", + documentation: "Documentation", + maintenance: "Maintenance", + voluntarism: "Voluntarism", +}; + +function decisionDetailsFor( + id: (typeof TEAM_RULE_DECISION_IDS)[number], +): NonNullable[string] { + const preset = decisionApproachPresetFor(id); + return { + ...preset, + selectedApplicableScope: [...preset.applicableScope], + }; +} + +function conflictDetailsFor( + id: (typeof TEAM_RULE_CONFLICT_IDS)[number], +): NonNullable[string] { + const preset = conflictManagementPresetFor(id); + return { + ...preset, + selectedApplicableScope: [...preset.applicableScope], + }; +} + +/** Create-flow state that publishes as the team's adopted Rule. */ +function teamRuleCreateFlowState(): CreateFlowState { + return { + title: TEAM_RULE_TITLE, + summary: TEAM_RULE_SUMMARY, + communityContext: TEAM_RULE_SUMMARY, + selectedCoreValueIds: [...TEAM_RULE_VALUE_IDS], + coreValuesChipsSnapshot: TEAM_RULE_VALUE_IDS.map((id) => ({ + id, + label: VALUE_LABELS[id], + state: "selected", + })), + selectedCommunicationMethodIds: [...TEAM_RULE_COMMUNICATION_IDS], + selectedMembershipMethodIds: [...TEAM_RULE_MEMBERSHIP_IDS], + selectedDecisionApproachIds: [...TEAM_RULE_DECISION_IDS], + selectedConflictManagementIds: [...TEAM_RULE_CONFLICT_IDS], + decisionApproachDetailsById: Object.fromEntries( + TEAM_RULE_DECISION_IDS.map((id) => [id, decisionDetailsFor(id)]), + ), + conflictManagementDetailsById: Object.fromEntries( + TEAM_RULE_CONFLICT_IDS.map((id) => [id, conflictDetailsFor(id)]), + ), + }; +} + +export type AdoptedTeamRule = { + title: string; + summary: string; + document: Record; +}; + +/** + * Title, summary, and document for the Rule the team adopted on 30 Oct. + * Card set matches the Home hero; method bodies are the remade-deck presets + * those chips carry. + */ +export function buildAdoptedTeamRule(): AdoptedTeamRule { + const result = buildPublishPayload(teamRuleCreateFlowState()); + if (result.ok === false) { + throw new Error(`Failed to build the adopted team Rule: ${result.error}`); + } + return { + title: result.title, + summary: result.summary ?? TEAM_RULE_SUMMARY, + document: result.document, + }; +} diff --git a/prisma/seed.ts b/prisma/seed.ts index 220ccae..4fff2a5 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -1,5 +1,6 @@ import { PrismaClient, type Prisma } from "@prisma/client"; import { seedMethodFacets } from "./seed/methodFacets"; +import { seedTeamRule } from "./seed/teamRule"; import { seedTemplateFacets } from "./seed/templateFacets"; /** @@ -402,6 +403,12 @@ async function main() { console.log( `Seeded TemplateFacet rows: ${templateFacetSeed.rowCount}`, ); + + const teamRuleSeed = await seedTeamRule(prisma); + // eslint-disable-next-line no-console -- seed CLI feedback + console.log( + `Seeded team Rule: ${teamRuleSeed.action} ${teamRuleSeed.title} (${teamRuleSeed.id})`, + ); } main() diff --git a/prisma/seed/teamRule.ts b/prisma/seed/teamRule.ts new file mode 100644 index 0000000..7ff8da2 --- /dev/null +++ b/prisma/seed/teamRule.ts @@ -0,0 +1,101 @@ +import { isDeepStrictEqual } from "node:util"; +import type { Prisma, PrismaClient } from "@prisma/client"; +import { publishedRuleAnalyticsFromDocument } from "../../lib/create/publishedRuleAnalytics"; +import { + TEAM_RULE_DRAFT_TITLE, + TEAM_RULE_TITLE, + buildAdoptedTeamRule, +} from "../../lib/create/teamRule"; +import { RULE_VISIBILITY } from "../../lib/ruleVisibility"; + +export type SeedTeamRuleResult = { + action: "created" | "updated" | "unchanged"; + id: string; + title: string; +}; + +/** + * Replaces the old "The CommunityRule Project" draft with the adopted Rule, + * or inserts it when the environment has neither row. + * Any other featured row with either title is taken out of the catalog so + * a second copy cannot stay public with a stale document. + */ +export async function seedTeamRule( + prisma: PrismaClient, +): Promise { + const adopted = buildAdoptedTeamRule(); + const document = adopted.document as Prisma.InputJsonValue; + const analytics = publishedRuleAnalyticsFromDocument(adopted.document); + const data = { + title: adopted.title, + summary: adopted.summary, + document, + visibility: RULE_VISIBILITY.public_and_featured, + communityLocation: analytics.communityLocation, + orgType: analytics.orgType, + }; + + const rows = await prisma.publishedRule.findMany({ + where: { + title: { in: [TEAM_RULE_DRAFT_TITLE, TEAM_RULE_TITLE] }, + }, + orderBy: { createdAt: "asc" }, + select: { + id: true, + title: true, + summary: true, + document: true, + visibility: true, + communityLocation: true, + orgType: true, + }, + }); + + const canonical = + rows.find((row) => row.title === TEAM_RULE_DRAFT_TITLE) ?? rows[0]; + + if (!canonical) { + const row = await prisma.publishedRule.create({ + data: { + userId: null, + ...data, + }, + select: { id: true, title: true }, + }); + return { action: "created", id: row.id, title: row.title }; + } + + const matches = + canonical.title === data.title && + canonical.summary === data.summary && + canonical.visibility === data.visibility && + canonical.communityLocation === data.communityLocation && + canonical.orgType === data.orgType && + isDeepStrictEqual(canonical.document, data.document); + + let action: SeedTeamRuleResult["action"] = "unchanged"; + if (!matches) { + await prisma.publishedRule.update({ + where: { id: canonical.id }, + data, + }); + action = "updated"; + } + + const extraIds = rows + .filter( + (row) => + row.id !== canonical.id && + row.visibility === RULE_VISIBILITY.public_and_featured, + ) + .map((row) => row.id); + if (extraIds.length > 0) { + await prisma.publishedRule.updateMany({ + where: { id: { in: extraIds } }, + data: { visibility: RULE_VISIBILITY.private }, + }); + action = "updated"; + } + + return { action, id: canonical.id, title: data.title }; +} diff --git a/scripts/seed-team-rule.ts b/scripts/seed-team-rule.ts new file mode 100644 index 0000000..a8eec01 --- /dev/null +++ b/scripts/seed-team-rule.ts @@ -0,0 +1,28 @@ +/** + * Writes the adopted team Rule, including its document, before the server + * listens. Container start runs the esbuild bundle of this file. + * + * Local: + * node --env-file=.env --import tsx scripts/seed-team-rule.ts + */ +import { PrismaClient } from "@prisma/client"; +import { seedTeamRule } from "../prisma/seed/teamRule"; + +const prisma = new PrismaClient(); + +async function main() { + const result = await seedTeamRule(prisma); + // eslint-disable-next-line no-console -- boot CLI feedback + console.log( + `Seeded team Rule: ${result.action} ${result.title} (${result.id})`, + ); +} + +main() + .catch((error) => { + console.error(error); + process.exit(1); + }) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/scripts/start.sh b/scripts/start.sh index cd2092c..8f8787f 100755 --- a/scripts/start.sh +++ b/scripts/start.sh @@ -18,7 +18,8 @@ chown -R node:node /app/data mkdir -p /tmp/next-cache chown -R node:node /tmp/next-cache -# Drop privileges, apply any pending migrations, then exec the server. +# Drop privileges, apply any pending migrations, write the adopted team Rule +# (document included) before anything listens, then exec the server. # Inner `exec` ensures SIGTERM from Cloudron reaches node for clean shutdown. exec gosu node:node sh -c \ - 'prisma migrate deploy && exec node server.js' + 'prisma migrate deploy && node team-rule.bundle.cjs && exec node server.js' diff --git a/tests/unit/seedTeamRule.test.ts b/tests/unit/seedTeamRule.test.ts new file mode 100644 index 0000000..9f44090 --- /dev/null +++ b/tests/unit/seedTeamRule.test.ts @@ -0,0 +1,184 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { publishedRuleAnalyticsFromDocument } from "../../lib/create/publishedRuleAnalytics"; +import { + TEAM_RULE_DRAFT_TITLE, + TEAM_RULE_TITLE, + buildAdoptedTeamRule, +} from "../../lib/create/teamRule"; +import { RULE_VISIBILITY } from "../../lib/ruleVisibility"; + +const findManyMock = vi.fn(); +const updateMock = vi.fn(); +const updateManyMock = vi.fn(); +const createMock = vi.fn(); + +import { seedTeamRule } from "../../prisma/seed/teamRule"; + +function prismaStub() { + return { + publishedRule: { + findMany: findManyMock, + update: updateMock, + updateMany: updateManyMock, + create: createMock, + }, + }; +} + +function staleRow( + id: string, + title: string, + visibility: string = RULE_VISIBILITY.private, +) { + return { + id, + title, + summary: "September draft", + document: { stale: true }, + visibility, + communityLocation: null, + orgType: null, + }; +} + +beforeEach(() => { + findManyMock.mockReset(); + updateMock.mockReset(); + updateManyMock.mockReset(); + createMock.mockReset(); + updateMock.mockResolvedValue({}); + updateManyMock.mockResolvedValue({ count: 1 }); +}); + +describe("seedTeamRule", () => { + it("replaces the old draft row in place, including the document", async () => { + const adopted = buildAdoptedTeamRule(); + findManyMock.mockResolvedValueOnce([ + staleRow("draft-1", TEAM_RULE_DRAFT_TITLE), + ]); + + const result = await seedTeamRule(prismaStub() as never); + + expect(result).toEqual({ + action: "updated", + id: "draft-1", + title: TEAM_RULE_TITLE, + }); + expect(findManyMock).toHaveBeenCalledWith({ + where: { + title: { in: [TEAM_RULE_DRAFT_TITLE, TEAM_RULE_TITLE] }, + }, + orderBy: { createdAt: "asc" }, + select: { + id: true, + title: true, + summary: true, + document: true, + visibility: true, + communityLocation: true, + orgType: true, + }, + }); + expect(updateMock).toHaveBeenCalledWith({ + where: { id: "draft-1" }, + data: { + title: adopted.title, + summary: adopted.summary, + document: adopted.document, + visibility: RULE_VISIBILITY.public_and_featured, + ...publishedRuleAnalyticsFromDocument(adopted.document), + }, + }); + expect(updateManyMock).not.toHaveBeenCalled(); + expect(createMock).not.toHaveBeenCalled(); + }); + + it("updates an already-renamed adopted row", async () => { + findManyMock.mockResolvedValueOnce([ + staleRow("adopted-1", TEAM_RULE_TITLE), + ]); + + const result = await seedTeamRule(prismaStub() as never); + + expect(result.action).toBe("updated"); + expect(updateMock).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: "adopted-1" } }), + ); + }); + + it("creates the adopted Rule when neither row exists", async () => { + const adopted = buildAdoptedTeamRule(); + findManyMock.mockResolvedValueOnce([]); + createMock.mockResolvedValueOnce({ + id: "new-1", + title: TEAM_RULE_TITLE, + }); + + const result = await seedTeamRule(prismaStub() as never); + + expect(result).toEqual({ + action: "created", + id: "new-1", + title: TEAM_RULE_TITLE, + }); + expect(createMock).toHaveBeenCalledWith({ + data: { + userId: null, + title: adopted.title, + summary: adopted.summary, + document: adopted.document, + visibility: RULE_VISIBILITY.public_and_featured, + ...publishedRuleAnalyticsFromDocument(adopted.document), + }, + select: { id: true, title: true }, + }); + }); + + it("unpublishes a second featured row instead of leaving its document public", async () => { + findManyMock.mockResolvedValueOnce([ + staleRow( + "adopted-1", + TEAM_RULE_TITLE, + RULE_VISIBILITY.public_and_featured, + ), + staleRow("draft-1", TEAM_RULE_DRAFT_TITLE), + ]); + + const result = await seedTeamRule(prismaStub() as never); + + expect(result).toEqual({ + action: "updated", + id: "draft-1", + title: TEAM_RULE_TITLE, + }); + expect(updateMock).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: "draft-1" } }), + ); + expect(updateManyMock).toHaveBeenCalledWith({ + where: { id: { in: ["adopted-1"] } }, + data: { visibility: RULE_VISIBILITY.private }, + }); + }); + + it("does not rewrite a row that already matches the adopted Rule", async () => { + const adopted = buildAdoptedTeamRule(); + const analytics = publishedRuleAnalyticsFromDocument(adopted.document); + findManyMock.mockResolvedValueOnce([ + { + id: "adopted-1", + title: adopted.title, + summary: adopted.summary, + document: adopted.document, + visibility: RULE_VISIBILITY.public_and_featured, + communityLocation: analytics.communityLocation, + orgType: analytics.orgType, + }, + ]); + + const result = await seedTeamRule(prismaStub() as never); + + expect(result.action).toBe("unchanged"); + expect(updateMock).not.toHaveBeenCalled(); + expect(updateManyMock).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/teamRule.test.ts b/tests/unit/teamRule.test.ts new file mode 100644 index 0000000..a99871b --- /dev/null +++ b/tests/unit/teamRule.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from "vitest"; +import { parsePublishedDocumentForCommunityRuleDisplay } from "../../lib/create/publishedDocumentToDisplaySections"; +import { + TEAM_RULE_DRAFT_TITLE, + TEAM_RULE_TITLE, + buildAdoptedTeamRule, +} from "../../lib/create/teamRule"; +import heroBanner from "../../messages/en/components/heroBanner.json"; + +function chipTitles(categoryName: string): string[] { + const rule = buildAdoptedTeamRule(); + const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document); + const section = sections.find((row) => row.categoryName === categoryName); + return (section?.entries ?? []).map((entry) => entry.title); +} + +describe("adopted team Rule", () => { + it("uses the adopted title and Home hero summary", () => { + const rule = buildAdoptedTeamRule(); + expect(rule.title).toBe(TEAM_RULE_TITLE); + expect(rule.title).toBe(heroBanner.ruleCard.title); + expect(rule.summary).toBe(heroBanner.ruleCard.description); + }); + + it("contains none of the old draft's title or summary", () => { + const serialized = JSON.stringify(buildAdoptedTeamRule()); + expect(serialized).not.toContain(TEAM_RULE_DRAFT_TITLE); + expect(serialized).not.toContain( + "a free toolkit for writing down how communities make decisions", + ); + expect(serialized).not.toContain("Skill-Based Contribution"); + expect(serialized).not.toContain("Conflict Resolution Council"); + }); + + it("publishes the remade-deck cards the Home hero shows", () => { + const rule = buildAdoptedTeamRule(); + const values = rule.document.coreValues as Array<{ chipId: string }>; + expect(values.map((row) => row.chipId)).toEqual([ + "transparency", + "forkability", + "documentation", + "maintenance", + "voluntarism", + ]); + + const methods = rule.document.methodSelections as { + communication: Array<{ id: string }>; + membership: Array<{ id: string }>; + decisionApproaches: Array<{ id: string }>; + conflictManagement: Array<{ id: string }>; + }; + expect(methods.communication.map((row) => row.id)).toEqual([ + "github-gitlab", + "matrix-element", + "email-distribution-list", + "how-we-run-meetings", + ]); + expect(methods.membership.map((row) => row.id)).toEqual([ + "join-by-contributing", + "companions", + ]); + expect(methods.decisionApproaches.map((row) => row.id)).toEqual([ + "consensus-decision-making", + "lazy-consensus", + "do-ocracy", + "changing-this-rule", + ]); + expect(methods.conflictManagement.map((row) => row.id)).toEqual([ + "conflict-ladder", + "hearing-panel", + "restorative-practices", + ]); + }); + + it("displays the Home hero chip labels, using the deck name for Consensus", () => { + const groups = heroBanner.ruleCard.categories; + expect(chipTitles("Values")).toEqual(groups.values.chips); + expect(chipTitles("Communication")).toEqual(groups.communication.chips); + expect(chipTitles("Membership")).toEqual(groups.membership.chips); + expect(chipTitles("Decision-making")).toEqual( + groups.decisionMaking.chips.map((label) => + label === "Consensus" ? "Consensus decision-making" : label, + ), + ); + expect(chipTitles("Conflict management")).toEqual( + groups.conflictManagement.chips, + ); + }); +});