feat: governance kernel, deployment hardening, local-dev stack

Adds proposals + proposal_votes + policies + incidents + incident_updates
tables with full RLS, async voting flow, dismissal-appeal pathway,
versioned policies with provenance, and an anonymous-incident token mode.
Adds per-space configurable areas, financial visibility settings, member
self-profile + COI disclosure, and a mission statement that renders in
the app footer.

Reorganises lib/actions.ts into per-domain files (tasks, projects,
members, payments, contacts, knowledge-base, secrets, area-leads,
settings, imports, proposals, incidents, policies, areas) plus a barrel.
Adds lib/permissions.ts and lib/auth-helpers.ts so action bodies stop
duplicating the user-to-member-to-role check. Wires every action that has
a Zod schema; introduces a flexibleDateTime preprocessor so HTML date
pickers no longer hit "Invalid datetime".

Hardens RLS: drops NOT NULL on space_members.user_id for offline members,
adds a privilege-escalation trigger that blocks self-edits to role / tier
/ status / approved / has_card_access / space_id, closes four
cross-tenant holes in the governance kernel, and adds a partial unique
index so two admins cannot concurrently activate two drafts of the same
policy slug.

Ships every deployment artifact: Dockerfile, docker-compose,
.do/app.yaml, .env.example, /api/health, plus a managed-Supabase guide
(docs/DEPLOYMENT.md), an end-to-end self-hosted Droplet guide
(docs/DEPLOY_DO_SELFHOSTED.md), and a Supabase-CLI local-dev quickstart
(docs/LOCAL_DEV.md). Replaces middleware.ts with proxy.ts for Next.js 16.
Adds scripts/schema.sql as the canonical idempotent full deploy plus
fourteen numbered incremental migrations.

Adds scripts/seed.sql so a fresh local DB renders something instead of
empty pages: a demo space, five members across all roles, a v1 code of
conduct, three proposals in different states with seven votes already
cast, an open incident, a project, three tasks, a KB entry, and matching
activity-log rows.

Replaces v0-generated test scaffolding with 266 real tests across
__tests__/{actions,auth-helpers,components,governance,permissions,
security,utils,validations}.test.ts. Adds react-markdown + remark-gfm
for proposal / incident / policy body rendering. Deletes four dead v0
fix-* scripts, the unused components/app-shell.tsx, and the duplicate
app/auth/login/page.tsx.

Routes (31 total): /api/health, /api/paypal/sync, /auth/callback, /,
/login, /signup, /signup/confirm, /dashboard, /tasks, /projects,
/members, /payments, /financials, /contacts, /ops, /ops/[id], /ops/new,
/proposals, /proposals/[id], /proposals/new, /incidents, /incidents/[id],
/incidents/new, /policies, /policies/[slug], /policies/new, /profile,
/recruitment, /settings, /comms, /import.

