chore(scripts): remove 29 more dead scripts (one-off + duplicate utilities)

Continuation of b6df91a cleanup. 29 additional scripts with 0
real references in the codebase (research/PIPELINE-LEARNINGS.md
mentions of fix-method-labels and show-requeue are historical
prose, not code dependencies).

12 inspection/diagnostic one-offs:
  check-batch-import-status, check-candidates, check-coverage,
  check-downgrades, check-prios, check-rescore-result,
  check-untracked-imports.sh, dump-candidates,
  diagnose-p1p3-gaps, list-rapid-p4, query-p4-next, show-requeue

7 numbered "write-*-application-urls" batch scripts:
  write-application-urls, write-application-urls-2,
  write-p3-application-urls (×5 numbered variants)
  (same pattern as the dated scripts in the prior cleanup —
   multiple sequential one-shot variants of the same operation,
   all already executed against the DB)

5 superseded utility scripts:
  dedup-foundations (replaced by dedupe-by-uid.ts in commit 20f5cf9),
  fix-method-labels (PIPELINE-LEARNINGS notes it as a one-time fix),
  upgrade-rapid-websites + upgrade-rapid-with-websites (duplicates),
  upgrade-start-foundation, upgrade-two-more (named for specific
  foundations from past sessions)

5 rescore experiments:
  full-rescore, rescore-enriched, rescore-phase2, test-rescore,
  (rescore-phase1 was already gone)
  These were exploratory passes during the priority-formula tuning
  in March; the formula now lives in lib/config/fit-scoring.ts and
  recompute happens in npm run sync.

scripts/ count: 64 → 35.

tsc clean, 425/425 tests pass, audit/sync unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-04-26 09:44:33 +02:00
1 parent b6df91ae9c
commit 1a16e5df1e
29 files changed
-2027

No files matched your search

