Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(connectors): one kind list and exhaustive kind switches

garrytan98cc1029d684
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 4cec1c8f79..904eff376b 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -10,7 +10,7 @@ import { pricingSetCommand } from '../../../core/budget/no-pricing.ts';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { checkError } from '../check-fix.ts';
-import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';
+import { CONNECTOR_KINDS_SQL, isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';
import { isCrossSourceLinksEnabled } from '../../../core/link-extraction.ts';
/**
@@ -492,7 +492,7 @@ export async function checkJunkEntityHubs(
(SELECT t.source_id FROM pages t LEFT JOIN sources ts ON ts.id = t.source_id
WHERE t.slug = p.slug AND t.source_id <> p.source_id AND t.deleted_at IS NULL
AND (t.frontmatter ->> 'google_contact_id') IS NULL
- AND COALESCE(ts.config ->> 'kind', '') NOT IN ('google', 'github')
+ AND COALESCE(ts.config ->> 'kind', '') NOT IN (${CONNECTOR_KINDS_SQL})
ORDER BY (t.source_id = 'default') DESC, t.source_id LIMIT 1) AS canonical_twin_source
FROM edge_counts ec
JOIN pages p ON p.id = ec.page_id AND p.deleted_at IS NULL
diff --git a/src/commands/sources-lifecycle-args.ts b/src/commands/sources-lifecycle-args.ts
index 25ab9965a9..57f3b99158 100644
--- a/src/commands/sources-lifecycle-args.ts
+++ b/src/commands/sources-lifecycle-args.ts
@@ -6,6 +6,7 @@ import { readFix } from '../core/ops/op-fix.ts';
import { isValidSourceId } from '../core/source-id.ts';
import { msysToNativePath } from '../core/path-confine.ts';
import { isWriteRequestId } from '../core/persistence/types.ts';
+import { isConnectorSourceKind } from '../core/persistence/connector-kinds.ts';
import { defaultCloneDir, type AddSourceOpts } from '../core/sources-ops.ts';
import { isValidRepoName } from '../core/github-source.ts';
import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID } from '../core/google/types.ts';
@@ -102,7 +103,7 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
if (flags.has('federated') && flags.has('no-federated')) throw invalid('Choose one federation setting.', 'Pass either --federated or --no-federated, not both.');
const kind = values.get('kind');
- if (kind !== undefined && !['google', 'github'].includes(kind)) throw invalid('Source kind must be github or google.',
+ if (kind !== undefined && !isConnectorSourceKind(kind)) throw invalid('Source kind must be github or google.',
'Pass --kind github or --kind google; a directory or Git remote source uses --path or --url instead of --kind.');
if ([values.has('path'), values.has('url'), kind !== undefined].filter(Boolean).length > 1) throw invalid('--path, --url and --kind are mutually exclusive.',
'Give exactly one of --path (a local directory), --url (an https Git remote) or --kind (github or google).');
diff --git a/src/commands/sync/connector.ts b/src/commands/sync/connector.ts
index fd805d84cb..a2c1a132d4 100644
--- a/src/commands/sync/connector.ts
+++ b/src/commands/sync/connector.ts
@@ -5,6 +5,8 @@ import { currentJobSignal } from '../../core/minions/submission-authority.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { serr } from '../../core/console-prefix.ts';
import { assertResetCheckpointSource } from '../../core/persistence/connector-reset.ts';
+import { isConnectorSourceKind, type ConnectorKind } from '../../core/persistence/connector-kinds.ts';
+import { assertNever } from '../../core/types.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
export async function runConnectorSync(engine: BrainEngine, opts: SyncOpts, managed: boolean): Promise<SyncResult | null> {
@@ -19,7 +21,7 @@ export async function runConnectorSync(engine: BrainEngine, opts: SyncOpts, mana
return null;
}
const config = typeof source.config === 'string' ? JSON.parse(source.config) : source.config ?? {};
- if (config.kind !== 'google' && config.kind !== 'github') {
+ if (!isConnectorSourceKind(config.kind)) {
if (opts.githubItem) throw new Error(`github_item refresh requires a github-kind source, but "${sourceId}" is not github-kind.`);
return null;
}
@@ -30,15 +32,21 @@ export async function runConnectorSync(engine: BrainEngine, opts: SyncOpts, mana
const options = signal ? { ...opts, signal } : opts;
const fallbackDir = source.local_path ?? (managed ? '' : (await import('../../core/sources-ops.ts')).defaultCloneDir(`${sourceId}-${config.kind}`));
serr(`[gbrain phase] sync.${config.kind}_materialize`);
- let result: SyncResult;
- if (config.kind === 'github') {
- const { parseGitHubSourceConfig, runGitHubSync } = await import('../../core/github-source.ts');
- result = await runGitHubSync(engine, sourceId, parseGitHubSourceConfig(config, fallbackDir), options);
- } else {
- const { parseGoogleSourceConfig, runGoogleSync } = await import('../../core/google/google-source.ts');
- result = await runGoogleSync(engine, sourceId, parseGoogleSourceConfig(config, fallbackDir), options);
+ return withConnectorPartialReason(await runConnectorKind(engine, sourceId, config, fallbackDir, options), signal);
+}
+
+async function runConnectorKind(engine: BrainEngine, sourceId: string, config: Record<string, unknown> & { kind: ConnectorKind }, fallbackDir: string, options: SyncOpts): Promise<SyncResult> {
+ switch (config.kind) {
+ case 'github': {
+ const { parseGitHubSourceConfig, runGitHubSync } = await import('../../core/github-source.ts');
+ return runGitHubSync(engine, sourceId, parseGitHubSourceConfig(config, fallbackDir), options);
+ }
+ case 'google': {
+ const { parseGoogleSourceConfig, runGoogleSync } = await import('../../core/google/google-source.ts');
+ return runGoogleSync(engine, sourceId, parseGoogleSourceConfig(config, fallbackDir), options);
+ }
+ default: return assertNever(config.kind);
}
- return withConnectorPartialReason(result, signal);
}
/**
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index ce7c1716b4..f5c4328655 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -26,6 +26,7 @@ import type { SyncOpts, SyncResult } from '../sync.ts';
import type { IdleSkip } from '../../core/persistence/sync-idle-skips.ts';
import { runConnectorSync } from './connector.ts';
import { performSyncInner } from './incremental.ts';
+import { isConnectorSourceKind } from '../../core/persistence/connector-kinds.ts';
export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {
assertSyncDispatchActive();
@@ -114,7 +115,7 @@ async function mayBeConnectorSource(engine: BrainEngine, opts: SyncOpts): Promis
if (routing.id === null) return false;
try {
const config = typeof routing.config === 'string' ? JSON.parse(routing.config) : routing.config ?? {};
- return config.kind === 'google' || config.kind === 'github';
+ return isConnectorSourceKind(config.kind);
} catch { return true; }
}
diff --git a/src/core/connectors/item-holds-store.ts b/src/core/connectors/item-holds-store.ts
index 57c10ff972..0a3b08f5f1 100644
--- a/src/core/connectors/item-holds-store.ts
+++ b/src/core/connectors/item-holds-store.ts
@@ -21,7 +21,7 @@ import { atomicWriteFileSync } from '../atomic-write.ts';
import { withFilesystemPublication } from '../persistence/filesystem-guard.ts';
import type { BrainEngine } from '../engine.ts';
import { digest } from '../persistence/digest.ts';
-import { connectorCheckpointKey, connectorIdentity, isConnectorSourceKind, type ConnectorKind } from '../persistence/connector-identity.ts';
+import { CONNECTOR_KINDS_SQL, connectorCheckpointKey, connectorIdentity, isConnectorSourceKind, type ConnectorKind } from '../persistence/connector-identity.ts';
import { connectorStateKey } from '../persistence/connector-state.ts';
import { readManagedMode } from '../persistence/managed-mode.ts';
import { heldItems, type ItemHoldRecord } from './item-holds.ts';
@@ -42,7 +42,7 @@ export function classicConnectorStateFile(source: ConnectorSourceRow): string |
const kind = source.config.kind;
if (!isConnectorSourceKind(kind)) return null;
const dir = (connectorIdentity(kind, source.config, source.local_path).config as { dir?: string }).dir;
- return dir ? join(dir, kind === 'google' ? '.google-source.json' : '.github-source.json') : null;
+ return dir ? join(dir, `.${kind}-source.json`) : null;
}
/** The connector's cursor state, wherever this brain keeps it. */
@@ -67,7 +67,7 @@ export interface SourceHolds { sourceId: string; kind: ConnectorKind; held: Item
/** Held items per connector source (sources with none are omitted). */
export async function readAllSourceHolds(engine: Exec, opts: { sourceIds?: string[] } = {}): Promise<SourceHolds[]> {
const sources = await engine.executeRaw<ConnectorSourceRow>(
- "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id");
+ `SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN (${CONNECTOR_KINDS_SQL}) ORDER BY id`);
const managed = await managedBrain(engine);
const out: SourceHolds[] = [];
for (const source of sources) {
@@ -90,7 +90,7 @@ export interface HoldCarry {
owner_host?: string;
}
-const CONNECTOR_SOURCES_SQL = "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id";
+const CONNECTOR_SOURCES_SQL = `SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN (${CONNECTOR_KINDS_SQL}) ORDER BY id`;
/** True when the hold cannot be carried from this host: deactivation keeps refusing for it. */
export function holdCarryBlocked(carry: HoldCarry): boolean {
diff --git a/src/core/persistence/connector-checkpoint-migration.ts b/src/core/persistence/connector-checkpoint-migration.ts
index 649e451c3f..2643663276 100644
--- a/src/core/persistence/connector-checkpoint-migration.ts
+++ b/src/core/persistence/connector-checkpoint-migration.ts
@@ -20,7 +20,7 @@
* older binary may still be using an old key during a mixed-version window.
*/
import type { BrainEngine } from '../engine.ts';
-import { connectorCheckpointKeys, connectorIdentity, type ConnectorKind } from './connector-identity.ts';
+import { CONNECTOR_KINDS_SQL, connectorCheckpointKeys, connectorIdentity, type ConnectorKind } from './connector-identity.ts';
import { CONNECTOR_STATE_OP, connectorStateKey, emptyConnectorState, type ConnectorState } from './connector-state.ts';
type Sql = Pick<BrainEngine, 'executeRaw' | 'transaction' | 'kind'>;
@@ -41,7 +41,7 @@ export interface LoadableConnectorKey { id: string; incarnation: string; archive
* under them are never orphans while the source exists.
*/
export async function loadableConnectorKeys(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, LoadableConnectorKey>> {
- const rows = await engine.executeRaw<SourceRow>("SELECT id,incarnation::text,local_path,config,archived FROM sources WHERE config->>'kind' IN ('google','github')");
+ const rows = await engine.executeRaw<SourceRow>(`SELECT id,incarnation::text,local_path,config,archived FROM sources WHERE config->>'kind' IN (${CONNECTOR_KINDS_SQL})`);
const keys = new Map<string, LoadableConnectorKey>();
for (const row of rows) {
const config = typeof row.config === 'string' ? JSON.parse(row.config) as Record<string, unknown> : row.config ?? {};
@@ -106,7 +106,7 @@ export async function deleteOrphanConnectorCheckpoints(engine: Pick<BrainEngine,
if (!rows.length) return removed;
// Connector source rows stay share-locked while loadability is recomputed and rows are deleted, so a config change cannot make a deleted key current.
await engine.transaction(async tx => {
- await tx.executeRaw("SELECT id FROM sources WHERE config->>'kind' IN ('google','github') ORDER BY id FOR SHARE");
+ await tx.executeRaw(`SELECT id FROM sources WHERE config->>'kind' IN (${CONNECTOR_KINDS_SQL}) ORDER BY id FOR SHARE`);
const loadable = [...(await loadableConnectorKeys(tx)).keys()];
for (const row of rows) {
const deleted = await tx.executeRaw<{ op: string }>(`DELETE FROM op_checkpoints c WHERE c.op=$1 AND c.fingerprint=$2 AND c.updated_at=$3::text::timestamptz
diff --git a/src/core/persistence/connector-errors.ts b/src/core/persistence/connector-errors.ts
index a1adef3756..3173f85dcf 100644
--- a/src/core/persistence/connector-errors.ts
+++ b/src/core/persistence/connector-errors.ts
@@ -7,6 +7,7 @@
* deterministically, from the code, the message and the receipt's own fields.
*/
import { OperationError } from '../ops/contract.ts';
+import { assertNever } from '../types.ts';
import { describeConnectorAccount, type ConnectorAccount } from './connector-state.ts';
import type { ConnectorConfig, ConnectorKind } from './connector-identity.ts';
import type { GitHubSourceConfig } from '../github-source.ts';
@@ -23,14 +24,17 @@ export function connectorAccountChanged(sourceId: string, kind: ConnectorKind, c
const show = (value: ConnectorAccount | string | null) => value === null ? 'no resolvable account' : typeof value === 'string' ? value : describeConnectorAccount(value);
let restore: string;
let replace: string;
- if (kind === 'google') {
+ switch (kind) {
+ case 'google': {
const google = config as GoogleSourceConfig;
const where = google.access === 'command' ? `the command configured as g_token_command (${google.tokenCommand ?? 'unset'})`
: google.access === 'env' ? `the environment variable configured as g_token_env (${google.tokenEnv ?? 'unset'})` : `the vault credential (gbrain google connect --account ${google.account})`;
restore = `restore ${where} so it yields a token for ${show(recorded)}, then retry: gbrain sync --source ${sourceId}`;
replace = `add a new source for the new account (gbrain google setup --account ${typeof resolved === 'object' && resolved?.kind === 'google' ? resolved.email : '<email>'}), `
+ `then archive this one: gbrain sources archive ${sourceId}`;
- } else {
+ break;
+ }
+ case 'github': {
const github = config as GitHubSourceConfig;
const installation = typeof resolved === 'object' && resolved?.kind === 'github' && resolved.installationId !== null ? resolved.installationId : '<installation-id>';
restore = github.app ? `restore the GitHub App credential (gh_app_id ${github.app.appId}, key at gh_app_pem_path) for ${show(recorded)}, then retry: gbrain sync --source ${sourceId}`
@@ -38,6 +42,9 @@ export function connectorAccountChanged(sourceId: string, kind: ConnectorKind, c
replace = `add a new source pinned to the intended installation (gbrain sources add <new-id> --kind github --scope ${github.scope}`
+ `${github.scope === 'repos' ? ` --repos ${github.repos.join(',')}` : ''}${github.app ? ` --app-id ${github.app.appId} --app-pem <path>` : ''} --app-install ${installation}), `
+ `then archive this one: gbrain sources archive ${sourceId}`;
+ break;
+ }
+ default: return assertNever(kind);
}
// Account emails and installation ids stay in the local suggestion: job records persist and serve the message remotely.
const error = new OperationError('connector_account_changed',
diff --git a/src/core/persistence/connector-identity.ts b/src/core/persistence/connector-identity.ts
index 27b70b7e4d..29db18192b 100644
--- a/src/core/persistence/connector-identity.ts
+++ b/src/core/persistence/connector-identity.ts
@@ -25,12 +25,11 @@ import { parseGoogleSourceConfig } from '../google/source-config.ts';
import { parseGitHubSourceConfig } from '../github-source-config.ts';
import type { GitHubSourceConfig } from '../github-source.ts';
import { DEFAULT_CONTACTS_DIR, type GoogleSourceConfig } from '../google/types.ts';
+import { assertNever } from '../types.ts';
-export type ConnectorKind = 'google' | 'github';
+import type { ConnectorKind } from './connector-kinds.ts';
-export const CONNECTOR_SOURCE_KINDS: readonly ConnectorKind[] = ['google', 'github'];
-/** A managed Google or GitHub connector source (`sources.config.kind`). */
-export function isConnectorSourceKind(kind: unknown): kind is ConnectorKind { return CONNECTOR_SOURCE_KINDS.includes(kind as ConnectorKind); }
+export { CONNECTOR_KINDS_SQL, CONNECTOR_SOURCE_KINDS, isConnectorSourceKind, type ConnectorKind } from './connector-kinds.ts';
export type ConnectorConfig = GoogleSourceConfig | GitHubSourceConfig;
type LeafClass = 'identity' | 'excluded';
/** An identity leaf left out of the digest while it holds the default it was introduced with (#6561). */
@@ -100,7 +99,11 @@ export function connectorIdentityLeaves(kind: ConnectorKind, config: ConnectorCo
export interface ConnectorIdentity { kind: ConnectorKind; config: ConnectorConfig; digest: string; aliasDigests: string[] }
export function parseConnectorConfig(kind: ConnectorKind, raw: Record<string, unknown>, localPath: string | null): ConnectorConfig {
- return kind === 'google' ? parseGoogleSourceConfig(raw, localPath ?? '') : parseGitHubSourceConfig(raw, localPath ?? '');
+ switch (kind) {
+ case 'google': return parseGoogleSourceConfig(raw, localPath ?? '');
+ case 'github': return parseGitHubSourceConfig(raw, localPath ?? '');
+ default: return assertNever(kind);
+ }
}
/** The parsed connector config plus its identity digest. The raw config is never an identity. */
diff --git a/src/core/persistence/connector-kinds.ts b/src/core/persistence/connector-kinds.ts
new file mode 100644
index 0000000000..b041a27b5c
--- /dev/null
+++ b/src/core/persistence/connector-kinds.ts
@@ -0,0 +1,21 @@
+/**
+ * The connector source kinds (`sources.config.kind`), with no imports so schema
+ * migrations and SQL builders can use them without loading a connector. Every
+ * kind list and kind branch reads these: a literal kind list elsewhere fails
+ * test/connector-kind-routing.test.ts.
+ */
+export type ConnectorKind = 'google' | 'github';
+
+export const CONNECTOR_SOURCE_KINDS: readonly ConnectorKind[] = ['google', 'github'];
+/** A connector source kind (`sources.config.kind`). */
+export function isConnectorSourceKind(kind: unknown): kind is ConnectorKind { return CONNECTOR_SOURCE_KINDS.includes(kind as ConnectorKind); }
+/** The `sources.config` key holding a connector source's directory. */
+export function connectorDirKey(kind: ConnectorKind): string {
+ switch (kind) {
+ case 'google': return 'g_dir';
+ case 'github': return 'gh_dir';
+ default: { const unhandled: never = kind; throw new Error(`Unhandled connector kind: ${String(unhandled)}`); }
+ }
+}
+/** The connector kinds as a quoted SQL list (`'google','github'`): every SQL filter on connector kinds interpolates it. */
+export const CONNECTOR_KINDS_SQL = CONNECTOR_SOURCE_KINDS.map(kind => `'${kind}'`).join(',');
diff --git a/src/core/persistence/connector-reset.ts b/src/core/persistence/connector-reset.ts
index 0fbd75b93f..d2dd875b3b 100644
--- a/src/core/persistence/connector-reset.ts
+++ b/src/core/persistence/connector-reset.ts
@@ -1,10 +1,11 @@
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
+import { isConnectorSourceKind } from './connector-kinds.ts';
/** `gbrain sync --reset-checkpoint` names exactly one connector source. */
export async function assertResetCheckpointSource(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string | undefined): Promise<void> {
const [source] = sourceId ? await engine.executeRaw<{ kind: string | null }>("SELECT config->>'kind' AS kind FROM sources WHERE id=$1 AND NOT archived", [sourceId]) : [];
- if (source?.kind === 'google' || source?.kind === 'github') return;
+ if (isConnectorSourceKind(source?.kind)) return;
throw new OperationError('invalid_params', `--reset-checkpoint applies only to a Google or GitHub connector source${sourceId ? `; ${sourceId} is not one` : ''}.`,
sourceId ? `Git-backed sources re-import with: gbrain sync --source ${sourceId} --full` : 'Name the connector source: gbrain sync --source <id> --reset-checkpoint');
}
diff --git a/src/core/persistence/connector-state.ts b/src/core/persistence/connector-state.ts
index 0850d56805..435d1b8f45 100644
--- a/src/core/persistence/connector-state.ts
+++ b/src/core/persistence/connector-state.ts
@@ -16,6 +16,8 @@
import type { BrainEngine } from '../engine.ts';
import { digest } from './digest.ts';
import { parseSourceConfig } from '../sources-load.ts';
+import { assertNever } from '../types.ts';
+import { isConnectorSourceKind } from './connector-kinds.ts';
export const CONNECTOR_STATE_OP = 'managed-connector-state';
@@ -168,7 +170,7 @@ export async function seedConnectorDispatchAttempts(engine: Pick<BrainEngine, 'e
// parseSourceConfig, as the dispatch loops read it (string-wrapped configs included). The syncEnabled test is
// isSyncDisabledConfig's (sync-policy.ts), inlined so the schema-migration closure stays small.
const config = parseSourceConfig(row.config);
- if (config.kind !== 'google' && config.kind !== 'github') continue;
+ if (!isConnectorSourceKind(config.kind)) continue;
if (config.syncEnabled === false) continue;
await recordConnectorSyncAttempt(engine, row.id, at);
seeded++;
@@ -191,14 +193,22 @@ export async function attemptedConnectorSourceIds(engine: Pick<BrainEngine, 'exe
/** Account pins compare the resolved identity only; the recorded display never includes credentials. */
export function sameConnectorAccount(a: ConnectorAccount, b: ConnectorAccount): boolean {
if (a.kind !== b.kind) return false;
- if (a.kind === 'google') return a.email === (b as typeof a).email;
- const other = b as typeof a;
- return (a.installationId ?? null) === (other.installationId ?? null) && (a.login ?? null)?.toLowerCase() === (other.login ?? null)?.toLowerCase();
+ switch (a.kind) {
+ case 'google': return a.email === (b as typeof a).email;
+ case 'github': {
+ const other = b as typeof a;
+ return (a.installationId ?? null) === (other.installationId ?? null) && (a.login ?? null)?.toLowerCase() === (other.login ?? null)?.toLowerCase();
+ }
+ default: return assertNever(a);
+ }
}
export function describeConnectorAccount(account: ConnectorAccount): string {
- if (account.kind === 'google') return account.email;
- return [account.installationId !== null ? `installation ${account.installationId}` : null, account.login ? `login ${account.login}` : null]
- .filter(Boolean).join(', ') || 'no installation or login';
+ switch (account.kind) {
+ case 'google': return account.email;
+ case 'github': return [account.installationId !== null ? `installation ${account.installationId}` : null, account.login ? `login ${account.login}` : null]
+ .filter(Boolean).join(', ') || 'no installation or login';
+ default: return assertNever(account);
+ }
}
diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.ts
index 6eea7b274c..24baf2ffb8 100644
--- a/src/core/persistence/connector-status.ts
+++ b/src/core/persistence/connector-status.ts
@@ -10,6 +10,7 @@
* `connector_held_items` stay connector-only.
*/
import type { BrainEngine } from '../engine.ts';
+import { CONNECTOR_KINDS_SQL } from './connector-kinds.ts';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { CONNECTOR_STOPPED_RUNS, readManagedConnectorState, type ConnectorPurgedItem, type ConnectorRunCounts, type ConnectorRunFailure, type UpgradeRecovery } from './connector-state.ts';
@@ -61,7 +62,7 @@ function connectorFailureFix(sourceId: string, failure: ConnectorRunFailure): Ac
/** #6831: the connector run failure recorded for a source (null for a non-connector source or a last run that finished). */
export async function readConnectorLastError(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<ConnectorLastError | null> {
const [source] = await engine.executeRaw<{ incarnation: string }>(
- "SELECT incarnation::text FROM sources WHERE id=$1 AND NOT archived AND config->>'kind' IN ('google','github')", [sourceId]);
+ `SELECT incarnation::text FROM sources WHERE id=$1 AND NOT archived AND config->>'kind' IN (${CONNECTOR_KINDS_SQL})`, [sourceId]);
const failure = source ? (await readManagedConnectorState(engine, sourceId, source.incarnation)).last_failure : null;
if (!failure) return null;
return { ...failure, stopped: failure.consecutive >= CONNECTOR_STOPPED_RUNS, ...classifySyncFault({ code: failure.code, message: failure.message }),
@@ -70,7 +71,7 @@ export async function readConnectorLastError(engine: Pick<BrainEngine, 'executeR
export async function readConnectorSourceStatuses(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<Map<string, ConnectorSourceStatus>> {
const sources = await engine.executeRaw<{ id: string; incarnation: string }>(
- "SELECT id,incarnation::text FROM sources WHERE NOT archived AND config->>'kind' IN ('google','github') AND ($1::text[] IS NULL OR id=ANY($1::text[]))",
+ `SELECT id,incarnation::text FROM sources WHERE NOT archived AND config->>'kind' IN (${CONNECTOR_KINDS_SQL}) AND ($1::text[] IS NULL OR id=ANY($1::text[]))`,
[sourceIds ?? null]);
const statuses = new Map<string, ConnectorSourceStatus>();
for (const source of sources) {
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 3cc1488d28..3a809baa5f 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -35,6 +35,7 @@ import type { PageSnapshot } from '../page-state/types.ts';
import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';
import { ownedGoogleReceipts, prepareGoogleReceiptPatch, type GoogleReceipts } from './connector-google-receipts.ts';
import { connectorCheckpointKeys, connectorIdentity, connectorIdentityMatches, type ConnectorIdentity, type ConnectorKind } from './connector-identity.ts';
+import { connectorDirKey } from './connector-kinds.ts';
import { CONNECTOR_PURGED_LIMIT, readManagedConnectorState, recordConnectorSyncAttempt, sameConnectorAccount, writeManagedConnectorState, type ConnectorAccount, type ConnectorPendingEntry, type ConnectorPurgedItem, type ConnectorRunCounts, type ConnectorState } from './connector-state.ts';
import { connectorConfigDigest } from './connector-account-mismatch.ts';
import { connectorAccountChanged, connectorFenceHint, docsAnchor, receiptDeliveredHint, CONNECTOR_INTENT_OUTDATED_OLD_HOST, CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE } from './connector-errors.ts';
@@ -193,7 +194,7 @@ function connectorBindingRoot(sourceId: string, source: ConnectorSource, binding
assertPhysicalRoot(localPath, { worktreeId: binding.worktree_id, coordinationPath });
try {
const root = realpathSync(join(localPath, binding.relative_path));
- const configured = source.config[source.config.kind === 'google' ? 'g_dir' : 'gh_dir'];
+ const configured = source.config[connectorDirKey(source.config.kind as ConnectorKind)];
const directory = typeof configured === 'string' && configured.length > 0 ? configured : sourcePath;
if (!containsPath(localPath, root) || !statSync(root).isDirectory() || realpathSync(sourcePath) !== root || realpathSync(directory) !== root) {
throw new Error('root mismatch');
diff --git a/src/core/repair/connector-fences.ts b/src/core/repair/connector-fences.ts
index 9f5ad058c5..4c4adec019 100644
--- a/src/core/repair/connector-fences.ts
+++ b/src/core/repair/connector-fences.ts
@@ -12,6 +12,7 @@
* marker, and each such page is counted (`segmented_pages`) and named.
*/
import type { BrainEngine } from '../engine.ts';
+import { CONNECTOR_KINDS_SQL } from '../persistence/connector-kinds.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
import { conceptPreservationHold } from '../cycle/concept-publication.ts';
@@ -56,14 +57,14 @@ const FENCE_MARKERS = ['gbrain:facts:', 'gbrain:takes:'];
async function candidates(engine: BrainEngine, sourceIds: string[]): Promise<FencePage[]> {
return engine.executeRaw<FencePage>(`SELECT p.id,p.source_id,p.slug,p.compiled_truth,p.timeline FROM pages p JOIN sources s ON s.id=p.source_id
- WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND s.config->>'kind' IN ('google','github')
+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND s.config->>'kind' IN (${CONNECTOR_KINDS_SQL})
AND (p.timeline LIKE '%gbrain:facts:%' OR p.timeline LIKE '%gbrain:takes:%') ORDER BY p.id`, [sourceIds]);
}
/** Segmented connector pages whose timeline region holds a facts or takes fence marker, as `source:slug`. */
async function segmentedCandidates(engine: BrainEngine, sourceIds: string[], after: RepairCursor | null): Promise<string[]> {
const pages = await engine.executeRaw<{ id: number; source_id: string; slug: string }>(`SELECT p.id,p.source_id,p.slug FROM pages p JOIN sources s ON s.id=p.source_id
- WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND s.config->>'kind' IN ('google','github') AND p.body_storage='segmented' ORDER BY p.id`, [sourceIds]);
+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND s.config->>'kind' IN (${CONNECTOR_KINDS_SQL}) AND p.body_storage='segmented' ORDER BY p.id`, [sourceIds]);
const found: string[] = [];
for (const page of pages) {
if (!afterCursor({ phase: 0, id: Number(page.id) }, after)) continue;
diff --git a/src/core/write-gate-scan.ts b/src/core/write-gate-scan.ts
index 9dba3cad3d..6746d86ccf 100644
--- a/src/core/write-gate-scan.ts
+++ b/src/core/write-gate-scan.ts
@@ -24,6 +24,7 @@ import {
} from './write-gate.ts';
import { WRITE_GATE_REASON_FAMILIES, type WriteGateReasonFamily } from './write-gate-patterns.ts';
import { minTrust } from './trust/tier.ts';
+import { CONNECTOR_KINDS_SQL } from './persistence/connector-kinds.ts';
export type WriteGateScanTable = 'pages' | 'facts' | 'takes' | 'timeline_entries';
export const WRITE_GATE_SCAN_TABLES: readonly WriteGateScanTable[] = ['pages', 'facts', 'takes', 'timeline_entries'];
@@ -84,7 +85,7 @@ export function projectTier(signals: ReadonlyArray<string | null | undefined>):
/** Page-level signal on alias `pg` (with sources alias `src`): connector/webhook/clipper -> external, agent channels -> agent. */
const PAGE_SIGNAL = (pg: string, src: string) => `CASE
- WHEN ${src}.config->>'kind' IN ('google','github') OR ${pg}.source_kind = 'webhook' OR COALESCE(${pg}.frontmatter, '{}'::jsonb) ? 'source_url' THEN 'external_untrusted'
+ WHEN ${src}.config->>'kind' IN (${CONNECTOR_KINDS_SQL}) OR ${pg}.source_kind = 'webhook' OR COALESCE(${pg}.frontmatter, '{}'::jsonb) ? 'source_url' THEN 'external_untrusted'
WHEN ${pg}.source_kind LIKE 'mcp:%' OR ${pg}.ingested_via LIKE 'mcp:%' OR ${pg}.source_kind = 'capture-cli'
OR ${pg}.frontmatter->>'capturedVia' IS NOT NULL OR COALESCE(${pg}.frontmatter, '{}'::jsonb) ? 'transcript_import' THEN 'agent_written'
END`;
diff --git a/test/connector-kind-routing.test.ts b/test/connector-kind-routing.test.ts
new file mode 100644
index 0000000000..cc192a4e46
--- /dev/null
+++ b/test/connector-kind-routing.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { CONNECTOR_KINDS_SQL, CONNECTOR_SOURCE_KINDS, connectorDirKey, isConnectorSourceKind } from '../src/core/persistence/connector-kinds.ts';
+
+const ROOT = join(import.meta.dir, '..');
+const KINDS_FILE = 'src/core/persistence/connector-kinds.ts';
+
+function sourceFiles(dir: string): string[] {
+ return readdirSync(dir).flatMap(name => {
+ const path = join(dir, name);
+ return statSync(path).isDirectory() ? sourceFiles(path) : path.endsWith('.ts') ? [path] : [];
+ });
+}
+
+const KIND = String.raw`'(?:google|github)'`;
+// A list of two or more literal connector kinds (SQL IN list or array), or a kind test chained over two literal kinds.
+const FORBIDDEN: Array<[string, RegExp]> = [
+ ['literal kind list', new RegExp(`[\\[(]\\s*${KIND}\\s*,\\s*${KIND}`)],
+ ['chained kind test', new RegExp(`kind\\s*[!=]==\\s*${KIND}\\s*(?:&&|\\|\\|)\\s*[\\w.?]*kind\\s*[!=]==\\s*${KIND}`)],
+];
+
+describe('connector kind routing', () => {
+ test('no source file outside connector-kinds.ts lists connector kinds literally', () => {
+ const offenders: string[] = [];
+ for (const file of sourceFiles(join(ROOT, 'src'))) {
+ const rel = relative(ROOT, file).split('\\').join('/');
+ if (rel === KINDS_FILE) continue;
+ readFileSync(file, 'utf8').split('\n').forEach((line, index) => {
+ for (const [what, pattern] of FORBIDDEN) if (pattern.test(line)) offenders.push(`${rel}:${index + 1} ${what}: ${line.trim()}`);
+ });
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ test('the lint catches the shapes it forbids', () => {
+ const hits = (line: string) => FORBIDDEN.some(([, pattern]) => pattern.test(line));
+ expect(hits("WHERE config->>'kind' IN ('google','github')")).toBe(true);
+ expect(hits("if (!['google', 'github'].includes(kind))")).toBe(true);
+ expect(hits("if (config.kind !== 'google' && config.kind !== 'github') continue;")).toBe(true);
+ expect(hits("return config.kind === 'google' || config.kind === 'github';")).toBe(true);
+ expect(hits("if (c.kind !== 'google') continue;")).toBe(false);
+ });
+
+ test('the SQL list, the guard and the directory keys cover exactly the declared kinds', () => {
+ expect(CONNECTOR_KINDS_SQL).toBe(CONNECTOR_SOURCE_KINDS.map(kind => `'${kind}'`).join(','));
+ for (const kind of CONNECTOR_SOURCE_KINDS) {
+ expect(isConnectorSourceKind(kind)).toBe(true);
+ expect(connectorDirKey(kind)).toMatch(/^[a-z]+_dir$/);
+ }
+ expect(isConnectorSourceKind('local')).toBe(false);
+ expect(isConnectorSourceKind(undefined)).toBe(false);
+ expect(connectorDirKey('google')).toBe('g_dir');
+ expect(connectorDirKey('github')).toBe('gh_dir');
+ });
+});