Full pass-by-pass history is in docs/HANDOFF.md; the roadmap is in
docs/GOVERNANCE_FEATURES.md.
This commit is contained in:
Moheeb Zara
2026-05-14 04:52:11 -07:00
parent 8b9128704b
commit ea8d7a5f91
99 changed files with 13823 additions and 1940 deletions
+175
View File
@@ -0,0 +1,175 @@
import Link from 'next/link'
import { redirect, notFound } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import type { Proposal, ProposalVote } from '@/lib/types'
import { ProposalStatusBadge } from '../proposal-badges'
import { ProposalActions } from './proposal-actions'
import { MarkdownBody } from '@/components/markdown'
export const dynamic = 'force-dynamic'
export default async function ProposalDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const { data: member } = await supabase
.from('space_members')
.select('id, space_id, role, display_name')
.eq('user_id', user.id)
.in('status', ['current', 'unverified', 'late'])
.maybeSingle()
if (!member?.space_id) redirect('/signup')
const { data: proposalRaw } = await supabase
.from('proposals')
.select('*')
.eq('id', id)
.eq('space_id', member.space_id)
.maybeSingle()
if (!proposalRaw) notFound()
const proposal = proposalRaw as unknown as Proposal
const { data: votesRaw } = await supabase
.from('proposal_votes')
.select('*')
.eq('proposal_id', proposal.id)
.order('voted_at', { ascending: false })
const votes = (votesRaw ?? []) as unknown as ProposalVote[]
// Resolve voter display names from space_members.
const voterIds = Array.from(new Set(votes.map(v => v.member_id)))
const { data: voters } = voterIds.length
? await supabase
.from('space_members')
.select('id, display_name')
.in('id', voterIds)
: { data: [] as Array<{ id: string; display_name: string | null }> }
const voterNames = new Map((voters ?? []).map(m => [m.id, m.display_name]))
const myVote = votes.find(v => v.member_id === (member as { id: string }).id) ?? null
const isAdminOrBoard = member.role === 'admin' || member.role === 'board'
const votingOpen =
proposal.status === 'open' &&
proposal.voting_opens_at !== null &&
proposal.voting_closes_at !== null &&
new Date(proposal.voting_opens_at) <= new Date() &&
new Date(proposal.voting_closes_at) > new Date()
const totalCounted = proposal.outcome_yes + proposal.outcome_no + proposal.outcome_abstain
const quorumPct = proposal.quorum_required > 0
? Math.min(100, Math.round((totalCounted / proposal.quorum_required) * 100))
: 0
return (
<div className="min-h-screen bg-background">
<div className="bg-sidebar px-4 md:px-6 py-3 flex items-center gap-3">
<Link href="/proposals" className="text-white/70 hover:text-white font-sans text-sm">
← Proposals
</Link>
</div>
<div className="p-4 md:p-6 max-w-4xl space-y-6">
<header className="bg-card rounded border border-border p-5">
<div className="flex items-start justify-between gap-3 mb-3">
<h1 className="font-sans text-xl font-semibold text-foreground flex-1">{proposal.title}</h1>
<ProposalStatusBadge status={proposal.status} />
</div>
<p className="font-mono text-[10px] text-muted-foreground">
{proposal.proposal_type.replace(/_/g, ' ')}
{proposal.proposer_name ? ` · proposed by ${proposal.proposer_name}` : ''}
{' · '}
{proposal.threshold.replace(/_/g, ' ')} required
</p>
{proposal.body && <MarkdownBody className="mt-4" content={proposal.body} />}
</header>
<section className="bg-card rounded border border-border p-5">
<p className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase mb-3">
Tally
</p>
<div className="grid grid-cols-4 gap-3 mb-4">
<Tally label="Yes" value={proposal.outcome_yes} accent="text-primary" />
<Tally label="No" value={proposal.outcome_no} accent="text-orange-600" />
<Tally label="Abstain" value={proposal.outcome_abstain} accent="text-muted-foreground" />
<Tally label="Recused" value={proposal.outcome_recused} accent="text-muted-foreground" />
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase">
Quorum
</span>
<span className="font-sans text-xs">
{totalCounted} of {proposal.quorum_required}
{' · '}
<span className={proposal.quorum_met ? 'text-primary' : 'text-orange-600'}>
{proposal.quorum_met ? 'met' : 'not met'}
</span>
</span>
</div>
<div className="h-1 bg-border rounded-full overflow-hidden">
<div className={`h-full rounded-full ${proposal.quorum_met ? 'bg-primary' : 'bg-orange-400'}`} style={{ width: `${quorumPct}%` }} />
</div>
{proposal.status === 'decided' && (
<p className="font-mono text-[10px] text-muted-foreground pt-1">
Outcome: <span className={proposal.passed ? 'text-primary' : 'text-orange-600'}>{proposal.passed ? 'PASSED' : 'DID NOT PASS'}</span>
{proposal.decided_at ? ` · ${new Date(proposal.decided_at).toLocaleString()}` : ''}
</p>
)}
</div>
</section>
<ProposalActions
proposalId={proposal.id}
status={proposal.status}
isAdminOrBoard={isAdminOrBoard}
isProposer={proposal.proposer_id === member.id}
votingOpen={votingOpen}
myVote={myVote}
/>
<section className="bg-card rounded border border-border p-5">
<p className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase mb-3">
Votes ({votes.length})
</p>
{votes.length === 0 ? (
<p className="font-sans text-sm text-muted-foreground">No votes cast yet.</p>
) : (
<ul className="divide-y divide-border">
{votes.map(v => (
<li key={v.id} className="py-2 flex items-start gap-3">
<span className="font-mono text-[10px] tracking-widest uppercase w-16 flex-shrink-0 mt-1">
{v.position}
</span>
<div className="flex-1 min-w-0">
<p className="font-sans text-sm text-foreground">{voterNames.get(v.member_id) ?? 'Unknown member'}</p>
{v.comment && <p className="font-sans text-xs text-muted-foreground mt-0.5">{v.comment}</p>}
{v.recusal_reason && (
<p className="font-sans text-xs text-muted-foreground italic mt-0.5">Recused: {v.recusal_reason}</p>
)}
</div>
<span className="font-mono text-[10px] text-muted-foreground/60 flex-shrink-0 mt-1">
{new Date(v.voted_at).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
</span>
</li>
))}
</ul>
)}
</section>
</div>
</div>
)
}
function Tally({ label, value, accent }: { label: string; value: number; accent: string }) {
return (
<div>
<p className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase mb-1">{label}</p>
<p className={`font-sans text-2xl font-semibold ${accent}`}>{value}</p>
</div>
)
}
@@ -0,0 +1,161 @@
'use client'
import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import {
castVote,
decideProposal,
openProposal,
withdrawProposal,
} from '@/lib/actions'
import type { ProposalStatus, ProposalVote, VotePosition } from '@/lib/types'
import { votePositions } from '@/lib/validations'
type Props = {
proposalId: string
status: ProposalStatus
isAdminOrBoard: boolean
isProposer: boolean
votingOpen: boolean
myVote: ProposalVote | null
}
export function ProposalActions({
proposalId,
status,
isAdminOrBoard,
isProposer,
votingOpen,
myVote,
}: Props) {
const router = useRouter()
const [isPending, startTransition] = useTransition()
const [error, setError] = useState('')
// Voting form state
const [position, setPosition] = useState<VotePosition>(myVote?.position ?? 'yes')
const [recusalReason, setRecusalReason] = useState(myVote?.recusal_reason ?? '')
const [comment, setComment] = useState(myVote?.comment ?? '')
function run<T>(fn: () => Promise<T>) {
setError('')
startTransition(async () => {
const r = (await fn()) as unknown as { error?: string }
if (r && r.error) setError(r.error)
router.refresh()
})
}
return (
<div className="space-y-3">
{votingOpen && (
<div className="bg-card rounded border border-border p-5">
<p className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase mb-3">
{myVote ? 'Update your vote' : 'Cast your vote'}
</p>
<div className="grid grid-cols-4 gap-2 mb-3">
{votePositions.map(p => (
<button
key={p}
type="button"
onClick={() => setPosition(p)}
className={`font-mono text-xs tracking-widest uppercase py-2 rounded border transition ${
position === p
? 'bg-primary text-white border-primary'
: 'border-border text-foreground hover:border-primary'
}`}
>
{p}
</button>
))}
</div>
{position === 'recused' && (
<div className="mb-3">
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">
Recusal reason (required)
</label>
<textarea
value={recusalReason}
onChange={e => setRecusalReason(e.target.value)}
rows={2}
maxLength={1000}
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
/>
</div>
)}
<div className="mb-3">
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">
Comment (optional, public)
</label>
<input
type="text"
value={comment}
onChange={e => setComment(e.target.value)}
maxLength={2000}
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
/>
</div>
<button
type="button"
disabled={isPending || (position === 'recused' && recusalReason.trim().length === 0)}
onClick={() =>
run(() =>
castVote({
proposalId,
position,
recusal_reason: position === 'recused' ? recusalReason : null,
comment: comment || null,
}),
)
}
className="bg-primary text-white font-sans text-sm font-medium px-4 py-2 rounded hover:bg-primary/90 transition disabled:opacity-50"
>
{isPending ? 'Saving...' : myVote ? 'Update vote' : 'Submit vote'}
</button>
</div>
)}
{(isAdminOrBoard || isProposer) && (
<div className="bg-card rounded border border-border p-5">
<p className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase mb-3">
Manage
</p>
<div className="flex flex-wrap gap-2">
{status === 'draft' && (
<button
type="button"
onClick={() => run(() => openProposal(proposalId))}
disabled={isPending}
className="font-sans text-xs border border-border px-3 py-1.5 rounded hover:border-primary hover:text-primary"
>
Open for voting
</button>
)}
{(status === 'draft' || status === 'open') && (
<button
type="button"
onClick={() => run(() => withdrawProposal(proposalId))}
disabled={isPending}
className="font-sans text-xs border border-border px-3 py-1.5 rounded hover:border-orange-500 hover:text-orange-600"
>
Withdraw
</button>
)}
{status === 'open' && isAdminOrBoard && (
<button
type="button"
onClick={() => run(() => decideProposal(proposalId))}
disabled={isPending}
className="font-sans text-xs border border-border px-3 py-1.5 rounded hover:border-primary hover:text-primary"
>
Mark decided
</button>
)}
</div>
</div>
)}
{error && <p className="font-mono text-xs text-red-500">{error}</p>}
</div>
)
}
@@ -0,0 +1,146 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { createProposal } from '@/lib/actions'
import {
proposalTypes,
thresholdRules,
} from '@/lib/validations'
export function NewProposalForm() {
const router = useRouter()
const [title, setTitle] = useState('')
const [body, setBody] = useState('')
const [proposalType, setProposalType] = useState<string>('advisory_poll')
const [threshold, setThreshold] = useState<string>('simple_majority')
const [openImmediately, setOpenImmediately] = useState(false)
const [error, setError] = useState('')
const [submitting, setSubmitting] = useState(false)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setSubmitting(true)
setError('')
const result = await createProposal({
title,
body,
proposal_type: proposalType,
threshold,
open_immediately: openImmediately,
})
if ('error' in result && result.error) {
setError(result.error)
setSubmitting(false)
return
}
if ('data' in result && result.data) {
router.push(`/proposals/${(result.data as { id: string }).id}`)
} else {
router.push('/proposals')
}
}
return (
<form onSubmit={handleSubmit} className="space-y-5 bg-card rounded border border-border p-5">
<div>
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">
Title
</label>
<input
type="text"
value={title}
onChange={e => setTitle(e.target.value)}
maxLength={200}
required
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
placeholder="Approve new laser station rules"
/>
</div>
<div>
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">
Body
</label>
<textarea
value={body}
onChange={e => setBody(e.target.value)}
rows={10}
maxLength={20000}
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
placeholder="Describe the proposal, the change being proposed, and the rationale."
/>
<p className="font-mono text-[10px] text-muted-foreground mt-1">Markdown is rendered on the detail page.</p>
</div>
<div className="grid md:grid-cols-2 gap-4">
<div>
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">
Type
</label>
<select
value={proposalType}
onChange={e => setProposalType(e.target.value)}
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
>
{proposalTypes.map(t => (
<option key={t} value={t}>
{t.replace(/_/g, ' ')}
</option>
))}
</select>
</div>
<div>
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">
Threshold to pass
</label>
<select
value={threshold}
onChange={e => setThreshold(e.target.value)}
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
>
{thresholdRules.map(t => (
<option key={t} value={t}>
{t.replace(/_/g, ' ')}
</option>
))}
</select>
</div>
</div>
<div>
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={openImmediately}
onChange={e => setOpenImmediately(e.target.checked)}
className="rounded border-border"
/>
<span className="font-sans">Open voting immediately. Quorum and voting window come from space defaults.</span>
</label>
</div>
{error && <p className="font-mono text-xs text-red-500">{error}</p>}
<div className="flex items-center justify-end gap-3">
<Link
href="/proposals"
className="font-sans text-sm text-muted-foreground hover:text-foreground"
>
Cancel
</Link>
<button
type="submit"
disabled={submitting || !title.trim()}
className="bg-primary text-white font-sans text-sm font-medium px-4 py-2 rounded hover:bg-primary/90 transition disabled:opacity-50"
>
{submitting ? 'Saving...' : 'Save proposal'}
</button>
</div>
</form>
)
}
+30
View File
@@ -0,0 +1,30 @@
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { NewProposalForm } from './new-proposal-form'
export const dynamic = 'force-dynamic'
export default async function NewProposalPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const { data: member } = await supabase
.from('space_members')
.select('space_id')
.eq('user_id', user.id)
.in('status', ['current', 'unverified', 'late'])
.maybeSingle()
if (!member?.space_id) redirect('/signup')
return (
<div className="min-h-screen bg-background">
<div className="bg-sidebar px-4 md:px-6 py-3">
<h1 className="text-white font-sans text-lg font-semibold">New proposal</h1>
</div>
<div className="p-4 md:p-6 max-w-2xl">
<NewProposalForm />
</div>
</div>
)
}
+99
View File
@@ -0,0 +1,99 @@
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import type { Proposal } from '@/lib/types'
import { ProposalStatusBadge } from './proposal-badges'
export const dynamic = 'force-dynamic'
export default async function ProposalsPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const { data: member } = await supabase
.from('space_members')
.select('space_id')
.eq('user_id', user.id)
.in('status', ['current', 'unverified', 'late'])
.maybeSingle()
if (!member?.space_id) redirect('/signup')
const { data: proposals } = await supabase
.from('proposals')
.select('*')
.eq('space_id', member.space_id)
.order('created_at', { ascending: false })
const list = (proposals ?? []) as unknown as Proposal[]
const open = list.filter(p => p.status === 'open')
const drafts = list.filter(p => p.status === 'draft')
const decided = list.filter(p => ['decided', 'withdrawn', 'expired'].includes(p.status))
return (
<div className="min-h-screen bg-background">
<div className="bg-sidebar px-4 md:px-6 py-3 flex items-center justify-between">
<h1 className="text-white font-sans text-lg font-semibold">Proposals</h1>
<Link
href="/proposals/new"
className="bg-primary text-white text-xs font-sans px-3 py-1.5 rounded hover:bg-primary/90 transition"
>
New proposal
</Link>
</div>
<div className="p-4 md:p-6 space-y-8 max-w-4xl">
<Section title="Open for voting" empty="No proposals are currently open." proposals={open} />
<Section title="Drafts" empty="No drafts." proposals={drafts} />
<Section title="Archive" empty="No decided or withdrawn proposals." proposals={decided} />
</div>
</div>
)
}
function Section({ title, empty, proposals }: { title: string; empty: string; proposals: Proposal[] }) {
return (
<div>
<p className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase mb-3">{title}</p>
<div className="bg-card rounded border border-border divide-y divide-border">
{proposals.length === 0 ? (
<div className="px-4 py-8 text-center text-muted-foreground font-sans text-sm">{empty}</div>
) : (
proposals.map(p => <ProposalRow key={p.id} p={p} />)
)}
</div>
</div>
)
}
function ProposalRow({ p }: { p: Proposal }) {
const totalVotes = p.outcome_yes + p.outcome_no + p.outcome_abstain
return (
<Link href={`/proposals/${p.id}`} className="block px-4 py-3 hover:bg-muted transition">
<div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<p className="font-sans text-sm font-medium text-foreground truncate">{p.title}</p>
<ProposalStatusBadge status={p.status} />
</div>
<p className="font-mono text-[10px] text-muted-foreground">
{p.proposal_type.replace(/_/g, ' ')}
{p.proposer_name ? ` · proposed by ${p.proposer_name}` : ''}
{p.voting_closes_at && p.status === 'open'
? ` · closes ${new Date(p.voting_closes_at).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}`
: ''}
</p>
</div>
<div className="text-right flex-shrink-0">
<p className="font-mono text-[10px] text-muted-foreground tracking-widest uppercase">
{p.outcome_yes} y · {p.outcome_no} n · {p.outcome_abstain} a
</p>
<p className="font-mono text-[10px] text-muted-foreground mt-0.5">
{totalVotes}/{p.quorum_required} for quorum
</p>
</div>
</div>
</Link>
)
}
+17
View File
@@ -0,0 +1,17 @@
import type { ProposalStatus } from '@/lib/types'
const STATUS_STYLE: Record<ProposalStatus, string> = {
draft: 'text-muted-foreground bg-muted',
open: 'text-primary bg-primary/10',
decided: 'text-blue-600 bg-blue-50',
withdrawn: 'text-muted-foreground bg-muted',
expired: 'text-orange-600 bg-orange-50',
}
export function ProposalStatusBadge({ status }: { status: ProposalStatus }) {
return (
<span className={`font-mono text-[10px] tracking-widest uppercase px-1.5 py-0.5 rounded ${STATUS_STYLE[status]}`}>
{status.replace(/_/g, ' ')}
</span>
)
}