-33
View File
@@ -1,33 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { readFileSync } from 'fs';
const sql = neon(process.env.DATABASE_URL!);
async function main() {
const slugs = readFileSync('/tmp/batch_slugs.txt', 'utf8').trim().split('\n');
const CHUNK = 200;
let alreadyImported = 0, notImported = 0, notInDB = 0;
const pending: string[] = [];
for (let i = 0; i < slugs.length; i += CHUNK) {
const batch = slugs.slice(i, i + CHUNK);
const rows = await sql`
SELECT id, config_data->>'applicationResearchMethod' as method
FROM fundraising_foundations WHERE id = ANY(${batch}::text[])
`;
const inDB = new Map(rows.map(r => [r.id, r.method]));
for (const s of batch) {
if (!inDB.has(s)) notInDB++;
else if (inDB.get(s) === 'claude-agent') alreadyImported++;
else { notImported++; pending.push(s); }
}
}
console.log('Already imported (claude-agent):', alreadyImported);
console.log('In DB but NOT yet imported:', notImported);
console.log('Not in DB at all:', notInDB);
if (pending.length > 0) {
console.log('\nSample not-yet-imported slugs:');
pending.slice(0, 10).forEach(s => console.log(' ', s));
}
}
main().catch(console.error);
-27
View File
@@ -1,27 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const slugs = [
'schoepflin-stiftung-assoziierter-partner','start-foundation',
'education-and-social-foundation-bildung-und-soziales-stiftun',
'schweizerische-stiftung-fuer-kinder-und-jugendliche-in-not',
'sozial-bildungsfonds-des-kaufmaennischen-verbandes-schweiz',
'stiftung-fuer-alphabetisierung-und-grundbildung-schweiz',
'fondation-hans-wilsdorf','cleantech21-foundation',
'fondation-free-future','gemeinnuetzige-gesellschaft-des-bezirks-uster',
'hand-in-hand-stiftung-fuer-eine-nachhaltige-entwicklung',
'hugo-bachmann-stiftung-fuer-nachhaltigkeit','impact-corner-stiftung',
'limmat-stiftung','pro-patria-schweiz-bundesfeierspende',
'stiftung-fokus-frauen','stiftung-wirtschaft-und-oekologie-swo',
'fondation-gandur-pour-la-jeunesse'
];
async function main() {
for (const slug of slugs) {
const [r] = await sql`SELECT id, fit_score, priority, research_depth FROM fundraising_foundations WHERE id = ${slug}`;
if (r) console.log(`${r.fit_score}→? | P${r.priority} | ${r.research_depth} | ${r.id}`);
else console.log(`NOT FOUND: ${slug}`);
}
}
main().catch(console.error);
-17
View File
@@ -1,17 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
async function main() {
const rows = await sql`
SELECT priority, COUNT(*) as total,
COUNT(*) FILTER (WHERE config_data->>'applicationUrl' IS NOT NULL AND config_data->>'applicationUrl' != '') as with_url,
COUNT(*) FILTER (WHERE config_data->>'applicationUrl' IS NULL OR config_data->>'applicationUrl' = '') as without_url
FROM fundraising_foundations
WHERE priority IN (1,2,3)
AND (data_confidence IS NULL OR data_confidence != 'unverified')
GROUP BY priority ORDER BY priority
`;
rows.forEach(r => console.log(`P${r.priority}: ${r.total} total | ${r.with_url} with applicationUrl | ${r.without_url} missing`));
}
main().catch(console.error);
-22
View File
@@ -1,22 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { computeFitScore } from '../src/lib/domain/fit-scoring';
const sql = neon(process.env.DATABASE_URL!);
async function main() {
const rows = await sql`
SELECT id, fit_score, priority, config_data
FROM fundraising_foundations
WHERE (data_confidence IS NULL OR data_confidence != 'unverified')
AND (archived IS NULL OR archived = false)
ORDER BY fit_score DESC LIMIT 20
`;
for (const row of rows) {
const cd = row.config_data as Record<string, unknown>;
const result = computeFitScore(cd as unknown as Parameters<typeof computeFitScore>[0]);
const delta = result.fitScore - (row.fit_score as number);
if (delta < 0) {
console.log(`${row.fit_score}→${result.fitScore} | P${row.priority} | ${row.id} | themes:${(cd.themes as string[])?.join(',') || 'none'}`);
}
}
}
main().catch(console.error);
-25
View File
@@ -1,25 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
async function main() {
const rows = await sql`
SELECT id, fit_score, priority,
config_data->>'websiteUrl' as website,
config_data->>'applicationUrl' as appurl,
config_data->>'acceptsApplications' as accepts,
config_data->>'applicationMethod' as method,
config_data->'contact'->>'email' as email
FROM fundraising_foundations
WHERE priority IN (1,2)
AND (data_confidence IS NULL OR data_confidence != 'unverified')
AND config_data->>'applicationUrl' IS NULL
AND config_data->>'websiteUrl' IS NOT NULL
AND config_data->>'websiteUrl' != ''
ORDER BY priority, fit_score DESC
`;
console.log(`P1-P2 with website but no applicationUrl: ${rows.length}`);
rows.forEach(r => console.log(
` P${r.priority} fitScore=${r.fit_score} | ${r.id} | ${r.method}/${r.accepts} | ${r.website}`
));
}
main().catch(console.error);
-22
View File
@@ -1,22 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const SLUGS = [
'start-foundation',
'education-and-social-foundation-bildung-und-soziales-stiftun',
'fondation-hans-wilsdorf',
'schoepflin-stiftung-assoziierter-partner',
'impact-corner-stiftung',
];
async function main() {
for (const slug of SLUGS) {
const [row] = await sql`SELECT id, fit_score, priority, research_depth, data_confidence, config_data FROM fundraising_foundations WHERE id = ${slug}`;
if (!row) { console.log(`NOT FOUND: ${slug}`); continue; }
const cd = row.config_data as Record<string, unknown>;
console.log(`${slug}: fit_score=${row.fit_score}, priority=P${row.priority}, depth=${row.research_depth}, conf=${row.data_confidence}, config.fitScore=${cd.fitScore}`);
}
}
main().catch(console.error);
-65
View File
@@ -1,65 +0,0 @@
#!/usr/bin/env bash
#
# check-untracked-imports.sh — Pre-push safety check
#
# Problem this solves: Files created locally but never `git add`'ed pass
# the local build (files exist on disk) but fail on Vercel (only committed
# files exist). This caused 4 consecutive failed deployments.
#
# How it works: Finds untracked files under src/ that could be imports,
# then checks if any tracked file imports them. If so, blocks the push.
set -euo pipefail
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Get untracked files in src/ (excluding test fixtures, etc.)
untracked=$(git ls-files --others --exclude-standard -- 'src/' | grep -E '\.(ts|tsx)$' || true)
if [ -z "$untracked" ]; then
exit 0
fi
# Build a list of potential import paths from untracked files
# e.g., src/lib/utils/share-token.ts → @/lib/utils/share-token
errors=()
for file in $untracked; do
# Strip src/ prefix and .ts/.tsx extension
import_path=$(echo "$file" | sed 's|^src/||; s|\.tsx\?$||; s|/index$||')
# Check if any tracked file imports this path
# Look for @/path or ./relative-path patterns
if git grep -l "from ['\"]@/${import_path}['\"]" -- '*.ts' '*.tsx' 2>/dev/null | head -1 > /dev/null 2>&1; then
importers=$(git grep -l "from ['\"]@/${import_path}['\"]" -- '*.ts' '*.tsx' 2>/dev/null | head -3)
errors+=(" ${RED}✗${NC} ${file} (imported by: $(echo "$importers" | tr '\n' ', ' | sed 's/,$//'))")
fi
done
if [ ${#errors[@]} -eq 0 ]; then
# Untracked files exist but none are imported — just warn
count=$(echo "$untracked" | wc -l)
echo -e "${YELLOW}⚠ ${count} untracked file(s) in src/ — consider committing:${NC}"
echo "$untracked" | head -5 | while read -r f; do echo " $f"; done
[ "$count" -gt 5 ] && echo " ... and $((count - 5)) more"
echo ""
exit 0
fi
# Imported untracked files found — this WILL break the Vercel build
echo ""
echo -e "${RED}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║ PUSH BLOCKED — Untracked files are imported by your code ║${NC}"
echo -e "${RED}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "These files exist locally but are NOT in git."
echo -e "The Vercel build WILL fail because it only sees committed files."
echo ""
for err in "${errors[@]}"; do
echo -e "$err"
done
echo ""
echo -e "Fix: ${YELLOW}git add <files>${NC} and commit before pushing."
echo ""
exit 1
-69
View File
@@ -1,69 +0,0 @@
#!/usr/bin/env tsx
import { config } from 'dotenv';
config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const dryRun = process.argv.includes('--dry-run');
async function main() {
const dupes = await sql`
SELECT config_data->>'uid' as uid, array_agg(id) as ids
FROM fundraising_foundations
WHERE config_data->>'uid' IS NOT NULL AND config_data->>'uid' != ''
AND (archived = false OR archived IS NULL)
AND (data_confidence IS NULL OR data_confidence != 'unverified')
GROUP BY config_data->>'uid' HAVING count(*) > 1`;
console.log(`Found ${dupes.length} duplicate groups\n`);
let mergedCount = 0, archivedCount = 0;
for (const dupe of dupes) {
const rows = await sql`
SELECT id, name, fit_score, config_data
FROM fundraising_foundations WHERE id = ANY(${dupe.ids})`;
rows.sort((a, b) => {
const fd = (Number(b.fit_score) || 0) - (Number(a.fit_score) || 0);
if (fd !== 0) return fd;
const cs = (r: any) => {
const c = r.config_data?.contact || {};
return [c.email, c.phone, c.address].filter(Boolean).length;
};
return cs(b) - cs(a);
});
const w = rows[0], losers = rows.slice(1);
const wContact = (w.config_data as any)?.contact || {};
const wWeb = (w.config_data as any)?.websiteUrl;
const email = wContact.email || losers.find(l => (l.config_data as any)?.contact?.email)?.config_data?.contact?.email || null;
const phone = wContact.phone || losers.find(l => (l.config_data as any)?.contact?.phone)?.config_data?.contact?.phone || null;
const addr = wContact.address || losers.find(l => (l.config_data as any)?.contact?.address)?.config_data?.contact?.address || null;
const web = (wWeb && !String(wWeb).includes('zefix')) ? wWeb
: losers.find(l => { const u = (l.config_data as any)?.websiteUrl; return u && !String(u).includes('zefix'); })?.config_data?.websiteUrl || wWeb;
console.log(`${dupe.uid}: KEEP ${w.id} (fit=${w.fit_score}), ARCHIVE ${losers.map(l=>l.id).join(', ')}`);
if (!dryRun) {
// Merge best contact data into winner's config_data
const cd = (w.config_data || {}) as Record<string, unknown>;
if (!cd.contact) cd.contact = {};
const contact = cd.contact as Record<string, string | null>;
if (email) contact.email = email;
if (phone) contact.phone = phone;
if (addr) contact.address = addr;
if (web) cd.websiteUrl = web;
await sql`UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd)}::jsonb, updated_at = NOW()
WHERE id = ${w.id}`;
mergedCount++;
for (const l of losers) {
await sql`UPDATE fundraising_foundations SET archived = true WHERE id = ${l.id}`;
archivedCount++;
}
}
}
console.log(`\n${mergedCount} merged, ${archivedCount} archived${dryRun ? ' (DRY RUN)' : ''}`);
}
main().catch(console.error);
-347
View File
@@ -1,347 +0,0 @@
#!/usr/bin/env tsx
/**
* Diagnose P1-P3 Gaps — Find foundations with strategic priority but insufficient data
*
* Loads STIFTUNGEN_DATA, computes readiness for all P1-P3 foundations,
* and reports which ones are below recherchiert tier (score < 45).
*
* No DB access needed — operates on the sync'd TypeScript data.
*
* Output: research/diagnostics/p1p3-gaps-YYYY-MM-DD.json
*
* Usage:
* npx tsx scripts/diagnose-p1p3-gaps.ts
* npx tsx scripts/diagnose-p1p3-gaps.ts --verbose # Per-foundation details
*/
import * as path from 'path';
import * as fs from 'fs';
import { STIFTUNGEN_DATA } from '../src/lib/config/foundations/index.js';
import { computeReadinessScore } from '../src/lib/domain/foundation-scores.js';
import { computePriorityScore } from '../src/lib/domain/foundation-scores.js';
import type { Foundation, QualityTier } from '../src/lib/schemas/foundation.js';
// ============================================================================
// CLI ARGS
// ============================================================================
const args = process.argv.slice(2);
const VERBOSE = args.includes('--verbose');
// ============================================================================
// Types
// ============================================================================
interface GapEntry {
slug: string;
name: string;
priority: number;
fitScore: number;
readinessScore: number;
tier: QualityTier;
pointsNeeded: number; // to reach recherchiert (score 45)
topImprovements: { label: string; points: number; dimension: string }[];
missingFields: string[];
}
interface WhatIfScenario {
field: string;
description: string;
affectedCount: number;
wouldGraduate: number;
}
// ============================================================================
// MAIN
// ============================================================================
function main() {
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(' P1-P3 Gap Diagnostic');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
const total = STIFTUNGEN_DATA.length;
console.log(` Total foundations in sync'd data: ${total}`);
// Filter P1-P3 foundations
const p1p3: Foundation[] = [];
for (const f of STIFTUNGEN_DATA) {
const pResult = computePriorityScore(f);
if (pResult.level <= 3) {
p1p3.push(f);
}
}
console.log(` P1-P3 foundations: ${p1p3.length}`);
// Compute readiness for each, find those below recherchiert
const RECHERCHIERT_THRESHOLD = 45; // readiness score needed for recherchiert tier
const gaps: GapEntry[] = [];
let alreadyQualified = 0;
for (const f of p1p3) {
const readiness = computeReadinessScore(f);
const priority = computePriorityScore(f, readiness.score);
if (readiness.tier === 'recherchiert' || readiness.tier === 'anwendungsbereit') {
alreadyQualified++;
continue;
}
const pointsNeeded = Math.max(0, RECHERCHIERT_THRESHOLD - readiness.score);
// Determine missing fields from unpassed checks
const missingFields: string[] = [];
for (const check of readiness.checks) {
if (!check.passed) {
missingFields.push(check.label);
}
}
gaps.push({
slug: f.slug,
name: f.name,
priority: priority.level,
fitScore: f.fitScore,
readinessScore: readiness.score,
tier: readiness.tier,
pointsNeeded,
topImprovements: readiness.topImprovements,
missingFields,
});
}
// Sort by priority (P1 first), then by points needed (lowest first = easiest wins)
gaps.sort((a, b) => {
if (a.priority !== b.priority) return a.priority - b.priority;
return a.pointsNeeded - b.pointsNeeded;
});
console.log(` Already qualified (recherchiert+): ${alreadyQualified}`);
console.log(` Below recherchiert (the gap): ${gaps.length}`);
// Breakdown by priority
const byPriority = { 1: 0, 2: 0, 3: 0 };
for (const g of gaps) {
byPriority[g.priority as 1 | 2 | 3]++;
}
console.log(`\n Gap by priority:`);
console.log(` P1: ${byPriority[1]} foundations below recherchiert`);
console.log(` P2: ${byPriority[2]} foundations below recherchiert`);
console.log(` P3: ${byPriority[3]} foundations below recherchiert`);
// Breakdown by current tier
const byTier: Record<string, number> = {};
for (const g of gaps) {
byTier[g.tier] = (byTier[g.tier] || 0) + 1;
}
console.log(`\n Gap by current tier:`);
for (const [tier, count] of Object.entries(byTier).sort()) {
console.log(` ${tier}: ${count}`);
}
// Aggregate missing fields
const fieldCounts: Record<string, number> = {};
for (const g of gaps) {
for (const field of g.missingFields) {
fieldCounts[field] = (fieldCounts[field] || 0) + 1;
}
}
const sortedFields = Object.entries(fieldCounts)
.sort(([, a], [, b]) => b - a);
console.log(`\n Most common missing fields:`);
for (const [field, count] of sortedFields.slice(0, 10)) {
const pct = ((count / gaps.length) * 100).toFixed(0);
console.log(` ${field}: ${count} (${pct}%)`);
}
// ============================================================================
// What-if scenarios — match by dimension (not label text)
// ============================================================================
console.log('\n━━━ What-If Scenarios ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
const scenarios: WhatIfScenario[] = [];
// Helper: compute what-if by dimension
function whatIfByDimension(dimensionId: string): { affected: number; wouldGraduate: number } {
let affected = 0;
let wouldGraduate = 0;
for (const g of gaps) {
const dimPoints = g.topImprovements
.filter(i => i.dimension === dimensionId)
.reduce((sum, i) => sum + i.points, 0);
if (dimPoints > 0) {
affected++;
if (g.readinessScore + dimPoints >= RECHERCHIERT_THRESHOLD) {
wouldGraduate++;
}
}
}
return { affected, wouldGraduate };
}
// Scenario: fix all tailoring fields (themes, purposeSummary, researchNotes, pastGrantees, applicationProcess)
const tailoring = whatIfByDimension('tailoring');
scenarios.push({
field: 'tailoring (themes, purpose, notes, process)',
description: 'Fill all tailoring intelligence fields',
affectedCount: tailoring.affected,
wouldGraduate: tailoring.wouldGraduate,
});
// Scenario: fix all actionability fields (contact, applicationUrl, method, deadline)
const actionability = whatIfByDimension('actionability');
scenarios.push({
field: 'actionability (contact, URL, method, deadline)',
description: 'Fill all actionability fields',
affectedCount: actionability.affected,
wouldGraduate: actionability.wouldGraduate,
});
// Scenario: fix all financial fields (amount range, budget, capital)
const financial = whatIfByDimension('financial');
scenarios.push({
field: 'financial (grant range, budget, capital)',
description: 'Fill all financial calibration fields',
affectedCount: financial.affected,
wouldGraduate: financial.wouldGraduate,
});
// Scenario: combined — all possible improvements
const allCombined = gaps.filter(g => {
const totalGain = g.topImprovements.reduce((sum, i) => sum + i.points, 0);
return g.readinessScore + totalGain >= RECHERCHIERT_THRESHOLD;
});
scenarios.push({
field: 'all dimensions combined',
description: 'Fill ALL missing fields (maximum possible from top 5 improvements)',
affectedCount: gaps.length,
wouldGraduate: allCombined.length,
});
// Specific what-if: just add 1 point (many are at 44)
const onePointAway = gaps.filter(g => g.pointsNeeded <= 1);
scenarios.push({
field: 'any single field (+1 point minimum)',
description: 'Foundations needing just 1 more point to graduate',
affectedCount: onePointAway.length,
wouldGraduate: onePointAway.length,
});
// Score distribution
const scoreDistribution: Record<string, number> = {};
for (const g of gaps) {
const bucket = `${Math.floor(g.readinessScore / 5) * 5}-${Math.floor(g.readinessScore / 5) * 5 + 4}`;
scoreDistribution[bucket] = (scoreDistribution[bucket] || 0) + 1;
}
console.log('\n Score distribution (gap foundations):');
for (const [bucket, count] of Object.entries(scoreDistribution).sort()) {
const bar = '█'.repeat(Math.ceil(count / 5));
console.log(` ${bucket.padStart(5)}: ${String(count).padStart(4)} ${bar}`);
};
for (const s of scenarios) {
console.log(`\n If we add "${s.field}":`);
console.log(` Affected: ${s.affectedCount} foundations`);
console.log(` Would graduate to recherchiert: ${s.wouldGraduate}`);
}
// ============================================================================
// Easy wins — foundations closest to graduating
// ============================================================================
console.log('\n━━━ Easy Wins (closest to recherchiert) ━━━━━━━━━━━━━━━━━━━━━━━');
const easyWins = gaps
.filter(g => g.pointsNeeded <= 20)
.slice(0, 20);
console.log(` Foundations within 20 points of recherchiert: ${easyWins.length}`);
for (const g of easyWins) {
console.log(` P${g.priority} | ${g.readinessScore}/100 (need +${g.pointsNeeded}) | ${g.name}`);
if (VERBOSE) {
for (const imp of g.topImprovements.slice(0, 3)) {
console.log(` → +${imp.points} pts: ${imp.label}`);
}
}
}
// ============================================================================
// Per-foundation breakdown (verbose)
// ============================================================================
if (VERBOSE) {
console.log('\n━━━ Full Gap Breakdown ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
for (const g of gaps.slice(0, 50)) {
console.log(`\n ${g.name} (P${g.priority}, fit=${g.fitScore})`);
console.log(` Score: ${g.readinessScore}/100 → ${g.tier} (need +${g.pointsNeeded} for recherchiert)`);
console.log(` Top improvements:`);
for (const imp of g.topImprovements) {
console.log(` +${imp.points} pts: ${imp.label} (${imp.dimension})`);
}
}
}
// ============================================================================
// Write output
// ============================================================================
const today = new Date().toISOString().split('T')[0];
const outDir = path.resolve('research/diagnostics');
fs.mkdirSync(outDir, { recursive: true });
const outFile = path.join(outDir, `p1p3-gaps-${today}.json`);
const report = {
date: today,
summary: {
totalFoundations: total,
totalP1P3: p1p3.length,
alreadyQualified,
belowRecherchiert: gaps.length,
byPriority,
byTier,
currentGesuchPages: alreadyQualified,
},
missingFieldCounts: Object.fromEntries(sortedFields),
scenarios: scenarios.map(s => ({
field: s.field,
description: s.description,
affectedCount: s.affectedCount,
wouldGraduate: s.wouldGraduate,
})),
easyWins: easyWins.map(g => ({
slug: g.slug,
name: g.name,
priority: g.priority,
readinessScore: g.readinessScore,
pointsNeeded: g.pointsNeeded,
topImprovements: g.topImprovements,
})),
gaps: gaps.map(g => ({
slug: g.slug,
name: g.name,
priority: g.priority,
fitScore: g.fitScore,
readinessScore: g.readinessScore,
tier: g.tier,
pointsNeeded: g.pointsNeeded,
topImprovements: g.topImprovements,
missingFields: g.missingFields,
})),
};
fs.writeFileSync(outFile, JSON.stringify(report, null, 2));
console.log(`\n Report written to: ${outFile}`);
// Summary
console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(` Current Gesuch-ready: ${alreadyQualified}`);
console.log(` P1-P3 gap (below recherchiert): ${gaps.length}`);
console.log(` Best-case with all enrichment: +${allCombined.length} → ~${alreadyQualified + allCombined.length} Gesuch pages`);
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
}
main();
-76
View File
@@ -1,76 +0,0 @@
#!/usr/bin/env tsx
/**
* Dump candidate data for inline Claude triage.
* Reads phase1 results + DB purpose text → outputs JSON for analysis.
*/
import { config } from 'dotenv';
config({ path: '.env.local' });
import * as fs from 'fs';
import * as path from 'path';
import { neon } from '@neondatabase/serverless';
const MIN_FIT = parseInt(process.argv.find(a => a.startsWith('--min-fit='))?.split('=')[1] || '4', 10);
const BATCH_SIZE = parseInt(process.argv.find(a => a.startsWith('--batch='))?.split('=')[1] || '50', 10);
const BATCH_NUM = parseInt(process.argv.find(a => a.startsWith('--batch-num='))?.split('=')[1] || '0', 10);
async function main() {
const sql = neon(process.env.DATABASE_URL!);
// Load phase1 candidates
const today = new Date().toISOString().split('T')[0];
const phase1File = path.resolve(`research/pipeline-graduate/phase1-${today}.json`);
const phase1 = JSON.parse(fs.readFileSync(phase1File, 'utf-8'));
// Load processed slugs
const processedFile = path.resolve(`research/pipeline-graduate/phase2-processed-${today}.json`);
const processed = new Set<string>(
fs.existsSync(processedFile) ? JSON.parse(fs.readFileSync(processedFile, 'utf-8')) : []
);
// Filter high-value unprocessed
const candidates = phase1.items.filter((i: any) =>
(i.themes.length > 0 || i.funderScore >= 2) &&
!processed.has(i.slug) &&
i.fitScore >= MIN_FIT
);
// Get batch
const start = BATCH_NUM * BATCH_SIZE;
const batch = candidates.slice(start, start + BATCH_SIZE);
if (batch.length === 0) {
console.error(`No candidates in batch ${BATCH_NUM} (total: ${candidates.length})`);
process.exit(1);
}
// Fetch purpose text from DB
const slugs = batch.map((c: any) => c.slug);
const rows = await sql`
SELECT
f.id as slug,
f.name,
COALESCE(f.config_data->>'officialPurpose', f.config_data->>'purposeSummary') as purpose
FROM fundraising_foundations f
WHERE f.id = ANY(${slugs})
` as { slug: string; name: string; purpose: string | null }[];
const purposeMap = new Map(rows.map(r => [r.slug, r.purpose || '']));
// Build output
const output = batch.map((c: any) => ({
slug: c.slug,
name: c.name,
fitScore: c.fitScore,
themes: c.themes,
funderScore: c.funderScore,
operatorScore: c.operatorScore,
isFunder: c.isFunder,
purpose: (purposeMap.get(c.slug) || '').substring(0, 500),
}));
console.log(JSON.stringify(output, null, 2));
console.error(`Batch ${BATCH_NUM}: ${output.length} candidates (${start}-${start + batch.length} of ${candidates.length})`);
}
main().catch(err => { console.error(err); process.exit(1); });
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env tsx
import { config } from 'dotenv';
import { neon } from '@neondatabase/serverless';
config({ path: '.env.local' });
const sql = neon(process.env.DATABASE_URL!);
// Foundations researched with Claude internal Agent (batches 23p, 23q, 23r)
// These were mislabeled as chatgpt-agent — fix to claude-agent
const slugs = [
'prototype-fund', 'minerva', 'sens-suisse', 'hans-trachsler-fonds', 'camille-graeser-stiftung',
'albert-lueck-stiftung', 'eranus-stiftung', 'anna-caroline-stiftung', 'orphelina-stiftung', 'credit-suisse-foundation',
'swiss-re-foundation-carolina-hess', 'fuer-die-kinder-fuer-die-zukunft', 'leo-future', 'elisabeth-weber-stiftung', 'coop-nachhaltigkeit',
];
async function main() {
for (const slug of slugs) {
const result = await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{applicationResearchMethod}', '"claude-agent"')
WHERE id = ${slug}
AND config_data->>'applicationResearchMethod' = 'chatgpt-agent'
RETURNING id
`;
console.log(result.length > 0 ? ` fixed: ${slug}` : ` skipped (not chatgpt-agent): ${slug}`);
}
console.log('Done.');
}
main().catch(console.error);
-72
View File
@@ -1,72 +0,0 @@
/**
* Full-rescore: recompute fitScore for ALL foundations in the generated file.
* Reports foundations where computed score differs from stored, then optionally applies.
* Only upgrades — never downgrades.
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { computeFitScore } from '../src/lib/domain/fit-scoring';
const sql = neon(process.env.DATABASE_URL!);
const DRY_RUN = process.argv.includes('--dry-run');
const MIN_DELTA = parseInt(process.argv.find(a => a.startsWith('--min-delta='))?.split('=')[1] || '1');
async function main() {
console.log(`=== Full rescore (min delta=${MIN_DELTA}, mode=${DRY_RUN ? 'DRY RUN' : 'LIVE'}) ===\n`);
// Only rescore foundations in the generated file (data_confidence != unverified)
const rows = await sql`
SELECT id, fit_score, priority, config_data
FROM fundraising_foundations
WHERE (data_confidence IS NULL OR data_confidence != 'unverified')
AND (archived IS NULL OR archived = false)
ORDER BY fit_score DESC
`;
let improved = 0, same = 0, would_downgrade = 0;
const upgrades: Array<{slug: string; old: number; new_: number; priority: number; themes: string[]}> = [];
for (const row of rows) {
const cd = row.config_data as Record<string, unknown>;
const result = computeFitScore(cd as unknown as Parameters<typeof computeFitScore>[0]);
const computed = result.fitScore;
const stored = row.fit_score as number;
if (computed > stored && (computed - stored) >= MIN_DELTA) {
improved++;
upgrades.push({ slug: row.id as string, old: stored, new_: computed, priority: row.priority as number, themes: (cd.themes as string[]) || [] });
} else if (computed < stored) {
would_downgrade++;
} else {
same++;
}
}
console.log(`Total: ${rows.length}, Upgrades (delta>=${MIN_DELTA}): ${improved}, Same: ${same}, Would-downgrade (skipped): ${would_downgrade}\n`);
// Show top upgrades
const top = upgrades.sort((a, b) => (b.new_ - b.old) - (a.new_ - a.old) || b.new_ - a.new_);
console.log(`Top upgrades:`);
for (const u of top.slice(0, 30)) {
console.log(` ${u.old}→${u.new_} | P${u.priority} | ${u.slug} | ${u.themes.join(',')}`);
}
if (!DRY_RUN && improved > 0) {
console.log(`\nApplying ${improved} upgrades...`);
let done = 0;
for (const u of upgrades) {
const [row] = await sql`SELECT config_data FROM fundraising_foundations WHERE id = ${u.slug}`;
if (!row) continue;
await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{fitScore}', ${u.new_}::jsonb),
updated_at = NOW()
WHERE id = ${u.slug}
`;
done++;
if (done % 50 === 0) console.log(` ${done}/${improved} done...`);
}
console.log(`Applied ${done} upgrades. Next: npm run sync`);
}
}
main().catch(console.error);
-26
View File
@@ -1,26 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const SLUGS = [
'education-and-social-foundation-bildung-und-soziales-stiftun',
'sozial-bildungsfonds-des-kaufmaennischen-verbandes-schweiz',
'stiftung-fuer-alphabetisierung-und-grundbildung-schweiz',
'cleantech21-foundation',
'gemeinnuetzige-gesellschaft-des-bezirks-uster',
'hand-in-hand-stiftung-fuer-eine-nachhaltige-entwicklung',
'hugo-bachmann-stiftung-fuer-nachhaltigkeit',
'impact-corner-stiftung',
'stiftung-fokus-frauen',
];
async function main() {
for (const slug of SLUGS) {
const [r] = await sql`SELECT config_data FROM fundraising_foundations WHERE id = ${slug}`;
if (!r) continue;
const cd = r.config_data as Record<string, unknown>;
const uid = cd.uid as string || '';
const name = cd.name as string || slug;
const zefix = cd.websiteUrl as string || '';
console.log(`${name} | ${uid} | ${zefix}`);
}
}
main().catch(console.error);
-25
View File
@@ -1,25 +0,0 @@
import { config } from 'dotenv';
config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
async function main() {
const offset = parseInt(process.argv[2] || '0');
const sql = neon(process.env.DATABASE_URL!);
const rows = await sql`
SELECT id as slug, name,
(config_data->>'fitScore')::int as fit,
config_data->>'applicationResearchMethod' as method
FROM fundraising_foundations
WHERE research_depth IN ('standard','deep')
AND priority = 4
AND (
config_data->>'applicationResearchMethod' IS NULL
OR config_data->>'applicationResearchMethod' NOT IN ('claude-agent','chatgpt-agent','manual')
)
AND archived = false
ORDER BY (config_data->>'fitScore')::int DESC NULLS LAST, name
LIMIT 10 OFFSET ${offset}
`;
rows.forEach((r: any) => console.log(r.fit, r.slug, '|', r.name, '|', r.method));
}
main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); });
-69
View File
@@ -1,69 +0,0 @@
/**
* Re-score foundations whose themes were enriched via claude-agent research
* but whose fitScore was never recomputed. Updates config_data.fitScore;
* the DB trigger syncs flat fit_score column automatically.
* Then run: npm run sync (to propagate priority changes)
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { computeFitScore } from '../src/lib/domain/fit-scoring';
const sql = neon(process.env.DATABASE_URL!);
const DRY_RUN = process.argv.includes('--dry-run');
const SLUGS = [
'start-foundation',
'education-and-social-foundation-bildung-und-soziales-stiftun',
'sozial-bildungsfonds-des-kaufmaennischen-verbandes-schweiz',
'stiftung-fuer-alphabetisierung-und-grundbildung-schweiz',
'cleantech21-foundation',
'gemeinnuetzige-gesellschaft-des-bezirks-uster',
'hand-in-hand-stiftung-fuer-eine-nachhaltige-entwicklung',
'hugo-bachmann-stiftung-fuer-nachhaltigkeit',
'impact-corner-stiftung',
'limmat-stiftung',
'pro-patria-schweiz-bundesfeierspende',
'stiftung-fokus-frauen',
'fondation-hans-wilsdorf',
'schoepflin-stiftung-assoziierter-partner',
];
async function main() {
console.log(`=== Re-score enriched foundations ===`);
console.log(`Mode: ${DRY_RUN ? 'DRY RUN' : 'LIVE'}\n`);
let updated = 0;
for (const slug of SLUGS) {
const [row] = await sql`SELECT id, fit_score, priority, config_data FROM fundraising_foundations WHERE id = ${slug}`;
if (!row) { console.log(` ❌ NOT FOUND: ${slug}`); continue; }
const cd = row.config_data as Record<string, unknown>;
const result = computeFitScore(cd as unknown as Parameters<typeof computeFitScore>[0]);
const newScore = result.fitScore;
const oldScore = row.fit_score as number;
// Only update if the score would increase (never downgrade)
if (newScore <= oldScore) {
console.log(` = ${slug} (fit_score=${oldScore}, no change needed)`);
continue;
}
console.log(` ↑ ${slug}: fit_score ${oldScore}→${newScore} (themes: ${(cd.themes as string[])?.join(',')})`);
if (!DRY_RUN) {
await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{fitScore}', ${newScore}::jsonb),
updated_at = NOW()
WHERE id = ${slug}
`;
}
updated++;
}
console.log(`\nUpdated: ${updated} foundations`);
if (!DRY_RUN && updated > 0) {
console.log('Next: npm run sync (recomputes priority from new fitScore)');
}
}
main().catch(console.error);
-320
View File
@@ -1,320 +0,0 @@
#!/usr/bin/env tsx
/**
* Re-score Phase2 results with stricter LLM prompt
*
* Problem: Phase2 LLM is hallucinating themes on medical/sports/culture foundations.
* This script re-runs Phase2 triage with a MUCH stricter prompt that explicitly
* rejects off-topic foundations and validates theme assignments.
*
* Usage:
* npx tsx scripts/rescore-phase2.ts # Re-score today's batch
* npx tsx scripts/rescore-phase2.ts --date=2026-03-28 # Specific date
* npx tsx scripts/rescore-phase2.ts --dry-run # Preview only
* npx tsx scripts/rescore-phase2.ts --limit=50 # Cap LLM calls
*/
import { config } from 'dotenv';
config({ path: '.env.local' });
import * as fs from 'fs';
import * as path from 'path';
import { computeFitScore } from '../src/lib/domain/fit-scoring';
import { THEME_LABELS } from './lib/theme-classifier';
import { callGroqJSON } from './lib/groq-client';
import { sleep } from './lib/utilities';
import { THEMES } from '../src/lib/config/foundations/metadata';
import { ThemeId } from '../src/lib/schemas/foundation';
// ============================================================================
// CLI ARGS
// ============================================================================
const args = process.argv.slice(2);
const DRY_RUN = args.includes('--dry-run');
const DATE_ARG = args.find(a => a.startsWith('--date='))?.split('=')[1];
const LIMIT = parseInt(args.find(a => a.startsWith('--limit='))?.split('=')[1] || '0', 10) || Infinity;
const DELAY_MS = parseInt(args.find(a => a.startsWith('--delay='))?.split('=')[1] || '2000', 10);
// ============================================================================
// TYPES
// ============================================================================
interface TriageResult {
slug: string;
name: string;
fitScore: number;
priority: number;
themes: string[];
purposeSummary: string;
researchNotes: string;
isFunder: boolean;
funderConfidence: string;
applicationMethod: string;
suggestedType: string;
}
const VALID_THEME_IDS: Set<string> = new Set(ThemeId.options);
const AVAILABLE_THEMES = Object.values(THEMES)
.map(t => ` "${t.id}": ${t.label} — ${t.description}`)
.join('\n');
// ============================================================================
// STRICT TRIAGE PROMPT — Reject hallucinations
// ============================================================================
const STRICT_TRIAGE_SYSTEM_PROMPT = `Du bist ein Schweizer Stiftungsexperte. Bewerte STRENG, ob diese Stiftung für Revamp-IT relevant ist.
## Über Revamp-IT (Kurzprofil)
- **Kerngeschäft**: IT-Geräte refurbishing (Hardware aufbereiten, nicht Forschung)
- **Soziale Mission**: Arbeitsintegration (8-10 Praktikumsplätze für Sozialhilfe/RAV/IV-Bezüger)
- **Bildung**: Linux-Kurse, Reparatur-Workshops (IT-fokussiert, keine allgemeine Bildung)
- **Standort**: Zürich (gemeinnütziger Verein seit 2009)
- **Kreislaufwirtschaft**: E-Waste, Ressourcenschonung, Secondhand-IT
## WICHTIG: Was IST KEINE Passung
**MEDIZIN/GESUNDHEIT**: Krebsforschung, Herz-Kreislauf, Kliniken, Spitäler, Pflege → **KEINE PASSUNG**
**SPORT**: Fussball, Leichtathletik, Sportförderung → **KEINE PASSUNG**
**KULTUR/KUNST**: Musik, Theater, Film, Denkmalpflege, Literatur → **KEINE PASSUNG**
**LANDWIRTSCHAFT**: Bauernhöfe, ökologischer Anbau → **KEINE PASSUNG**
**ALLGEMEINE BILDUNG**: Schulen, Universitäten, Stipendien (ohne IT/Digital-Fokus) → **KEINE PASSUNG**
**INTERNATIONALE ENTWICKLUNG**: Afrika, Asien, Südamerika (ohne CH-Fokus) → **KEINE PASSUNG**
## WICHTIG: Themen-Validierung
Weise NUR Themen zu, die **EXPLIZIT** im Stiftungszweck stehen:
- "arbeitsintegration": NUR wenn "berufliche Integration", "Arbeitsmarkt", "Beschäftigungsmassnahmen" WÖRTLICH vorkommen
- "digitale-bildung": NUR wenn "IT", "Informatik", "digitale Kompetenz", "Medienkompetenz" WÖRTLICH vorkommen
- "kreislaufwirtschaft": NUR wenn "Recycling", "Ressourcen", "Kreislauf", "Wiederverwendung" WÖRTLICH vorkommen
- "soziale-integration": NUR wenn "Benachteiligte", "Migration", "Randgruppen", "soziale Teilhabe" WÖRTLICH vorkommen
**Keine Halluzinationen**: Wenn der Stiftungszweck "Krebsforschung" sagt, hat er NICHTS mit IT, Arbeitsintegration oder Kreislaufwirtschaft zu tun.
## Verfügbare Themen
${AVAILABLE_THEMES}
## JSON-Format (STRENG validieren)
{
"isFunder": boolean,
"funderConfidence": "high"|"medium"|"low",
"themes": ["theme-id", ...], // NUR wenn EXPLIZIT im Zweck
"suggestedType": "A"|"B"|"C"|"D"|"network",
"suggestedFit": 0-3, // 0 = keine Passung, 1-3 = Passung
"suggestedPriority": 1-4,
"purposeSummary": "string (150+ Zeichen, spezifische Förderbereiche)",
"researchNotes": "string (100+ Zeichen, EHRLICHE Passung-Einschätzung)",
"applicationMethod": "online"|"email"|"invitation"|"unknown",
"warnings": []
}
WICHTIG:
- Schweizer Schriftdeutsch (ss statt ß)
- Nur valides JSON
- Bei KEINER Passung: themes=[], suggestedFit=0, researchNotes="Keine Passung zu Revamp-IT"`;
function buildTriagePrompt(item: TriageResult, phase1: any): string {
const lines = [
`# ${item.name}`,
'',
'## Offizieller Stiftungszweck (ESA/ZHAW)',
phase1.officialPurpose.substring(0, 1500),
'',
`## Bisherige (möglicherweise falsche) Bewertung`,
`Themes: ${item.themes.map(t => THEME_LABELS[t] || t).join(', ') || 'keine'}`,
`FitScore: ${item.fitScore}/10`,
`isFunder: ${item.isFunder}`,
'',
'**Prüfe kritisch**: Passt diese Stiftung WIRKLICH zu Revamp-IT (IT-Refurbishing + Arbeitsintegration)?',
'Bitte bewerte EHRLICH als JSON.',
];
return lines.join('\n');
}
// ============================================================================
// MAIN
// ============================================================================
async function main() {
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(' Re-score Phase2 with Strict Prompt');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
if (DRY_RUN) console.log(' DRY RUN — preview only');
const today = DATE_ARG || new Date().toISOString().split('T')[0];
const outDir = path.resolve('research/pipeline-graduate');
// Load Phase 1 and Phase 2 results
const phase1File = path.join(outDir, `phase1-${today}.json`);
const phase2File = path.join(outDir, `phase2-results-${today}.json`);
if (!fs.existsSync(phase1File) || !fs.existsSync(phase2File)) {
console.error(` Missing files for ${today}. Run pipeline-graduate first.`);
process.exit(1);
}
const phase1Data = JSON.parse(fs.readFileSync(phase1File, 'utf-8'));
const phase2Data = JSON.parse(fs.readFileSync(phase2File, 'utf-8'));
// Build lookup from Phase1 (for officialPurpose)
const phase1Lookup = new Map<string, any>();
for (const item of phase1Data.items) {
phase1Lookup.set(item.slug, item);
}
// Filter: only re-score items with fitScore >= 4 (the ones we care about)
const toRescore = (phase2Data.items as TriageResult[])
.filter(item => item.fitScore >= 4)
.slice(0, Math.min(LIMIT, Infinity));
console.log(` Phase2 items: ${phase2Data.items.length}`);
console.log(` FitScore >= 4: ${toRescore.length}`);
console.log(` Re-scoring: ${Math.min(toRescore.length, LIMIT)}`);
if (!process.env.GROQ_API_KEY) {
console.error(' GROQ_API_KEY not set.');
process.exit(1);
}
const corrected: TriageResult[] = [];
const unchanged: TriageResult[] = [];
let errors = 0;
let tokensUsed = 0;
for (let i = 0; i < toRescore.length; i++) {
const item = toRescore[i];
const phase1 = phase1Lookup.get(item.slug);
if (!phase1) {
console.error(` ${item.slug}: No Phase1 data found, skipping`);
continue;
}
const progress = `[${i + 1}/${toRescore.length}]`;
const prompt = buildTriagePrompt(item, phase1);
console.log(` ${progress} ${item.name} (old fit=${item.fitScore})...`);
if (DRY_RUN && i >= 3) {
console.log(` DRY RUN — stopping after 3 previews`);
break;
}
const groqResult = await callGroqJSON<Record<string, unknown>>(
STRICT_TRIAGE_SYSTEM_PROMPT, prompt,
{ maxTokens: 512, temperature: 0.2, timeoutMs: 30_000 },
);
if (!groqResult.ok) {
console.error(` ERROR: ${groqResult.error}`);
errors++;
await sleep(DELAY_MS * 2);
continue;
}
if (groqResult.usage) {
tokensUsed += groqResult.usage.prompt_tokens + groqResult.usage.completion_tokens;
}
const raw = groqResult.data;
// Extract and validate themes
const rawThemes = Array.isArray(raw.themes) ? raw.themes : [];
const validThemes = rawThemes.filter((t: unknown) =>
typeof t === 'string' && VALID_THEME_IDS.has(t)
) as string[];
// Compute real fitScore from LLM themes (algorithmic)
const applicationMethod = (raw.applicationMethod as string) || 'unknown';
const isFunder = typeof raw.isFunder === 'boolean' ? raw.isFunder : item.isFunder;
const { fitScore: algoScore } = computeFitScore({
themes: validThemes,
canton: phase1.canton,
city: phase1.city,
applicationMethod,
isFunder,
});
// LLM's contextual assessment (0-3 scale → map to 0-10)
const LLM_FIT_MAP = [0, 4, 6, 8] as const;
const suggestedFit = typeof raw.suggestedFit === 'number' ? Math.min(3, Math.max(0, Math.round(raw.suggestedFit))) : 0;
const llmScore = LLM_FIT_MAP[suggestedFit] ?? 0;
// Use best of algorithmic and LLM-assessed score
const newFitScore = Math.max(algoScore, llmScore);
// Priority from fitScore
const isZurich = phase1.canton === 'ZH';
let priority: 1 | 2 | 3 | 4;
if (newFitScore >= 7 && isFunder) priority = 1;
else if (newFitScore >= 4 && (isFunder || isZurich)) priority = 2;
else if (newFitScore >= 4) priority = 3;
else priority = 4;
const correctedItem: TriageResult = {
slug: item.slug,
name: item.name,
fitScore: newFitScore,
priority,
themes: validThemes,
purposeSummary: (raw.purposeSummary as string) || item.purposeSummary,
researchNotes: (raw.researchNotes as string) || item.researchNotes,
isFunder,
funderConfidence: (raw.funderConfidence as string) || 'low',
applicationMethod,
suggestedType: (raw.suggestedType as string) || 'C',
};
const changed = newFitScore !== item.fitScore || validThemes.join(',') !== item.themes.join(',');
if (changed) {
corrected.push(correctedItem);
const oldFit = item.fitScore >= 7 ? '★★★' : item.fitScore >= 4 ? '★★☆' : '★☆☆';
const newFit = newFitScore >= 7 ? '★★★' : newFitScore >= 4 ? '★★☆' : '★☆☆';
console.log(` CORRECTED: ${item.fitScore} ${oldFit} → ${newFitScore} ${newFit}`);
console.log(` Old themes: [${item.themes.join(',')}]`);
console.log(` New themes: [${validThemes.join(',')}]`);
} else {
unchanged.push(correctedItem);
console.log(` OK: fit=${newFitScore}, themes=[${validThemes.join(',')}]`);
}
if (i < toRescore.length - 1) {
await sleep(DELAY_MS);
}
}
console.log(`\n Re-scoring complete: ${corrected.length} corrected, ${unchanged.length} unchanged, ${errors} errors`);
console.log(` Tokens used: ${tokensUsed}`);
// Save corrected results
if (!DRY_RUN && corrected.length > 0) {
const correctedFile = path.join(outDir, `phase2-corrected-${today}.json`);
// Merge with unchanged items and original low-fit items
const allItems = [
...corrected,
...unchanged,
...(phase2Data.items as TriageResult[]).filter((item: TriageResult) => item.fitScore < 4),
];
fs.writeFileSync(correctedFile, JSON.stringify({
date: today,
total: allItems.length,
correctedCount: corrected.length,
items: allItems.sort((a, b) => b.fitScore - a.fitScore),
}, null, 2));
console.log(` Corrected results: ${correctedFile}`);
// Summary of corrections
const demotedToZero = corrected.filter(c => c.fitScore === 0).length;
const stillHighFit = corrected.filter(c => c.fitScore >= 7).length;
console.log(`\n Summary:`);
console.log(` Demoted to fitScore=0: ${demotedToZero}`);
console.log(` Still fitScore>=7: ${stillHighFit}`);
}
}
main().catch((err) => {
console.error('Re-scoring failed:', err);
process.exit(1);
});
-53
View File
@@ -1,53 +0,0 @@
#!/usr/bin/env tsx
/**
* Shows foundations that need ChatGPT agent re-research:
* 1. claude-agent results with missing/unknown data (blocked sites, SSL errors, etc.)
* 2. Count of foundations not yet researched at all
*/
import { config } from 'dotenv';
import { neon } from '@neondatabase/serverless';
import { RESEARCHED_METHODS } from '../src/lib/schemas/foundation';
config({ path: '.env.local' });
const sql = neon(process.env.DATABASE_URL!);
async function main() {
// claude-agent results that are incomplete
const incomplete = await sql`
SELECT id, name, config_data->>'websiteUrl' as website,
config_data->>'purposeSummary' as purposeSummary,
config_data->>'acceptsApplications' as accepts
FROM fundraising_foundations
WHERE priority IN (1,2,3) AND research_depth != 'rapid' AND archived = false
AND config_data->>'applicationResearchMethod' = 'claude-agent'
AND (
config_data->>'purposeSummary' IS NULL
OR config_data->>'acceptsApplications' = 'unknown'
OR config_data->>'acceptsApplications' IS NULL
)
ORDER BY priority ASC, fit_score DESC
`;
console.log('=== claude-agent results needing ChatGPT upgrade ===');
for (const r of incomplete) {
const reason = !r.purposesummary ? 'no purposeSummary (blocked/SSL)' : `acceptsApplications=${r.accepts||'null'}`;
console.log(` ${r.id} | ${(r.name as string).padEnd(45)} | ${reason} | ${r.website||'-'}`);
}
console.log(`\n Total needing upgrade: ${incomplete.length}`);
// Not yet researched at all — filter in JS using RESEARCHED_METHODS as SSOT
const _all = await sql`
SELECT COUNT(*) as count
FROM fundraising_foundations
WHERE priority IN (1,2,3) AND research_depth != 'rapid' AND archived = false
AND id NOT IN ('seif','stiftung-raphael','jugendhilfeverein-des-bezirkes-dielsdorf','z43-netzero','responsability')
`;
const remaining = await sql`
SELECT config_data->>'applicationResearchMethod' as method
FROM fundraising_foundations
WHERE priority IN (1,2,3) AND research_depth != 'rapid' AND archived = false
AND id NOT IN ('seif','stiftung-raphael','jugendhilfeverein-des-bezirkes-dielsdorf','z43-netzero','responsability')
`;
const notResearched = remaining.filter(r => !RESEARCHED_METHODS.includes((r.method || 'unknown') as any));
console.log(`\n=== Not yet researched (P1-P3, non-rapid): ${notResearched.length} foundations ===`);
}
main().catch(console.error);
-36
View File
@@ -1,36 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { computeFitScore } from '../src/lib/domain/fit-scoring';
const sql = neon(process.env.DATABASE_URL!);
const SLUGS = [
'start-foundation',
'education-and-social-foundation-bildung-und-soziales-stiftun',
'sozial-bildungsfonds-des-kaufmaennischen-verbandes-schweiz',
'stiftung-fuer-alphabetisierung-und-grundbildung-schweiz',
'cleantech21-foundation',
'gemeinnuetzige-gesellschaft-des-bezirks-uster',
'hand-in-hand-stiftung-fuer-eine-nachhaltige-entwicklung',
'hugo-bachmann-stiftung-fuer-nachhaltigkeit',
'impact-corner-stiftung',
'limmat-stiftung',
'pro-patria-schweiz-bundesfeierspende',
'stiftung-fokus-frauen',
'fondation-hans-wilsdorf',
'schoepflin-stiftung-assoziierter-partner',
];
async function main() {
for (const slug of SLUGS) {
const [row] = await sql`SELECT id, fit_score, priority, config_data FROM fundraising_foundations WHERE id = ${slug}`;
if (!row) { console.log(`NOT FOUND: ${slug}`); continue; }
const cd = row.config_data as Record<string, unknown>;
const result = computeFitScore(cd as unknown as Parameters<typeof computeFitScore>[0]);
const delta = result.fitScore - (row.fit_score as number);
const themes = (cd.themes as string[])?.join(',') || 'none';
const marker = delta > 0 ? `↑ ${row.fit_score}→${result.fitScore}` : `= ${row.fit_score}`;
console.log(`${marker.padEnd(8)} | P${row.priority} | ${slug.substring(0,45)} | ${themes}`);
}
}
main().catch(console.error);
-30
View File
@@ -1,30 +0,0 @@
/**
* Upgrade rapid foundations whose real website URLs were found in applicationProcess text.
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const UPGRADES = [
{ slug: 'limmat-stiftung', url: 'https://www.limmatstiftung.ch' },
{ slug: 'pro-patria-schweiz-bundesfeierspende', url: 'https://www.propatria.ch' },
];
async function main() {
for (const { slug, url } of UPGRADES) {
const [row] = await sql`SELECT config_data FROM fundraising_foundations WHERE id = ${slug}`;
if (!row) { console.log(`NOT FOUND: ${slug}`); continue; }
const cd = row.config_data as Record<string, unknown>;
cd.websiteUrl = url;
cd.researchDepth = 'standard';
await sql`
UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd)}::jsonb,
research_depth = 'standard',
updated_at = NOW()
WHERE id = ${slug}
`;
console.log(`Updated ${slug}: websiteUrl=${url}, researchDepth=standard`);
}
}
main().catch(console.error);
-78
View File
@@ -1,78 +0,0 @@
/**
* Backfill: upgrade researchDepth from 'rapid' to 'standard' for foundations
* that already have a real website URL (not a registry/directory link).
*
* Root cause: import-research-results.ts never set researchDepth='standard'
* when it added a websiteUrl. Hundreds of foundations got real websites but
* stayed 'rapid', which kept them at P4 regardless of fitScore.
*
* After running this, run: npm run sync (recomputes priorities)
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { isRegistryUrl } from '../src/lib/config/registry-domains';
const sql = neon(process.env.DATABASE_URL!);
const DRY_RUN = process.argv.includes('--dry-run');
async function main() {
console.log(`=== Upgrade rapid→standard for foundations with real websites ===`);
console.log(`Mode: ${DRY_RUN ? 'DRY RUN' : 'LIVE'}\n`);
// Fetch all rapid non-unverified foundations with a websiteUrl set
const rows = await sql`
SELECT id, fit_score, config_data->>'websiteUrl' as url
FROM fundraising_foundations
WHERE (data_confidence IS NULL OR data_confidence != 'unverified')
AND (archived IS NULL OR archived = false)
AND config_data->>'researchDepth' = 'rapid'
AND config_data->>'websiteUrl' IS NOT NULL
AND config_data->>'websiteUrl' != ''
ORDER BY fit_score DESC
`;
// Filter out registry URLs using the same logic as the app
const toUpgrade = rows.filter(r => !isRegistryUrl(r.url as string));
console.log(`Found ${rows.length} rapid foundations with websiteUrl set`);
console.log(`Registry URLs filtered out: ${rows.length - toUpgrade.length}`);
console.log(`To upgrade: ${toUpgrade.length}\n`);
console.log('Top 10 by fitScore:');
toUpgrade.slice(0, 10).forEach(r =>
console.log(` fitScore=${r.fit_score} | ${r.id} | ${r.url}`)
);
if (DRY_RUN) {
console.log('\nDRY RUN — no changes made. Remove --dry-run to apply.');
return;
}
if (toUpgrade.length === 0) {
console.log('Nothing to upgrade.');
return;
}
// Bulk UPDATE using IN clause with the filtered IDs
const ids = toUpgrade.map(r => r.id as string);
// Process in batches of 100 to avoid parameter limits
const BATCH = 100;
let upgraded = 0;
for (let i = 0; i < ids.length; i += BATCH) {
const batch = ids.slice(i, i + BATCH);
await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{researchDepth}', '"standard"'),
updated_at = NOW()
WHERE id = ANY(${batch}::text[])
AND config_data->>'researchDepth' = 'rapid'
`;
upgraded += batch.length;
process.stdout.write(` ${upgraded}/${ids.length}...\r`);
}
console.log(`\nUpgraded ${upgraded} foundations rapid→standard`);
console.log('Next: npm run sync (recomputes priority from new researchDepth)');
}
main().catch(console.error);
-33
View File
@@ -1,33 +0,0 @@
/**
* One-time fix: start-foundation has its real website mentioned in
* applicationProcess ("startfoundation.ch") but websiteUrl still points to
* zefix. Updating to the real URL upgrades research_depth to standard.
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
async function main() {
const REAL_URL = 'https://www.startfoundation.ch';
const SLUG = 'start-foundation';
const [row] = await sql`SELECT config_data FROM fundraising_foundations WHERE id = ${SLUG}`;
if (!row) { console.error('Not found'); process.exit(1); }
const cd = row.config_data as Record<string, unknown>;
cd.websiteUrl = REAL_URL;
cd.researchDepth = 'standard'; // has real website now
await sql`
UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd)}::jsonb,
research_depth = 'standard',
updated_at = NOW()
WHERE id = ${SLUG}
`;
console.log(`Updated ${SLUG}: websiteUrl=${REAL_URL}, researchDepth=standard`);
console.log('Next: npm run sync (priority will be recomputed)');
}
main().catch(console.error);
-27
View File
@@ -1,27 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const UPGRADES = [
{ slug: 'cleantech21-foundation', url: 'https://www.cleantech21.org' },
{ slug: 'stiftung-fokus-frauen', url: 'https://www.fokusfrauen.ch' },
];
async function main() {
for (const { slug, url } of UPGRADES) {
const [row] = await sql`SELECT config_data FROM fundraising_foundations WHERE id = ${slug}`;
if (!row) { console.log(`NOT FOUND: ${slug}`); continue; }
const cd = row.config_data as Record<string, unknown>;
cd.websiteUrl = url;
cd.researchDepth = 'standard';
await sql`
UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd)}::jsonb,
research_depth = 'standard',
updated_at = NOW()
WHERE id = ${slug}
`;
console.log(`Updated ${slug}: ${url}`);
}
}
main().catch(console.error);
-34
View File
@@ -1,34 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const updates = [
// Confirmed application/contact pages
{ id: 'zuerich-jobs', url: 'https://stiftungzuerichjobs.ch/kontakt/' },
{ id: 'stiftung-accentus', url: 'https://www.accentus.ch/kontakt/' },
{ id: 'hans-eggenberger', url: 'https://www.hans-eggenberger-stiftung.ch/antrag.html' },
{ id: 'alfred-und-bertha-zangger-weber-stiftung', url: 'https://zanggerweberstiftung.ch/gesuchseingabe/' },
{ id: 'hans-konrad-rahn-stiftung', url: 'https://rahnstiftung.ch/gesuch-einreichen' },
{ id: 'stiftung-solidaritaet-mit-sehgeschaedigten', url: 'https://www.blind.ch/kontakt.html' },
{ id: 's-eustachius-stiftung', url: 'http://eustachius-stiftung.ch/' },
// Homepage is the only contact point
{ id: 'respact-foundation', url: 'https://www.respact-foundation.ch' },
];
async function main() {
for (const { id, url } of updates) {
const result = await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{applicationUrl}', ${JSON.stringify(url)}::jsonb),
updated_at = NOW()
WHERE id = ${id}
RETURNING id, config_data->>'applicationUrl' as url
`;
if (result.length > 0) {
console.log(`✅ ${id} → ${result[0].url}`);
} else {
console.log(`❌ NOT FOUND: ${id}`);
}
}
}
main().catch(console.error);
-30
View File
@@ -1,30 +0,0 @@
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const updates = [
{ id: 'ubs-sozialstiftung', url: 'https://www.ubs.com/global/de/ubs-society/foundations/social-issues-education/contact.html' },
{ id: 'rahn-stiftung', url: 'https://rahn-stiftung.ch/gesuch-einreichen' },
{ id: 'gruetli', url: 'https://www.gruetli-stiftung.ch/#kontakt' },
{ id: 'vontobel-stiftung', url: 'https://www.vontobel-stiftung.ch/de-ch/ihr-gesuch/' },
{ id: 'temperatio', url: 'https://www.temperatio.ch/gesuche.html' },
{ id: 'albert-lueck-stiftung', url: 'https://albert-lueck-stiftung.ch/kontakt/' },
];
async function main() {
for (const { id, url } of updates) {
const result = await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{applicationUrl}', ${JSON.stringify(url)}::jsonb),
updated_at = NOW()
WHERE id = ${id}
RETURNING id, config_data->>'applicationUrl' as url
`;
if (result.length > 0) {
console.log(`✅ ${id} → ${result[0].url}`);
} else {
console.log(`❌ NOT FOUND: ${id}`);
}
}
}
main().catch(console.error);
-86
View File
@@ -1,86 +0,0 @@
/**
* Write confirmed applicationUrls for P3 foundations — batch 6-9 (2026-04-24)
* Also fixes 3 wrong websiteUrls discovered during research.
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const applicationUrls: Array<{ id: string; url: string }> = [
// Batch 6
{ id: 'kath-kirche-zh', url: 'https://www.zhkath.ch/ueber-uns/kontakt' },
{ id: 'stiftung-fh-schweiz-zur-foerderung-des-dualen-bildungswegs', url: 'https://www.stiftungfhschweiz.ch/persoenlicher-kontakt' },
{ id: 'efort-foundation', url: 'https://www.efort.org/contact-us/' },
{ id: 'digitale-gesellschaft', url: 'https://www.digitale-gesellschaft.ch/uber-uns/kontakt/' },
{ id: 'stiftung-david-dienst-schweiz', url: 'https://stiftungdaviddienstschweiz.ch/ueber-uns/kontakt/' },
{ id: 'schwab-foundation', url: 'https://www.schwabfound.org/contact' },
{ id: 'oak-foundation-assoziierter-partner', url: 'https://oakfnd.org/submit-enquiry/' },
{ id: 'stiftung-sahee', url: 'https://www.sahee.org/pages/gesuche.php?lg=en' },
// Batch 7
{ id: 'stiftung-morgental', url: 'https://www.morgental.ch/kontakt/' },
{ id: 'arthur-waser-stiftung', url: 'https://www.arthur-waser-foundation.ch/kontakt/#gesuchstellung' },
{ id: 'stiftung-lernforum', url: 'https://www.stiftung-lernforum.ch/kontakt' },
{ id: 'emdo-stiftung', url: 'https://emdo.ch' },
{ id: 'coubertin-meets-dunant', url: 'https://coubertin-meets-dunant.ch/anmeldung' },
{ id: 'sebastiana-stiftung', url: 'https://www.sebastiana.ch/kontakt' },
{ id: 'hans-asperger-stiftung', url: 'https://www.hans-asperger-stiftung.ch/formular.html' },
{ id: 'agid-svizzer-per-la-muntogna', url: 'https://www.berghilfe.ch/gesuche/gesuch-einreichen' },
{ id: 'erwin-blaser-stiftung', url: 'https://erwin-blaser-stiftung.ch/de/kontakt.html' },
{ id: 'stiftung-luzerner-sterntaler', url: 'https://sterntaler.lu/' },
// Batch 8
{ id: 'stiftung-mckinsey-kinderhilfe-schweiz', url: 'https://www.mks-stiftung.ch/de/foerderung-beantragen/' },
{ id: 'palatin-stiftung', url: 'https://www.palatin.ch/gesuch-einreichen/' },
{ id: 'metrohm-stiftung', url: 'https://www.metrohm-stiftung.ch/gesuch/' },
{ id: 'steinegg-stiftung', url: 'https://www.steinegg.ch/kontakt' },
{ id: 'fondation-suisa', url: 'https://fondation-suisa.ch/de/gesuche/' },
{ id: 'medicor-foundation', url: 'https://www.medicor.li/grants' },
{ id: 'sanni-foundation', url: 'https://sanni-foundation.com/kontakt/' },
{ id: 'meltwater-foundation', url: 'https://meltwater.org/mest-ai-startup-program/' },
{ id: 'landscape-resilience', url: 'https://landscaperesiliencefund.org/contact-us/' },
{ id: 'stiftung-swisscontact', url: 'https://www.swisscontact.org/en/get-involved-with-us/philanthropic-engagement' },
// Batch 9
{ id: 'stipendienstiftung-reiser-siemssen-selve-gerdtzen', url: 'https://www.studienfinanzierung.uzh.ch/de/gesuche_fristen.html' },
];
// Wrong websiteUrls found during research — fix to correct domain
const fixWebsiteUrls: Array<{ id: string; url: string }> = [
// fhschweiz.ch is the alumni/association site; foundation is at stiftungfhschweiz.ch
{ id: 'stiftung-fh-schweiz-zur-foerderung-des-dualen-bildungswegs', url: 'https://www.stiftungfhschweiz.ch' },
// arthur-waser-stiftung.ch doesn't match; real domain is arthur-waser-foundation.ch
{ id: 'arthur-waser-stiftung', url: 'https://www.arthur-waser-foundation.ch' },
// stiftung-david-dienst-schweiz.ch vs stiftungdaviddienstschweiz.ch (no hyphens)
{ id: 'stiftung-david-dienst-schweiz', url: 'https://stiftungdaviddienstschweiz.ch' },
];
async function main() {
let written = 0;
console.log('Writing applicationUrls...');
for (const { id, url } of applicationUrls) {
const r = await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{applicationUrl}', ${JSON.stringify(url)}::jsonb),
updated_at = NOW()
WHERE id = ${id}
RETURNING id
`;
if (r.length > 0) { written++; process.stdout.write(` ✅ ${id}\n`); }
else process.stdout.write(` ❌ NOT FOUND: ${id}\n`);
}
console.log('\nFixing wrong websiteUrls...');
for (const { id, url } of fixWebsiteUrls) {
const r = await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{websiteUrl}', ${JSON.stringify(url)}::jsonb),
updated_at = NOW()
WHERE id = ${id}
RETURNING id
`;
if (r.length > 0) console.log(` ✅ fixed websiteUrl: ${id} → ${url}`);
else console.log(` ❌ NOT FOUND: ${id}`);
}
console.log(`\nDone: ${written}/${applicationUrls.length} applicationUrls written`);
}
main().catch(console.error);
-59
View File
@@ -1,59 +0,0 @@
/**
* Write confirmed applicationUrls for P2-P3 foundations — batch 10 (2026-04-24)
* Also fixes 1 wrong websiteUrl discovered during research.
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const applicationUrls: Array<{ id: string; url: string }> = [
// avina-stiftung: contact page; note they do NOT accept unsolicited applications
// (they approach projects proactively), but contact page is the correct applicationUrl
{ id: 'avina-stiftung', url: 'https://avinastiftung.ch/en/contact/' },
// stiftung-helene-arnold: contact page; foundation explicitly does not accept unsolicited applications
{ id: 'stiftung-helene-arnold', url: 'https://www.stiftung-helene-arnold.ch/kontakt.html' },
// wirtschaft-gesellschaft: operates through Vita Perspektiv AG; contact page confirmed live
{ id: 'wirtschaft-gesellschaft', url: 'https://vitaperspektiv.ch/ueber-uns/kontakt/' },
// templeton-stiftung: Swiss Templeton entity uses global John Templeton Foundation grant portal
{ id: 'templeton-stiftung', url: 'https://www.templeton.org/grants/apply-for-grant' },
];
// Wrong websiteUrls found during research — clear to empty
// emil-huber-stockar-stiftung: ethz.ch was set incorrectly — the actual foundation is an
// alpine accident/rescue foundation in Zollikon with no connection to ETH Zurich
const clearWebsiteUrls: Array<{ id: string; reason: string }> = [
{ id: 'emil-huber-stockar-stiftung', reason: 'ethz.ch is wrong — alpine rescue foundation, not ETH-related' },
];
async function main() {
let written = 0;
console.log('Writing applicationUrls...');
for (const { id, url } of applicationUrls) {
const r = await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{applicationUrl}', ${JSON.stringify(url)}::jsonb),
updated_at = NOW()
WHERE id = ${id}
RETURNING id
`;
if (r.length > 0) { written++; process.stdout.write(` ✅ ${id}\n`); }
else process.stdout.write(` ❌ NOT FOUND: ${id}\n`);
}
console.log('\nClearing wrong websiteUrls...');
for (const { id, reason } of clearWebsiteUrls) {
const r = await sql`
UPDATE fundraising_foundations
SET config_data = config_data - 'websiteUrl',
updated_at = NOW()
WHERE id = ${id}
RETURNING id
`;
if (r.length > 0) console.log(` ✅ cleared websiteUrl: ${id} (${reason})`);
else console.log(` ❌ NOT FOUND: ${id}`);
}
console.log(`\nDone: ${written}/${applicationUrls.length} applicationUrls written`);
}
main().catch(console.error);
-89
View File
@@ -1,89 +0,0 @@
/**
* Write applicationUrl findings from 2026-04-24 research on P3 foundations with websites.
*
* Findings:
* 1. start-foundation: www.startfoundation.ch is dead — real URL is www.start-foundation.com.
* No inbound applications accepted (they select own partners). Fix websiteUrl, set method=none.
* 2. paul-und-anna-klaproth-stiftung: klaprothstiftung.ch has form on homepage, but this is an
* individual beneficiary foundation (elderly Swiss Protestants 75+), NOT an org funder.
* Revamp-IT ineligible. Lower fit, add note.
* 3. vindobona: www.vindobona.ch is a minimal single-page site — only email (info@vindobona.ch).
* Very new (Oct 2023), no established process. Set applicationMethod=email, add email contact.
* 4. options-for-growth-foundation: partnership model — no open application. Set method=contact.
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
async function patch(
id: string,
updater: (cd: Record<string, unknown>) => void,
fitScore?: number,
): Promise<void> {
const [row] = await sql`SELECT config_data, fit_score FROM fundraising_foundations WHERE id = ${id}`;
if (!row) { console.log(` ❌ NOT FOUND: ${id}`); return; }
const cd = row.config_data as Record<string, unknown>;
updater(cd);
const fs = fitScore ?? (row.fit_score as number);
await sql`
UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd) as unknown}::jsonb,
fit_score = ${fs},
updated_at = NOW()
WHERE id = ${id}
`;
console.log(` ✅ updated: ${id}`);
}
async function main() {
// 1. start-foundation — fix dead websiteUrl, mark no inbound applications
console.log('\n1. start-foundation...');
await patch('start-foundation', (cd) => {
cd.websiteUrl = 'https://www.start-foundation.com';
cd.applicationMethod = 'none';
delete cd.applicationUrl;
cd.acceptsApplications = 'no';
cd.researchNotes = (cd.researchNotes as string | undefined) ??
'start-foundation.com — fördert Start-up-Ökosysteme (Inkubatoren, Acceleratoren) in Europa. Wählt eigene Partnerorganisationen proaktiv aus — keine offene Bewerbung. Ursprüngliche websiteUrl (startfoundation.ch) ist eine tote Domain. Für Revamp-IT nicht relevant (tech startup focus, kein Sozial-/Umweltmandat).';
});
// 2. paul-und-anna-klaproth-stiftung — individual beneficiary foundation, not org funder
console.log('\n2. paul-und-anna-klaproth-stiftung...');
await patch('paul-und-anna-klaproth-stiftung', (cd) => {
cd.applicationUrl = 'http://www.klaprothstiftung.ch/';
cd.applicationMethod = 'contact'; // form on homepage, but for individuals only
cd.acceptsApplications = 'no'; // not for organizations
const c = (cd.contact as Record<string, unknown> | null) ?? {};
c.email = 'jakob.hoehn@plplaw.ch';
c.address = 'c/o Pestalozzi Lachenal Patry AG, Löwenstrasse 1, 8001 Zürich';
c.phone = '+41 44 217 91 11';
cd.contact = c;
cd.researchNotes = 'Klaproth-Stiftung unterstützt bedürftige Schweizer Bürger:innen über 75 Jahre protestantischen Glaubens — Einzelpersonen, KEINE Organisationen. Gesuchsformular auf der Homepage. Kontakt: Dr. Jakob Höhn, Pestalozzi Lachenal Patry AG. Revamp-IT ist als Organisation nicht antragsberichtigt — Stiftungszweck richtet sich ausschliesslich an Einzelpersonen.';
cd.purposeSummary = 'Unterstützt bedürftige Schweizer Bürgerinnen und Bürger über 75 Jahre protestantischen Glaubens mit Einzelfallhilfen. Keine Förderung von Organisationen oder Projekten.';
}, 1); // fit→1 (individual beneficiaries only, ineligible for orgs)
// 3. vindobona — email contact only (minimal website)
console.log('\n3. vindobona...');
await patch('vindobona', (cd) => {
cd.applicationMethod = 'email';
cd.applicationUrl = 'https://www.vindobona.ch';
const c = (cd.contact as Record<string, unknown> | null) ?? {};
c.email = 'info@vindobona.ch';
c.address = 'Masanserstrasse 35, 7000 Chur';
cd.contact = c;
cd.researchNotes = (cd.researchNotes && String(cd.researchNotes).length > 100)
? cd.researchNotes
: 'Sehr junge Stiftung (gegr. Okt 2023), Aufsicht EDI. Website ist eine minimale Single-Page mit nur Kontaktangaben — kein Antragsformular. Kontakt: RA lic. iur. Flavia Buchli Jörimann, info@vindobona.ch. Adresse: Masanserstrasse 35, 7000 Chur. Förderbereiche: Kultur, Bildung, Antidiskriminierung, Umwelt, Kinderunterstützung, Menschenrechte, jüdische Institutionen. Kein publiziertes Bewerbungsverfahren — Anfrage per E-Mail möglich.';
});
// 4. options-for-growth-foundation — partnership model, no open application
console.log('\n4. options-for-growth-foundation...');
await patch('options-for-growth-foundation', (cd) => {
cd.applicationMethod = 'contact';
cd.applicationUrl = 'https://optionsforgrowth.ch';
cd.acceptsApplications = 'unknown'; // selective partnership model, not open application
});
console.log('\n✅ Done.');
}
main().catch(console.error);
-127
View File
@@ -1,127 +0,0 @@
/**
* P3 applicationUrl gap fixes — 2026-04-24.
*
* Research findings for 4 P3 foundations:
* - cambiata-stiftung: feeder foundation for Stiftung Mercator Schweiz (fit 5→2)
* - youthaid-foundation: developing countries focus (fit 5→3), email found
* - alice-ackermann: phone-only contact, good thematic fit (fit=4, keep)
* - hamasil-stiftung: operative Kulturpark operator, no applications (fit 4→2)
*
* Also: correct low-fit P3 gaps that don't need application research:
* - dcs-stiftung: chemistry/biology research, wrong theme (fit 3→1)
* - elsa-stiftung: no info, fit=2 already minimal
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
async function patch(
id: string,
updater: (cd: Record<string, unknown>) => void,
options?: { newFitScore?: number }
): Promise<void> {
const [row] = await sql`SELECT config_data, fit_score FROM fundraising_foundations WHERE id = ${id}`;
if (!row) { console.log(` ❌ NOT FOUND: ${id}`); return; }
const cd = row.config_data as Record<string, unknown>;
updater(cd);
const fs = options?.newFitScore ?? (row.fit_score as number);
await sql`
UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd) as unknown}::jsonb,
fit_score = ${fs},
updated_at = NOW()
WHERE id = ${id}
`;
console.log(` ✅ updated: ${id}`);
}
async function main() {
console.log('\n1. Fixing researched P3 gaps...');
// cambiata-stiftung: Feeder foundation — passes all funds to Stiftung Mercator Schweiz
await patch('cambiata-stiftung', (cd) => {
delete cd.websiteUrl; // no standalone website
cd.applicationMethod = 'none';
cd.acceptsApplications = 'no';
const c = (cd.contact as Record<string, unknown> | null) ?? {};
c.address = 'c/o Stiftung Mercator Schweiz, Gartenstrasse 33, 8002 Zürich';
c.email = 'info@stiftung-mercator.ch';
c.phone = '+41 44 206 55 80';
cd.contact = c;
cd.purposeSummary = 'Intermediäre Stiftung (gegr. von Meridian Foundation): leitet Mittel ausschliesslich an Stiftung Mercator Schweiz (Zürich) und Stiftung Mercator GmbH (Essen) weiter. Kein eigenständiges Förderprogramm für externe Organisationen. Die eigentliche Anlaufstelle für NGOs ist Stiftung Mercator Schweiz direkt.';
cd.researchNotes = 'CHE-343.217.992. Cambiata ist eine Pass-through-Stiftung der Meridian Foundation, die ausschliesslich Stiftung Mercator Schweiz finanziert — dieselbe Adresse, kein separates Bewerbungsverfahren. Revamp-IT sollte direkt Stiftung Mercator Schweiz kontaktieren, nicht Cambiata.';
}, { newFitScore: 2 });
// youthaid-foundation: primarily developing countries, email found
await patch('youthaid-foundation', (cd) => {
delete cd.websiteUrl; // no confirmed Swiss website (youthaidfoundation.org is an Indian NGO)
cd.applicationUrl = 'mailto:info@youthaid.org';
cd.applicationMethod = 'email';
cd.acceptsApplications = 'unknown';
const c = (cd.contact as Record<string, unknown> | null) ?? {};
c.address = 'Bahnhofstrasse 16, 8001 Zürich';
c.email = 'info@youthaid.org';
cd.contact = c;
cd.purposeSummary = 'Unterstützt benachteiligte Jugendliche, primär in Entwicklungs- und Schwellenländern. Breitere Zwecke umfassen auch Bildung, Soziales, Ökologie und Kultur in der Schweiz und im Ausland. Kleine Zürich-Stiftung ohne öffentlichen Bewerbungsprozess.';
cd.researchNotes = 'CHE-431.910.176. Primärfokus liegt auf Entwicklungsländern — Schweizer Inlandsprojekte sind Sekundärzweck. Bestätigte E-Mail: info@youthaid.org. Direkte Anfrage nötig, um zu klären, ob Schweizer NGOs in Frage kommen. Kein öffentlicher Bewerbungsweg gefunden.';
}, { newFitScore: 3 });
// alice-ackermann: good fit, phone-only contact (no email found)
await patch('alice-ackermann', (cd) => {
// websiteUrl stays as StiftungSchweiz link (registry, but best available)
cd.applicationMethod = 'contact';
cd.acceptsApplications = 'unknown';
// No email found — phone/postal only
const c = (cd.contact as Record<string, unknown> | null) ?? {};
c.address = 'c/o Michael Manser, Riedstrasse 92, 9050 Appenzell';
c.phone = '+41 33 534 99 75';
cd.contact = c;
cd.purposeSummary = 'Alice Ackermann Stiftung (gegr. 2018, Appenzell): Fördert Bildung, Ausbildung und berufliche Weiterentwicklung von benachteiligten Kindern, Jugendlichen und jungen Erwachsenen in der Schweiz. Unterstützt auch schweizer und kantonale Institutionen, die diese Zielgruppen betreuen.';
cd.researchNotes = 'Kleine Stiftung ohne Website und ohne veröffentlichte E-Mail. Kontakt nur per Telefon (+41 33 534 99 75) oder Post an Michael Manser, Appenzell. Thematisch gute Überschneidung mit Revamp-ITs Arbeitsintegrations- und Digitalprogrammen für benachteiligte Jugendliche. Betrag pro Ereignis bis CHF 3,000 — wahrscheinlich kleine Zuwendungen.';
// Keep themes: soziale-integration, digitale-bildung, arbeitsintegration — accurate
}); // keep fit=4
// hamasil-stiftung: operative Kulturpark operator, explicitly no applications
await patch('hamasil-stiftung', (cd) => {
cd.websiteUrl = 'https://www.hamasil.ch';
cd.isOperative = true;
cd.applicationMethod = 'none';
cd.acceptsApplications = 'no';
const c = (cd.contact as Record<string, unknown> | null) ?? {};
c.address = 'Pfingstweidstrasse 16, 8005 Zürich';
c.email = 'info@hamasil.ch';
c.phone = '+41 44 448 40 40';
cd.contact = c;
cd.purposeSummary = 'Operative Stiftung: Eigentümerin und Betreiberin des Kulturpark-Komplexes in Zürich-West (5 Liegenschaften, Pfingstweidstrasse). Beherbergt ca. 20 Zivilgesellschaftsorganisationen (UNICEF, Myclimate, ZEWO). Vergibt ausdrücklich keine Fördergesuche — sucht proaktiv langfristige Partnerschaften.';
cd.researchNotes = 'SwissFoundations-Mitglied. Explizite Aussage: "Die Stiftung nimmt grundsätzlich keine Anträge entgegen." Operative Immobilien-/Trägerschaftsstiftung für den Kulturpark Zürich-West. Einzig mögliche Verbindung: Mietgespräch für Büroraum im Kulturpark — aber kein klassischer Förderantrag möglich.';
cd.themes = ['soziale-integration', 'zuerich']; // remove incorrectly broad themes
}, { newFitScore: 2 });
console.log('\n2. Correcting clearly mismatched lower-fit P3 entries...');
// dcs-stiftung: chemistry/biology/technology research — wrong themes
await patch('dcs-stiftung', (cd) => {
delete cd.websiteUrl; // no public website
cd.applicationMethod = 'contact';
cd.acceptsApplications = 'yes';
const c = (cd.contact as Record<string, unknown> | null) ?? {};
if (!c.address) c.address = 'Basel (exact address not publicly listed)';
cd.contact = c;
cd.purposeSummary = 'Dorit und Caspar Stürm Stiftung (gegr. 2018, Basel): fördert wissenschaftliche Forschung in Chemie, Biologie und Technologie (Pharmakologie, Diagnostik, Kosmetik); kulturelle Austauschprojekte zwischen Deutschland und der Schweiz; und junge Künstler:innen.';
cd.researchNotes = 'CHE-141.215.768. Primärfokus auf naturwissenschaftliche Forschung (Chemie, Biologie, Pharma) und Kulturprojekte D-CH. Das DB-Thema "digitale-bildung" war eine Fehleinstufung. Kein Bezug zu Revamp-ITs Kernbereichen IT-Refurbishing, Arbeitsintegration oder digitaler Inklusion.';
cd.themes = []; // remove digitale-bildung (wrong)
}, { newFitScore: 1 });
// emil-huber-stockar-stiftung: Alpine accident/ETH library focus — wrong for Revamp-IT
await patch('emil-huber-stockar-stiftung', (cd) => {
delete cd.websiteUrl;
cd.applicationMethod = 'contact';
cd.acceptsApplications = 'unknown';
cd.purposeSummary = 'Fördert alpine Unfallhilfe, Bergrettung, Ausbildungsmassnahmen zur Verhütung von Bergunfällen und Schutzm assnahmen in Berggebieten sowie die ETH-Bibliothek (Grafik-Sammlung). Kein Bezug zu IT, Kreislaufwirtschaft oder Arbeitsintegration.';
cd.researchNotes = 'Stiftung mit sehr engem Zweck: alpine Sicherheit/Bergrettung und ETH-Bibliothekssammlung. Kein Revamp-IT-Bezug; Thema "zuerich" ist der einzige Überschneidungspunkt.';
cd.themes = ['zuerich'];
}, { newFitScore: 1 });
console.log('\n✅ All done.');
}
main().catch(console.error);
-100
View File
@@ -1,100 +0,0 @@
/**
* Write confirmed applicationUrls for P3 foundations (batch research 2026-04-23)
* Also clears wrong websiteUrls where research confirmed the stored URL is wrong.
*/
import { config } from 'dotenv'; config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
const applicationUrls: Array<{ id: string; url: string }> = [
// Batch 1 — major foundations
{ id: 'sens-suisse', url: 'https://sens-suisse.ch/mitmachen/' },
{ id: 'impacthub-zuerich', url: 'https://zurich.impacthub.ch/angebot/impact-programme/partner-werden/' },
{ id: 'jacobs-stiftung', url: 'https://jacobsfoundation.org/work-with-us/' },
{ id: 'fondation-leenaards', url: 'https://leenaards.ch/contact/' },
{ id: 'fondation-vareille', url: 'https://www.vareillefoundation.org/contacts/' },
{ id: 'fondation-gandur-pour-la-jeunesse', url: 'https://fg-jeunesse.org/soumettre-un-projet/' },
{ id: 'fondazione-minerva', url: 'https://minerva-stiftung.org/was-wir-tun/gesuch-einreichen/' },
{ id: 'innosuisse', url: 'https://innolink.innosuisse.ch/' },
// Batch 2
{ id: 'somaha-stiftung', url: 'https://somaha-stiftung.ch/foerderantrag-einreichen/' },
{ id: 'bridging-nations-stiftung', url: 'https://bridging-nations.org/submit-a-project/' },
{ id: 'cleantech21-foundation', url: 'https://www.cleantech21.org/contact' },
{ id: 'schweizerische-stiftung-fuer-kinder-und-jugendliche-in-not', url: 'https://www.kinder-stiftung.ch/gesuche' },
{ id: 'svc-unternehmertum', url: 'https://svc.swiss/de/kontakt' },
// Batch 3
{ id: 'accordeos-stiftung', url: 'https://www.accordeos.ch/gesuche.html' },
{ id: 'gebauer-stiftung', url: 'https://www.gebauer-stiftung.ch/#gesuche' },
{ id: 'stiftung-soliterra', url: 'https://www.soliterra.ch' },
{ id: 'cardano-stiftung', url: 'https://projectcatalyst.io' },
{ id: 'kyria-stiftung', url: 'https://kyria.ch/kontakt/' },
{ id: 'foundation-benedict', url: 'https://www.foundation-benedict.org/kontakt/' },
{ id: 'thomas-abegg-foundation', url: 'https://www.thomas-abegg-foundation.ch/kontakt/' },
// Batch 4
{ id: 'fondation-futur', url: 'https://www.futur.ch/Kontakt' },
{ id: 'denk-an-mich', url: 'https://denkanmich.ch/gesuch-einreichen' },
{ id: 'iff-mauderli-stiftung', url: 'https://www.iff-mauderli-stiftung.ch' },
{ id: 'stiftung-uitikon', url: 'https://stiftung-uitikon.org/#kontakt' },
{ id: 'fondation-hans-wilsdorf', url: 'https://hanswilsdorf.ch/depot-de-demande/demande-de-soutien-institutionnel' },
{ id: 'ekt-energiestiftung', url: 'https://www.ekt-energiestiftung.ch/foerderung/gesuche/' },
{ id: 'fondation-sonja-knapp', url: 'https://www.fondationsk.ch' },
{ id: 'fondazione-mantello-filantropia', url: 'https://www.filantropia.ch/contatti/' },
{ id: 'swisslos-sportfonds-zh', url: 'https://www.zks-zuerich.ch/dienstleistungen/sportfonds-gesuche' },
// Batch 5
{ id: 'credis-stiftung', url: 'https://www.credis-stiftung.ch/contact/bewerbung' },
{ id: 'dignitas-academy', url: 'https://www.dignitas-academy.ch/gesuche/' },
{ id: 'martha-bock-stiftung', url: 'https://www.martha-bock-stiftung.ch/gesuche' },
{ id: 'hans-henny-fonds-der-albertus-magnus-stiftung', url: 'https://albertusmagnus.ch/#kontakt' },
{ id: 'fondation-charles-leopold-mayer-pour-le-progres-humain-fph', url: 'https://www.fph.ch/rubrique6_fr.html' },
{ id: 'ueli-schlageter-stiftung', url: 'https://easynpo.schlageter-stiftung.ch/' },
{ id: 'stiftung-klimarappen', url: 'https://www.klimarappen.ch/de/Kontakt.21.html' },
{ id: 'stiftung-greuter-briner', url: 'https://stiftung-gb.ch' },
{ id: 'stiftung-giuvenils', url: 'https://giuvenils.ch/gesuche-einreichen/' },
{ id: 'birkenhof-stiftung', url: 'https://stiftung-birkenhof.ch/kontakt/' },
{ id: 'eruv-stiftung', url: 'https://eruv.ch/#kontakt' },
];
// Wrong websiteUrls confirmed by research — clear them
const clearWebsiteUrl: string[] = [
'hamasil-stiftung', // hamasil.ch redirects to kulturpark.ch (unrelated venue)
'dcs-stiftung', // dcs.ch is an IT services company, not the foundation
'cambiata-stiftung', // domain shows bare "Maildomain" page, no foundation site
'youthaid-foundation', // domain parked for sale (Namoxy.com)
'templeton-stiftung', // templeton.ch → Franklin Templeton (investment firm)
'start-foundation', // www.startfoundation.ch is NXDOMAIN
'leo-future', // leofuturefoundation.ch does not resolve
];
async function main() {
let written = 0;
let notFound = 0;
console.log('Writing applicationUrls...');
for (const { id, url } of applicationUrls) {
const r = await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{applicationUrl}', ${JSON.stringify(url)}::jsonb),
updated_at = NOW()
WHERE id = ${id}
RETURNING id
`;
if (r.length > 0) { written++; console.log(` ✅ ${id}`); }
else { notFound++; console.log(` ❌ NOT FOUND: ${id}`); }
}
console.log('\nClearing wrong websiteUrls...');
for (const id of clearWebsiteUrl) {
const r = await sql`
UPDATE fundraising_foundations
SET config_data = config_data - 'websiteUrl',
updated_at = NOW()
WHERE id = ${id}
RETURNING id
`;
if (r.length > 0) console.log(` ✅ cleared websiteUrl: ${id}`);
else console.log(` ❌ NOT FOUND: ${id}`);
}
console.log(`\nDone: ${written} applicationUrls written, ${notFound} not found`);
}
main().catch(console.error);