Files
loki/scripts/db/link-prod-runtime.ts
CatoandClaude Opus 5 58174f45ef fix(hardcoded): give every duplicated constant one home (#758)
* fix(hardcoded): give every duplicated constant one home

A sweep of all 44 repos' default branches for literals that duplicate an
existing source of truth. Loki's share, in four groups.

WRONG, and live on the public footer. src/config/fleet-site-copy.ts still
called the Zürich clinic "VitaReBa", a name retired on 2026-09-10 — its own
title says "Vita · Metabolische Psychiatrie & Systemische Longevity". The
generated fleet-sites.ts carried it onto loki.orangecat.ch, where it was
serving until this commit. Fixed at the copy file, which is the one place that
owns a site's own words, and the footer regenerated from it.

WOULD HAVE WRITTEN STALE DATA. scripts/seed-fleet-site-urls.ts kept a hand-typed
slug → URL map "read 2026-08-06". Two of its fifteen entries pointed at hosts
retired since (aoz-wohnen.orangecat.ch, revampit.orangecat.ch), so running it
would have filled empty live_url columns with addresses that only 308. It now
derives the map from apps.conf — the same register the footer is generated from
— which also fixes the six live sites the hand list never had. Verified: 19
sites, zero retired hosts.

THE BOX ADDRESS, in seven places. scripts/hetzner/_box-env.sh has been the SSOT
for it all along and sixteen scripts source it; four did not, and the shared
deploy workflow — reused by ~20 repos — had the IP inline twice, so moving the
box meant twenty edits. The workflow now reads the org-level Actions variable
HETZNER_IP and fails loudly if it is unset, rather than ssh-ing to an empty
string. loki's own deploy.yml had `vars.HETZNER_IP || '<literal>'`, a fallback
that guaranteed the variable was never needed and so never noticed if wrong.

ONE LAPTOP, baked into shipped code. site-cd-local.ts listed /home/g/.ssh and
/home/ubuntu/.ssh as deploy-key candidates beside os.homedir() — which already
IS those paths, since loki-app runs as `ubuntu` and a laptop runs as its owner;
both spelled one homedir for one named person. install-push-deploy.sh wired
hooks to /home/g/dev/loki, link-prod-runtime.ts to /home/g/dev/bitbaum, and
scripts/fleet printed an install line only true on one machine: all now DEV_ROOT
or the script's own resolved path.

The two scripts in scripts/local are INSTALLED BY COPY into ~/.local/bin and run
there by systemd timers, so they resolve _box-env.sh beside the real file first,
then under DEV_ROOT, and exit loudly if neither exists — a security check that
cannot find its target must not look like one that found nothing.

Deliberately unchanged: the slug alias map (the mechanism that makes a rename
safe), an executed migration's data row, the retired-handle detector's own
handle list, and test fixtures reproducing past incidents.

Verified: fleet-sites-derived in sync (14 sites), bash -n on every edited
script, and the branch's only remaining literals are in scripts/test fixtures.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(push-deploy): the generated hook must not bake one laptop's path

install-push-deploy.sh writes the hook body through an UNQUOTED heredoc, so
$HERE expanded at generation time and the absolute path of one machine was
committed into every repo's .husky/pre-push. kivvi and botsmann both carried it;
anyone cloning those repos got a hook pointing into a stranger's home directory,
and re-running the installer would have put it straight back after those repos
were cleaned.

The hook now resolves ${DEV_ROOT:-$HOME/dev}/loki/... at RUN time, so the
generator stops re-introducing what the cleanup just removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 02:03:58 -07:00

97 lines
3.4 KiB
TypeScript

/**
* Wire prod user_projects rows to local dir paths (Fleet Runner dispatch).
*
* Usage:
* npx tsx scripts/db/link-prod-runtime.ts # dry run
* npx tsx scripts/db/link-prod-runtime.ts --apply # execute
*
* Env: LOKI_DB_PASSWORD + HETZNER_IP from .env.hetzner.local
*/
import { config } from "dotenv";
import { homedir } from "node:os";
import { join } from "node:path";
config({ path: ".env.hetzner.local" });
const APPLY = process.argv.includes("--apply");
/** Entity display name → absolute dir on the operator machine. */
const RUNTIME_LINKS: Array<{ name: string; dirPath: string; reason: string }> = [
{
name: "Bitbaum",
dirPath: join(process.env.DEV_ROOT ?? join(homedir(), "dev"), "bitbaum"),
reason: "Entity enriched but missing user_projects dir",
},
];
async function main() {
const password = process.env.LOKI_DB_PASSWORD;
const host = process.env.HETZNER_IP;
if (!password || !host)
throw new Error("LOKI_DB_PASSWORD / HETZNER_IP missing from .env.hetzner.local");
process.env.DATABASE_URL = `postgres://loki:${encodeURIComponent(password)}@${host}:5432/loki?sslmode=require`;
const { db } = await import("../../src/db");
const { entities, users, userProjects } = await import("../../src/db/schema");
const { and, eq, sql } = await import("drizzle-orm");
const { ENTITY_TYPE } = await import("../../src/lib/constants/statuses");
const { upsertLocalUserProject } = await import("../../src/db/queries/user-projects");
const { findProjectEntityByName } = await import("../../src/db/queries/project-merge");
const projectOwners = await db
.select({ userId: entities.userId, count: sql<number>`count(*)::int` })
.from(entities)
.where(eq(entities.type, ENTITY_TYPE.PROJECT))
.groupBy(entities.userId);
const ownerCounts = new Map(projectOwners.map((r) => [r.userId, r.count]));
const allUsers = await db
.select({ id: users.id, email: users.email, name: users.name })
.from(users);
const ownerUser = allUsers
.filter((u) => (ownerCounts.get(u.id) ?? 0) > 0)
.sort((a, b) => (ownerCounts.get(b.id) ?? 0) - (ownerCounts.get(a.id) ?? 0))[0];
if (!ownerUser) throw new Error("No project owner found");
const userId = ownerUser.id;
console.log(
`${APPLY ? "Applying" : "Dry run"} link-prod-runtime for ${ownerUser.name ?? ownerUser.email}\n`,
);
for (const link of RUNTIME_LINKS) {
const entity = await findProjectEntityByName(userId, link.name);
if (!entity) {
console.log(`— skip ${link.name}: entity not found`);
continue;
}
const [existing] = await db
.select({ dir: userProjects.dirPath, entityId: userProjects.entityProjectId })
.from(userProjects)
.where(
and(
eq(userProjects.userId, userId),
sql`lower(${userProjects.name}) = lower(${link.name.trim()})`,
),
);
if (existing?.dir === link.dirPath && existing.entityId === entity.id) {
console.log(`— skip ${link.name}: already linked (${link.dirPath})`);
continue;
}
console.log(`${APPLY ? "✚" : "DRY"} ${link.name} → ${link.dirPath} — ${link.reason}`);
if (APPLY) {
await upsertLocalUserProject({ userId, name: link.name, dirPath: link.dirPath });
console.log(` linked entity ${entity.id.slice(0, 8)}`);
}
}
if (!APPLY) console.log("\nRe-run with --apply to write changes.");
process.exit(0);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});