Files
loki/scripts/seed.ts
T
CatoandClaude Opus 5 e7b37710d1 fix(identity): the retired pseudonym was still live, and the scaffold signed with it (#533)
* fix(identity): the retired pseudonym was still live, and the scaffold signed with it

Caught by a --dry-run, minutes before scaffolding a new public repository.
new-site.sh hardcoded the retired pseudonym as the commit author:

  git -c user.name='<retired>' ... commit -m 'feat: scaffold <Title>'

Every site the scaffold has ever created carries that name in its FIRST COMMIT,
in a public repo, permanently. Nothing surfaces it: it is one flag on a long
line, it never appears in the app, and the dry-run prints it only if you read
the command it would run.

Sweeping for it found thirteen more, and the shipped ones were not internal:

  privacy, terms, license, support   the operator named on the LEGAL pages
  PublicFooter                       the copyright line on every public page
  config/ecosystem.ts                the `owner` field
  seed.ts                            the seeded profile name
  Avatar.tsx, initials.ts            doc examples

All four legal pages were serving it live on fleetcrown.orangecat.ch, verified
by curl before and after.

The doc examples are replaced rather than renamed: both demonstrated two words
producing two initials, so substituting a one-word name would have broken what
they exist to show. They use "Ada Lovelace" now.

WHAT THIS DELIBERATELY DOES NOT TOUCH

legal/IP_ASSIGNMENT_MEMO.md, legal/PRIVACY_POLICY.md and
legal/TERMS_OF_SERVICE.md still carry the retired name, on purpose. An IP
assignment memo reading "I, <name>, sole author and copyright holder" and a
privacy policy naming a data controller are instruments executed under a name.
Renaming a party on a signed document is not a find-and-replace; it is a
decision for the person who signed it. The check below excludes legal/ so its
contents are not mistaken for a defect, and so nobody "fixes" them mechanically.

THE CHECK

scripts/hetzner/test-no-retired-name.sh fails if the name returns to src/ or
scripts/. docs/ is allowed, because HANDOFF.md has to NAME the retired
pseudonym in order to forbid it — a gate that cannot tolerate its own rule
being written down forces the rule to be deleted.

It assembles the pattern from two literals instead of writing it whole, so the
check does not match its own source. That is asserted, not assumed: one case
fails if the pattern is ever "tidied" into a single literal, and another checks
it assembled to the expected value, because an empty pattern matches everything
and a mistyped one matches nothing and passes silently.

Mutation-proven against the real defect, not a fixture: the commit-author line
was reverted to its pre-fix state, the check failed and named new-site.sh, and
the line was restored. Wired into `test:ops`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G2LBioUzJP4oBL9LeH9qAe

* style: prettier

Replacing the retired name with a shorter one changed the JSX text reflow on
the three legal pages, so prettier wants them rewrapped. verify's first gate is
`prettier --check .`, which makes a formatting-only miss a red build with
nothing else wrong.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 08:52:38 -07:00

386 lines
12 KiB
TypeScript

import Database from "better-sqlite3";
import { drizzle } from "drizzle-orm/postgres-js";
import { sql } from "drizzle-orm";
import postgres from "postgres";
import { readFileSync } from "fs";
import { homedir } from "os";
import * as schema from "../src/db/schema";
import type {
EntityType,
SubStatus,
CommitmentStatus,
EventStatus,
} from "../src/lib/constants/statuses";
import type { SubscriptionCurrency, SubscriptionFrequency } from "../src/config/subscriptions";
// Owner-only: this script truncates every table and inserts the owner's
// historical data from ~/.openclaw. It must never run in a multi-tenant SaaS
// deployment. Gate behind COCKPIT_OWNER_SEED=1 so an accidental invocation in
// production can't wipe customer data.
if (process.env.COCKPIT_OWNER_SEED !== "1") {
console.error("Refusing to run seed.ts without COCKPIT_OWNER_SEED=1 (this wipes the DB).");
process.exit(1);
}
const HOME = homedir();
const DATABASE_URL = process.env.DATABASE_URL!;
function safeDate(v: string | null | undefined): Date | null {
if (!v) return null;
const d = new Date(v);
return isNaN(d.getTime()) ? null : d;
}
function safeDateRequired(v: string | null | undefined): Date {
const d = safeDate(v);
return d ?? new Date();
}
const SQLITE_PATH = `${HOME}/.openclaw/knowledge.sqlite`;
const CONTACTS_PATH = `${HOME}/.openclaw/workspace/data/contact-resolver.json`;
const OWNER_USER_ID = "00000000-0000-0000-0000-000000000001";
async function main() {
console.log("Connecting to Postgres...");
const client = postgres(DATABASE_URL);
const db = drizzle(client, { schema });
// Truncate all tables
console.log("Truncating tables...");
await db.execute(
sql`TRUNCATE users, entities, entity_relations, attributes, interactions, goals, commitments, subscriptions, events CASCADE`,
);
// Create default user
console.log("Creating default user...");
await db.insert(schema.users).values({
id: OWNER_USER_ID,
name: "Cato", // pseudonym — never seed the operator's real name (it surfaces on the public /u/ profile)
// Real login email comes from SEED_OWNER_EMAIL so it is never committed.
email: process.env.SEED_OWNER_EMAIL ?? "mao@orangecat.ch",
isDefault: true,
});
// Read SQLite
console.log(`Reading ${SQLITE_PATH}...`);
const sqlite = new Database(SQLITE_PATH, { readonly: true });
// Import entities
const sqliteEntities = sqlite.prepare("SELECT * FROM entities").all() as Array<{
id: number;
name: string;
type: string;
created_at: string;
updated_at: string;
}>;
const idMap = new Map<number, string>(); // sqlite id -> postgres uuid
console.log(`Importing ${sqliteEntities.length} entities...`);
for (const e of sqliteEntities) {
const [inserted] = await db
.insert(schema.entities)
.values({
userId: OWNER_USER_ID,
name: e.name,
// Sqlite is the legacy boundary; types are validated upstream of the import.
type: e.type as EntityType,
source: "knowledge.sqlite",
createdAt: safeDateRequired(e.created_at),
updatedAt: safeDateRequired(e.updated_at),
})
.returning({ id: schema.entities.id });
idMap.set(e.id, inserted.id);
}
// Import attributes
const sqliteAttrs = sqlite.prepare("SELECT * FROM attributes").all() as Array<{
id: number;
entity_id: number;
key: string;
value: string;
confidence: number;
source: string;
temporal: string;
valid_until: string;
created_at: string;
updated_at: string;
}>;
console.log(`Importing ${sqliteAttrs.length} attributes...`);
for (const a of sqliteAttrs) {
const entityId = idMap.get(a.entity_id);
if (!entityId) continue;
await db.insert(schema.attributes).values({
userId: OWNER_USER_ID,
entityId,
key: a.key,
value: a.value,
confidence: a.confidence,
source: a.source ?? "knowledge.sqlite",
temporal: a.temporal ?? "permanent",
validUntil: safeDate(a.valid_until),
createdAt: safeDateRequired(a.created_at),
updatedAt: safeDateRequired(a.updated_at),
});
}
// Import relations
const sqliteRelations = sqlite.prepare("SELECT * FROM relations").all() as Array<{
id: number;
from_entity_id: number;
relation: string;
to_entity_id: number;
properties: string;
confidence: number;
source: string;
created_at: string;
updated_at: string;
}>;
console.log(`Importing ${sqliteRelations.length} relations...`);
for (const r of sqliteRelations) {
const fromId = idMap.get(r.from_entity_id);
const toId = idMap.get(r.to_entity_id);
if (!fromId || !toId) continue;
await db.insert(schema.entityRelations).values({
userId: OWNER_USER_ID,
fromEntityId: fromId,
toEntityId: toId,
type: r.relation,
metadata: r.properties ? JSON.parse(r.properties) : null,
confidence: r.confidence,
source: r.source ?? "knowledge.sqlite",
createdAt: safeDateRequired(r.created_at),
updatedAt: safeDateRequired(r.updated_at),
});
}
// Import commitments
const sqliteCommitments = sqlite.prepare("SELECT * FROM commitments").all() as Array<{
id: number;
description: string;
entity_id: number;
due_date: string;
status: string;
financial_impact: string;
source: string;
created_at: string;
updated_at: string;
}>;
console.log(`Importing ${sqliteCommitments.length} commitments...`);
for (const c of sqliteCommitments) {
const entityId = c.entity_id ? idMap.get(c.entity_id) : null;
await db.insert(schema.commitments).values({
userId: OWNER_USER_ID,
entityId: entityId ?? null,
description: c.description,
dueDate: safeDate(c.due_date),
status: c.status as CommitmentStatus,
financialImpact: c.financial_impact,
source: c.source ?? "knowledge.sqlite",
createdAt: safeDateRequired(c.created_at),
updatedAt: safeDateRequired(c.updated_at),
});
}
// Import subscriptions
const sqliteSubs = sqlite.prepare("SELECT * FROM subscriptions").all() as Array<{
id: number;
entity_id: number;
name: string;
vendor: string;
amount: number;
currency: string;
frequency: string;
category: string;
status: string;
next_due: string;
payment_method: string;
notes: string;
created_at: string;
updated_at: string;
}>;
console.log(`Importing ${sqliteSubs.length} subscriptions...`);
for (const s of sqliteSubs) {
const entityId = s.entity_id ? idMap.get(s.entity_id) : null;
await db.insert(schema.subscriptions).values({
userId: OWNER_USER_ID,
entityId: entityId ?? null,
name: s.name,
vendor: s.vendor,
amount: s.amount,
currency: (s.currency ?? "CHF") as SubscriptionCurrency,
frequency: (s.frequency ?? "monthly") as SubscriptionFrequency,
category: s.category,
status: s.status as SubStatus,
nextDue: safeDate(s.next_due),
paymentMethod: s.payment_method,
notes: s.notes,
createdAt: safeDateRequired(s.created_at),
updatedAt: safeDateRequired(s.updated_at),
});
}
// Import events
const sqliteEvents = sqlite.prepare("SELECT * FROM events").all() as Array<{
id: number;
name: string;
type: string;
description: string;
url: string;
location: string;
date_start: string;
date_end: string;
deadline: string;
cost: string;
category: string;
status: string;
source: string;
metadata: string;
created_at: string;
updated_at: string;
}>;
console.log(`Importing ${sqliteEvents.length} events...`);
for (const e of sqliteEvents) {
await db.insert(schema.events).values({
userId: OWNER_USER_ID,
name: e.name,
type: e.type,
description: e.description,
url: e.url,
location: e.location,
dateStart: safeDate(e.date_start),
dateEnd: safeDate(e.date_end),
deadline: safeDate(e.deadline),
category: e.category,
status: e.status as EventStatus,
source: e.source ?? "knowledge.sqlite",
metadata: e.metadata ? JSON.parse(e.metadata) : null,
createdAt: safeDateRequired(e.created_at),
updatedAt: safeDateRequired(e.updated_at),
});
}
sqlite.close();
// Import contacts from contact-resolver.json
console.log(`\nReading ${CONTACTS_PATH}...`);
const contactsRaw = JSON.parse(readFileSync(CONTACTS_PATH, "utf-8")) as {
contacts: Array<{
id: string;
displayName: string;
aliases?: string[];
channels?: Record<string, Record<string, string>>;
}>;
};
// Build name→uuid lookup from existing entities (case-insensitive)
const existingByName = new Map<string, string>();
for (const [sqliteId, pgId] of idMap) {
const entity = sqliteEntities.find((e) => e.id === sqliteId);
if (entity && entity.type === "person") {
existingByName.set(entity.name.toLowerCase().trim(), pgId);
}
}
let contactsNew = 0;
let contactsEnriched = 0;
for (const contact of contactsRaw.contacts) {
const nameLower = contact.displayName.toLowerCase().trim();
let entityId = existingByName.get(nameLower);
if (!entityId) {
// Create new person entity
const [inserted] = await db
.insert(schema.entities)
.values({
userId: OWNER_USER_ID,
name: contact.displayName,
type: "person",
externalId: contact.id,
source: "contact-resolver",
})
.returning({ id: schema.entities.id });
entityId = inserted.id;
contactsNew++;
} else {
// Update external_id on existing entity
await db
.update(schema.entities)
.set({ externalId: contact.id, source: "knowledge.sqlite+contact-resolver" })
.where(sql`${schema.entities.id} = ${entityId}`);
contactsEnriched++;
}
// Add aliases as attribute
if (contact.aliases && contact.aliases.length > 0) {
await db
.insert(schema.attributes)
.values({
userId: OWNER_USER_ID,
entityId,
key: "aliases",
value: JSON.stringify(contact.aliases),
source: "contact-resolver",
})
.onConflictDoNothing();
}
// Add channel attributes
if (contact.channels) {
for (const [channel, data] of Object.entries(contact.channels)) {
const value = Object.entries(data)
.map(([k, v]) => `${k}:${v}`)
.join(",");
await db
.insert(schema.attributes)
.values({
userId: OWNER_USER_ID,
entityId,
key: `channel:${channel}`,
value,
source: "contact-resolver",
})
.onConflictDoNothing();
}
}
}
// Print summary
const [entityCount] = await db.execute(sql`SELECT COUNT(*) as count FROM entities`);
const [attrCount] = await db.execute(sql`SELECT COUNT(*) as count FROM attributes`);
const [relCount] = await db.execute(sql`SELECT COUNT(*) as count FROM entity_relations`);
const [commitCount] = await db.execute(sql`SELECT COUNT(*) as count FROM commitments`);
const [subCount] = await db.execute(sql`SELECT COUNT(*) as count FROM subscriptions`);
const [eventCount] = await db.execute(sql`SELECT COUNT(*) as count FROM events`);
const extractCount = (row: unknown): string => {
if (row && typeof row === "object" && "count" in row) {
return String((row as { count: unknown }).count);
}
return "0";
};
console.log("\n--- Seed Summary ---");
console.log(
`Entities: ${extractCount(entityCount)} (${contactsNew} new from contacts, ${contactsEnriched} enriched)`,
);
console.log(`Attributes: ${extractCount(attrCount)}`);
console.log(`Relations: ${extractCount(relCount)}`);
console.log(`Commitments: ${extractCount(commitCount)}`);
console.log(`Subscriptions: ${extractCount(subCount)}`);
console.log(`Events: ${extractCount(eventCount)}`);
await client.end();
console.log("\nDone.");
}
main().catch((err) => {
console.error("Seed failed:", err);
process.exit(1);
});