ai-refinery.ts — 6 functions, 423 lines of AI logic
The AI Refinery is the intelligence layer of the Fora proposal system. It transforms raw citizen input into structured civic contributions, finds collaboration opportunities, synthesizes community intelligence, and advises on funding. Every function follows strict guardrails to ensure AI enhances — never replaces — citizen voice.
Proposal SolutionsuggestFundingSourcesFunding Advisory (requires human review)
refineArgument()low risk
Argument Refiner
Takes a citizen's raw argument (pro or con) and produces a structured analysis with summary, key insight, credibility score, tags, and constructive feedback.
Input
{ argumentId: number }
Output
{
summary: string, // 1-2 sentence core point
keyInsight: string, // <100 chars takeaway
credibilityScore: 0-100, // evidence-based scoring
suggestedTags: string[], // 2-5 topic tags
refinedTitle: string, // clearer version of title
constructiveFeedback: string // how to strengthen
}
Tag extraction — maps arguments to civic topic taxonomy
Governance Rules
MUST preserve the citizen's original intent — refinement, not replacement
MUST NOT change the position (for/against) of the argument
Credibility score is based on evidence quality, NOT agreement with any position
Constructive feedback must be encouraging, never dismissive
AI-refined content is stored alongside originals, never overwrites
refineSolution()medium risk
Solution Refiner
Polishes citizen-proposed solutions with structured format (problem→action→outcome→timeline), identifies strengths/weaknesses, and scores implementability.
Gap analysis — identifies missing implementation details
Feasibility assessment — scores based on specificity, timeline, and resource requirements
Collaboration matching — suggests expertise types that would strengthen the solution
Governance Rules
Refined version MUST preserve the citizen's core solution approach
MUST NOT introduce new policy positions not present in the original
Weaknesses must be constructive, not discouraging
Implementation score reflects actionability, NOT political feasibility
Cost estimates in refined version must be clearly marked as AI-generated
reshapeToProposal()low risk
Solution Forge
The most transformative function — takes raw citizen input (rants, complaints, half-formed ideas) and extracts the civic gold, reshaping it into a structured proposal contribution.
Emotion-to-insight translation — converts frustration into actionable civic language
Issue extraction — finds the real question behind complaints
Solution synthesis — if the citizen hints at a solution, fleshes it out; if purely a complaint, proposes a direction
Tone detection — categorizes input tone for appropriate response calibration
Governance Rules
MUST respect the citizen's underlying concern — never dismiss or minimize
MUST NOT fabricate positions the citizen didn't express
If the input is genuinely off-topic or harmful, return a gentle redirect
The structured output is a SUGGESTION — citizen must review and approve before publishing
No auto-publishing of reshaped content
findCollaborations()low risk
Collaboration Matchmaker
Analyzes all contributions to a proposal and identifies pairs or groups that could strengthen each other. Matches complementary expertise and overlapping interests.
Input
{ proposalId: number }
Output
{
collaborations: [{
contributionIds: string[], // e.g. ["Argument #3", "Research #7"]
reason: string, // why they should collaborate
suggestedAction: string, // what to do together
strength: "high"|"medium"|"low"
}],
overallInsight: string // state of collaboration
}
AI Skills
Expertise complementarity detection — finds where one person's data fills another's gap
Interest overlap mapping — identifies shared concerns across different contribution types
Collaboration strength scoring — based on specificity of overlap and potential impact
Governance Rules
Maximum 5 collaboration suggestions per proposal
MUST NOT reveal private user data — only references contribution IDs
Collaboration suggestions are optional — no forced connections
Requires minimum 2 contributions to function
generateCommunityReport()medium risk
Community Intelligence Report
The flagship synthesis function — aggregates ALL contributions (arguments, solutions, research, reviews) into a comprehensive intelligence report that represents every voice, not just the loudest.
Input
{ proposalId: number }
Output
{
executiveSummary: string, // 2-3 paragraph markdown
consensusPoints: string[], // 2-5 points of agreement
tensionPoints: string[], // 1-4 areas of disagreement
topSolutions: [{title, reason}], // top 2-3 ranked solutions
evidenceStrength: "strong"|"moderate"|"weak",
gapsIdentified: string[], // 2-3 research gaps
recommendedNextSteps: string[], // 3-5 concrete actions
communityVoiceScore: 0-100, // how well community was heard
contributionStats: {...} // actual counts (overridden by real data)
}
AI Skills
Multi-perspective synthesis — weighs all viewpoints proportionally
Consensus detection — finds common ground across opposing positions
Tension mapping — fairly represents both sides of disagreements
Evidence quality assessment — rates the overall strength of cited evidence
Community Voice Score — measures diversity of perspectives and quality of debate
Governance Rules
MUST represent minority viewpoints — not just majority consensus
contributionStats are ALWAYS overridden with actual database counts (never AI-hallucinated)
MUST NOT editorialize or take a position on the proposal
Evidence strength rating must be based on citation quality, not volume
Report is clearly labeled as AI-synthesized
No individual attribution — aggregated insights only
suggestFundingSources()high risk financial impact
AI Funding Advisor
The highest-risk AI function — suggests specific California funding sources (grants, bonds, fees, taxes) for proposal solutions. Outputs include confidence scores, application URLs, approval requirements, and risk factors.
Input
{ solutionId: number }
Output
{
suggestions: [{
sourceType: string, // e.g. "state_grant", "municipal_bond"
sourceName: string, // e.g. "CA Prop 68 Parks Bond"
fundingEntity: string, // who provides it
estimatedAmount: string, // dollar estimate or "varies"
confidence: 0.0-1.0, // likelihood of availability
reasoning: string, // 2-3 sentences
requiresVoterApproval: boolean,
requiresCouncilApproval: boolean,
applicationUrl: string|null,
termLengthMonths: number|null,
renewalType: string
}],
overallAssessment: string,
fundingGap: string,
riskFactors: string[]
}
AI Skills
California municipal finance expertise — knows actual grant programs, bond types, fee structures