fix(dashboard): scope areas and responsibilities to each user (#22513)

This commit is contained in:
scotttong authored and GitHub committed 2026-11-21 13:59:00 -08:00
1 parent 558dbb0132
commit 856f14e507
68 files changed
+2708 -559

No files matched your search

+16 -9
View File
@@ -1,3 +1,4 @@
import { isDashboardActivity } from "./responsibility-privacy.js";
import { notifyActiveRunSilence } from "./live-run-recovery-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { beginRunPhase } from "./execution-preparation-timing.js";
@@ -152,15 +153,21 @@ export async function resolveResponsibleUserIdForActivity(db: Db, input: LogActi
export function publishActivity(publication: ActivityPublication) {
const finish = beginRunPhase("execution.realtime");
try {
publishLiveEvent({
companyId: publication.companyId,
type: "activity.logged",
payload: publication.payload,
});
if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent);
} catch (error) {
finish(true);
throw error;
if (isDashboardActivity(publication.payload.entityType)) {
// The company bus carries only an invalidation. Each viewer fetches their own data.
publishLiveEvent({
companyId: publication.companyId,
type: "activity.logged",
payload: { action: "responsibility.dashboard_changed", entityType: "responsibility" },
});
return;
}
publishLiveEvent({
companyId: publication.companyId,
type: "activity.logged",
payload: publication.payload,
});
if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent);
} finally { finish(); }
}
+3
View File
@@ -1,3 +1,4 @@
import { dashboardActivityCondition, dashboardAuditConversationCondition } from "./responsibility-privacy.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { skillAccessService } from "./skill-access.js";
import { credentialAccessConnectionNameSql } from "./credential-access-visibility.js";
@@ -37,6 +38,7 @@ export interface ActivityFilters {
limit?: number;
readCondition?: SQL<boolean>;
caseReadCondition?: SQL<boolean>;
dashboardUserId?: string | null;
}
const DEFAULT_ACTIVITY_LIMIT = 100;
@@ -418,6 +420,7 @@ export function activityService(db: Db) {
return {
list: async (filters: ActivityFilters) => {
const conditions = [eq(activityLog.companyId, filters.companyId), await skillAccessService(db).activityCondition(filters.companyId),
dashboardActivityCondition(filters.dashboardUserId), dashboardAuditConversationCondition(filters.dashboardUserId),
filters.caseReadCondition ?? sql<boolean>`${activityLog.entityType} <> 'case'`];
const limit = normalizeActivityLimit(filters.limit);
@@ -1,3 +1,4 @@
import { dashboardActivityCondition, dashboardAuditConversationCondition } from "./responsibility-privacy.js";
import { and, desc, eq, gte, inArray, isNotNull, isNull, lt, lte, or, sql, type SQL } from "drizzle-orm";
import { z } from "zod";
import type { Db } from "@paperclipai/db";
@@ -22,6 +23,7 @@ export interface AgentActionAuditFilters {
cursor?: string;
limit: number;
caseReadCondition?: SQL<boolean>;
dashboardUserId?: string | null;
}
type CursorValue = { createdAt: string; id: string };
@@ -57,6 +59,7 @@ export function agentActionAuditService(db: Db) {
if (filters.cursor && !cursor) throw badRequest("Invalid audit cursor");
const effectiveResponsibleUserId = sql<string | null>`coalesce(${activityLog.responsibleUserId}, ${heartbeatRuns.responsibleUserId})`;
const conditions = [eq(activityLog.companyId, filters.companyId),
dashboardActivityCondition(filters.dashboardUserId), dashboardAuditConversationCondition(filters.dashboardUserId),
filters.caseReadCondition ?? sql<boolean>`${activityLog.entityType} <> 'case'`];
// Preserve the historical agent-audit query unless the caller opts into
// the unified all-actors feed explicitly.
+19 -8
View File
@@ -1,3 +1,4 @@
import { dashboardConversationCondition, dashboardConversationReadable } from "./responsibility-privacy.js";
import { readOncePerRequest } from "./authorization-read-scope.js";
import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
@@ -172,6 +173,7 @@ export type AuthorizationDecision = {
| "deny_agent_interaction"
| "deny_low_trust_boundary"
| "deny_issue_private"
| "deny_dashboard_conversation_private"
| "deny_project_private"
| "deny_scope"
| "deny_unsupported_action";
@@ -226,6 +228,7 @@ const PLAIN_DELEGATED_USER_DENIALS: Record<AuthorizationDenialReason, (subject:
deny_low_trust_boundary: (subject, action) => `This company's limits for this agent do not let ${lowerFirst(subject)} ${action}.`,
deny_agent_interaction: (_subject, action) => `Agents are not allowed to ${action} in this company; a person who manages permissions can change this.`,
deny_issue_private: (subject) => `${subject} cannot see this private task.`,
deny_dashboard_conversation_private: (subject) => `${subject} cannot see this personal dashboard conversation.`,
deny_project_private: (subject) => `${subject} cannot see this private project.`,
inbox_target_user_unresolved: () => "Paperclip could not tell whose inbox this is.",
inbox_management_disabled: () => "This person has turned off agent management of their inbox.",
@@ -741,12 +744,13 @@ export async function readInstanceAdmin(db: Db | DbTransaction, userId: string):
}
export async function issueReadSqlCondition(db: Db | DbTransaction, actor: AuthorizationActor): Promise<SQL<boolean>> {
if (actor.authorizingUserId) return issuePrivacyCondition(actor);
if (issuePrivacyMode() !== "enforce") return sql<boolean>`true`;
if (actor.source === "local_implicit" || actor.isInstanceAdmin) return sql<boolean>`true`;
const personal = dashboardConversationCondition(actor);
if (actor.authorizingUserId) return sql<boolean>`(${personal} and ${issuePrivacyCondition(actor)})`;
if (issuePrivacyMode() !== "enforce") return personal;
if (actor.source === "local_implicit" || actor.isInstanceAdmin) return personal;
if (actor.type === "board" && !actor.ignoreInstanceAdmin && actor.source !== "cloud_tenant"
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return sql<boolean>`true`;
return issuePrivacyCondition(actor);
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return personal;
return sql<boolean>`(${personal} and ${issuePrivacyCondition(actor)})`;
}
/** SQL equivalent used for project list/search pushdown. */
@@ -3017,9 +3021,6 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|| input.resource.type !== "issue"
|| !input.resource.issueId
|| !intersectedDecision.allowed
|| intersectedDecision.reason === "allow_instance_admin"
|| intersectedDecision.reason === "allow_local_board"
|| (!input.actor.authorizingUserId && issuePrivacyMode() === "off")
) return intersectedDecision;
const resource = input.resource;
@@ -3029,6 +3030,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
.select({
id: issues.id,
companyId: issues.companyId,
originKind: issues.originKind, originId: issues.originId,
visibility: issues.visibility,
privacyRootIssueId: issues.privacyRootIssueId,
responsibleUserId: issues.responsibleUserId,
@@ -3040,6 +3042,15 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
.from(issues)
.where(and(eq(issues.id, resource.issueId!), eq(issues.companyId, resource.companyId)))
.then((rows) => rows[0] ?? null);
if (issue && !dashboardConversationReadable(input.actor, issue)) {
return deny({
action: input.action,
reason: "deny_dashboard_conversation_private",
explanation: "This personal dashboard conversation is private.",
});
}
if (intersectedDecision.reason === "allow_instance_admin" || intersectedDecision.reason === "allow_local_board"
|| (!input.actor.authorizingUserId && issuePrivacyMode() === "off")) return intersectedDecision;
if (!issue || (retainedIssue?.companyId === resource.companyId
? retainedIssue.readable : await canActorReadIssuePrivacy(db, input.actor, issue))) return intersectedDecision;
+12 -10
View File
@@ -885,11 +885,11 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
}
/** Company-wide unfinished projects, open tasks and active routines under no live responsibility. */
async function looseWork(companyId: string, scope: ResponsibilityReadScope): Promise<ResponsibilityLooseWork> {
async function looseWork(companyId: string, ownerUserId: string, scope: ResponsibilityReadScope): Promise<ResponsibilityLooseWork> {
const liveLink = (column: SQL) => sql`exists (
select 1 from ${responsibilityLinks} ll
join ${responsibilities} lr on lr.id = ll.responsibility_id
where ${column} and lr.status in ${LIVE_STATUS_SQL})`;
where ${column} and lr.owner_user_id = ${ownerUserId} and lr.status in ${LIVE_STATUS_SQL})`;
const projectLoose = sql`not ${liveLink(sql`ll.project_id = ${projects.id}`)}`;
const issueLoose = sql`not ${liveLink(sql`ll.issue_id = ${issues.id}`)}
and (${issues.projectId} is null or not ${liveLink(sql`ll.project_id = ${issues.projectId}`)})`;
@@ -977,8 +977,8 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
return row;
}
async function assertAreaUsable(companyId: string, areaId: string, database: Db | DbTransaction = db) {
const area = await areasSvc.getInCompany(companyId, areaId, database);
async function assertAreaUsable(companyId: string, ownerUserId: string, areaId: string, database: Db | DbTransaction = db) {
const area = await areasSvc.getInCompany(companyId, ownerUserId, areaId, database);
if (!area) throw notFound("Area not found");
if (area.status === "archived") throw unprocessable("That area is archived; restore it or choose another area");
return area;
@@ -1017,7 +1017,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
/** Inside `tx`: when the row is active and its area is proposed, the area becomes active. */
async function activateAreaFor(tx: DbTransaction, row: ResponsibilityRow): Promise<ResponsibilityArea | null> {
if (row.status !== "active" || !row.areaId) return null;
return areasSvc.activateIfProposed(tx, row.companyId, row.areaId);
return areasSvc.activateIfProposed(tx, row.companyId, row.ownerUserId, row.areaId);
}
/** Agent rule for an active responsibility: it runs it, or is assigned a member task or routine. */
@@ -1208,8 +1208,8 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
withRollups(rows, opts.scope),
distinctTaskTotals(activeIds, opts.scope),
distinctProjectTotals(activeIds, opts.scope),
looseWork(companyId, opts.scope),
areasSvc.listActiveAnd(companyId, referencedAreaIds),
looseWork(companyId, ownerUserId, opts.scope),
areasSvc.listActiveAnd(companyId, ownerUserId, referencedAreaIds),
]);
const responsibilitiesList = all.filter((row) => row.status !== "proposed");
const proposed = all.filter((row) => row.status === "proposed");
@@ -1271,7 +1271,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
rollups, area, projectRows, directRoutineRows, projectRoutineRows, directTaskRows, projectTaskRows, skills, artifacts, projectTaskCounts,
] = await Promise.all([
computeRollups([row], scope),
row.areaId ? areasSvc.getInCompany(row.companyId, row.areaId) : Promise.resolve(null),
row.areaId ? areasSvc.getInCompany(row.companyId, row.ownerUserId, row.areaId) : Promise.resolve(null),
db.select({
linkId: responsibilityLinks.id,
id: projects.id,
@@ -1386,7 +1386,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
metricHigh: input.metricHigh ?? null,
});
}
if (input.areaId) await assertAreaUsable(companyId, input.areaId);
if (input.areaId) await assertAreaUsable(companyId, ownerUserId, input.areaId);
if (input.runByAgentId) await assertAgentInCompany(companyId, input.runByAgentId);
const now = new Date();
// The schema guarantees a metric is either whole or absent; without one
@@ -1518,7 +1518,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
throw forbidden("Agents can only propose or dismiss a responsibility; a board user confirms it");
}
}
if (patch.areaId) await assertAreaUsable(existing.companyId, patch.areaId);
if (patch.areaId) await assertAreaUsable(existing.companyId, existing.ownerUserId, patch.areaId);
if (patch.runByAgentId) await assertAgentInCompany(existing.companyId, patch.runByAgentId);
const nextStatus = patch.status ?? existing.status;
@@ -1736,6 +1736,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
*/
async lookup(
companyId: string,
ownerUserId: string,
target: ResponsibilityLinkTarget,
scope: ResponsibilityReadScope,
): Promise<ResponsibilityLinkLookupEntry[]> {
@@ -1752,6 +1753,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
.innerJoin(responsibilities, eq(responsibilities.id, responsibilityLinks.responsibilityId))
.where(and(
eq(responsibilities.companyId, companyId),
eq(responsibilities.ownerUserId, ownerUserId),
inArray(responsibilities.status, [...LIVE_STATUSES]),
projectId
? or(eq(column, target.id), eq(responsibilityLinks.projectId, projectId))
@@ -97,7 +97,7 @@ export function responsibilityAgentChangeService(db: Db) {
agentId: string;
interactionId: string | undefined;
key: string;
ownerUserId?: string;
ownerUserId: string;
}) {
const refuse = () => forbidden(
"A permanent delete needs the person's confirmation: post a confirmation card, then delete with its id after they accept it",
@@ -129,8 +129,7 @@ export function responsibilityAgentChangeService(db: Db) {
eq(companyMemberships.principalId, resolverUserId),
eq(companyMemberships.status, "active"),
));
const allowed = membership && (!input.ownerUserId || resolverUserId === input.ownerUserId
|| membership.role === "owner" || membership.role === "admin");
const allowed = membership && resolverUserId === input.ownerUserId;
if (!allowed) throw refuse();
return card;
},
+29 -30
View File
@@ -11,7 +11,7 @@ import { conflict, notFound } from "../errors.js";
type AreaRow = typeof responsibilityAreas.$inferSelect;
type DbOrTransaction = Db | Parameters<Parameters<Db["transaction"]>[0]>[0];
const TITLE_UNIQUE_INDEX = "responsibility_areas_company_title_uq";
const TITLE_UNIQUE_INDEX = "responsibility_areas_owner_title_uq";
/** `board` with `viaAgentId`: an agent acting for a member of the company, which creates what that person could. */
export type ResponsibilityAreaCreateActor =
@@ -20,7 +20,14 @@ export type ResponsibilityAreaCreateActor =
export function toResponsibilityArea(row: AreaRow): ResponsibilityArea {
return {
...row,
id: row.id,
companyId: row.companyId,
title: row.title,
description: row.description,
proposedByAgentId: row.proposedByAgentId,
sortOrder: row.sortOrder,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
status: row.status as ResponsibilityArea["status"],
source: row.source as ResponsibilityArea["source"],
};
@@ -46,15 +53,13 @@ const AREA_ORDER = [
] as const;
/**
* Areas: broad nouns a company cares about. No owner. Board users, and agents
* acting for a member of the company, manage them; other agents can only
* propose one (idempotently, by case-insensitive title).
* Area titles are unique within one person's dashboard in a company.
*/
export function responsibilityAreaService(db: Db) {
async function findLiveByTitle(companyId: string, title: string, database: DbOrTransaction = db) {
async function findLiveByTitle(companyId: string, ownerUserId: string, title: string, database: DbOrTransaction = db) {
return database.select().from(responsibilityAreas)
.where(and(
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
sql`lower(${responsibilityAreas.title}) = lower(${title})`,
ne(responsibilityAreas.status, "archived"),
))
@@ -66,16 +71,16 @@ export function responsibilityAreaService(db: Db) {
getById: (id: string) =>
db.select().from(responsibilityAreas).where(eq(responsibilityAreas.id, id)).then((rows) => rows[0] ?? null),
async getInCompany(companyId: string, id: string, database: DbOrTransaction = db) {
async getInCompany(companyId: string, ownerUserId: string, id: string, database: DbOrTransaction = db) {
return database.select().from(responsibilityAreas)
.where(and(eq(responsibilityAreas.id, id), eq(responsibilityAreas.companyId, companyId)))
.where(and(eq(responsibilityAreas.id, id), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId)))
.then((rows) => rows[0] ?? null);
},
async list(companyId: string, opts: { includeArchived?: boolean } = {}): Promise<ResponsibilityArea[]> {
async list(companyId: string, ownerUserId: string, opts: { includeArchived?: boolean } = {}): Promise<ResponsibilityArea[]> {
const rows = await db.select().from(responsibilityAreas)
.where(and(
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
opts.includeArchived ? undefined : ne(responsibilityAreas.status, "archived"),
))
.orderBy(...AREA_ORDER);
@@ -83,10 +88,10 @@ export function responsibilityAreaService(db: Db) {
},
/** Active areas in the company plus the listed ids (whatever their status). */
async listActiveAnd(companyId: string, ids: readonly string[]): Promise<ResponsibilityArea[]> {
async listActiveAnd(companyId: string, ownerUserId: string, ids: readonly string[]): Promise<ResponsibilityArea[]> {
const rows = await db.select().from(responsibilityAreas)
.where(and(
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
ids.length > 0
? or(eq(responsibilityAreas.status, "active"), inArray(responsibilityAreas.id, [...ids]))
: eq(responsibilityAreas.status, "active"),
@@ -102,13 +107,14 @@ export function responsibilityAreaService(db: Db) {
*/
async create(
companyId: string,
ownerUserId: string,
input: CreateResponsibilityArea,
actor: ResponsibilityAreaCreateActor,
): Promise<{ area: ResponsibilityArea; created: boolean }> {
const existing = await findLiveByTitle(companyId, input.title);
const existing = await findLiveByTitle(companyId, ownerUserId, input.title);
if (existing) return { area: toResponsibilityArea(existing), created: false };
const values: typeof responsibilityAreas.$inferInsert = {
companyId,
companyId, ownerUserId,
title: input.title,
description: input.description ?? null,
sortOrder: input.sortOrder ?? 0,
@@ -123,13 +129,14 @@ export function responsibilityAreaService(db: Db) {
} catch (error) {
if (!isTitleConflict(error)) throw error;
// A concurrent request created the same title first; return it.
const winner = await findLiveByTitle(companyId, input.title);
const winner = await findLiveByTitle(companyId, ownerUserId, input.title);
if (!winner) throw error;
return { area: toResponsibilityArea(winner), created: false };
}
},
async update(existing: AreaRow, patch: UpdateResponsibilityArea): Promise<ResponsibilityArea> {
if (!existing.ownerUserId) throw notFound("Area not found");
const set: Partial<typeof responsibilityAreas.$inferInsert> = { updatedAt: new Date() };
for (const key of ["title", "description", "sortOrder", "status"] as const) {
if (patch[key] !== undefined) (set as Record<string, unknown>)[key] = patch[key];
@@ -137,7 +144,7 @@ export function responsibilityAreaService(db: Db) {
const nextTitle = patch.title ?? existing.title;
const nextStatus = patch.status ?? existing.status;
if (nextStatus !== "archived" && (patch.title !== undefined || patch.status !== undefined)) {
const clash = await findLiveByTitle(existing.companyId, nextTitle);
const clash = await findLiveByTitle(existing.companyId, existing.ownerUserId, nextTitle);
if (clash && clash.id !== existing.id) {
throw conflict(`Another area is already called "${clash.title}"`, { areaId: clash.id });
}
@@ -160,12 +167,14 @@ export function responsibilityAreaService(db: Db) {
* otherwise left with `areaId` null (FK on delete set null).
*/
async remove(existing: AreaRow, opts: { moveTo?: string | null } = {}): Promise<{ area: ResponsibilityArea; moved: number } | null> {
const ownerUserId = existing.ownerUserId;
if (!ownerUserId) throw notFound("Area not found");
return db.transaction(async (tx) => {
let moved = 0;
if (opts.moveTo) {
if (opts.moveTo === existing.id) throw conflict("Move its responsibilities to a different area");
const target = await tx.select().from(responsibilityAreas)
.where(and(eq(responsibilityAreas.id, opts.moveTo), eq(responsibilityAreas.companyId, existing.companyId)))
.where(and(eq(responsibilityAreas.id, opts.moveTo), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, existing.companyId)))
.then((rows) => rows[0] ?? null);
if (!target) throw notFound("Area to move responsibilities to not found");
if (target.status === "archived") throw conflict("That area is archived; restore it or choose another area");
@@ -181,23 +190,13 @@ export function responsibilityAreaService(db: Db) {
});
},
/** The people with an active responsibility in the area, whose Dashboards show it. */
async ownersInArea(companyId: string, areaId: string, statuses: readonly string[] = ["active"]): Promise<string[]> {
const rows = await db.selectDistinct({ ownerUserId: responsibilities.ownerUserId }).from(responsibilities).where(and(
eq(responsibilities.companyId, companyId),
eq(responsibilities.areaId, areaId),
inArray(responsibilities.status, [...statuses]),
));
return rows.map((row) => row.ownerUserId);
},
/** Inside `tx`: make a proposed area active. Returns the area when it changed. */
async activateIfProposed(tx: DbOrTransaction, companyId: string, areaId: string): Promise<ResponsibilityArea | null> {
async activateIfProposed(tx: DbOrTransaction, companyId: string, ownerUserId: string, areaId: string): Promise<ResponsibilityArea | null> {
const [row] = await tx.update(responsibilityAreas)
.set({ status: "active", updatedAt: new Date() })
.where(and(
eq(responsibilityAreas.id, areaId),
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.status, "proposed"),
))
.returning();
@@ -96,15 +96,15 @@ export function automationConversationService(
* responsibility the task is under (the one the person started from first);
* otherwise the organization's first-created agent that can be assigned.
*/
async function defaultAgentId(source: Pick<IssueRow, "id" | "companyId" | "assigneeAgentId">, responsibilityId?: string): Promise<string | null> {
async function defaultAgentId(source: Pick<IssueRow, "id" | "companyId" | "assigneeAgentId">, ownerUserId: string, responsibilityId?: string): Promise<string | null> {
const [{ rows, usable }, under] = await Promise.all([
companyAgents(source.companyId),
responsibilitiesSvc.lookup(source.companyId, { kind: "issue", id: source.id }, unrestricted).catch(() => []),
responsibilitiesSvc.lookup(source.companyId, ownerUserId, { kind: "issue", id: source.id }, unrestricted).catch(() => []),
]);
const ids = [...new Set([responsibilityId, ...under.map((entry) => entry.id)].filter((id): id is string => !!id))];
const runners = ids.length === 0 ? [] : await db.select({ id: responsibilities.id, runByAgentId: responsibilities.runByAgentId })
.from(responsibilities)
.where(and(eq(responsibilities.companyId, source.companyId), inArray(responsibilities.id, ids)));
.where(and(eq(responsibilities.companyId, source.companyId), eq(responsibilities.ownerUserId, ownerUserId), inArray(responsibilities.id, ids)));
const runnerIds = ids.map((id) => runners.find((row) => row.id === id)?.runByAgentId).filter((id): id is string => !!id);
return responsibleAutomationAgentId({
taskAgentId: source.assigneeAgentId,
@@ -114,11 +114,12 @@ export function automationConversationService(
});
}
async function latestConversation(source: Pick<IssueRow, "id" | "companyId">): Promise<IssueRow | null> {
async function latestConversation(source: Pick<IssueRow, "id" | "companyId">, ownerUserId: string): Promise<IssueRow | null> {
const [issue] = await db.select().from(issues).where(and(
eq(issues.companyId, source.companyId),
eq(issues.originKind, AUTOMATION_CONVERSATION_ORIGIN_KIND),
eq(issues.originId, source.id),
eq(issues.createdByUserId, ownerUserId),
ne(issues.status, "cancelled"),
)).orderBy(desc(issues.createdAt), desc(issues.id)).limit(1);
return issue ?? null;
@@ -168,8 +169,8 @@ export function automationConversationService(
}
/** Where the automation conversation for a task stands. */
async function conversation(source: IssueRow): Promise<AutomationConversation> {
const [issue, agentId] = await Promise.all([latestConversation(source), defaultAgentId(source)]);
async function conversation(source: IssueRow, ownerUserId: string): Promise<AutomationConversation> {
const [issue, agentId] = await Promise.all([latestConversation(source, ownerUserId), defaultAgentId(source, ownerUserId)]);
const proposal = issue ? await pendingProposal(issue) : null;
const state: AutomationConversation["state"] = !issue ? "none"
: proposal ? "proposal_waiting"
@@ -201,7 +202,7 @@ export function automationConversationService(
* not cancelled, while it is open or has a proposal waiting). Two queries
* whatever the count.
*/
async conversationsForTasks(companyId: string, taskIds: readonly string[]): Promise<Map<string, AutomationConversationRef>> {
async conversationsForTasks(companyId: string, taskIds: readonly string[], ownerUserId: string): Promise<Map<string, AutomationConversationRef>> {
const found = new Map<string, AutomationConversationRef>();
if (taskIds.length === 0) return found;
const rows = await db.selectDistinctOn([issues.originId], {
@@ -213,6 +214,7 @@ export function automationConversationService(
}).from(issues).where(and(
eq(issues.companyId, companyId),
eq(issues.originKind, AUTOMATION_CONVERSATION_ORIGIN_KIND),
eq(issues.createdByUserId, ownerUserId),
inArray(issues.originId, [...new Set(taskIds)]),
ne(issues.status, "cancelled"),
)).orderBy(issues.originId, desc(issues.createdAt), desc(issues.id));
@@ -238,9 +240,9 @@ export function automationConversationService(
return found;
},
async conversationFor(issueRef: { id: string; companyId: string }) {
async conversationFor(issueRef: { id: string; companyId: string }, ownerUserId: string) {
await assertEnabled();
return conversation(await loadSource(issueRef.companyId, issueRef.id));
return conversation(await loadSource(issueRef.companyId, issueRef.id), ownerUserId);
},
/**
@@ -259,11 +261,11 @@ export function automationConversationService(
await suggestions.assertCanBeAutomated(issueRef);
const source = await loadSource(issueRef.companyId, issueRef.id);
await assertNotAutomatedYet(source);
const existing = await latestConversation(source);
const existing = await latestConversation(source, actor.userId);
if (existing && (!isClosed(existing.status) || (await pendingProposal(existing)))) {
return { source, issue: existing, created: false };
}
const agentId = input.agentId ?? await defaultAgentId(source, input.responsibilityId);
const agentId = input.agentId ?? await defaultAgentId(source, actor.userId, input.responsibilityId);
if (!agentId) {
throw unprocessable("No agent in this organization can talk this through; set the automation up by hand", {
code: "automation_conversation_no_agent",
@@ -288,14 +290,9 @@ export function automationConversationService(
...(hint ? ["", `Quick suggestion from its title (only a guess): ${hint.why}`] : []),
...(backLink ? ["", backLink] : []),
].join("\n");
// The conversation copies the task's title and identifier, so a private
// task's conversation is private too: only the person and the agent see it.
const sourceIsPrivate = source.visibility === "private" || source.privacyRootIssueId !== null
|| (source.projectId !== null && await db.select({ id: projects.id }).from(projects)
.where(and(eq(projects.id, source.projectId), eq(projects.companyId, source.companyId), eq(projects.visibility, "private")))
.limit(1).then((rows) => rows.length > 0));
const issue = await issuesSvc.create(source.companyId, {
...(sourceIsPrivate ? { visibility: "private" as const } : {}),
visibility: "private",
responsibleUserId: actor.userId,
title: clip(`Automate “${source.title}”`, 200),
description,
status: "todo",
@@ -344,7 +341,7 @@ export function automationConversationService(
code: "automation_standing_check_no_heartbeat",
});
}
const filedUnder = (await responsibilitiesSvc.lookup(issue.companyId, { kind: "issue", id: source.id }, unrestricted))
const filedUnder = (await responsibilitiesSvc.lookup(issue.companyId, issue.createdByUserId!, { kind: "issue", id: source.id }, unrestricted))
.map((entry) => ({ id: entry.id, title: entry.title }));
const trigger: ProposeAutomationPayload["trigger"] = data.trigger.kind === "schedule"
? (() => {
@@ -93,7 +93,7 @@ export function responsibilityAutomationService(
suggestions.unrepeatableIssueIds(companyId, taskIds),
routinesSvc.liveOriginIds(companyId, ROUTINE_FROM_TASK_ORIGIN_KIND, taskIds),
interactions.routineSuggestionsForIssues(companyId, taskIds),
conversations.conversationsForTasks(companyId, taskIds),
conversations.conversationsForTasks(companyId, taskIds, ownerUserId),
conversations.companyAgents(companyId),
standingChecks.lastResults(companyId, routineIds, opts.scope.issueReadCondition),
]);
@@ -273,6 +273,8 @@ export function responsibilityBarService(db: Db) {
status: "todo",
priority: "medium",
assigneeAgentId: agentId,
visibility: "private",
responsibleUserId: row.ownerUserId,
originKind: RESPONSIBILITY_BAR_ORIGIN_KIND,
originId: row.id,
createdByUserId: actor.userId,
@@ -1,4 +1,4 @@
import { and, desc, eq, inArray, ne, sql } from "drizzle-orm";
import { and, desc, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { authUsers, issueThreadInteractions, issues, responsibilities, responsibilityAreas } from "@paperclipai/db";
import {
@@ -24,8 +24,6 @@ const OTHER_AREA_LIMIT = 40;
export interface DashboardGuidanceArea {
id: string;
title: string;
/** How many other people have responsibilities in it. */
others: number;
/** This person's active responsibilities in it. */
items: Array<{ id: string; sentence: string }>;
}
@@ -40,8 +38,8 @@ export interface DashboardGuidanceInput {
areas: DashboardGuidanceArea[];
/** The person's active responsibilities filed under no area. */
unfiled: Array<{ id: string; sentence: string }>;
/** Other live areas in the organization. */
otherAreas: Array<{ id: string; title: string; others: number }>;
/** Their other live areas. */
otherAreas: Array<{ id: string; title: string }>;
/** Responsibilities proposed earlier that wait for the person. */
proposed: string[];
/** Newest first. */
@@ -61,7 +59,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
return null;
}
const ownerUserId = issue.originId;
const [issueRow, owner, items, areaRows, others, history] = await Promise.all([
const [issueRow, owner, items, areaRows, history] = await Promise.all([
db.select({ originFingerprint: issues.originFingerprint }).from(issues)
.where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)))
.then((rows) => rows[0] ?? null),
@@ -80,14 +78,8 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
)).orderBy(responsibilities.sortOrder, responsibilities.createdAt),
db.select({ id: responsibilityAreas.id, title: responsibilityAreas.title, status: responsibilityAreas.status })
.from(responsibilityAreas)
.where(eq(responsibilityAreas.companyId, issue.companyId))
.where(and(eq(responsibilityAreas.companyId, issue.companyId), eq(responsibilityAreas.ownerUserId, ownerUserId)))
.orderBy(responsibilityAreas.sortOrder, sql`lower(${responsibilityAreas.title})`),
db.select({ areaId: responsibilities.areaId, count: sql<number>`count(distinct ${responsibilities.ownerUserId})::int` })
.from(responsibilities).where(and(
eq(responsibilities.companyId, issue.companyId),
ne(responsibilities.ownerUserId, ownerUserId),
inArray(responsibilities.status, ["active", "proposed"]),
)).groupBy(responsibilities.areaId),
db.select({ status: issueThreadInteractions.status, payload: issueThreadInteractions.payload, result: issueThreadInteractions.result })
.from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, issue.companyId),
@@ -96,7 +88,6 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
)).orderBy(desc(issueThreadInteractions.createdAt)).limit(PROPOSAL_HISTORY),
]);
if (!issueRow) return null;
const othersByArea = new Map(others.filter((row) => row.areaId).map((row) => [row.areaId!, row.count]));
const active = items.filter((item) => item.status === "active");
const mine = new Set(active.map((item) => item.areaId).filter((id): id is string => id !== null));
const areas: DashboardGuidanceArea[] = areaRows
@@ -104,7 +95,6 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
.map((area) => ({
id: area.id,
title: area.title,
others: othersByArea.get(area.id) ?? 0,
items: active.filter((item) => item.areaId === area.id).map((item) => ({ id: item.id, sentence: responsibilityDashboardSentence(item) })),
}));
return buildDashboardConversationGuidance({
@@ -118,7 +108,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
otherAreas: areaRows
.filter((area) => area.status !== "archived" && !mine.has(area.id))
.slice(0, OTHER_AREA_LIMIT)
.map((area) => ({ id: area.id, title: area.title, others: othersByArea.get(area.id) ?? 0 })),
.map((area) => ({ id: area.id, title: area.title })),
proposed: items.filter((item) => item.status === "proposed").map((item) => responsibilityDashboardSentence(item)),
proposals: history.map((entry) => {
const payload = entry.payload as Partial<ProposeDashboardChangesPayload> | null;
@@ -137,9 +127,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
});
}
function shared(others: number) {
return others === 0 ? "" : `; ${others === 1 ? "1 other person has" : `${others} other people have`} responsibilities in it`;
}
const CREATE_EXAMPLE = {
message: "Here is a first dashboard from your answers and what I found in your calendar and mail.",
@@ -169,7 +157,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
: "They asked you to help change the dashboard they have."} End it with one proposed set of changes they can accept with one tap. You never change the dashboard yourself: only the person can, by accepting your proposal, and they can undo it afterwards.`,
"",
"What a dashboard is made of (reason from this, not only from the rules):",
"- An area is a noun for something the person cares about: \"Fundraising\", \"Customers\", \"Hiring\". Nobody owns an area and it has no deadline; it groups what sits under it. Areas are shared across the organization, so other people may have responsibilities in the same area.",
"- An area is a noun for something the person cares about: \"Fundraising\", \"Customers\", \"Hiring\". An area belongs to this person and groups their responsibilities.",
"- A responsibility is something this person owns and answers for, on an ongoing basis. Write it as one sentence saying what must be true and stay true: \"Every prospective LP hears from us at least every two weeks.\" \"Customers get a reply within one working day.\" If it can be finished, it is a task or a project, not a responsibility: \"Send the deck to two LPs\" is a task, and \"Close Fund VI\" is a project that serves a responsibility.",
"- Each responsibility passes three tests. Ongoing: it still makes sense after the current project ships. Theirs: they answer for it, not just take part in it (attending a meeting series is not owning it; running it is). In their words: the words their answers, mail subjects and calendar titles use, not job-description words.",
`- Keep it small. A person can hold perhaps five to seven areas in their head, and one to three responsibilities under each is plenty. A few that are right beat a full list: every line is something they will look at every day, and a list that is mostly wrong teaches them to ignore it. Each sentence is at most ${RESPONSIBILITY_DASHBOARD_SENTENCE_MAX} characters.`,
@@ -183,7 +171,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
lines.push("- Empty: they own no responsibilities yet.");
}
for (const area of input.areas) {
lines.push(`- Area "${area.title}" (areaId ${area.id}${shared(area.others)}):`);
lines.push(`- Area "${area.title}" (areaId ${area.id}):`);
for (const item of area.items) lines.push(` - "${item.sentence}" (responsibilityId ${item.id})`);
}
if (input.unfiled.length > 0) {
@@ -191,8 +179,8 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
for (const item of input.unfiled) lines.push(` - "${item.sentence}" (responsibilityId ${item.id})`);
}
if (input.otherAreas.length > 0) {
lines.push("", "Other areas in the organization (file under one by its areaId rather than adding a near-duplicate):");
for (const area of input.otherAreas) lines.push(`- "${area.title}" (areaId ${area.id}${shared(area.others)})`);
lines.push("", "Their other areas (file under one by its areaId rather than adding a near-duplicate):");
for (const area of input.otherAreas) lines.push(`- "${area.title}" (areaId ${area.id})`);
}
if (input.proposed.length > 0) {
lines.push("", "Proposed to them earlier and still waiting for them (do not propose these again):");
@@ -227,7 +215,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
"The changes, as an ordered list (each may carry a one-line reason; removals must):",
"- { op: \"add_area\", ref, name }: ref is your own short key for the new area, used by later changes in the same list.",
"- { op: \"rename_area\", areaId, name }: it is renamed for everyone with responsibilities in it.",
"- { op: \"remove_area\", areaId, reason }: archives it and lets go of this person's responsibilities still in it (move any worth keeping). Refused when other people have responsibilities in it.",
"- { op: \"remove_area\", areaId, reason }: archives it and lets go of this person's responsibilities still in it (move any worth keeping).",
"- { op: \"add_responsibility\", areaId or areaRef, sentence }: one sentence of what must be true.",
"- { op: \"reword_responsibility\", responsibilityId, sentence }",
"- { op: \"move_responsibility\", responsibilityId, areaId or areaRef }",
@@ -34,7 +34,6 @@ type VersionRow = typeof responsibilityDashboardVersions.$inferSelect;
type AreaRow = typeof responsibilityAreas.$inferSelect;
type ResponsibilityRow = typeof responsibilities.$inferSelect;
const LIVE = ["proposed", "active"] as const;
/** One activity entry a restore or an applied change set writes after commit. */
export interface DashboardActivityEvent {
@@ -121,7 +120,7 @@ export function responsibilityDashboardVersionService(db: Db) {
createdNow: readonly string[] = [],
touched: readonly string[] = [],
): Promise<ResponsibilityDashboardSnapshot> {
const [rows, linkRows, created] = await Promise.all([
const [rows, linkRows] = await Promise.all([
database.select({
id: responsibilities.id,
title: responsibilities.title,
@@ -152,12 +151,6 @@ export function responsibilityDashboardVersionService(db: Db) {
eq(responsibilities.ownerUserId, ownerUserId),
eq(responsibilities.status, "active"),
)),
database.selectDistinct({ id: sql<string>`jsonb_array_elements_text(${responsibilityDashboardVersions.snapshot} -> 'createdAreaIds')` })
.from(responsibilityDashboardVersions)
.where(and(
eq(responsibilityDashboardVersions.companyId, companyId),
eq(responsibilityDashboardVersions.ownerUserId, ownerUserId),
)),
]);
const linksBy = new Map<string, ResponsibilityDashboardSnapshotLinks>();
for (const link of linkRows) {
@@ -179,20 +172,19 @@ export function responsibilityDashboardVersionService(db: Db) {
...item, links: sortedLinks(item.id), description, runByAgentId, evidence, healthOverride, healthNote,
}));
const referenced = [...new Set(items.map((item) => item.areaId).filter((value): value is string => value !== null))];
const createdIds = [...new Set([...created.map((row) => row.id), ...createdNow])].filter((value) => !referenced.includes(value));
// An area a change is about to touch is held whatever its status, so undoing a restore archives it again.
const touchedIds = touched.filter((value) => !referenced.includes(value));
const areas = referenced.length + createdIds.length + touchedIds.length === 0 ? [] : await database.select({
const areas = await database.select({
id: responsibilityAreas.id,
title: responsibilityAreas.title,
status: responsibilityAreas.status,
sortOrder: responsibilityAreas.sortOrder,
description: responsibilityAreas.description,
}).from(responsibilityAreas).where(and(
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
or(
referenced.length > 0 ? inArray(responsibilityAreas.id, referenced) : undefined,
createdIds.length > 0 ? and(inArray(responsibilityAreas.id, createdIds), ne(responsibilityAreas.status, "archived")) : undefined,
ne(responsibilityAreas.status, "archived"),
touchedIds.length > 0 ? inArray(responsibilityAreas.id, touchedIds) : undefined,
),
));
@@ -247,7 +239,9 @@ export function responsibilityDashboardVersionService(db: Db) {
// A version saved before snapshots held filed items is compared on what it holds.
const legacy = previousSnapshot ? isLegacySnapshot(previousSnapshot) : false;
const comparable = legacy ? dashboardSnapshotHash(input.snapshot, { legacy: true }) : hash;
if (previous && previous.snapshotHash === comparable) {
const previousHash = previous?.snapshotHash === "remapped" && previousSnapshot
? dashboardSnapshotHash(previousSnapshot, { legacy }) : previous?.snapshotHash;
if (previous && previousHash === comparable) {
// One saved before skills could be filed hashes the same (no filed skills) but must hold the empty list too.
if (!legacy && !lacksFiledSkills(previousSnapshot!)) return { row: previous, created: false };
// The same dashboard as an older version that held no filed items,
@@ -307,8 +301,7 @@ export function responsibilityDashboardVersionService(db: Db) {
* agent that runs it puts those back too (see restoreDetailsInTx); an older
* version leaves them as they are.
*
* Areas other people have responsibilities in keep their name and order
* (they see them too); a responsibility deleted since is created again with
* A responsibility deleted since is created again with
* its sentence; an area deleted since is created again (or the live area now
* holding its name is used); when an area's old name is now another area's,
* that area is used instead.
@@ -326,20 +319,11 @@ export function responsibilityDashboardVersionService(db: Db) {
const now = new Date();
const areaIds = [...new Set([...target.areas.map((area) => area.id), ...current.areas.map((area) => area.id)])];
const targetItemIds = target.responsibilities.map((item) => item.id);
const [areaRows, liveAreas, othersByArea, ownRows] = await Promise.all([
const [areaRows, liveAreas, ownRows] = await Promise.all([
areaIds.length === 0 ? Promise.resolve([] as AreaRow[]) : tx.select().from(responsibilityAreas)
.where(and(eq(responsibilityAreas.companyId, companyId), inArray(responsibilityAreas.id, areaIds))),
.where(and(eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), inArray(responsibilityAreas.id, areaIds))),
tx.select({ id: responsibilityAreas.id, title: responsibilityAreas.title }).from(responsibilityAreas)
.where(and(eq(responsibilityAreas.companyId, companyId), ne(responsibilityAreas.status, "archived"))),
areaIds.length === 0 ? Promise.resolve([] as Array<{ areaId: string | null; count: number }>) : tx.select({
areaId: responsibilities.areaId,
count: sql<number>`count(*)::int`,
}).from(responsibilities).where(and(
eq(responsibilities.companyId, companyId),
inArray(responsibilities.areaId, areaIds),
ne(responsibilities.ownerUserId, ownerUserId),
inArray(responsibilities.status, [...LIVE]),
)).groupBy(responsibilities.areaId),
.where(and(eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), ne(responsibilityAreas.status, "archived"))),
targetItemIds.length === 0 ? Promise.resolve([] as ResponsibilityRow[]) : tx.select().from(responsibilities).where(and(
eq(responsibilities.companyId, companyId),
eq(responsibilities.ownerUserId, ownerUserId),
@@ -347,7 +331,6 @@ export function responsibilityDashboardVersionService(db: Db) {
)),
]);
const areasById = new Map(areaRows.map((row) => [row.id, row]));
const shared = new Set(othersByArea.filter((row) => row.areaId && row.count > 0).map((row) => row.areaId!));
// Live titles, kept current as this restore renames and archives, for the one-live-name-per-area rule.
const liveTitle = new Map(liveAreas.map((row) => [lower(row.title), row.id]));
const setLive = (row: { id: string; title: string; status: string }) => {
@@ -368,7 +351,7 @@ export function responsibilityDashboardVersionService(db: Db) {
return true;
}
const [created] = await tx.insert(responsibilityAreas).values({
companyId,
companyId, ownerUserId,
title: want.title,
description: want.description ?? null,
status: want.status === "archived" ? "archived" : "active",
@@ -380,13 +363,8 @@ export function responsibilityDashboardVersionService(db: Db) {
events.push({ action: "responsibility_area.created", entityType: "responsibility_area", entityId: created!.id, details: { title: created!.title, status: created!.status, ...source } });
return true;
}
const isShared = shared.has(row.id);
// Other people see a shared area: only bring it back if it was archived, never rename or reorder it.
const nextTitle = isShared ? row.title : want.title;
const nextStatus = isShared ? (row.status === "archived" && want.status !== "archived" ? "active" : row.status) : want.status;
const nextOrder = isShared ? row.sortOrder : want.sortOrder;
// A version that holds the description puts it back, except on an area others share.
const nextDescription = isShared || want.description === undefined ? row.description : want.description;
const { title: nextTitle, status: nextStatus, sortOrder: nextOrder } = want;
const nextDescription = want.description === undefined ? row.description : want.description;
if (nextTitle === row.title && nextStatus === row.status && nextOrder === row.sortOrder && nextDescription === row.description) {
areaFor.set(want.id, row.id);
return true;
@@ -402,7 +380,7 @@ export function responsibilityDashboardVersionService(db: Db) {
}
const [updated] = await tx.update(responsibilityAreas)
.set({ title: nextTitle, status: nextStatus, sortOrder: nextOrder, description: nextDescription, updatedAt: now })
.where(and(eq(responsibilityAreas.id, row.id), eq(responsibilityAreas.companyId, companyId)))
.where(and(eq(responsibilityAreas.id, row.id), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId)))
.returning();
areasById.set(row.id, updated!);
setLive(updated!);
@@ -505,7 +483,7 @@ export function responsibilityDashboardVersionService(db: Db) {
// Areas the snapshot does not hold that are now empty of anyone's live responsibilities: archived.
const kept = new Set(areaFor.values());
const candidates = [...new Set([...current.areas.map((area) => area.id), ...touchedAreas])].filter((areaId) => !kept.has(areaId));
events.push(...await archiveIfEmpty(tx, companyId, candidates, source));
events.push(...await archiveIfEmpty(tx, companyId, ownerUserId, candidates, source));
return { events, createdAreaIds };
}
@@ -611,10 +589,10 @@ export function responsibilityDashboardVersionService(db: Db) {
}
/** Inside `tx`: archive each listed area that is not archived and holds no proposed or active responsibility of anyone. */
async function archiveIfEmpty(tx: DashboardTransaction, companyId: string, areaIds: readonly string[], source: Record<string, unknown>) {
async function archiveIfEmpty(tx: DashboardTransaction, companyId: string, ownerUserId: string, areaIds: readonly string[], source: Record<string, unknown>) {
if (areaIds.length === 0) return [];
const archived = await tx.update(responsibilityAreas).set({ status: "archived", updatedAt: new Date() }).where(and(
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
inArray(responsibilityAreas.id, [...areaIds]),
ne(responsibilityAreas.status, "archived"),
sql`not exists (select 1 from ${responsibilities} r where r.area_id = ${responsibilityAreas.id} and r.status in ('proposed', 'active'))`,
+18 -35
View File
@@ -38,7 +38,6 @@ import {
type IssueRow = typeof issues.$inferSelect;
type AreaRow = typeof responsibilityAreas.$inferSelect;
const LIVE = ["proposed", "active"] as const;
const NO_AREA = "No area";
function isClosed(status: string) {
@@ -77,14 +76,15 @@ export function responsibilityDashboardService(db: Db) {
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
/** Empty: no active responsibility and none proposed. One query. */
async function isEmpty(companyId: string, ownerUserId: string) {
const [row] = await db.select({ id: responsibilities.id }).from(responsibilities).where(and(
eq(responsibilities.companyId, companyId),
eq(responsibilities.ownerUserId, ownerUserId),
inArray(responsibilities.status, [...LIVE]),
)).limit(1);
return !row;
const [state] = await db.execute<{ empty: boolean }>(sql`select not exists (
select 1 from ${responsibilityAreas} where ${responsibilityAreas.companyId} = ${companyId}
and ${responsibilityAreas.ownerUserId} = ${ownerUserId} and ${responsibilityAreas.status} <> 'archived'
) and not exists (
select 1 from ${responsibilities} where ${responsibilities.companyId} = ${companyId}
and ${responsibilities.ownerUserId} = ${ownerUserId} and ${responsibilities.status} in ('active', 'proposed')
) as empty`);
return state.empty;
}
async function latestConversation(companyId: string, ownerUserId: string): Promise<IssueRow | null> {
@@ -123,7 +123,7 @@ export function responsibilityDashboardService(db: Db) {
/**
* Check a change set against the person's dashboard as it is and resolve
* the words the card shows. Three queries.
* the words the card shows. Two queries.
*/
async function buildPayload(
companyId: string,
@@ -132,7 +132,7 @@ export function responsibilityDashboardService(db: Db) {
data: CreateDashboardChangeSet,
): Promise<ProposeDashboardChangesPayload> {
const namedAreaIds = [...new Set(data.changes.flatMap((change) => ("areaId" in change && change.areaId ? [change.areaId] : [])))];
const [own, areaRows, others] = await Promise.all([
const [own, areaRows] = await Promise.all([
db.select({
id: responsibilities.id,
title: responsibilities.title,
@@ -144,23 +144,15 @@ export function responsibilityDashboardService(db: Db) {
eq(responsibilities.status, "active"),
)),
db.select().from(responsibilityAreas).where(and(
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
namedAreaIds.length > 0
? or(ne(responsibilityAreas.status, "archived"), inArray(responsibilityAreas.id, namedAreaIds))
: ne(responsibilityAreas.status, "archived"),
)),
db.select({ areaId: responsibilities.areaId, count: sql<number>`count(distinct ${responsibilities.ownerUserId})::int` })
.from(responsibilities).where(and(
eq(responsibilities.companyId, companyId),
ne(responsibilities.ownerUserId, ownerUserId),
inArray(responsibilities.status, [...LIVE]),
sql`${responsibilities.areaId} is not null`,
)).groupBy(responsibilities.areaId),
]);
const ownById = new Map(own.map((row) => [row.id, row]));
const areasById = new Map(areaRows.map((row) => [row.id, row]));
const liveByTitle = new Map(areaRows.filter((row) => row.status !== "archived").map((row) => [lower(row.title), row]));
const sharedWith = new Map(others.map((row) => [row.areaId!, row.count]));
const refs = new Map<string, { index: number; name: string }>();
const problems: string[] = [];
const problem = (index: number, message: string) => problems.push(`changes[${index}]: ${message}`);
@@ -239,16 +231,12 @@ export function responsibilityDashboardService(db: Db) {
groupName: area.title,
name: change.name.trim(),
fromName: area.title,
sharedWith: sharedWith.get(area.id) ?? 0,
sharedWith: 0,
};
}
case "remove_area": {
const area = usableArea(index, change.areaId);
if (!area) return base;
const shared = sharedWith.get(area.id) ?? 0;
if (shared > 0) {
problem(index, `"${area.title}" holds responsibilities of ${shared === 1 ? "another person" : `${shared} other people`}, so it stays; move or remove this person's responsibilities in it instead`);
}
return {
...base,
groupAreaId: area.id,
@@ -338,12 +326,12 @@ export function responsibilityDashboardService(db: Db) {
const stale = (message: string) => conflict(`${message}. Ask for the proposal again.`, { code: "responsibility_dashboard_changes_stale" });
const loadArea = async (areaId: string) => {
const [row] = await tx.select().from(responsibilityAreas)
.where(and(eq(responsibilityAreas.id, areaId), eq(responsibilityAreas.companyId, companyId))).for("update");
.where(and(eq(responsibilityAreas.id, areaId), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId))).for("update");
return row ?? null;
};
const liveAreaNamed = async (title: string, except?: string) => {
const [row] = await tx.select().from(responsibilityAreas).where(and(
eq(responsibilityAreas.companyId, companyId),
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
sql`lower(${responsibilityAreas.title}) = lower(${title})`,
ne(responsibilityAreas.status, "archived"),
except ? ne(responsibilityAreas.id, except) : undefined,
@@ -378,7 +366,7 @@ export function responsibilityDashboardService(db: Db) {
refToArea.set(change.groupRef!, existing.id);
continue;
}
const [created] = await tx.insert(responsibilityAreas).values({ companyId, title: change.name!, status: "active", source: "manual" }).returning();
const [created] = await tx.insert(responsibilityAreas).values({ companyId, ownerUserId, title: change.name!, status: "active", source: "manual" }).returning();
refToArea.set(change.groupRef!, created!.id);
createdAreaIds.push(created!.id);
events.push({ action: "responsibility_area.created", entityType: "responsibility_area", entityId: created!.id, details: { title: created!.title, status: "active", source: "manual", ...source } });
@@ -435,13 +423,6 @@ export function responsibilityDashboardService(db: Db) {
for (const change of byOp("remove_area")) {
const area = await loadArea(change.groupAreaId!);
if (!area || area.status === "archived") continue;
const [others] = await tx.select({ id: responsibilities.id }).from(responsibilities).where(and(
eq(responsibilities.companyId, companyId),
eq(responsibilities.areaId, area.id),
ne(responsibilities.ownerUserId, ownerUserId),
inArray(responsibilities.status, [...LIVE]),
)).limit(1);
if (others) throw stale(`Someone else now has responsibilities in "${area.title}", so it stays`);
const remaining = await tx.select({ id: responsibilities.id }).from(responsibilities).where(and(
eq(responsibilities.companyId, companyId),
eq(responsibilities.areaId, area.id),
@@ -449,7 +430,7 @@ export function responsibilityDashboardService(db: Db) {
eq(responsibilities.status, "active"),
));
for (const row of remaining) await letGo(row.id);
events.push(...await versions.archiveIfEmpty(tx, companyId, [area.id], source));
events.push(...await versions.archiveIfEmpty(tx, companyId, ownerUserId, [area.id], source));
}
return { events, createdAreaIds };
}
@@ -543,6 +524,8 @@ export function responsibilityDashboardService(db: Db) {
status: "todo",
priority: "medium",
assigneeAgentId: agentId,
visibility: "private",
responsibleUserId: ownerUserId,
originKind: RESPONSIBILITY_DASHBOARD_ORIGIN_KIND,
originId: ownerUserId,
originFingerprint: input.mode,
@@ -0,0 +1,68 @@
import { sql } from "drizzle-orm";
import { activityLog, issues } from "@paperclipai/db";
import type { AuthorizationActor } from "./authorization.js";
const conversationKinds = ["responsibility_dashboard", "responsibility_bar", "responsibility_status_update", "automation_conversation"];
export function isPersonalDashboardConversation(kind: string | null) {
return kind !== null && conversationKinds.includes(kind);
}
export type DashboardConversationFields = {
originKind?: string | null;
originId?: string | null;
responsibleUserId?: string | null;
assigneeAgentId?: string | null;
};
export function dashboardConversationReadable(actor: AuthorizationActor, issue: DashboardConversationFields) {
if (!isPersonalDashboardConversation(issue.originKind ?? null)) return true;
const ownerId = issue.originKind === "responsibility_dashboard" ? issue.originId : issue.responsibleUserId;
if (!ownerId) return false;
if (actor.type === "board") return actor.userId === ownerId;
return actor.type === "agent" && !!issue.assigneeAgentId && actor.agentId === issue.assigneeAgentId
&& (!actor.onBehalfOfUserId || actor.onBehalfOfUserId === ownerId)
&& (!actor.authorizingUserId || actor.authorizingUserId === ownerId);
}
const personalConversationKinds = sql.join(conversationKinds.map(kind => sql`${kind}`), sql`, `);
export function dashboardConversationCondition(actor: AuthorizationActor) {
const owner = sql`case when ${issues.originKind} = 'responsibility_dashboard' then ${issues.originId} else ${issues.responsibleUserId} end`;
const allowed = actor.type === "board" ? sql`${owner} = ${actor.userId ?? null}`
: actor.type === "agent" ? sql`${issues.assigneeAgentId} = ${actor.agentId ?? null}
and ${actor.onBehalfOfUserId ? sql`${owner} = ${actor.onBehalfOfUserId}` : sql`true`}
and ${actor.authorizingUserId ? sql`${owner} = ${actor.authorizingUserId}` : sql`true`}` : sql`false`;
return sql<boolean>`(${issues.originKind} not in (${personalConversationKinds}) or (${owner} is not null and ${allowed}))`;
}
const entities = ["responsibility", "responsibility_area", "responsibility_dashboard_version"];
export function isDashboardActivity(entityType: unknown) {
return typeof entityType === "string" && entities.includes(entityType);
}
/** Activity without a current owner stays in the audit store and is invisible in company feeds. */
export function dashboardActivityCondition(userId?: string | null) {
const ordinary = sql`${activityLog.entityType} not in ('responsibility', 'responsibility_area', 'responsibility_dashboard_version')`;
if (!userId) return sql<boolean>`${ordinary}`;
return sql<boolean>`(${ordinary} or case ${activityLog.entityType}
when 'responsibility' then exists (select 1 from responsibilities r where r.id::text = ${activityLog.entityId} and r.company_id = ${activityLog.companyId} and r.owner_user_id = ${userId})
when 'responsibility_area' then exists (select 1 from responsibility_areas a where a.id::text = ${activityLog.entityId} and a.company_id = ${activityLog.companyId} and a.owner_user_id = ${userId})
when 'responsibility_dashboard_version' then exists (select 1 from responsibility_dashboard_versions v where v.id::text = ${activityLog.entityId} and v.company_id = ${activityLog.companyId} and v.owner_user_id = ${userId})
else false end)`;
}
/** Audit entries can refer to a conversation directly, through a comment or through a document. */
export function dashboardAuditConversationCondition(userId?: string | null) {
const entity = activityLog.entityId;
const privateIssue = sql`select 1 from issues i where i.company_id = ${activityLog.companyId}
and i.origin_kind in (${personalConversationKinds})
and (${userId ?? null}::text is null or (case when i.origin_kind = 'responsibility_dashboard' then i.origin_id else i.responsible_user_id end)
is distinct from ${userId ?? null})`;
return sql<boolean>`case ${activityLog.entityType}
when 'issue' then not exists (${privateIssue} and i.id::text = ${entity})
when 'issue_comment' then not exists (${privateIssue} and i.id in
(select c.issue_id from issue_comments c where c.id::text = ${entity}))
when 'issue_document' then not exists (${privateIssue} and i.id in
(select d.issue_id from issue_documents d where d.id::text = ${entity} or d.document_id::text = ${entity}))
else true end`;
}
@@ -197,6 +197,8 @@ export function responsibilityStatusReportService(db: Db) {
status: "todo",
priority: "low",
assigneeAgentId: reporter.agentId,
visibility: "private",
responsibleUserId: row.ownerUserId,
originKind: RESPONSIBILITY_STATUS_UPDATE_ORIGIN_KIND,
originId: row.id,
createdByUserId: actor.userId,
+4 -4
View File
@@ -44,7 +44,7 @@ const ROUTINE_EXECUTION_ORIGIN_KIND = "routine_execution";
*/
export interface RoutineSuggestionResponsibilityFiling {
/** Every responsibility the task is under (directly or through its project); empty when loose. */
responsibilitiesForIssue(companyId: string, issueId: string): Promise<Array<{ id: string }>>;
responsibilitiesForIssue(companyId: string, issueId: string, ownerUserId: string): Promise<Array<{ id: string }>>;
/** File the routine under one responsibility. Linking is additive and idempotent. */
fileRoutine(responsibilityId: string, routineId: string): Promise<{ linkId: string; created: boolean } | null>;
}
@@ -60,8 +60,8 @@ export function responsibilityFilingForRoutineSuggestions(db: Db): RoutineSugges
// linking a routine reads no task or project rows, so no further read scope applies.
const unrestricted = { issueReadCondition: sql<boolean>`true`, projectReadCondition: sql<boolean>`true` };
return {
async responsibilitiesForIssue(companyId, issueId) {
return svc.lookup(companyId, { kind: "issue", id: issueId }, unrestricted);
async responsibilitiesForIssue(companyId, issueId, ownerUserId) {
return svc.lookup(companyId, ownerUserId, { kind: "issue", id: issueId }, unrestricted);
},
async fileRoutine(responsibilityId, routineId) {
const row = await svc.getById(responsibilityId);
@@ -346,7 +346,7 @@ export function routineSuggestionService(
const filed: FiledUnder = [];
try {
for (const responsibility of await filing.responsibilitiesForIssue(issue.companyId, issue.id)) {
for (const responsibility of await filing.responsibilitiesForIssue(issue.companyId, issue.id, actor.userId)) {
try {
const link = await filing.fileRoutine(responsibility.id, routine.id);
if (link) filed.push({ responsibilityId: responsibility.id, ...link });
+2 -1
View File
@@ -2180,6 +2180,7 @@ export function routineService(
responsibleUserId?: string;
/** Filed under this responsibility, directly or through its project. */
responsibilityId?: string;
ownerUserId?: string;
/** Filed under no proposed or active responsibility, directly or through its project. */
unfiled?: boolean;
},
@@ -2197,7 +2198,7 @@ export function routineService(
const filedUnder = (responsibility: SQL) => sql`exists (
select 1 from ${responsibilityLinks} fl
join ${responsibilities} fr on fr.id = fl.responsibility_id
where ${responsibility} and fr.company_id = ${companyId}
where ${responsibility} and fr.company_id = ${companyId} and fr.owner_user_id = ${filters?.ownerUserId ?? null}
and (fl.routine_id = ${routines.id} or (${routines.projectId} is not null and fl.project_id = ${routines.projectId})))`;
if (filters?.responsibilityId) conditions.push(filedUnder(sql`fr.id = ${filters.responsibilityId}`));
if (filters?.unfiled) conditions.push(sql`not ${filedUnder(sql`fr.status in ('proposed', 'active')`)}`);