Remove final AppDatabase pass-through methods with ESLint guard (C1 part 3/3)
Migrate all remaining pass-through call sites (social, skills, budget,
entityCrud, documents, knowledge, automation, wakeup, backup, threads,
settings, snapshot, connectors, workspaces, activity) to their owning
domain modules. `AppDatabase` now carries only three methods:
- createHireRequest (multi-module composite: agents + approvalsMod)
- rollbackConfigRevision (multi-module composite: documents + entityCrud)
- queryAll (raw-SQL escape hatch, @internal)
The vault/env-binding infrastructure previously passed argument-by-
argument into `entityCrud.saveSecret`/`resolveSecretEnv` now binds at
module construction, letting callers invoke `db.entityCrud.saveSecret({...})`
without carrying vault plumbing.
Structural types that narrowed AppDatabase to a bag of flat methods
(`ConnectorModelPolicyDeps` callers, `CapabilityMatchDb`, test mocks in
budget-enforcement / budget-incidents / task-quality-gates /
failure-escalation / task-quality-gates-sweep) are reshaped to the new
namespace. `connectorPolicyDepsFromDb` replaces the old pattern of
handing the whole AppDatabase to `validateConnectorModelSelection`.
A new ESLint rule in eslint.config.mjs blocks new top-level methods on
AppDatabase so the pass-through layer cannot silently grow back.
`AppDatabase.ts` dropped from 193 lines to 58; `AppDatabaseBase` lost
the 270-line trailing pass-through block.
This commit is contained in:
1 parent
a69fbb053b
commit
118e3d8795
120 files changed
+838
-933
No files matched your search
@@ -41,7 +41,7 @@ const SKIPPED = (reason: HeartbeatSkipReason): HeartbeatStartResult => ({
|
||||
|
||||
export function createHeartbeat(
|
||||
deps: OrchestrationDependencies,
|
||||
resolveWorkspace: (task: { workspaceId: string | null; projectId?: string | null } | null, agent: { workspaceId: string | null }, companyId: string) => { workspace: ReturnType<AppDatabase["getWorkspace"]>; lockMode: "exclusive" | "shared" | "none"; source: string },
|
||||
resolveWorkspace: (task: { workspaceId: string | null; projectId?: string | null } | null, agent: { workspaceId: string | null }, companyId: string) => { workspace: ReturnType<AppDatabase["workspacesMod"]["getWorkspace"]>; lockMode: "exclusive" | "shared" | "none"; source: string },
|
||||
getRunEligibilityFailure: (agent: AgentRecord, connector: ConnectorRecord, projectId?: string | null) => string | null,
|
||||
dispatchRunToWorker: (params: RunDispatchParams) => void,
|
||||
hasActiveRun: (filter: { taskId?: string; agentId?: string; companyId: string }) => boolean,
|
||||
@@ -74,14 +74,14 @@ export function createHeartbeat(
|
||||
return SKIPPED("cross_company");
|
||||
}
|
||||
const pick = pickModelForAgent(agent, {
|
||||
getConnector: (id) => db.getConnector(id),
|
||||
getDisabledModels: (id) => db.getDisabledModels(agent.companyId, id),
|
||||
getConnector: (id) => db.connectorsCrud.getConnector(id),
|
||||
getDisabledModels: (id) => db.settings.getDisabledModels(agent.companyId, id),
|
||||
listModelCapabilities: () => db.modelCapabilities.listModelCapabilities(),
|
||||
readConnectors: () => db.connectorsCrud.readConnectors(),
|
||||
});
|
||||
if (!pick.ok) {
|
||||
logger.warn(`[heartbeat] Model pick failed for agent ${agent.name}: ${pick.message}`);
|
||||
db.addActivity({
|
||||
db.activityMod.addActivity({
|
||||
companyId,
|
||||
actor: "system",
|
||||
action: "heartbeat.model_pick_failed",
|
||||
@@ -92,7 +92,7 @@ export function createHeartbeat(
|
||||
return SKIPPED("model_pick_failed");
|
||||
}
|
||||
const assignment = pick.assignment;
|
||||
const connector = db.getConnector(assignment.connectorId);
|
||||
const connector = db.connectorsCrud.getConnector(assignment.connectorId);
|
||||
const effectiveAgentForEligibility: AgentRecord = { ...agent, model: assignment.modelId };
|
||||
const eligibilityFailure = getRunEligibilityFailure(effectiveAgentForEligibility, connector, null);
|
||||
if (eligibilityFailure) {
|
||||
@@ -168,7 +168,7 @@ export function createHeartbeat(
|
||||
if (candidateTask) {
|
||||
const checkoutSuccess = db.tasks.checkoutTask(candidateTask.id, runId);
|
||||
if (!checkoutSuccess) {
|
||||
db.addActivity({
|
||||
db.activityMod.addActivity({
|
||||
companyId,
|
||||
actor: "system",
|
||||
action: "execution.checkout_rejected",
|
||||
@@ -187,7 +187,7 @@ export function createHeartbeat(
|
||||
|
||||
const isCeo = !agent.reportsTo;
|
||||
const isManager = db.agents.getDirectReports(agent.id, companyId).length > 0;
|
||||
const goalCount = db.countActiveGoalsForCompany(companyId);
|
||||
const goalCount = db.entityCrud.countActiveGoalsForCompany(companyId);
|
||||
const taskCount = db.tasks.countActiveTasksForCompany(companyId);
|
||||
const companyNeedsBootstrap = goalCount > 0 && taskCount < goalCount;
|
||||
|
||||
@@ -227,7 +227,7 @@ export function createHeartbeat(
|
||||
workspaceMode: workspaceResolution.lockMode,
|
||||
companyName: companyBasic?.name ?? "Unknown",
|
||||
companyDescription: companyBasic?.description ?? "",
|
||||
snapshot: db.listSnapshot(),
|
||||
snapshot: db.snap.listSnapshot(),
|
||||
trigger,
|
||||
resolvedModel: assignment.modelId,
|
||||
});
|
||||
@@ -245,7 +245,7 @@ export function createHeartbeat(
|
||||
);
|
||||
}
|
||||
|
||||
db.addActivity({
|
||||
db.activityMod.addActivity({
|
||||
companyId,
|
||||
actor: "system",
|
||||
action: "heartbeat.triggered",
|
||||
@@ -284,16 +284,16 @@ export function createHeartbeat(
|
||||
|
||||
const agentBusy = hasActiveRun({ agentId, companyId });
|
||||
if (agentBusy) {
|
||||
db.enqueueWakeupRequest(companyId, agentId, trigger, `Wake for agent: ${trigger}`, context);
|
||||
db.wakeup.enqueueWakeupRequest(companyId, agentId, trigger, `Wake for agent: ${trigger}`, context);
|
||||
return null;
|
||||
}
|
||||
|
||||
const result = startAgentHeartbeatRun(agentId, companyId, trigger);
|
||||
if (result.status === "skipped") {
|
||||
db.enqueueWakeupRequest(companyId, agentId, trigger, `Wake for agent (deferred:${result.reason}): ${trigger}`, context);
|
||||
db.wakeup.enqueueWakeupRequest(companyId, agentId, trigger, `Wake for agent (deferred:${result.reason}): ${trigger}`, context);
|
||||
return null;
|
||||
}
|
||||
db.completePendingWakeupRequests(agentId, companyId, result.runId);
|
||||
db.wakeup.completePendingWakeupRequests(agentId, companyId, result.runId);
|
||||
return result.runId;
|
||||
}
|
||||
|
||||
|
||||
@@ -31,28 +31,28 @@ export function resolveWorkspaceWithLockMode(
|
||||
agent: { workspaceId: string | null },
|
||||
companyId: string,
|
||||
): {
|
||||
workspace: ReturnType<AppDatabase["getWorkspace"]>;
|
||||
workspace: ReturnType<AppDatabase["workspacesMod"]["getWorkspace"]>;
|
||||
lockMode: WorkspaceLockMode;
|
||||
source: "task" | "agent" | "project" | "company_fallback" | "none";
|
||||
} {
|
||||
if (task) {
|
||||
const taskWorkspace = db.getWorkspace(task.workspaceId);
|
||||
const taskWorkspace = db.workspacesMod.getWorkspace(task.workspaceId);
|
||||
if (taskWorkspace) {
|
||||
return { workspace: taskWorkspace, lockMode: "exclusive", source: "task" };
|
||||
}
|
||||
}
|
||||
|
||||
const agentWorkspace = db.getWorkspace(agent.workspaceId);
|
||||
const agentWorkspace = db.workspacesMod.getWorkspace(agent.workspaceId);
|
||||
if (agentWorkspace) {
|
||||
return { workspace: agentWorkspace, lockMode: "exclusive", source: "agent" };
|
||||
}
|
||||
|
||||
const projectWorkspace = db.getProjectPrimaryWorkspace(task?.projectId ?? null, companyId);
|
||||
const projectWorkspace = db.workspacesMod.getProjectPrimaryWorkspace(task?.projectId ?? null, companyId);
|
||||
if (projectWorkspace) {
|
||||
return { workspace: projectWorkspace, lockMode: "exclusive", source: "project" };
|
||||
}
|
||||
|
||||
const fallbackWorkspace = db.getAnyCompanyWorkspace(companyId);
|
||||
const fallbackWorkspace = db.workspacesMod.getAnyCompanyWorkspace(companyId);
|
||||
if (fallbackWorkspace) {
|
||||
return { workspace: fallbackWorkspace, lockMode: "exclusive", source: "company_fallback" };
|
||||
}
|
||||
|
||||
@@ -47,7 +47,15 @@ export function createRunDispatch(deps: OrchestrationDependencies) {
|
||||
logger.info(`[run] Agent ${agent.name} connector ${connector.id} blocked: ${issue}`);
|
||||
return "CONNECTOR_NOT_READY";
|
||||
}
|
||||
const modelSelection = validateConnectorModelSelection(db, agent.companyId, connector.id, agent.model ?? null);
|
||||
const modelSelection = validateConnectorModelSelection(
|
||||
{
|
||||
getConnector: (id) => db.connectorsCrud.getConnector(id),
|
||||
getDisabledModels: (cid, connId) => db.settings.getDisabledModels(cid, connId),
|
||||
},
|
||||
agent.companyId,
|
||||
connector.id,
|
||||
agent.model ?? null,
|
||||
);
|
||||
if (!modelSelection.ok) {
|
||||
logger.info(`[run] Agent ${agent.name} connector model blocked: ${modelSelection.error}`);
|
||||
return "CONNECTOR_MODEL_NOT_ALLOWED";
|
||||
@@ -81,7 +89,7 @@ export function createRunDispatch(deps: OrchestrationDependencies) {
|
||||
if (
|
||||
params.workspaceMode === "exclusive" &&
|
||||
params.workspace &&
|
||||
!db.claimWorkspaceLock(params.workspace.id, params.runId)
|
||||
!db.workspacesMod.claimWorkspaceLock(params.workspace.id, params.runId)
|
||||
) {
|
||||
db.runs.finishRun({
|
||||
runId: params.runId,
|
||||
|
||||
@@ -94,7 +94,7 @@ export function createHeartbeatScheduler(
|
||||
tryWake(agent.id, company.id, agent.name, "timer");
|
||||
}
|
||||
|
||||
const goalCount = db.countActiveGoalsForCompany(company.id);
|
||||
const goalCount = db.entityCrud.countActiveGoalsForCompany(company.id);
|
||||
// Bootstrap when the company has active goals but no work is
|
||||
// actually advancing. The previous gate ("taskCount === 0")
|
||||
// missed the case where every task is in_review or blocked —
|
||||
|
||||
@@ -32,10 +32,10 @@ export function createHousekeepingScheduler(
|
||||
for (const company of activeCompanies) {
|
||||
try {
|
||||
const currentMonth = new Date().toISOString().slice(0, 7);
|
||||
const lastResetMonth = db.getLastBudgetResetMonth(company.id) ?? "";
|
||||
const lastResetMonth = db.settings.getLastBudgetResetMonth(company.id) ?? "";
|
||||
if (currentMonth !== lastResetMonth) {
|
||||
db.agents.resetMonthlyBudgets(company.id);
|
||||
db.setLastBudgetResetMonth(company.id, currentMonth);
|
||||
db.settings.setLastBudgetResetMonth(company.id, currentMonth);
|
||||
logger.info(`[housekeeping] Reset monthly budgets for company ${company.name} (${currentMonth})`);
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ export function createHousekeepingScheduler(
|
||||
}
|
||||
|
||||
try {
|
||||
const staleWakeups = db.purgeExpiredWakeupRequests();
|
||||
const staleWakeups = db.wakeup.purgeExpiredWakeupRequests();
|
||||
if (staleWakeups > 0) {
|
||||
logger.info(`[housekeeping] Purged ${staleWakeups} expired wakeup request(s)`);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ export function createLockRecoveryScheduler(deps: OrchestrationDependencies) {
|
||||
try {
|
||||
const recovered = db.recoverStaleLocks();
|
||||
for (const task of recovered) {
|
||||
db.addActivity({
|
||||
db.activityMod.addActivity({
|
||||
companyId: task.companyId,
|
||||
actor: "system",
|
||||
action: "execution.lock_recovered",
|
||||
@@ -31,7 +31,7 @@ export function createLockRecoveryScheduler(deps: OrchestrationDependencies) {
|
||||
}
|
||||
|
||||
try {
|
||||
const staleReleased = db.releaseStaleWorkspaceLocks();
|
||||
const staleReleased = db.workspacesMod.releaseStaleWorkspaceLocks();
|
||||
if (staleReleased > 0) {
|
||||
logger.info(`[lock-recovery] Released ${staleReleased} stale workspace lock(s)`);
|
||||
publishDomainChanged();
|
||||
|
||||
@@ -8,7 +8,7 @@ import { pickModelForAgent } from "../model-dispatch";
|
||||
|
||||
export function createTaskRunner(
|
||||
deps: OrchestrationDependencies,
|
||||
resolveWorkspace: (task: { workspaceId: string | null; projectId?: string | null } | null, agent: { workspaceId: string | null }, companyId: string) => { workspace: ReturnType<AppDatabase["getWorkspace"]>; lockMode: "exclusive" | "shared" | "none"; source: string },
|
||||
resolveWorkspace: (task: { workspaceId: string | null; projectId?: string | null } | null, agent: { workspaceId: string | null }, companyId: string) => { workspace: ReturnType<AppDatabase["workspacesMod"]["getWorkspace"]>; lockMode: "exclusive" | "shared" | "none"; source: string },
|
||||
getRunEligibilityFailure: (agent: AgentRecord, connector: ConnectorRecord, projectId?: string | null) => string | null,
|
||||
dispatchRunToWorker: (params: RunDispatchParams) => void,
|
||||
hasActiveRun: (filter: { taskId?: string; agentId?: string; companyId: string }) => boolean,
|
||||
@@ -48,8 +48,8 @@ export function createTaskRunner(
|
||||
return fail("AGENT_COMPANY_MISMATCH", "The assigned agent does not belong to the task company.");
|
||||
}
|
||||
const pick = pickModelForAgent(agent, {
|
||||
getConnector: (id) => db.getConnector(id),
|
||||
getDisabledModels: (id) => db.getDisabledModels(agent.companyId, id),
|
||||
getConnector: (id) => db.connectorsCrud.getConnector(id),
|
||||
getDisabledModels: (id) => db.settings.getDisabledModels(agent.companyId, id),
|
||||
listModelCapabilities: () => db.modelCapabilities.listModelCapabilities(),
|
||||
readConnectors: () => db.connectorsCrud.readConnectors(),
|
||||
});
|
||||
@@ -57,7 +57,7 @@ export function createTaskRunner(
|
||||
return fail("MODEL_PICK_FAILED", pick.message);
|
||||
}
|
||||
const assignment = pick.assignment;
|
||||
const connector = db.getConnector(assignment.connectorId);
|
||||
const connector = db.connectorsCrud.getConnector(assignment.connectorId);
|
||||
const effectiveAgentForEligibility: AgentRecord = { ...agent, model: assignment.modelId };
|
||||
const eligibilityFailure = getRunEligibilityFailure(effectiveAgentForEligibility, connector, task.projectId ?? null);
|
||||
if (eligibilityFailure === "AGENT_NOT_RUNNABLE") {
|
||||
@@ -119,11 +119,11 @@ export function createTaskRunner(
|
||||
workspaceMode: workspaceResolution.lockMode,
|
||||
companyName: companyBasic?.name ?? "Unknown",
|
||||
companyDescription: companyBasic?.description ?? "",
|
||||
snapshot: db.listSnapshot(),
|
||||
snapshot: db.snap.listSnapshot(),
|
||||
trigger,
|
||||
resolvedModel: assignment.modelId,
|
||||
});
|
||||
db.addActivity({
|
||||
db.activityMod.addActivity({
|
||||
companyId: task.companyId,
|
||||
actor,
|
||||
action: "run.queued",
|
||||
@@ -140,7 +140,7 @@ export function createTaskRunner(
|
||||
try {
|
||||
const recovered = db.recoverStaleLocks();
|
||||
for (const task of recovered) {
|
||||
db.addActivity({
|
||||
db.activityMod.addActivity({
|
||||
companyId: task.companyId,
|
||||
actor: "system",
|
||||
action: "execution.lock_recovered",
|
||||
@@ -160,7 +160,7 @@ export function createTaskRunner(
|
||||
if (isQuitting() || !hasWorkerReady()) {
|
||||
return;
|
||||
}
|
||||
const snapshot = db.listSnapshot();
|
||||
const snapshot = db.snap.listSnapshot();
|
||||
const companiesById = new Map(snapshot.companies.map((company) => [company.id, company]));
|
||||
|
||||
for (const run of db.runs.listQueuedRuns()) {
|
||||
@@ -182,7 +182,7 @@ export function createTaskRunner(
|
||||
try {
|
||||
const task = run.taskId ? db.entityCrud.getTask(run.taskId) : null;
|
||||
const agent = db.entityCrud.getAgent(run.agentId);
|
||||
const connector = db.getConnector(run.connectorId);
|
||||
const connector = db.connectorsCrud.getConnector(run.connectorId);
|
||||
const eligibilityFailure = getRunEligibilityFailure(agent, connector, task?.projectId ?? null);
|
||||
if (eligibilityFailure) {
|
||||
if (eligibilityFailure === "CONNECTOR_MODEL_NOT_ALLOWED") {
|
||||
@@ -196,7 +196,7 @@ export function createTaskRunner(
|
||||
model: null,
|
||||
unattributedCost: true,
|
||||
});
|
||||
db.addActivity({
|
||||
db.activityMod.addActivity({
|
||||
companyId: run.companyId,
|
||||
actor: "system",
|
||||
action: "run.recovery_blocked",
|
||||
|
||||
@@ -23,12 +23,12 @@ export interface RunDispatchParams {
|
||||
// Downstream code (prompt builder, worker payload, session pointer)
|
||||
// branches on this — when null, skip task-scoped state.
|
||||
task: ReturnType<AppDatabase["entityCrud"]["getTask"]> | null;
|
||||
connector: ReturnType<AppDatabase["getConnector"]>;
|
||||
workspace: ReturnType<AppDatabase["getWorkspace"]>;
|
||||
connector: ReturnType<AppDatabase["connectorsCrud"]["getConnector"]>;
|
||||
workspace: ReturnType<AppDatabase["workspacesMod"]["getWorkspace"]>;
|
||||
workspaceMode: WorkspaceLockMode;
|
||||
companyName: string;
|
||||
companyDescription: string;
|
||||
snapshot: ReturnType<AppDatabase["listSnapshot"]>;
|
||||
snapshot: ReturnType<AppDatabase["snap"]["listSnapshot"]>;
|
||||
trigger: string;
|
||||
/**
|
||||
* Model id resolved by `pickModelForAgent` at dispatch time. When the
|
||||
@@ -63,7 +63,7 @@ function assembleApiEnv(
|
||||
trigger: string,
|
||||
deps: Pick<TurnContextDeps, "getApiPort" | "createRunToken">,
|
||||
) {
|
||||
const env = db.resolveSecretEnv(connector.envBindingText, companyId);
|
||||
const env = db.entityCrud.resolveSecretEnv(connector.envBindingText, companyId);
|
||||
const apiPort = deps.getApiPort();
|
||||
const apiUrl = apiPort ? `http://127.0.0.1:${apiPort}` : "";
|
||||
const apiKey = apiUrl ? deps.createRunToken(agentId, companyId, runId) : "";
|
||||
@@ -136,7 +136,14 @@ function resolveEnabledConnectorModels(
|
||||
companyId: string,
|
||||
connector: { id: string; model: string | null },
|
||||
): string[] {
|
||||
return getConnectorModelPolicy(db, companyId, connector.id as ConnectorId).enabledModels.map((model) => model.id);
|
||||
return getConnectorModelPolicy(
|
||||
{
|
||||
getConnector: (id) => db.connectorsCrud.getConnector(id),
|
||||
getDisabledModels: (cid, connId) => db.settings.getDisabledModels(cid, connId),
|
||||
},
|
||||
companyId,
|
||||
connector.id as ConnectorId,
|
||||
).enabledModels.map((model) => model.id);
|
||||
}
|
||||
|
||||
function resolveSession(
|
||||
@@ -252,7 +259,7 @@ function buildConnectorCatalog(
|
||||
) {
|
||||
return connectors
|
||||
.filter((c) => c.status === "ready")
|
||||
.filter((c) => db.hasModelPoolSettings(companyId, c.id))
|
||||
.filter((c) => db.settings.hasModelPoolSettings(companyId, c.id))
|
||||
.map((c) => ({
|
||||
id: c.id,
|
||||
label: c.label,
|
||||
@@ -301,7 +308,7 @@ export function buildRunPayload(params: RunDispatchParams, deps: TurnContextDeps
|
||||
allTasks: snapshot.tasks.filter((entry) => entry.companyId === companyId),
|
||||
recentComments: normalizeCommentsForPrompt(recentComments),
|
||||
companyDescription,
|
||||
socialAccounts: db.listSocialAccounts(companyId).map((account) => ({
|
||||
socialAccounts: db.social.listSocialAccounts(companyId).map((account) => ({
|
||||
id: account.id,
|
||||
platform: account.platform,
|
||||
accountName: account.accountName,
|
||||
@@ -315,7 +322,7 @@ export function buildRunPayload(params: RunDispatchParams, deps: TurnContextDeps
|
||||
allConnectors: buildConnectorCatalog(db, companyId, snapshot.connectors),
|
||||
sessionHandoff,
|
||||
skills,
|
||||
companySkillCatalog: db.listCompanySkills(companyId).map((skill) => ({
|
||||
companySkillCatalog: db.skills.listCompanySkills(companyId).map((skill) => ({
|
||||
name: skill.name,
|
||||
slug: skill.slug,
|
||||
description: skill.description,
|
||||
@@ -328,7 +335,15 @@ export function buildRunPayload(params: RunDispatchParams, deps: TurnContextDeps
|
||||
|
||||
const thinkingEffort = extractThinkingEffort(agent.metadataJson, deps.logger, agent.id);
|
||||
const modelForRun = params.resolvedModel !== undefined ? params.resolvedModel : agent.model;
|
||||
const modelSelection = validateConnectorModelSelection(db, companyId, connector.id, modelForRun);
|
||||
const modelSelection = validateConnectorModelSelection(
|
||||
{
|
||||
getConnector: (id) => db.connectorsCrud.getConnector(id),
|
||||
getDisabledModels: (cid, connId) => db.settings.getDisabledModels(cid, connId),
|
||||
},
|
||||
companyId,
|
||||
connector.id,
|
||||
modelForRun,
|
||||
);
|
||||
if (!modelSelection.ok) {
|
||||
throw new Error(modelSelection.error);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user