2026-03-19 08:39:24 -05:00
|
|
|
import { and, asc, desc, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
|
2026-03-03 08:45:26 -06:00
|
|
|
import type { Db } from "@paperclipai/db";
|
2026-02-20 10:31:56 -06:00
|
|
|
import {
|
2026-03-21 12:20:48 -05:00
|
|
|
activityLog,
|
2026-02-20 10:31:56 -06:00
|
|
|
agents,
|
|
|
|
|
assets,
|
|
|
|
|
companies,
|
2026-02-23 14:40:32 -06:00
|
|
|
companyMemberships,
|
2026-03-13 22:17:49 -05:00
|
|
|
documents,
|
2026-02-20 10:31:56 -06:00
|
|
|
goals,
|
2026-02-21 08:23:44 -06:00
|
|
|
heartbeatRuns,
|
2026-03-13 17:12:25 -05:00
|
|
|
executionWorkspaces,
|
2026-02-20 10:31:56 -06:00
|
|
|
issueAttachments,
|
2026-03-26 08:19:16 -05:00
|
|
|
issueInboxArchives,
|
2026-02-25 08:38:37 -06:00
|
|
|
issueLabels,
|
2026-04-04 13:56:04 -05:00
|
|
|
issueRelations,
|
2026-02-20 10:31:56 -06:00
|
|
|
issueComments,
|
2026-03-13 22:17:49 -05:00
|
|
|
issueDocuments,
|
2026-03-06 08:34:19 -06:00
|
|
|
issueReadStates,
|
2026-02-20 10:31:56 -06:00
|
|
|
issues,
|
2026-02-25 08:38:37 -06:00
|
|
|
labels,
|
|
|
|
|
projectWorkspaces,
|
2026-02-20 10:31:56 -06:00
|
|
|
projects,
|
2026-03-03 08:45:26 -06:00
|
|
|
} from "@paperclipai/db";
|
2026-04-04 13:56:04 -05:00
|
|
|
import type { IssueRelationIssueSummary } from "@paperclipai/shared";
|
2026-04-02 09:11:49 -05:00
|
|
|
import { extractAgentMentionIds, extractProjectMentionIds, isUuidLike } from "@paperclipai/shared";
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
import { conflict, notFound, unprocessable } from "../errors.js";
|
2026-03-10 09:03:31 -05:00
|
|
|
import {
|
|
|
|
|
defaultIssueExecutionWorkspaceSettingsForProject,
|
2026-03-17 09:24:28 -05:00
|
|
|
gateProjectExecutionWorkspacePolicy,
|
2026-03-30 14:08:44 -05:00
|
|
|
issueExecutionWorkspaceModeForPersistedWorkspace,
|
2026-03-10 09:03:31 -05:00
|
|
|
parseProjectExecutionWorkspacePolicy,
|
|
|
|
|
} from "./execution-workspace-policy.js";
|
2026-03-17 09:24:28 -05:00
|
|
|
import { instanceSettingsService } from "./instance-settings.js";
|
2026-03-11 22:17:21 -05:00
|
|
|
import { redactCurrentUserText } from "../log-redaction.js";
|
2026-03-12 08:50:31 -05:00
|
|
|
import { resolveIssueGoalId, resolveNextIssueGoalId } from "./issue-goal-fallback.js";
|
|
|
|
|
import { getDefaultCompanyGoal } from "./goals.js";
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
Agent management: hire endpoint with permission gates and pending_approval status,
config revision tracking with rollback, agent duplicate route, permission CRUD.
Block pending_approval agents from auth, heartbeat, and assignments.
Approvals: revision request/resubmit flow, approval comments CRUD, issue-approval
linking, auto-wake agents on approval decisions with context snapshot.
Costs: per-agent breakdown, period filtering (month/week/day/all), cost by agent
list endpoint.
Adapters: agentConfigurationDoc on all adapters, /llms/agent-configuration.txt
reflection routes. Inject PAPERCLIP_APPROVAL_ID, PAPERCLIP_APPROVAL_STATUS,
PAPERCLIP_LINKED_ISSUE_IDS into adapter environments.
Sidebar badges endpoint for pending approval/inbox counts. Dashboard and company
settings extensions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 13:02:41 -06:00
|
|
|
const ALL_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"];
|
2026-03-13 10:18:00 -05:00
|
|
|
const MAX_ISSUE_COMMENT_PAGE_LIMIT = 500;
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
|
|
|
|
function assertTransition(from: string, to: string) {
|
|
|
|
|
if (from === to) return;
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
Agent management: hire endpoint with permission gates and pending_approval status,
config revision tracking with rollback, agent duplicate route, permission CRUD.
Block pending_approval agents from auth, heartbeat, and assignments.
Approvals: revision request/resubmit flow, approval comments CRUD, issue-approval
linking, auto-wake agents on approval decisions with context snapshot.
Costs: per-agent breakdown, period filtering (month/week/day/all), cost by agent
list endpoint.
Adapters: agentConfigurationDoc on all adapters, /llms/agent-configuration.txt
reflection routes. Inject PAPERCLIP_APPROVAL_ID, PAPERCLIP_APPROVAL_STATUS,
PAPERCLIP_LINKED_ISSUE_IDS into adapter environments.
Sidebar badges endpoint for pending approval/inbox counts. Dashboard and company
settings extensions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 13:02:41 -06:00
|
|
|
if (!ALL_ISSUE_STATUSES.includes(to)) {
|
|
|
|
|
throw conflict(`Unknown issue status: ${to}`);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function applyStatusSideEffects(
|
|
|
|
|
status: string | undefined,
|
|
|
|
|
patch: Partial<typeof issues.$inferInsert>,
|
|
|
|
|
): Partial<typeof issues.$inferInsert> {
|
|
|
|
|
if (!status) return patch;
|
|
|
|
|
|
|
|
|
|
if (status === "in_progress" && !patch.startedAt) {
|
|
|
|
|
patch.startedAt = new Date();
|
|
|
|
|
}
|
|
|
|
|
if (status === "done") {
|
|
|
|
|
patch.completedAt = new Date();
|
|
|
|
|
}
|
|
|
|
|
if (status === "cancelled") {
|
|
|
|
|
patch.cancelledAt = new Date();
|
|
|
|
|
}
|
|
|
|
|
return patch;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface IssueFilters {
|
|
|
|
|
status?: string;
|
|
|
|
|
assigneeAgentId?: string;
|
2026-03-21 12:20:48 -05:00
|
|
|
participantAgentId?: string;
|
2026-02-26 16:33:39 -06:00
|
|
|
assigneeUserId?: string;
|
2026-03-06 08:21:03 -06:00
|
|
|
touchedByUserId?: string;
|
2026-03-26 08:19:16 -05:00
|
|
|
inboxArchivedByUserId?: string;
|
2026-03-06 08:21:03 -06:00
|
|
|
unreadForUserId?: string;
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
projectId?: string;
|
2026-03-28 22:21:24 -05:00
|
|
|
executionWorkspaceId?: string;
|
2026-03-10 15:54:31 +02:00
|
|
|
parentId?: string;
|
2026-02-25 08:38:37 -06:00
|
|
|
labelId?: string;
|
2026-03-19 08:39:24 -05:00
|
|
|
originKind?: string;
|
|
|
|
|
originId?: string;
|
|
|
|
|
includeRoutineExecutions?: boolean;
|
[codex] improve issue and routine UI responsiveness (#3744)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - Operators rely on issue, inbox, and routine views to understand what
the company is doing in real time
> - Those views need to stay fast and readable even when issue lists,
markdown comments, and run metadata get large
> - The current branch had a coherent set of UI and live-update
improvements spread across issue search, issue detail rendering, routine
affordances, and workspace lookups
> - This pull request groups those board-facing changes into one
standalone branch that can merge independently of the heartbeat/runtime
work
> - The benefit is a faster, clearer issue and routine workflow without
changing the underlying task model
## What Changed
- Show routine execution issues by default and rename the filter to
`Hide routine runs` so the default state no longer looks like an active
filter.
- Show the routine name in the run dialog and tighten the issue
properties pane with a workspace link, copy-on-click behavior, and an
inline parent arrow.
- Reduce issue detail rerenders, keep queued issue chat mounted, improve
issues page search responsiveness, and speed up issues first paint.
- Add inbox "other search results", refresh visible issue runs after
status updates, and optimize workspace lookups through summary-mode
execution workspace queries.
- Improve markdown wrapping and scrolling behavior for long strings and
self-comment code blocks.
- Relax the markdown sanitizer assertion so the test still validates
safety after the new wrap-friendly inline styles.
## Verification
- `pnpm vitest run ui/src/components/IssuesList.test.tsx
ui/src/lib/inbox.test.ts ui/src/pages/Issues.test.tsx
ui/src/context/BreadcrumbContext.test.tsx
ui/src/context/LiveUpdatesProvider.test.ts
ui/src/components/MarkdownBody.test.tsx
ui/src/api/execution-workspaces.test.ts
server/src/__tests__/execution-workspaces-routes.test.ts`
## Risks
- This touches several issue-facing UI surfaces at once, so regressions
would most likely show up as stale rendering, search result mismatches,
or small markdown presentation differences.
- The workspace lookup optimization depends on the summary-mode route
shape staying aligned between server and UI.
## Model Used
- OpenAI Codex, GPT-5-based coding agent in the Codex CLI environment.
Exact backend model deployment ID was not exposed in-session.
Tool-assisted editing and shell execution were used.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 15:54:05 -05:00
|
|
|
excludeRoutineExecutions?: boolean;
|
2026-02-26 16:33:39 -06:00
|
|
|
q?: string;
|
2026-04-06 20:30:50 -05:00
|
|
|
limit?: number;
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
}
|
2026-02-16 13:31:58 -06:00
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
type IssueRow = typeof issues.$inferSelect;
|
|
|
|
|
type IssueLabelRow = typeof labels.$inferSelect;
|
2026-03-02 16:43:59 -06:00
|
|
|
type IssueActiveRunRow = {
|
|
|
|
|
id: string;
|
|
|
|
|
status: string;
|
|
|
|
|
agentId: string;
|
|
|
|
|
invocationSource: string;
|
|
|
|
|
triggerDetail: string | null;
|
|
|
|
|
startedAt: Date | null;
|
|
|
|
|
finishedAt: Date | null;
|
|
|
|
|
createdAt: Date;
|
|
|
|
|
};
|
2026-02-25 08:38:37 -06:00
|
|
|
type IssueWithLabels = IssueRow & { labels: IssueLabelRow[]; labelIds: string[] };
|
2026-03-02 16:43:59 -06:00
|
|
|
type IssueWithLabelsAndRun = IssueWithLabels & { activeRun: IssueActiveRunRow | null };
|
2026-03-06 08:21:03 -06:00
|
|
|
type IssueUserCommentStats = {
|
|
|
|
|
issueId: string;
|
|
|
|
|
myLastCommentAt: Date | null;
|
|
|
|
|
lastExternalCommentAt: Date | null;
|
|
|
|
|
};
|
2026-04-02 11:38:57 -05:00
|
|
|
type IssueLastActivityStat = {
|
|
|
|
|
issueId: string;
|
|
|
|
|
latestCommentAt: Date | null;
|
|
|
|
|
latestLogAt: Date | null;
|
|
|
|
|
};
|
2026-03-06 08:21:03 -06:00
|
|
|
type IssueUserContextInput = {
|
|
|
|
|
createdByUserId: string | null;
|
|
|
|
|
assigneeUserId: string | null;
|
2026-03-06 09:03:27 -06:00
|
|
|
createdAt: Date | string;
|
|
|
|
|
updatedAt: Date | string;
|
2026-03-06 08:21:03 -06:00
|
|
|
};
|
2026-03-24 08:11:09 -05:00
|
|
|
type ProjectGoalReader = Pick<Db, "select">;
|
2026-03-30 14:08:44 -05:00
|
|
|
type DbReader = Pick<Db, "select">;
|
|
|
|
|
type IssueCreateInput = Omit<typeof issues.$inferInsert, "companyId"> & {
|
|
|
|
|
labelIds?: string[];
|
2026-04-04 13:56:04 -05:00
|
|
|
blockedByIssueIds?: string[];
|
2026-03-30 14:08:44 -05:00
|
|
|
inheritExecutionWorkspaceFromIssueId?: string | null;
|
|
|
|
|
};
|
2026-04-04 13:56:04 -05:00
|
|
|
type IssueRelationSummaryMap = {
|
|
|
|
|
blockedBy: IssueRelationIssueSummary[];
|
|
|
|
|
blocks: IssueRelationIssueSummary[];
|
|
|
|
|
};
|
2026-02-25 08:38:37 -06:00
|
|
|
|
2026-02-20 15:48:22 -06:00
|
|
|
function sameRunLock(checkoutRunId: string | null, actorRunId: string | null) {
|
|
|
|
|
if (actorRunId) return checkoutRunId === actorRunId;
|
|
|
|
|
return checkoutRunId == null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-21 08:23:44 -06:00
|
|
|
const TERMINAL_HEARTBEAT_RUN_STATUSES = new Set(["succeeded", "failed", "cancelled", "timed_out"]);
|
Sync/master post pap1497 followups 2026 04 15 (#3779)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - The board depends on issue, inbox, cost, and company-skill surfaces
to stay accurate and fast while agents are actively working
> - The PAP-1497 follow-up branch exposed a few rough edges in those
surfaces: stale active-run state on completed issues, missing creator
filters, oversized issue payload scans, and placeholder issue-route
parsing
> - Those gaps make the control plane harder to trust because operators
can see misleading run state, miss the right subset of work, or pay
extra query/render cost on large issue records
> - This pull request tightens those follow-ups across server and UI
code, and adds regression coverage for the affected paths
> - The benefit is a more reliable issue workflow, safer high-volume
cost aggregation, and clearer board/operator navigation
## What Changed
- Added the `v2026.415.0` release changelog entry.
- Fixed stale issue-run presentation after completion and reused the
shared issue-path parser so literal route placeholders no longer become
issue links.
- Added creator filters to the Issues page and Inbox, including
persisted filter-state normalization and regression coverage.
- Bounded issue detail/list project-mention scans and trimmed large
issue-list payload fields to keep issue reads lighter.
- Hardened company-skill list projection and cost/finance aggregation so
large markdown blobs and large summed values do not leak into list
responses or overflow 32-bit casts.
- Added targeted server/UI regression tests for company skills,
costs/finance, issue mention scanning, creator filters, inbox
normalization, and issue reference parsing.
## Verification
- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/issues-goal-context-routes.test.ts
server/src/__tests__/issues-service.test.ts ui/src/lib/inbox.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-reference.test.ts`
- `gh pr checks 3779`
Current pass set on the PR head: `policy`, `verify`, `e2e`,
`security/snyk (cryppadotta)`, `Greptile Review`
## Risks
- Creator filter options are derived from the currently loaded
issue/agent data, so very sparse result sets may not surface every
historical creator until they appear in the active dataset.
- Cost/finance aggregate casts now use `double precision`; that removes
the current overflow risk, but future schema changes should keep
large-value aggregation behavior under review.
- Issue detail mention scanning now skips comment-body scans on the
detail route, so any consumer that relied on comment-only project
mentions there would need to fetch them separately.
## Model Used
- OpenAI Codex, GPT-5-based coding agent with terminal tool use and
local code execution in the Paperclip workspace. Exact internal model
ID/context-window exposure is not surfaced in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 21:13:56 -05:00
|
|
|
const ISSUE_LIST_DESCRIPTION_MAX_CHARS = 1200;
|
2026-02-21 08:23:44 -06:00
|
|
|
|
2026-02-26 16:33:39 -06:00
|
|
|
function escapeLikePattern(value: string): string {
|
|
|
|
|
return value.replace(/[\\%_]/g, "\\$&");
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-24 08:11:09 -05:00
|
|
|
async function getProjectDefaultGoalId(
|
|
|
|
|
db: ProjectGoalReader,
|
|
|
|
|
companyId: string,
|
|
|
|
|
projectId: string | null | undefined,
|
|
|
|
|
) {
|
|
|
|
|
if (!projectId) return null;
|
|
|
|
|
const row = await db
|
|
|
|
|
.select({ goalId: projects.goalId })
|
|
|
|
|
.from(projects)
|
|
|
|
|
.where(and(eq(projects.id, projectId), eq(projects.companyId, companyId)))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
return row?.goalId ?? null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-30 14:08:44 -05:00
|
|
|
async function getWorkspaceInheritanceIssue(
|
|
|
|
|
db: DbReader,
|
|
|
|
|
companyId: string,
|
|
|
|
|
issueId: string,
|
|
|
|
|
) {
|
|
|
|
|
const issue = await db
|
|
|
|
|
.select({
|
|
|
|
|
id: issues.id,
|
|
|
|
|
projectId: issues.projectId,
|
|
|
|
|
projectWorkspaceId: issues.projectWorkspaceId,
|
|
|
|
|
executionWorkspaceId: issues.executionWorkspaceId,
|
|
|
|
|
executionWorkspaceSettings: issues.executionWorkspaceSettings,
|
|
|
|
|
})
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(and(eq(issues.id, issueId), eq(issues.companyId, companyId)))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!issue) {
|
|
|
|
|
throw notFound("Workspace inheritance issue not found");
|
|
|
|
|
}
|
|
|
|
|
return issue;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 08:21:03 -06:00
|
|
|
function touchedByUserCondition(companyId: string, userId: string) {
|
|
|
|
|
return sql<boolean>`
|
|
|
|
|
(
|
|
|
|
|
${issues.createdByUserId} = ${userId}
|
|
|
|
|
OR ${issues.assigneeUserId} = ${userId}
|
2026-03-06 08:34:19 -06:00
|
|
|
OR EXISTS (
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ${issueReadStates}
|
|
|
|
|
WHERE ${issueReadStates.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueReadStates.companyId} = ${companyId}
|
|
|
|
|
AND ${issueReadStates.userId} = ${userId}
|
|
|
|
|
)
|
2026-03-06 08:21:03 -06:00
|
|
|
OR EXISTS (
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ${issueComments}
|
|
|
|
|
WHERE ${issueComments.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueComments.companyId} = ${companyId}
|
|
|
|
|
AND ${issueComments.authorUserId} = ${userId}
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 12:20:48 -05:00
|
|
|
function participatedByAgentCondition(companyId: string, agentId: string) {
|
|
|
|
|
return sql<boolean>`
|
|
|
|
|
(
|
|
|
|
|
${issues.createdByAgentId} = ${agentId}
|
|
|
|
|
OR ${issues.assigneeAgentId} = ${agentId}
|
|
|
|
|
OR EXISTS (
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ${issueComments}
|
|
|
|
|
WHERE ${issueComments.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueComments.companyId} = ${companyId}
|
|
|
|
|
AND ${issueComments.authorAgentId} = ${agentId}
|
|
|
|
|
)
|
|
|
|
|
OR EXISTS (
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ${activityLog}
|
|
|
|
|
WHERE ${activityLog.companyId} = ${companyId}
|
|
|
|
|
AND ${activityLog.entityType} = 'issue'
|
|
|
|
|
AND ${activityLog.entityId} = ${issues.id}::text
|
|
|
|
|
AND ${activityLog.agentId} = ${agentId}
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 08:21:03 -06:00
|
|
|
function myLastCommentAtExpr(companyId: string, userId: string) {
|
|
|
|
|
return sql<Date | null>`
|
|
|
|
|
(
|
|
|
|
|
SELECT MAX(${issueComments.createdAt})
|
|
|
|
|
FROM ${issueComments}
|
|
|
|
|
WHERE ${issueComments.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueComments.companyId} = ${companyId}
|
|
|
|
|
AND ${issueComments.authorUserId} = ${userId}
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 08:34:19 -06:00
|
|
|
function myLastReadAtExpr(companyId: string, userId: string) {
|
|
|
|
|
return sql<Date | null>`
|
|
|
|
|
(
|
|
|
|
|
SELECT MAX(${issueReadStates.lastReadAt})
|
|
|
|
|
FROM ${issueReadStates}
|
|
|
|
|
WHERE ${issueReadStates.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueReadStates.companyId} = ${companyId}
|
|
|
|
|
AND ${issueReadStates.userId} = ${userId}
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 08:21:03 -06:00
|
|
|
function myLastTouchAtExpr(companyId: string, userId: string) {
|
|
|
|
|
const myLastCommentAt = myLastCommentAtExpr(companyId, userId);
|
2026-03-06 08:34:19 -06:00
|
|
|
const myLastReadAt = myLastReadAtExpr(companyId, userId);
|
2026-03-06 08:21:03 -06:00
|
|
|
return sql<Date | null>`
|
2026-03-06 08:34:19 -06:00
|
|
|
GREATEST(
|
|
|
|
|
COALESCE(${myLastCommentAt}, to_timestamp(0)),
|
|
|
|
|
COALESCE(${myLastReadAt}, to_timestamp(0)),
|
|
|
|
|
COALESCE(CASE WHEN ${issues.createdByUserId} = ${userId} THEN ${issues.createdAt} ELSE NULL END, to_timestamp(0)),
|
|
|
|
|
COALESCE(CASE WHEN ${issues.assigneeUserId} = ${userId} THEN ${issues.updatedAt} ELSE NULL END, to_timestamp(0))
|
2026-03-06 08:21:03 -06:00
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-26 08:19:16 -05:00
|
|
|
function lastExternalCommentAtExpr(companyId: string, userId: string) {
|
|
|
|
|
return sql<Date | null>`
|
|
|
|
|
(
|
|
|
|
|
SELECT MAX(${issueComments.createdAt})
|
|
|
|
|
FROM ${issueComments}
|
|
|
|
|
WHERE ${issueComments.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueComments.companyId} = ${companyId}
|
|
|
|
|
AND (
|
|
|
|
|
${issueComments.authorUserId} IS NULL
|
|
|
|
|
OR ${issueComments.authorUserId} <> ${userId}
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function issueLastActivityAtExpr(companyId: string, userId: string) {
|
|
|
|
|
const lastExternalCommentAt = lastExternalCommentAtExpr(companyId, userId);
|
|
|
|
|
const myLastTouchAt = myLastTouchAtExpr(companyId, userId);
|
|
|
|
|
return sql<Date>`
|
2026-04-02 11:38:57 -05:00
|
|
|
GREATEST(
|
|
|
|
|
COALESCE(${lastExternalCommentAt}, to_timestamp(0)),
|
2026-03-26 08:19:16 -05:00
|
|
|
CASE
|
|
|
|
|
WHEN ${issues.updatedAt} > COALESCE(${myLastTouchAt}, to_timestamp(0))
|
|
|
|
|
THEN ${issues.updatedAt}
|
|
|
|
|
ELSE to_timestamp(0)
|
|
|
|
|
END
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-02 11:38:57 -05:00
|
|
|
const ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS = [
|
|
|
|
|
"issue.read_marked",
|
|
|
|
|
"issue.read_unmarked",
|
|
|
|
|
"issue.inbox_archived",
|
|
|
|
|
"issue.inbox_unarchived",
|
|
|
|
|
] as const;
|
|
|
|
|
|
|
|
|
|
function issueLatestCommentAtExpr(companyId: string) {
|
|
|
|
|
return sql<Date | null>`
|
|
|
|
|
(
|
|
|
|
|
SELECT MAX(${issueComments.createdAt})
|
|
|
|
|
FROM ${issueComments}
|
|
|
|
|
WHERE ${issueComments.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueComments.companyId} = ${companyId}
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function issueLatestLogAtExpr(companyId: string) {
|
|
|
|
|
return sql<Date | null>`
|
|
|
|
|
(
|
|
|
|
|
SELECT MAX(${activityLog.createdAt})
|
|
|
|
|
FROM ${activityLog}
|
|
|
|
|
WHERE ${activityLog.companyId} = ${companyId}
|
|
|
|
|
AND ${activityLog.entityType} = 'issue'
|
|
|
|
|
AND ${activityLog.entityId} = ${issues.id}::text
|
|
|
|
|
AND ${activityLog.action} NOT IN (${sql.join(
|
|
|
|
|
ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS.map((action) => sql`${action}`),
|
|
|
|
|
sql`, `,
|
|
|
|
|
)})
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function issueCanonicalLastActivityAtExpr(companyId: string) {
|
|
|
|
|
const latestCommentAt = issueLatestCommentAtExpr(companyId);
|
|
|
|
|
const latestLogAt = issueLatestLogAtExpr(companyId);
|
|
|
|
|
return sql<Date>`
|
|
|
|
|
GREATEST(
|
|
|
|
|
${issues.updatedAt},
|
|
|
|
|
COALESCE(${latestCommentAt}, to_timestamp(0)),
|
|
|
|
|
COALESCE(${latestLogAt}, to_timestamp(0))
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 08:21:03 -06:00
|
|
|
function unreadForUserCondition(companyId: string, userId: string) {
|
|
|
|
|
const touchedCondition = touchedByUserCondition(companyId, userId);
|
|
|
|
|
const myLastTouchAt = myLastTouchAtExpr(companyId, userId);
|
|
|
|
|
return sql<boolean>`
|
|
|
|
|
(
|
|
|
|
|
${touchedCondition}
|
|
|
|
|
AND EXISTS (
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ${issueComments}
|
|
|
|
|
WHERE ${issueComments.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueComments.companyId} = ${companyId}
|
|
|
|
|
AND (
|
|
|
|
|
${issueComments.authorUserId} IS NULL
|
|
|
|
|
OR ${issueComments.authorUserId} <> ${userId}
|
|
|
|
|
)
|
|
|
|
|
AND ${issueComments.createdAt} > ${myLastTouchAt}
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-26 08:19:16 -05:00
|
|
|
function inboxVisibleForUserCondition(companyId: string, userId: string) {
|
|
|
|
|
const issueLastActivityAt = issueLastActivityAtExpr(companyId, userId);
|
|
|
|
|
return sql<boolean>`
|
|
|
|
|
NOT EXISTS (
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ${issueInboxArchives}
|
|
|
|
|
WHERE ${issueInboxArchives.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueInboxArchives.companyId} = ${companyId}
|
|
|
|
|
AND ${issueInboxArchives.userId} = ${userId}
|
|
|
|
|
AND ${issueInboxArchives.archivedAt} >= ${issueLastActivityAt}
|
|
|
|
|
)
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-24 15:22:21 +02:00
|
|
|
/** Named entities commonly emitted in saved issue bodies; unknown `&name;` sequences are left unchanged. */
|
|
|
|
|
const WELL_KNOWN_NAMED_HTML_ENTITIES: Readonly<Record<string, string>> = {
|
|
|
|
|
amp: "&",
|
|
|
|
|
apos: "'",
|
|
|
|
|
copy: "\u00A9",
|
|
|
|
|
gt: ">",
|
|
|
|
|
lt: "<",
|
|
|
|
|
nbsp: "\u00A0",
|
|
|
|
|
quot: '"',
|
|
|
|
|
ensp: "\u2002",
|
|
|
|
|
emsp: "\u2003",
|
|
|
|
|
thinsp: "\u2009",
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
function decodeNumericHtmlEntity(digits: string, radix: 16 | 10): string | null {
|
|
|
|
|
const n = Number.parseInt(digits, radix);
|
|
|
|
|
if (Number.isNaN(n) || n < 0 || n > 0x10ffff) return null;
|
|
|
|
|
try {
|
|
|
|
|
return String.fromCodePoint(n);
|
|
|
|
|
} catch {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Decodes HTML character references in a raw @mention capture so UI-encoded bodies match agent names. */
|
2026-03-20 16:38:55 +00:00
|
|
|
export function normalizeAgentMentionToken(raw: string): string {
|
2026-03-24 15:22:21 +02:00
|
|
|
let s = raw.replace(/&#x([0-9a-fA-F]+);/gi, (full, hex: string) => decodeNumericHtmlEntity(hex, 16) ?? full);
|
|
|
|
|
s = s.replace(/&#([0-9]+);/g, (full, dec: string) => decodeNumericHtmlEntity(dec, 10) ?? full);
|
|
|
|
|
s = s.replace(/&([a-z][a-z0-9]*);/gi, (full, name: string) => {
|
|
|
|
|
const decoded = WELL_KNOWN_NAMED_HTML_ENTITIES[name.toLowerCase()];
|
|
|
|
|
return decoded !== undefined ? decoded : full;
|
|
|
|
|
});
|
|
|
|
|
return s.trim();
|
2026-03-20 16:38:55 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-06 08:21:03 -06:00
|
|
|
export function deriveIssueUserContext(
|
|
|
|
|
issue: IssueUserContextInput,
|
|
|
|
|
userId: string,
|
2026-03-06 08:34:19 -06:00
|
|
|
stats:
|
2026-03-06 09:03:27 -06:00
|
|
|
| {
|
|
|
|
|
myLastCommentAt: Date | string | null;
|
|
|
|
|
myLastReadAt: Date | string | null;
|
|
|
|
|
lastExternalCommentAt: Date | string | null;
|
|
|
|
|
}
|
2026-03-06 08:34:19 -06:00
|
|
|
| null
|
|
|
|
|
| undefined,
|
2026-03-06 08:21:03 -06:00
|
|
|
) {
|
2026-03-06 09:03:27 -06:00
|
|
|
const normalizeDate = (value: Date | string | null | undefined) => {
|
|
|
|
|
if (!value) return null;
|
|
|
|
|
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
|
|
|
|
|
const parsed = new Date(value);
|
|
|
|
|
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const myLastCommentAt = normalizeDate(stats?.myLastCommentAt);
|
|
|
|
|
const myLastReadAt = normalizeDate(stats?.myLastReadAt);
|
|
|
|
|
const createdTouchAt = issue.createdByUserId === userId ? normalizeDate(issue.createdAt) : null;
|
|
|
|
|
const assignedTouchAt = issue.assigneeUserId === userId ? normalizeDate(issue.updatedAt) : null;
|
2026-03-06 08:34:19 -06:00
|
|
|
const myLastTouchAt = [myLastCommentAt, myLastReadAt, createdTouchAt, assignedTouchAt]
|
|
|
|
|
.filter((value): value is Date => value instanceof Date)
|
|
|
|
|
.sort((a, b) => b.getTime() - a.getTime())[0] ?? null;
|
2026-03-06 09:03:27 -06:00
|
|
|
const lastExternalCommentAt = normalizeDate(stats?.lastExternalCommentAt);
|
2026-03-06 08:21:03 -06:00
|
|
|
const isUnreadForMe = Boolean(
|
|
|
|
|
myLastTouchAt &&
|
|
|
|
|
lastExternalCommentAt &&
|
|
|
|
|
lastExternalCommentAt.getTime() > myLastTouchAt.getTime(),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
myLastTouchAt,
|
|
|
|
|
lastExternalCommentAt,
|
|
|
|
|
isUnreadForMe,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-02 11:38:57 -05:00
|
|
|
function latestIssueActivityAt(...values: Array<Date | string | null | undefined>): Date | null {
|
|
|
|
|
const normalized = values
|
|
|
|
|
.map((value) => {
|
|
|
|
|
if (!value) return null;
|
|
|
|
|
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
|
|
|
|
|
const parsed = new Date(value);
|
|
|
|
|
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
|
|
|
})
|
|
|
|
|
.filter((value): value is Date => value instanceof Date)
|
|
|
|
|
.sort((a, b) => b.getTime() - a.getTime());
|
|
|
|
|
return normalized[0] ?? null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
async function labelMapForIssues(dbOrTx: any, issueIds: string[]): Promise<Map<string, IssueLabelRow[]>> {
|
|
|
|
|
const map = new Map<string, IssueLabelRow[]>();
|
|
|
|
|
if (issueIds.length === 0) return map;
|
|
|
|
|
const rows = await dbOrTx
|
|
|
|
|
.select({
|
|
|
|
|
issueId: issueLabels.issueId,
|
|
|
|
|
label: labels,
|
|
|
|
|
})
|
|
|
|
|
.from(issueLabels)
|
|
|
|
|
.innerJoin(labels, eq(issueLabels.labelId, labels.id))
|
|
|
|
|
.where(inArray(issueLabels.issueId, issueIds))
|
|
|
|
|
.orderBy(asc(labels.name), asc(labels.id));
|
|
|
|
|
|
|
|
|
|
for (const row of rows) {
|
|
|
|
|
const existing = map.get(row.issueId);
|
|
|
|
|
if (existing) existing.push(row.label);
|
|
|
|
|
else map.set(row.issueId, [row.label]);
|
|
|
|
|
}
|
|
|
|
|
return map;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function withIssueLabels(dbOrTx: any, rows: IssueRow[]): Promise<IssueWithLabels[]> {
|
|
|
|
|
if (rows.length === 0) return [];
|
|
|
|
|
const labelsByIssueId = await labelMapForIssues(dbOrTx, rows.map((row) => row.id));
|
|
|
|
|
return rows.map((row) => {
|
|
|
|
|
const issueLabels = labelsByIssueId.get(row.id) ?? [];
|
|
|
|
|
return {
|
|
|
|
|
...row,
|
|
|
|
|
labels: issueLabels,
|
|
|
|
|
labelIds: issueLabels.map((label) => label.id),
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-02 16:43:59 -06:00
|
|
|
const ACTIVE_RUN_STATUSES = ["queued", "running"];
|
|
|
|
|
|
|
|
|
|
async function activeRunMapForIssues(
|
|
|
|
|
dbOrTx: any,
|
|
|
|
|
issueRows: IssueWithLabels[],
|
|
|
|
|
): Promise<Map<string, IssueActiveRunRow>> {
|
|
|
|
|
const map = new Map<string, IssueActiveRunRow>();
|
|
|
|
|
const runIds = issueRows
|
|
|
|
|
.map((row) => row.executionRunId)
|
|
|
|
|
.filter((id): id is string => id != null);
|
|
|
|
|
if (runIds.length === 0) return map;
|
|
|
|
|
|
|
|
|
|
const rows = await dbOrTx
|
|
|
|
|
.select({
|
|
|
|
|
id: heartbeatRuns.id,
|
|
|
|
|
status: heartbeatRuns.status,
|
|
|
|
|
agentId: heartbeatRuns.agentId,
|
|
|
|
|
invocationSource: heartbeatRuns.invocationSource,
|
|
|
|
|
triggerDetail: heartbeatRuns.triggerDetail,
|
|
|
|
|
startedAt: heartbeatRuns.startedAt,
|
|
|
|
|
finishedAt: heartbeatRuns.finishedAt,
|
|
|
|
|
createdAt: heartbeatRuns.createdAt,
|
|
|
|
|
})
|
|
|
|
|
.from(heartbeatRuns)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
inArray(heartbeatRuns.id, runIds),
|
|
|
|
|
inArray(heartbeatRuns.status, ACTIVE_RUN_STATUSES),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
for (const row of rows) {
|
|
|
|
|
map.set(row.id, row);
|
|
|
|
|
}
|
|
|
|
|
return map;
|
|
|
|
|
}
|
|
|
|
|
|
Sync/master post pap1497 followups 2026 04 15 (#3779)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - The board depends on issue, inbox, cost, and company-skill surfaces
to stay accurate and fast while agents are actively working
> - The PAP-1497 follow-up branch exposed a few rough edges in those
surfaces: stale active-run state on completed issues, missing creator
filters, oversized issue payload scans, and placeholder issue-route
parsing
> - Those gaps make the control plane harder to trust because operators
can see misleading run state, miss the right subset of work, or pay
extra query/render cost on large issue records
> - This pull request tightens those follow-ups across server and UI
code, and adds regression coverage for the affected paths
> - The benefit is a more reliable issue workflow, safer high-volume
cost aggregation, and clearer board/operator navigation
## What Changed
- Added the `v2026.415.0` release changelog entry.
- Fixed stale issue-run presentation after completion and reused the
shared issue-path parser so literal route placeholders no longer become
issue links.
- Added creator filters to the Issues page and Inbox, including
persisted filter-state normalization and regression coverage.
- Bounded issue detail/list project-mention scans and trimmed large
issue-list payload fields to keep issue reads lighter.
- Hardened company-skill list projection and cost/finance aggregation so
large markdown blobs and large summed values do not leak into list
responses or overflow 32-bit casts.
- Added targeted server/UI regression tests for company skills,
costs/finance, issue mention scanning, creator filters, inbox
normalization, and issue reference parsing.
## Verification
- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/issues-goal-context-routes.test.ts
server/src/__tests__/issues-service.test.ts ui/src/lib/inbox.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-reference.test.ts`
- `gh pr checks 3779`
Current pass set on the PR head: `policy`, `verify`, `e2e`,
`security/snyk (cryppadotta)`, `Greptile Review`
## Risks
- Creator filter options are derived from the currently loaded
issue/agent data, so very sparse result sets may not surface every
historical creator until they appear in the active dataset.
- Cost/finance aggregate casts now use `double precision`; that removes
the current overflow risk, but future schema changes should keep
large-value aggregation behavior under review.
- Issue detail mention scanning now skips comment-body scans on the
detail route, so any consumer that relied on comment-only project
mentions there would need to fetch them separately.
## Model Used
- OpenAI Codex, GPT-5-based coding agent with terminal tool use and
local code execution in the Paperclip workspace. Exact internal model
ID/context-window exposure is not surfaced in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 21:13:56 -05:00
|
|
|
const issueListSelect = {
|
|
|
|
|
id: issues.id,
|
|
|
|
|
companyId: issues.companyId,
|
|
|
|
|
projectId: issues.projectId,
|
|
|
|
|
projectWorkspaceId: issues.projectWorkspaceId,
|
|
|
|
|
goalId: issues.goalId,
|
|
|
|
|
parentId: issues.parentId,
|
|
|
|
|
title: issues.title,
|
|
|
|
|
description: sql<string | null>`
|
|
|
|
|
CASE
|
|
|
|
|
WHEN ${issues.description} IS NULL THEN NULL
|
|
|
|
|
ELSE substring(${issues.description} FROM 1 FOR ${ISSUE_LIST_DESCRIPTION_MAX_CHARS})
|
|
|
|
|
END
|
|
|
|
|
`,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
priority: issues.priority,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
|
|
|
|
assigneeUserId: issues.assigneeUserId,
|
|
|
|
|
checkoutRunId: issues.checkoutRunId,
|
|
|
|
|
executionRunId: issues.executionRunId,
|
|
|
|
|
executionAgentNameKey: issues.executionAgentNameKey,
|
|
|
|
|
executionLockedAt: issues.executionLockedAt,
|
|
|
|
|
createdByAgentId: issues.createdByAgentId,
|
|
|
|
|
createdByUserId: issues.createdByUserId,
|
|
|
|
|
issueNumber: issues.issueNumber,
|
|
|
|
|
identifier: issues.identifier,
|
|
|
|
|
originKind: issues.originKind,
|
|
|
|
|
originId: issues.originId,
|
|
|
|
|
originRunId: issues.originRunId,
|
|
|
|
|
requestDepth: issues.requestDepth,
|
|
|
|
|
billingCode: issues.billingCode,
|
|
|
|
|
assigneeAdapterOverrides: issues.assigneeAdapterOverrides,
|
|
|
|
|
executionPolicy: sql<null>`null`,
|
|
|
|
|
executionState: sql<null>`null`,
|
|
|
|
|
executionWorkspaceId: issues.executionWorkspaceId,
|
|
|
|
|
executionWorkspacePreference: issues.executionWorkspacePreference,
|
|
|
|
|
executionWorkspaceSettings: sql<null>`null`,
|
|
|
|
|
startedAt: issues.startedAt,
|
|
|
|
|
completedAt: issues.completedAt,
|
|
|
|
|
cancelledAt: issues.cancelledAt,
|
|
|
|
|
hiddenAt: issues.hiddenAt,
|
|
|
|
|
createdAt: issues.createdAt,
|
|
|
|
|
updatedAt: issues.updatedAt,
|
|
|
|
|
};
|
|
|
|
|
|
2026-03-02 16:43:59 -06:00
|
|
|
function withActiveRuns(
|
|
|
|
|
issueRows: IssueWithLabels[],
|
|
|
|
|
runMap: Map<string, IssueActiveRunRow>,
|
|
|
|
|
): IssueWithLabelsAndRun[] {
|
|
|
|
|
return issueRows.map((row) => ({
|
|
|
|
|
...row,
|
|
|
|
|
activeRun: row.executionRunId ? (runMap.get(row.executionRunId) ?? null) : null,
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-16 13:31:58 -06:00
|
|
|
export function issueService(db: Db) {
|
2026-03-17 09:24:28 -05:00
|
|
|
const instanceSettings = instanceSettingsService(db);
|
|
|
|
|
|
2026-04-02 09:11:49 -05:00
|
|
|
async function getIssueByUuid(id: string) {
|
|
|
|
|
const row = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!row) return null;
|
|
|
|
|
const [enriched] = await withIssueLabels(db, [row]);
|
|
|
|
|
return enriched;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function getIssueByIdentifier(identifier: string) {
|
|
|
|
|
const row = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.identifier, identifier.toUpperCase()))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!row) return null;
|
|
|
|
|
const [enriched] = await withIssueLabels(db, [row]);
|
|
|
|
|
return enriched;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 08:00:39 -05:00
|
|
|
function redactIssueComment<T extends { body: string }>(comment: T, censorUsernameInLogs: boolean): T {
|
|
|
|
|
return {
|
|
|
|
|
...comment,
|
|
|
|
|
body: redactCurrentUserText(comment.body, { enabled: censorUsernameInLogs }),
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
Agent management: hire endpoint with permission gates and pending_approval status,
config revision tracking with rollback, agent duplicate route, permission CRUD.
Block pending_approval agents from auth, heartbeat, and assignments.
Approvals: revision request/resubmit flow, approval comments CRUD, issue-approval
linking, auto-wake agents on approval decisions with context snapshot.
Costs: per-agent breakdown, period filtering (month/week/day/all), cost by agent
list endpoint.
Adapters: agentConfigurationDoc on all adapters, /llms/agent-configuration.txt
reflection routes. Inject PAPERCLIP_APPROVAL_ID, PAPERCLIP_APPROVAL_STATUS,
PAPERCLIP_LINKED_ISSUE_IDS into adapter environments.
Sidebar badges endpoint for pending approval/inbox counts. Dashboard and company
settings extensions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 13:02:41 -06:00
|
|
|
async function assertAssignableAgent(companyId: string, agentId: string) {
|
|
|
|
|
const assignee = await db
|
|
|
|
|
.select({
|
|
|
|
|
id: agents.id,
|
|
|
|
|
companyId: agents.companyId,
|
|
|
|
|
status: agents.status,
|
|
|
|
|
})
|
|
|
|
|
.from(agents)
|
|
|
|
|
.where(eq(agents.id, agentId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (!assignee) throw notFound("Assignee agent not found");
|
|
|
|
|
if (assignee.companyId !== companyId) {
|
|
|
|
|
throw unprocessable("Assignee must belong to same company");
|
|
|
|
|
}
|
|
|
|
|
if (assignee.status === "pending_approval") {
|
|
|
|
|
throw conflict("Cannot assign work to pending approval agents");
|
|
|
|
|
}
|
|
|
|
|
if (assignee.status === "terminated") {
|
|
|
|
|
throw conflict("Cannot assign work to terminated agents");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-23 14:40:32 -06:00
|
|
|
async function assertAssignableUser(companyId: string, userId: string) {
|
|
|
|
|
const membership = await db
|
|
|
|
|
.select({ id: companyMemberships.id })
|
|
|
|
|
.from(companyMemberships)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(companyMemberships.companyId, companyId),
|
|
|
|
|
eq(companyMemberships.principalType, "user"),
|
|
|
|
|
eq(companyMemberships.principalId, userId),
|
|
|
|
|
eq(companyMemberships.status, "active"),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!membership) {
|
|
|
|
|
throw notFound("Assignee user not found");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-30 14:08:44 -05:00
|
|
|
async function assertValidProjectWorkspace(
|
|
|
|
|
companyId: string,
|
|
|
|
|
projectId: string | null | undefined,
|
|
|
|
|
projectWorkspaceId: string,
|
|
|
|
|
dbOrTx: DbReader = db,
|
|
|
|
|
) {
|
|
|
|
|
const workspace = await dbOrTx
|
2026-03-13 17:12:25 -05:00
|
|
|
.select({
|
|
|
|
|
id: projectWorkspaces.id,
|
|
|
|
|
companyId: projectWorkspaces.companyId,
|
|
|
|
|
projectId: projectWorkspaces.projectId,
|
|
|
|
|
})
|
|
|
|
|
.from(projectWorkspaces)
|
|
|
|
|
.where(eq(projectWorkspaces.id, projectWorkspaceId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!workspace) throw notFound("Project workspace not found");
|
|
|
|
|
if (workspace.companyId !== companyId) throw unprocessable("Project workspace must belong to same company");
|
|
|
|
|
if (projectId && workspace.projectId !== projectId) {
|
|
|
|
|
throw unprocessable("Project workspace must belong to the selected project");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-30 14:08:44 -05:00
|
|
|
async function assertValidExecutionWorkspace(
|
|
|
|
|
companyId: string,
|
|
|
|
|
projectId: string | null | undefined,
|
|
|
|
|
executionWorkspaceId: string,
|
|
|
|
|
dbOrTx: DbReader = db,
|
|
|
|
|
) {
|
|
|
|
|
const workspace = await dbOrTx
|
2026-03-13 17:12:25 -05:00
|
|
|
.select({
|
|
|
|
|
id: executionWorkspaces.id,
|
|
|
|
|
companyId: executionWorkspaces.companyId,
|
|
|
|
|
projectId: executionWorkspaces.projectId,
|
|
|
|
|
})
|
|
|
|
|
.from(executionWorkspaces)
|
|
|
|
|
.where(eq(executionWorkspaces.id, executionWorkspaceId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!workspace) throw notFound("Execution workspace not found");
|
|
|
|
|
if (workspace.companyId !== companyId) throw unprocessable("Execution workspace must belong to same company");
|
|
|
|
|
if (projectId && workspace.projectId !== projectId) {
|
|
|
|
|
throw unprocessable("Execution workspace must belong to the selected project");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
async function assertValidLabelIds(companyId: string, labelIds: string[], dbOrTx: any = db) {
|
|
|
|
|
if (labelIds.length === 0) return;
|
|
|
|
|
const existing = await dbOrTx
|
|
|
|
|
.select({ id: labels.id })
|
|
|
|
|
.from(labels)
|
|
|
|
|
.where(and(eq(labels.companyId, companyId), inArray(labels.id, labelIds)));
|
|
|
|
|
if (existing.length !== new Set(labelIds).size) {
|
|
|
|
|
throw unprocessable("One or more labels are invalid for this company");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function syncIssueLabels(
|
|
|
|
|
issueId: string,
|
|
|
|
|
companyId: string,
|
|
|
|
|
labelIds: string[],
|
|
|
|
|
dbOrTx: any = db,
|
|
|
|
|
) {
|
|
|
|
|
const deduped = [...new Set(labelIds)];
|
|
|
|
|
await assertValidLabelIds(companyId, deduped, dbOrTx);
|
|
|
|
|
await dbOrTx.delete(issueLabels).where(eq(issueLabels.issueId, issueId));
|
|
|
|
|
if (deduped.length === 0) return;
|
|
|
|
|
await dbOrTx.insert(issueLabels).values(
|
|
|
|
|
deduped.map((labelId) => ({
|
|
|
|
|
issueId,
|
|
|
|
|
labelId,
|
|
|
|
|
companyId,
|
|
|
|
|
})),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-04 13:56:04 -05:00
|
|
|
async function getIssueRelationSummaryMap(
|
|
|
|
|
companyId: string,
|
|
|
|
|
issueIds: string[],
|
|
|
|
|
dbOrTx: DbReader = db,
|
|
|
|
|
): Promise<Map<string, IssueRelationSummaryMap>> {
|
|
|
|
|
const uniqueIssueIds = [...new Set(issueIds)];
|
|
|
|
|
const empty = new Map<string, IssueRelationSummaryMap>();
|
|
|
|
|
for (const issueId of uniqueIssueIds) {
|
|
|
|
|
empty.set(issueId, { blockedBy: [], blocks: [] });
|
|
|
|
|
}
|
|
|
|
|
if (uniqueIssueIds.length === 0) return empty;
|
|
|
|
|
|
|
|
|
|
const [blockedByRows, blockingRows] = await Promise.all([
|
|
|
|
|
dbOrTx
|
|
|
|
|
.select({
|
|
|
|
|
currentIssueId: issueRelations.relatedIssueId,
|
|
|
|
|
relatedId: issues.id,
|
|
|
|
|
identifier: issues.identifier,
|
|
|
|
|
title: issues.title,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
priority: issues.priority,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
|
|
|
|
assigneeUserId: issues.assigneeUserId,
|
|
|
|
|
})
|
|
|
|
|
.from(issueRelations)
|
|
|
|
|
.innerJoin(issues, eq(issueRelations.issueId, issues.id))
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueRelations.companyId, companyId),
|
|
|
|
|
eq(issueRelations.type, "blocks"),
|
|
|
|
|
inArray(issueRelations.relatedIssueId, uniqueIssueIds),
|
|
|
|
|
),
|
|
|
|
|
),
|
|
|
|
|
dbOrTx
|
|
|
|
|
.select({
|
|
|
|
|
currentIssueId: issueRelations.issueId,
|
|
|
|
|
relatedId: issues.id,
|
|
|
|
|
identifier: issues.identifier,
|
|
|
|
|
title: issues.title,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
priority: issues.priority,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
|
|
|
|
assigneeUserId: issues.assigneeUserId,
|
|
|
|
|
})
|
|
|
|
|
.from(issueRelations)
|
|
|
|
|
.innerJoin(issues, eq(issueRelations.relatedIssueId, issues.id))
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueRelations.companyId, companyId),
|
|
|
|
|
eq(issueRelations.type, "blocks"),
|
|
|
|
|
inArray(issueRelations.issueId, uniqueIssueIds),
|
|
|
|
|
),
|
|
|
|
|
),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
for (const row of blockedByRows) {
|
|
|
|
|
empty.get(row.currentIssueId)?.blockedBy.push({
|
|
|
|
|
id: row.relatedId,
|
|
|
|
|
identifier: row.identifier,
|
|
|
|
|
title: row.title,
|
|
|
|
|
status: row.status as IssueRelationIssueSummary["status"],
|
|
|
|
|
priority: row.priority as IssueRelationIssueSummary["priority"],
|
|
|
|
|
assigneeAgentId: row.assigneeAgentId,
|
|
|
|
|
assigneeUserId: row.assigneeUserId,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
for (const row of blockingRows) {
|
|
|
|
|
empty.get(row.currentIssueId)?.blocks.push({
|
|
|
|
|
id: row.relatedId,
|
|
|
|
|
identifier: row.identifier,
|
|
|
|
|
title: row.title,
|
|
|
|
|
status: row.status as IssueRelationIssueSummary["status"],
|
|
|
|
|
priority: row.priority as IssueRelationIssueSummary["priority"],
|
|
|
|
|
assigneeAgentId: row.assigneeAgentId,
|
|
|
|
|
assigneeUserId: row.assigneeUserId,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const relations of empty.values()) {
|
|
|
|
|
relations.blockedBy.sort((a, b) => a.title.localeCompare(b.title));
|
|
|
|
|
relations.blocks.sort((a, b) => a.title.localeCompare(b.title));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return empty;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function assertNoBlockingCycles(
|
|
|
|
|
companyId: string,
|
|
|
|
|
issueId: string,
|
|
|
|
|
blockerIssueIds: string[],
|
|
|
|
|
dbOrTx: DbReader = db,
|
|
|
|
|
) {
|
|
|
|
|
if (blockerIssueIds.length === 0) return;
|
|
|
|
|
|
|
|
|
|
const rows = await dbOrTx
|
|
|
|
|
.select({
|
|
|
|
|
blockerIssueId: issueRelations.issueId,
|
|
|
|
|
blockedIssueId: issueRelations.relatedIssueId,
|
|
|
|
|
})
|
|
|
|
|
.from(issueRelations)
|
|
|
|
|
.where(and(eq(issueRelations.companyId, companyId), eq(issueRelations.type, "blocks")));
|
|
|
|
|
|
|
|
|
|
const adjacency = new Map<string, string[]>();
|
|
|
|
|
for (const row of rows) {
|
|
|
|
|
const list = adjacency.get(row.blockerIssueId) ?? [];
|
|
|
|
|
list.push(row.blockedIssueId);
|
|
|
|
|
adjacency.set(row.blockerIssueId, list);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const blockerIssueId of blockerIssueIds) {
|
|
|
|
|
const queue = [...(adjacency.get(issueId) ?? [])];
|
|
|
|
|
const visited = new Set<string>([issueId]);
|
|
|
|
|
while (queue.length > 0) {
|
|
|
|
|
const current = queue.shift()!;
|
|
|
|
|
if (current === blockerIssueId) {
|
|
|
|
|
throw unprocessable("Blocking relations cannot contain cycles");
|
|
|
|
|
}
|
|
|
|
|
if (visited.has(current)) continue;
|
|
|
|
|
visited.add(current);
|
|
|
|
|
queue.push(...(adjacency.get(current) ?? []));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function syncBlockedByIssueIds(
|
|
|
|
|
issueId: string,
|
|
|
|
|
companyId: string,
|
|
|
|
|
blockedByIssueIds: string[],
|
|
|
|
|
actor: { agentId?: string | null; userId?: string | null } = {},
|
|
|
|
|
dbOrTx: any = db,
|
|
|
|
|
) {
|
|
|
|
|
const deduped = [...new Set(blockedByIssueIds)];
|
|
|
|
|
if (deduped.some((candidate) => candidate === issueId)) {
|
|
|
|
|
throw unprocessable("Issue cannot be blocked by itself");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (deduped.length > 0) {
|
2026-04-06 08:29:23 -05:00
|
|
|
const lockedIssueIds = [issueId, ...deduped].sort();
|
|
|
|
|
await dbOrTx.execute(
|
|
|
|
|
sql`SELECT ${issues.id} FROM ${issues}
|
|
|
|
|
WHERE ${and(eq(issues.companyId, companyId), inArray(issues.id, lockedIssueIds))}
|
|
|
|
|
ORDER BY ${issues.id}
|
|
|
|
|
FOR UPDATE`,
|
|
|
|
|
);
|
2026-04-04 13:56:04 -05:00
|
|
|
const relatedIssues = await dbOrTx
|
|
|
|
|
.select({ id: issues.id })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(and(eq(issues.companyId, companyId), inArray(issues.id, deduped)));
|
|
|
|
|
if (relatedIssues.length !== deduped.length) {
|
|
|
|
|
throw unprocessable("Blocked-by issues must belong to the same company");
|
|
|
|
|
}
|
|
|
|
|
await assertNoBlockingCycles(companyId, issueId, deduped, dbOrTx);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await dbOrTx
|
|
|
|
|
.delete(issueRelations)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueRelations.companyId, companyId),
|
|
|
|
|
eq(issueRelations.relatedIssueId, issueId),
|
|
|
|
|
eq(issueRelations.type, "blocks"),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (deduped.length === 0) return;
|
|
|
|
|
|
|
|
|
|
await dbOrTx.insert(issueRelations).values(
|
|
|
|
|
deduped.map((blockerIssueId) => ({
|
|
|
|
|
companyId,
|
|
|
|
|
issueId: blockerIssueId,
|
|
|
|
|
relatedIssueId: issueId,
|
|
|
|
|
type: "blocks",
|
|
|
|
|
createdByAgentId: actor.agentId ?? null,
|
|
|
|
|
createdByUserId: actor.userId ?? null,
|
|
|
|
|
})),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-21 08:23:44 -06:00
|
|
|
async function isTerminalOrMissingHeartbeatRun(runId: string) {
|
|
|
|
|
const run = await db
|
|
|
|
|
.select({ status: heartbeatRuns.status })
|
|
|
|
|
.from(heartbeatRuns)
|
|
|
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!run) return true;
|
|
|
|
|
return TERMINAL_HEARTBEAT_RUN_STATUSES.has(run.status);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function adoptStaleCheckoutRun(input: {
|
|
|
|
|
issueId: string;
|
|
|
|
|
actorAgentId: string;
|
|
|
|
|
actorRunId: string;
|
|
|
|
|
expectedCheckoutRunId: string;
|
|
|
|
|
}) {
|
|
|
|
|
const stale = await isTerminalOrMissingHeartbeatRun(input.expectedCheckoutRunId);
|
|
|
|
|
if (!stale) return null;
|
|
|
|
|
|
|
|
|
|
const now = new Date();
|
|
|
|
|
const adopted = await db
|
|
|
|
|
.update(issues)
|
|
|
|
|
.set({
|
|
|
|
|
checkoutRunId: input.actorRunId,
|
|
|
|
|
executionRunId: input.actorRunId,
|
|
|
|
|
executionLockedAt: now,
|
|
|
|
|
updatedAt: now,
|
|
|
|
|
})
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issues.id, input.issueId),
|
|
|
|
|
eq(issues.status, "in_progress"),
|
|
|
|
|
eq(issues.assigneeAgentId, input.actorAgentId),
|
|
|
|
|
eq(issues.checkoutRunId, input.expectedCheckoutRunId),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.returning({
|
|
|
|
|
id: issues.id,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
|
|
|
|
checkoutRunId: issues.checkoutRunId,
|
|
|
|
|
executionRunId: issues.executionRunId,
|
|
|
|
|
})
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
return adopted;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-16 13:31:58 -06:00
|
|
|
return {
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
list: async (companyId: string, filters?: IssueFilters) => {
|
|
|
|
|
const conditions = [eq(issues.companyId, companyId)];
|
2026-04-06 20:30:50 -05:00
|
|
|
const limit = typeof filters?.limit === "number" && Number.isFinite(filters.limit)
|
|
|
|
|
? Math.max(1, Math.floor(filters.limit))
|
|
|
|
|
: undefined;
|
2026-03-06 08:21:03 -06:00
|
|
|
const touchedByUserId = filters?.touchedByUserId?.trim() || undefined;
|
2026-03-26 08:19:16 -05:00
|
|
|
const inboxArchivedByUserId = filters?.inboxArchivedByUserId?.trim() || undefined;
|
2026-03-06 08:21:03 -06:00
|
|
|
const unreadForUserId = filters?.unreadForUserId?.trim() || undefined;
|
2026-03-26 08:19:16 -05:00
|
|
|
const contextUserId = unreadForUserId ?? touchedByUserId ?? inboxArchivedByUserId;
|
2026-02-26 16:33:39 -06:00
|
|
|
const rawSearch = filters?.q?.trim() ?? "";
|
|
|
|
|
const hasSearch = rawSearch.length > 0;
|
|
|
|
|
const escapedSearch = hasSearch ? escapeLikePattern(rawSearch) : "";
|
|
|
|
|
const startsWithPattern = `${escapedSearch}%`;
|
|
|
|
|
const containsPattern = `%${escapedSearch}%`;
|
|
|
|
|
const titleStartsWithMatch = sql<boolean>`${issues.title} ILIKE ${startsWithPattern} ESCAPE '\\'`;
|
|
|
|
|
const titleContainsMatch = sql<boolean>`${issues.title} ILIKE ${containsPattern} ESCAPE '\\'`;
|
|
|
|
|
const identifierStartsWithMatch = sql<boolean>`${issues.identifier} ILIKE ${startsWithPattern} ESCAPE '\\'`;
|
|
|
|
|
const identifierContainsMatch = sql<boolean>`${issues.identifier} ILIKE ${containsPattern} ESCAPE '\\'`;
|
|
|
|
|
const descriptionContainsMatch = sql<boolean>`${issues.description} ILIKE ${containsPattern} ESCAPE '\\'`;
|
|
|
|
|
const commentContainsMatch = sql<boolean>`
|
|
|
|
|
EXISTS (
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ${issueComments}
|
|
|
|
|
WHERE ${issueComments.issueId} = ${issues.id}
|
|
|
|
|
AND ${issueComments.companyId} = ${companyId}
|
|
|
|
|
AND ${issueComments.body} ILIKE ${containsPattern} ESCAPE '\\'
|
|
|
|
|
)
|
|
|
|
|
`;
|
2026-02-18 16:46:45 -06:00
|
|
|
if (filters?.status) {
|
|
|
|
|
const statuses = filters.status.split(",").map((s) => s.trim());
|
|
|
|
|
conditions.push(statuses.length === 1 ? eq(issues.status, statuses[0]) : inArray(issues.status, statuses));
|
|
|
|
|
}
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
if (filters?.assigneeAgentId) {
|
|
|
|
|
conditions.push(eq(issues.assigneeAgentId, filters.assigneeAgentId));
|
|
|
|
|
}
|
2026-03-21 12:20:48 -05:00
|
|
|
if (filters?.participantAgentId) {
|
|
|
|
|
conditions.push(participatedByAgentCondition(companyId, filters.participantAgentId));
|
|
|
|
|
}
|
2026-02-26 16:33:39 -06:00
|
|
|
if (filters?.assigneeUserId) {
|
|
|
|
|
conditions.push(eq(issues.assigneeUserId, filters.assigneeUserId));
|
|
|
|
|
}
|
2026-03-06 08:21:03 -06:00
|
|
|
if (touchedByUserId) {
|
|
|
|
|
conditions.push(touchedByUserCondition(companyId, touchedByUserId));
|
|
|
|
|
}
|
2026-03-26 08:19:16 -05:00
|
|
|
if (inboxArchivedByUserId) {
|
|
|
|
|
conditions.push(inboxVisibleForUserCondition(companyId, inboxArchivedByUserId));
|
|
|
|
|
}
|
2026-03-06 08:21:03 -06:00
|
|
|
if (unreadForUserId) {
|
|
|
|
|
conditions.push(unreadForUserCondition(companyId, unreadForUserId));
|
|
|
|
|
}
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
if (filters?.projectId) conditions.push(eq(issues.projectId, filters.projectId));
|
2026-03-28 22:21:24 -05:00
|
|
|
if (filters?.executionWorkspaceId) {
|
|
|
|
|
conditions.push(eq(issues.executionWorkspaceId, filters.executionWorkspaceId));
|
|
|
|
|
}
|
2026-03-10 15:54:31 +02:00
|
|
|
if (filters?.parentId) conditions.push(eq(issues.parentId, filters.parentId));
|
2026-03-19 08:39:24 -05:00
|
|
|
if (filters?.originKind) conditions.push(eq(issues.originKind, filters.originKind));
|
|
|
|
|
if (filters?.originId) conditions.push(eq(issues.originId, filters.originId));
|
2026-02-25 08:38:37 -06:00
|
|
|
if (filters?.labelId) {
|
|
|
|
|
const labeledIssueIds = await db
|
|
|
|
|
.select({ issueId: issueLabels.issueId })
|
|
|
|
|
.from(issueLabels)
|
|
|
|
|
.where(and(eq(issueLabels.companyId, companyId), eq(issueLabels.labelId, filters.labelId)));
|
|
|
|
|
if (labeledIssueIds.length === 0) return [];
|
|
|
|
|
conditions.push(inArray(issues.id, labeledIssueIds.map((row) => row.issueId)));
|
|
|
|
|
}
|
2026-02-26 16:33:39 -06:00
|
|
|
if (hasSearch) {
|
|
|
|
|
conditions.push(
|
|
|
|
|
or(
|
|
|
|
|
titleContainsMatch,
|
|
|
|
|
identifierContainsMatch,
|
|
|
|
|
descriptionContainsMatch,
|
|
|
|
|
commentContainsMatch,
|
|
|
|
|
)!,
|
|
|
|
|
);
|
|
|
|
|
}
|
[codex] improve issue and routine UI responsiveness (#3744)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - Operators rely on issue, inbox, and routine views to understand what
the company is doing in real time
> - Those views need to stay fast and readable even when issue lists,
markdown comments, and run metadata get large
> - The current branch had a coherent set of UI and live-update
improvements spread across issue search, issue detail rendering, routine
affordances, and workspace lookups
> - This pull request groups those board-facing changes into one
standalone branch that can merge independently of the heartbeat/runtime
work
> - The benefit is a faster, clearer issue and routine workflow without
changing the underlying task model
## What Changed
- Show routine execution issues by default and rename the filter to
`Hide routine runs` so the default state no longer looks like an active
filter.
- Show the routine name in the run dialog and tighten the issue
properties pane with a workspace link, copy-on-click behavior, and an
inline parent arrow.
- Reduce issue detail rerenders, keep queued issue chat mounted, improve
issues page search responsiveness, and speed up issues first paint.
- Add inbox "other search results", refresh visible issue runs after
status updates, and optimize workspace lookups through summary-mode
execution workspace queries.
- Improve markdown wrapping and scrolling behavior for long strings and
self-comment code blocks.
- Relax the markdown sanitizer assertion so the test still validates
safety after the new wrap-friendly inline styles.
## Verification
- `pnpm vitest run ui/src/components/IssuesList.test.tsx
ui/src/lib/inbox.test.ts ui/src/pages/Issues.test.tsx
ui/src/context/BreadcrumbContext.test.tsx
ui/src/context/LiveUpdatesProvider.test.ts
ui/src/components/MarkdownBody.test.tsx
ui/src/api/execution-workspaces.test.ts
server/src/__tests__/execution-workspaces-routes.test.ts`
## Risks
- This touches several issue-facing UI surfaces at once, so regressions
would most likely show up as stale rendering, search result mismatches,
or small markdown presentation differences.
- The workspace lookup optimization depends on the summary-mode route
shape staying aligned between server and UI.
## Model Used
- OpenAI Codex, GPT-5-based coding agent in the Codex CLI environment.
Exact backend model deployment ID was not exposed in-session.
Tool-assisted editing and shell execution were used.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 15:54:05 -05:00
|
|
|
if (filters?.excludeRoutineExecutions && !filters?.originKind && !filters?.originId) {
|
2026-03-19 08:39:24 -05:00
|
|
|
conditions.push(ne(issues.originKind, "routine_execution"));
|
|
|
|
|
}
|
2026-02-19 15:43:52 -06:00
|
|
|
conditions.push(isNull(issues.hiddenAt));
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
2026-02-17 20:46:12 -06:00
|
|
|
const priorityOrder = sql`CASE ${issues.priority} WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END`;
|
2026-02-26 16:33:39 -06:00
|
|
|
const searchOrder = sql<number>`
|
|
|
|
|
CASE
|
|
|
|
|
WHEN ${titleStartsWithMatch} THEN 0
|
|
|
|
|
WHEN ${titleContainsMatch} THEN 1
|
|
|
|
|
WHEN ${identifierStartsWithMatch} THEN 2
|
|
|
|
|
WHEN ${identifierContainsMatch} THEN 3
|
2026-04-11 06:57:49 -05:00
|
|
|
WHEN ${commentContainsMatch} THEN 4
|
|
|
|
|
WHEN ${descriptionContainsMatch} THEN 5
|
2026-02-26 16:33:39 -06:00
|
|
|
ELSE 6
|
|
|
|
|
END
|
|
|
|
|
`;
|
2026-04-02 11:38:57 -05:00
|
|
|
const canonicalLastActivityAt = issueCanonicalLastActivityAtExpr(companyId);
|
2026-04-06 20:30:50 -05:00
|
|
|
const baseQuery = db
|
Sync/master post pap1497 followups 2026 04 15 (#3779)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - The board depends on issue, inbox, cost, and company-skill surfaces
to stay accurate and fast while agents are actively working
> - The PAP-1497 follow-up branch exposed a few rough edges in those
surfaces: stale active-run state on completed issues, missing creator
filters, oversized issue payload scans, and placeholder issue-route
parsing
> - Those gaps make the control plane harder to trust because operators
can see misleading run state, miss the right subset of work, or pay
extra query/render cost on large issue records
> - This pull request tightens those follow-ups across server and UI
code, and adds regression coverage for the affected paths
> - The benefit is a more reliable issue workflow, safer high-volume
cost aggregation, and clearer board/operator navigation
## What Changed
- Added the `v2026.415.0` release changelog entry.
- Fixed stale issue-run presentation after completion and reused the
shared issue-path parser so literal route placeholders no longer become
issue links.
- Added creator filters to the Issues page and Inbox, including
persisted filter-state normalization and regression coverage.
- Bounded issue detail/list project-mention scans and trimmed large
issue-list payload fields to keep issue reads lighter.
- Hardened company-skill list projection and cost/finance aggregation so
large markdown blobs and large summed values do not leak into list
responses or overflow 32-bit casts.
- Added targeted server/UI regression tests for company skills,
costs/finance, issue mention scanning, creator filters, inbox
normalization, and issue reference parsing.
## Verification
- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/issues-goal-context-routes.test.ts
server/src/__tests__/issues-service.test.ts ui/src/lib/inbox.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-reference.test.ts`
- `gh pr checks 3779`
Current pass set on the PR head: `policy`, `verify`, `e2e`,
`security/snyk (cryppadotta)`, `Greptile Review`
## Risks
- Creator filter options are derived from the currently loaded
issue/agent data, so very sparse result sets may not surface every
historical creator until they appear in the active dataset.
- Cost/finance aggregate casts now use `double precision`; that removes
the current overflow risk, but future schema changes should keep
large-value aggregation behavior under review.
- Issue detail mention scanning now skips comment-body scans on the
detail route, so any consumer that relied on comment-only project
mentions there would need to fetch them separately.
## Model Used
- OpenAI Codex, GPT-5-based coding agent with terminal tool use and
local code execution in the Paperclip workspace. Exact internal model
ID/context-window exposure is not surfaced in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 21:13:56 -05:00
|
|
|
.select(issueListSelect)
|
2026-02-25 08:38:37 -06:00
|
|
|
.from(issues)
|
|
|
|
|
.where(and(...conditions))
|
2026-04-02 11:38:57 -05:00
|
|
|
.orderBy(
|
|
|
|
|
hasSearch ? asc(searchOrder) : asc(priorityOrder),
|
|
|
|
|
asc(priorityOrder),
|
|
|
|
|
desc(canonicalLastActivityAt),
|
|
|
|
|
desc(issues.updatedAt),
|
|
|
|
|
);
|
2026-04-06 20:30:50 -05:00
|
|
|
const rows = limit === undefined ? await baseQuery : await baseQuery.limit(limit);
|
2026-03-02 16:43:59 -06:00
|
|
|
const withLabels = await withIssueLabels(db, rows);
|
|
|
|
|
const runMap = await activeRunMapForIssues(db, withLabels);
|
2026-03-06 08:21:03 -06:00
|
|
|
const withRuns = withActiveRuns(withLabels, runMap);
|
2026-04-02 11:38:57 -05:00
|
|
|
if (withRuns.length === 0) {
|
2026-03-06 08:21:03 -06:00
|
|
|
return withRuns;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const issueIds = withRuns.map((row) => row.id);
|
2026-04-02 11:38:57 -05:00
|
|
|
const [statsRows, readRows, lastActivityRows] = await Promise.all([
|
|
|
|
|
contextUserId
|
|
|
|
|
? db
|
|
|
|
|
.select({
|
|
|
|
|
issueId: issueComments.issueId,
|
|
|
|
|
myLastCommentAt: sql<Date | null>`
|
|
|
|
|
MAX(CASE WHEN ${issueComments.authorUserId} = ${contextUserId} THEN ${issueComments.createdAt} END)
|
|
|
|
|
`,
|
|
|
|
|
lastExternalCommentAt: sql<Date | null>`
|
|
|
|
|
MAX(
|
|
|
|
|
CASE
|
|
|
|
|
WHEN ${issueComments.authorUserId} IS NULL OR ${issueComments.authorUserId} <> ${contextUserId}
|
|
|
|
|
THEN ${issueComments.createdAt}
|
|
|
|
|
END
|
|
|
|
|
)
|
|
|
|
|
`,
|
|
|
|
|
})
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueComments.companyId, companyId),
|
|
|
|
|
inArray(issueComments.issueId, issueIds),
|
|
|
|
|
),
|
2026-03-06 08:21:03 -06:00
|
|
|
)
|
2026-04-02 11:38:57 -05:00
|
|
|
.groupBy(issueComments.issueId)
|
|
|
|
|
: Promise.resolve([]),
|
|
|
|
|
contextUserId
|
|
|
|
|
? db
|
|
|
|
|
.select({
|
|
|
|
|
issueId: issueReadStates.issueId,
|
|
|
|
|
myLastReadAt: issueReadStates.lastReadAt,
|
|
|
|
|
})
|
|
|
|
|
.from(issueReadStates)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueReadStates.companyId, companyId),
|
|
|
|
|
eq(issueReadStates.userId, contextUserId),
|
|
|
|
|
inArray(issueReadStates.issueId, issueIds),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
: Promise.resolve([]),
|
|
|
|
|
Promise.all([
|
|
|
|
|
db
|
|
|
|
|
.select({
|
|
|
|
|
issueId: issueComments.issueId,
|
|
|
|
|
latestCommentAt: sql<Date | null>`MAX(${issueComments.createdAt})`,
|
|
|
|
|
})
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueComments.companyId, companyId),
|
|
|
|
|
inArray(issueComments.issueId, issueIds),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.groupBy(issueComments.issueId),
|
|
|
|
|
db
|
|
|
|
|
.select({
|
|
|
|
|
issueId: activityLog.entityId,
|
|
|
|
|
latestLogAt: sql<Date | null>`MAX(${activityLog.createdAt})`,
|
|
|
|
|
})
|
|
|
|
|
.from(activityLog)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(activityLog.companyId, companyId),
|
|
|
|
|
eq(activityLog.entityType, "issue"),
|
|
|
|
|
inArray(activityLog.entityId, issueIds),
|
|
|
|
|
sql`${activityLog.action} NOT IN (${sql.join(
|
|
|
|
|
ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS.map((action) => sql`${action}`),
|
|
|
|
|
sql`, `,
|
|
|
|
|
)})`,
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.groupBy(activityLog.entityId),
|
|
|
|
|
]).then(([commentRows, logRows]) => {
|
|
|
|
|
const byIssueId = new Map<string, IssueLastActivityStat>();
|
|
|
|
|
for (const row of commentRows) {
|
|
|
|
|
byIssueId.set(row.issueId, {
|
|
|
|
|
issueId: row.issueId,
|
|
|
|
|
latestCommentAt: row.latestCommentAt,
|
|
|
|
|
latestLogAt: null,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
for (const row of logRows) {
|
|
|
|
|
const existing = byIssueId.get(row.issueId);
|
|
|
|
|
if (existing) existing.latestLogAt = row.latestLogAt;
|
|
|
|
|
else {
|
|
|
|
|
byIssueId.set(row.issueId, {
|
|
|
|
|
issueId: row.issueId,
|
|
|
|
|
latestCommentAt: null,
|
|
|
|
|
latestLogAt: row.latestLogAt,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return [...byIssueId.values()];
|
|
|
|
|
}),
|
|
|
|
|
]);
|
2026-03-06 08:21:03 -06:00
|
|
|
const statsByIssueId = new Map(statsRows.map((row) => [row.issueId, row]));
|
2026-04-02 11:38:57 -05:00
|
|
|
const lastActivityByIssueId = new Map(lastActivityRows.map((row) => [row.issueId, row]));
|
|
|
|
|
|
|
|
|
|
if (!contextUserId) {
|
|
|
|
|
return withRuns.map((row) => {
|
|
|
|
|
const activity = lastActivityByIssueId.get(row.id);
|
|
|
|
|
const lastActivityAt = latestIssueActivityAt(
|
|
|
|
|
row.updatedAt,
|
|
|
|
|
activity?.latestCommentAt ?? null,
|
|
|
|
|
activity?.latestLogAt ?? null,
|
|
|
|
|
) ?? row.updatedAt;
|
|
|
|
|
return {
|
|
|
|
|
...row,
|
|
|
|
|
lastActivityAt,
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 08:34:19 -06:00
|
|
|
const readByIssueId = new Map(readRows.map((row) => [row.issueId, row.myLastReadAt]));
|
2026-03-06 08:21:03 -06:00
|
|
|
|
2026-04-02 11:38:57 -05:00
|
|
|
return withRuns.map((row) => {
|
|
|
|
|
const activity = lastActivityByIssueId.get(row.id);
|
|
|
|
|
const lastActivityAt = latestIssueActivityAt(
|
|
|
|
|
row.updatedAt,
|
|
|
|
|
activity?.latestCommentAt ?? null,
|
|
|
|
|
activity?.latestLogAt ?? null,
|
|
|
|
|
) ?? row.updatedAt;
|
|
|
|
|
return {
|
|
|
|
|
...row,
|
|
|
|
|
lastActivityAt,
|
|
|
|
|
...deriveIssueUserContext(row, contextUserId, {
|
|
|
|
|
myLastCommentAt: statsByIssueId.get(row.id)?.myLastCommentAt ?? null,
|
|
|
|
|
myLastReadAt: readByIssueId.get(row.id) ?? null,
|
|
|
|
|
lastExternalCommentAt: statsByIssueId.get(row.id)?.lastExternalCommentAt ?? null,
|
|
|
|
|
}),
|
|
|
|
|
};
|
|
|
|
|
});
|
2026-03-06 08:21:03 -06:00
|
|
|
},
|
|
|
|
|
|
|
|
|
|
countUnreadTouchedByUser: async (companyId: string, userId: string, status?: string) => {
|
|
|
|
|
const conditions = [
|
|
|
|
|
eq(issues.companyId, companyId),
|
|
|
|
|
isNull(issues.hiddenAt),
|
|
|
|
|
unreadForUserCondition(companyId, userId),
|
|
|
|
|
];
|
|
|
|
|
if (status) {
|
|
|
|
|
const statuses = status.split(",").map((s) => s.trim()).filter(Boolean);
|
|
|
|
|
if (statuses.length === 1) {
|
|
|
|
|
conditions.push(eq(issues.status, statuses[0]));
|
|
|
|
|
} else if (statuses.length > 1) {
|
|
|
|
|
conditions.push(inArray(issues.status, statuses));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
const [row] = await db
|
|
|
|
|
.select({ count: sql<number>`count(*)` })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(and(...conditions));
|
|
|
|
|
return Number(row?.count ?? 0);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
},
|
2026-02-16 13:31:58 -06:00
|
|
|
|
2026-03-06 08:34:19 -06:00
|
|
|
markRead: async (companyId: string, issueId: string, userId: string, readAt: Date = new Date()) => {
|
|
|
|
|
const now = new Date();
|
|
|
|
|
const [row] = await db
|
|
|
|
|
.insert(issueReadStates)
|
|
|
|
|
.values({
|
|
|
|
|
companyId,
|
|
|
|
|
issueId,
|
|
|
|
|
userId,
|
|
|
|
|
lastReadAt: readAt,
|
|
|
|
|
updatedAt: now,
|
|
|
|
|
})
|
|
|
|
|
.onConflictDoUpdate({
|
|
|
|
|
target: [issueReadStates.companyId, issueReadStates.issueId, issueReadStates.userId],
|
|
|
|
|
set: {
|
|
|
|
|
lastReadAt: readAt,
|
|
|
|
|
updatedAt: now,
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
return row;
|
|
|
|
|
},
|
|
|
|
|
|
2026-03-26 16:49:11 -05:00
|
|
|
markUnread: async (companyId: string, issueId: string, userId: string) => {
|
|
|
|
|
const deleted = await db
|
|
|
|
|
.delete(issueReadStates)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueReadStates.companyId, companyId),
|
|
|
|
|
eq(issueReadStates.issueId, issueId),
|
|
|
|
|
eq(issueReadStates.userId, userId),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.returning();
|
|
|
|
|
return deleted.length > 0;
|
|
|
|
|
},
|
|
|
|
|
|
2026-03-26 08:19:16 -05:00
|
|
|
archiveInbox: async (companyId: string, issueId: string, userId: string, archivedAt: Date = new Date()) => {
|
|
|
|
|
const now = new Date();
|
|
|
|
|
const [row] = await db
|
|
|
|
|
.insert(issueInboxArchives)
|
|
|
|
|
.values({
|
|
|
|
|
companyId,
|
|
|
|
|
issueId,
|
|
|
|
|
userId,
|
|
|
|
|
archivedAt,
|
|
|
|
|
updatedAt: now,
|
|
|
|
|
})
|
|
|
|
|
.onConflictDoUpdate({
|
|
|
|
|
target: [issueInboxArchives.companyId, issueInboxArchives.issueId, issueInboxArchives.userId],
|
|
|
|
|
set: {
|
|
|
|
|
archivedAt,
|
|
|
|
|
updatedAt: now,
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
return row;
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
unarchiveInbox: async (companyId: string, issueId: string, userId: string) => {
|
|
|
|
|
const [row] = await db
|
|
|
|
|
.delete(issueInboxArchives)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueInboxArchives.companyId, companyId),
|
|
|
|
|
eq(issueInboxArchives.issueId, issueId),
|
|
|
|
|
eq(issueInboxArchives.userId, userId),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.returning();
|
|
|
|
|
return row ?? null;
|
|
|
|
|
},
|
|
|
|
|
|
2026-04-02 09:11:49 -05:00
|
|
|
getById: async (raw: string) => {
|
|
|
|
|
const id = raw.trim();
|
|
|
|
|
if (/^[A-Z]+-\d+$/i.test(id)) {
|
|
|
|
|
return getIssueByIdentifier(id);
|
|
|
|
|
}
|
|
|
|
|
if (!isUuidLike(id)) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return getIssueByUuid(id);
|
2026-02-25 08:38:37 -06:00
|
|
|
},
|
2026-02-16 13:31:58 -06:00
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
getByIdentifier: async (identifier: string) => {
|
2026-04-02 09:11:49 -05:00
|
|
|
return getIssueByIdentifier(identifier);
|
2026-02-25 08:38:37 -06:00
|
|
|
},
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
2026-04-04 13:56:04 -05:00
|
|
|
getRelationSummaries: async (issueId: string) => {
|
|
|
|
|
const issue = await db
|
|
|
|
|
.select({ id: issues.id, companyId: issues.companyId })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, issueId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!issue) throw notFound("Issue not found");
|
|
|
|
|
const relations = await getIssueRelationSummaryMap(issue.companyId, [issueId], db);
|
|
|
|
|
return relations.get(issueId) ?? { blockedBy: [], blocks: [] };
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
listWakeableBlockedDependents: async (blockerIssueId: string) => {
|
|
|
|
|
const blockerIssue = await db
|
|
|
|
|
.select({ id: issues.id, companyId: issues.companyId })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, blockerIssueId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!blockerIssue) return [];
|
|
|
|
|
|
|
|
|
|
const candidates = await db
|
|
|
|
|
.select({
|
|
|
|
|
id: issues.id,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
})
|
|
|
|
|
.from(issueRelations)
|
|
|
|
|
.innerJoin(issues, eq(issueRelations.relatedIssueId, issues.id))
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueRelations.companyId, blockerIssue.companyId),
|
|
|
|
|
eq(issueRelations.type, "blocks"),
|
|
|
|
|
eq(issueRelations.issueId, blockerIssueId),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
if (candidates.length === 0) return [];
|
|
|
|
|
|
|
|
|
|
const candidateIds = candidates.map((candidate) => candidate.id);
|
|
|
|
|
const blockerRows = await db
|
|
|
|
|
.select({
|
|
|
|
|
issueId: issueRelations.relatedIssueId,
|
|
|
|
|
blockerIssueId: issueRelations.issueId,
|
|
|
|
|
blockerStatus: issues.status,
|
|
|
|
|
})
|
|
|
|
|
.from(issueRelations)
|
|
|
|
|
.innerJoin(issues, eq(issueRelations.issueId, issues.id))
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issueRelations.companyId, blockerIssue.companyId),
|
|
|
|
|
eq(issueRelations.type, "blocks"),
|
|
|
|
|
inArray(issueRelations.relatedIssueId, candidateIds),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const blockersByIssueId = new Map<string, Array<{ blockerIssueId: string; blockerStatus: string }>>();
|
|
|
|
|
for (const row of blockerRows) {
|
|
|
|
|
const list = blockersByIssueId.get(row.issueId) ?? [];
|
|
|
|
|
list.push({ blockerIssueId: row.blockerIssueId, blockerStatus: row.blockerStatus });
|
|
|
|
|
blockersByIssueId.set(row.issueId, list);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return candidates
|
|
|
|
|
.filter((candidate) => candidate.assigneeAgentId && !["backlog", "done", "cancelled"].includes(candidate.status))
|
|
|
|
|
.map((candidate) => {
|
|
|
|
|
const blockers = blockersByIssueId.get(candidate.id) ?? [];
|
|
|
|
|
return {
|
|
|
|
|
...candidate,
|
|
|
|
|
blockerIssueIds: blockers.map((blocker) => blocker.blockerIssueId),
|
|
|
|
|
allBlockersDone: blockers.length > 0 && blockers.every((blocker) => blocker.blockerStatus === "done"),
|
|
|
|
|
};
|
|
|
|
|
})
|
|
|
|
|
.filter((candidate) => candidate.allBlockersDone)
|
|
|
|
|
.map((candidate) => ({
|
|
|
|
|
id: candidate.id,
|
|
|
|
|
assigneeAgentId: candidate.assigneeAgentId!,
|
|
|
|
|
blockerIssueIds: candidate.blockerIssueIds,
|
|
|
|
|
}));
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
getWakeableParentAfterChildCompletion: async (parentIssueId: string) => {
|
|
|
|
|
const parent = await db
|
|
|
|
|
.select({
|
|
|
|
|
id: issues.id,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
companyId: issues.companyId,
|
|
|
|
|
})
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, parentIssueId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!parent || !parent.assigneeAgentId || ["backlog", "done", "cancelled"].includes(parent.status)) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const children = await db
|
|
|
|
|
.select({ id: issues.id, status: issues.status })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(and(eq(issues.companyId, parent.companyId), eq(issues.parentId, parentIssueId)));
|
|
|
|
|
if (children.length === 0) return null;
|
|
|
|
|
if (!children.every((child) => child.status === "done" || child.status === "cancelled")) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
id: parent.id,
|
|
|
|
|
assigneeAgentId: parent.assigneeAgentId,
|
|
|
|
|
childIssueIds: children.map((child) => child.id),
|
|
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
create: async (
|
|
|
|
|
companyId: string,
|
2026-03-30 14:08:44 -05:00
|
|
|
data: IssueCreateInput,
|
2026-02-25 08:38:37 -06:00
|
|
|
) => {
|
2026-04-04 13:56:04 -05:00
|
|
|
const {
|
|
|
|
|
labelIds: inputLabelIds,
|
|
|
|
|
blockedByIssueIds,
|
|
|
|
|
inheritExecutionWorkspaceFromIssueId,
|
|
|
|
|
...issueData
|
|
|
|
|
} = data;
|
2026-03-17 09:24:28 -05:00
|
|
|
const isolatedWorkspacesEnabled = (await instanceSettings.getExperimental()).enableIsolatedWorkspaces;
|
|
|
|
|
if (!isolatedWorkspacesEnabled) {
|
|
|
|
|
delete issueData.executionWorkspaceId;
|
|
|
|
|
delete issueData.executionWorkspacePreference;
|
|
|
|
|
delete issueData.executionWorkspaceSettings;
|
|
|
|
|
}
|
2026-02-23 14:40:32 -06:00
|
|
|
if (data.assigneeAgentId && data.assigneeUserId) {
|
|
|
|
|
throw unprocessable("Issue can only have one assignee");
|
|
|
|
|
}
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
Agent management: hire endpoint with permission gates and pending_approval status,
config revision tracking with rollback, agent duplicate route, permission CRUD.
Block pending_approval agents from auth, heartbeat, and assignments.
Approvals: revision request/resubmit flow, approval comments CRUD, issue-approval
linking, auto-wake agents on approval decisions with context snapshot.
Costs: per-agent breakdown, period filtering (month/week/day/all), cost by agent
list endpoint.
Adapters: agentConfigurationDoc on all adapters, /llms/agent-configuration.txt
reflection routes. Inject PAPERCLIP_APPROVAL_ID, PAPERCLIP_APPROVAL_STATUS,
PAPERCLIP_LINKED_ISSUE_IDS into adapter environments.
Sidebar badges endpoint for pending approval/inbox counts. Dashboard and company
settings extensions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 13:02:41 -06:00
|
|
|
if (data.assigneeAgentId) {
|
|
|
|
|
await assertAssignableAgent(companyId, data.assigneeAgentId);
|
|
|
|
|
}
|
2026-02-23 14:40:32 -06:00
|
|
|
if (data.assigneeUserId) {
|
|
|
|
|
await assertAssignableUser(companyId, data.assigneeUserId);
|
|
|
|
|
}
|
|
|
|
|
if (data.status === "in_progress" && !data.assigneeAgentId && !data.assigneeUserId) {
|
|
|
|
|
throw unprocessable("in_progress issues require an assignee");
|
|
|
|
|
}
|
2026-02-19 09:09:40 -06:00
|
|
|
return db.transaction(async (tx) => {
|
2026-03-12 08:50:31 -05:00
|
|
|
const defaultCompanyGoal = await getDefaultCompanyGoal(tx, companyId);
|
2026-03-24 08:11:09 -05:00
|
|
|
const projectGoalId = await getProjectDefaultGoalId(tx, companyId, issueData.projectId);
|
2026-03-30 14:08:44 -05:00
|
|
|
let projectWorkspaceId = issueData.projectWorkspaceId ?? null;
|
|
|
|
|
let executionWorkspaceId = issueData.executionWorkspaceId ?? null;
|
|
|
|
|
let executionWorkspacePreference = issueData.executionWorkspacePreference ?? null;
|
2026-03-10 09:03:31 -05:00
|
|
|
let executionWorkspaceSettings =
|
|
|
|
|
(issueData.executionWorkspaceSettings as Record<string, unknown> | null | undefined) ?? null;
|
2026-03-30 14:08:44 -05:00
|
|
|
const workspaceInheritanceIssueId = inheritExecutionWorkspaceFromIssueId ?? issueData.parentId ?? null;
|
|
|
|
|
const hasExplicitExecutionWorkspaceOverride =
|
|
|
|
|
issueData.executionWorkspaceId !== undefined ||
|
|
|
|
|
issueData.executionWorkspacePreference !== undefined ||
|
|
|
|
|
issueData.executionWorkspaceSettings !== undefined;
|
|
|
|
|
if (workspaceInheritanceIssueId) {
|
|
|
|
|
const workspaceSource = await getWorkspaceInheritanceIssue(tx, companyId, workspaceInheritanceIssueId);
|
|
|
|
|
if (projectWorkspaceId == null && workspaceSource.projectWorkspaceId) {
|
|
|
|
|
projectWorkspaceId = workspaceSource.projectWorkspaceId;
|
|
|
|
|
}
|
|
|
|
|
if (
|
|
|
|
|
isolatedWorkspacesEnabled &&
|
|
|
|
|
!hasExplicitExecutionWorkspaceOverride &&
|
|
|
|
|
workspaceSource.executionWorkspaceId
|
|
|
|
|
) {
|
|
|
|
|
const sourceWorkspace = await tx
|
|
|
|
|
.select({
|
|
|
|
|
id: executionWorkspaces.id,
|
|
|
|
|
mode: executionWorkspaces.mode,
|
|
|
|
|
})
|
|
|
|
|
.from(executionWorkspaces)
|
|
|
|
|
.where(eq(executionWorkspaces.id, workspaceSource.executionWorkspaceId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (sourceWorkspace) {
|
|
|
|
|
executionWorkspaceId = sourceWorkspace.id;
|
|
|
|
|
executionWorkspacePreference = "reuse_existing";
|
|
|
|
|
executionWorkspaceSettings = {
|
|
|
|
|
...((workspaceSource.executionWorkspaceSettings as Record<string, unknown> | null | undefined) ?? {}),
|
|
|
|
|
mode: issueExecutionWorkspaceModeForPersistedWorkspace(sourceWorkspace.mode),
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (
|
|
|
|
|
executionWorkspaceSettings == null &&
|
|
|
|
|
executionWorkspaceId == null &&
|
|
|
|
|
issueData.projectId
|
|
|
|
|
) {
|
2026-03-10 09:03:31 -05:00
|
|
|
const project = await tx
|
|
|
|
|
.select({ executionWorkspacePolicy: projects.executionWorkspacePolicy })
|
|
|
|
|
.from(projects)
|
|
|
|
|
.where(and(eq(projects.id, issueData.projectId), eq(projects.companyId, companyId)))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
executionWorkspaceSettings =
|
|
|
|
|
defaultIssueExecutionWorkspaceSettingsForProject(
|
2026-03-17 09:24:28 -05:00
|
|
|
gateProjectExecutionWorkspacePolicy(
|
|
|
|
|
parseProjectExecutionWorkspacePolicy(project?.executionWorkspacePolicy),
|
|
|
|
|
isolatedWorkspacesEnabled,
|
|
|
|
|
),
|
2026-03-10 09:03:31 -05:00
|
|
|
) as Record<string, unknown> | null;
|
|
|
|
|
}
|
2026-03-13 17:12:25 -05:00
|
|
|
if (!projectWorkspaceId && issueData.projectId) {
|
|
|
|
|
const project = await tx
|
|
|
|
|
.select({
|
|
|
|
|
executionWorkspacePolicy: projects.executionWorkspacePolicy,
|
|
|
|
|
})
|
|
|
|
|
.from(projects)
|
|
|
|
|
.where(and(eq(projects.id, issueData.projectId), eq(projects.companyId, companyId)))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
const projectPolicy = parseProjectExecutionWorkspacePolicy(project?.executionWorkspacePolicy);
|
|
|
|
|
projectWorkspaceId = projectPolicy?.defaultProjectWorkspaceId ?? null;
|
|
|
|
|
if (!projectWorkspaceId) {
|
|
|
|
|
projectWorkspaceId = await tx
|
|
|
|
|
.select({ id: projectWorkspaces.id })
|
|
|
|
|
.from(projectWorkspaces)
|
|
|
|
|
.where(and(eq(projectWorkspaces.projectId, issueData.projectId), eq(projectWorkspaces.companyId, companyId)))
|
|
|
|
|
.orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id))
|
|
|
|
|
.then((rows) => rows[0]?.id ?? null);
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-03-30 14:08:44 -05:00
|
|
|
if (projectWorkspaceId) {
|
|
|
|
|
await assertValidProjectWorkspace(companyId, issueData.projectId, projectWorkspaceId, tx);
|
|
|
|
|
}
|
|
|
|
|
if (executionWorkspaceId) {
|
|
|
|
|
await assertValidExecutionWorkspace(companyId, issueData.projectId, executionWorkspaceId, tx);
|
|
|
|
|
}
|
2026-04-04 22:57:25 -07:00
|
|
|
// Self-correcting counter: use MAX(issue_number) + 1 if the counter
|
|
|
|
|
// has drifted below the actual max, preventing identifier collisions.
|
|
|
|
|
const [maxRow] = await tx
|
|
|
|
|
.select({ maxNum: sql<number>`coalesce(max(${issues.issueNumber}), 0)` })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.companyId, companyId));
|
|
|
|
|
const currentMax = maxRow?.maxNum ?? 0;
|
|
|
|
|
|
2026-02-19 09:09:40 -06:00
|
|
|
const [company] = await tx
|
|
|
|
|
.update(companies)
|
2026-04-04 22:57:25 -07:00
|
|
|
.set({
|
|
|
|
|
issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`,
|
|
|
|
|
})
|
2026-02-19 09:09:40 -06:00
|
|
|
.where(eq(companies.id, companyId))
|
|
|
|
|
.returning({ issueCounter: companies.issueCounter, issuePrefix: companies.issuePrefix });
|
|
|
|
|
|
|
|
|
|
const issueNumber = company.issueCounter;
|
|
|
|
|
const identifier = `${company.issuePrefix}-${issueNumber}`;
|
|
|
|
|
|
2026-03-10 09:03:31 -05:00
|
|
|
const values = {
|
|
|
|
|
...issueData,
|
2026-03-19 08:39:24 -05:00
|
|
|
originKind: issueData.originKind ?? "manual",
|
2026-03-12 08:50:31 -05:00
|
|
|
goalId: resolveIssueGoalId({
|
|
|
|
|
projectId: issueData.projectId,
|
|
|
|
|
goalId: issueData.goalId,
|
2026-03-24 08:11:09 -05:00
|
|
|
projectGoalId,
|
2026-03-12 08:50:31 -05:00
|
|
|
defaultGoalId: defaultCompanyGoal?.id ?? null,
|
|
|
|
|
}),
|
2026-03-13 17:12:25 -05:00
|
|
|
...(projectWorkspaceId ? { projectWorkspaceId } : {}),
|
2026-03-30 14:08:44 -05:00
|
|
|
...(executionWorkspaceId ? { executionWorkspaceId } : {}),
|
|
|
|
|
...(executionWorkspacePreference ? { executionWorkspacePreference } : {}),
|
2026-03-10 09:03:31 -05:00
|
|
|
...(executionWorkspaceSettings ? { executionWorkspaceSettings } : {}),
|
|
|
|
|
companyId,
|
|
|
|
|
issueNumber,
|
|
|
|
|
identifier,
|
|
|
|
|
} as typeof issues.$inferInsert;
|
2026-02-19 09:09:40 -06:00
|
|
|
if (values.status === "in_progress" && !values.startedAt) {
|
|
|
|
|
values.startedAt = new Date();
|
|
|
|
|
}
|
|
|
|
|
if (values.status === "done") {
|
|
|
|
|
values.completedAt = new Date();
|
|
|
|
|
}
|
|
|
|
|
if (values.status === "cancelled") {
|
|
|
|
|
values.cancelledAt = new Date();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const [issue] = await tx.insert(issues).values(values).returning();
|
2026-02-25 08:38:37 -06:00
|
|
|
if (inputLabelIds) {
|
|
|
|
|
await syncIssueLabels(issue.id, companyId, inputLabelIds, tx);
|
|
|
|
|
}
|
2026-04-04 13:56:04 -05:00
|
|
|
if (blockedByIssueIds !== undefined) {
|
|
|
|
|
await syncBlockedByIssueIds(
|
|
|
|
|
issue.id,
|
|
|
|
|
companyId,
|
|
|
|
|
blockedByIssueIds,
|
|
|
|
|
{
|
|
|
|
|
agentId: issueData.createdByAgentId ?? null,
|
|
|
|
|
userId: issueData.createdByUserId ?? null,
|
|
|
|
|
},
|
|
|
|
|
tx,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-02-25 08:38:37 -06:00
|
|
|
const [enriched] = await withIssueLabels(tx, [issue]);
|
|
|
|
|
return enriched;
|
2026-02-19 09:09:40 -06:00
|
|
|
});
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
},
|
2026-02-16 13:31:58 -06:00
|
|
|
|
2026-04-04 13:56:04 -05:00
|
|
|
update: async (
|
|
|
|
|
id: string,
|
|
|
|
|
data: Partial<typeof issues.$inferInsert> & {
|
|
|
|
|
labelIds?: string[];
|
|
|
|
|
blockedByIssueIds?: string[];
|
|
|
|
|
actorAgentId?: string | null;
|
|
|
|
|
actorUserId?: string | null;
|
|
|
|
|
},
|
2026-04-07 17:07:10 -05:00
|
|
|
dbOrTx: any = db,
|
2026-04-04 13:56:04 -05:00
|
|
|
) => {
|
2026-04-07 17:07:10 -05:00
|
|
|
const existing = await dbOrTx
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
.select()
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
2026-04-07 17:07:10 -05:00
|
|
|
.then((rows: Array<typeof issues.$inferSelect>) => rows[0] ?? null);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
if (!existing) return null;
|
|
|
|
|
|
2026-04-04 13:56:04 -05:00
|
|
|
const {
|
|
|
|
|
labelIds: nextLabelIds,
|
|
|
|
|
blockedByIssueIds,
|
|
|
|
|
actorAgentId,
|
|
|
|
|
actorUserId,
|
|
|
|
|
...issueData
|
|
|
|
|
} = data;
|
2026-03-17 09:24:28 -05:00
|
|
|
const isolatedWorkspacesEnabled = (await instanceSettings.getExperimental()).enableIsolatedWorkspaces;
|
|
|
|
|
if (!isolatedWorkspacesEnabled) {
|
|
|
|
|
delete issueData.executionWorkspaceId;
|
|
|
|
|
delete issueData.executionWorkspacePreference;
|
|
|
|
|
delete issueData.executionWorkspaceSettings;
|
|
|
|
|
}
|
2026-02-25 08:38:37 -06:00
|
|
|
|
|
|
|
|
if (issueData.status) {
|
|
|
|
|
assertTransition(existing.status, issueData.status);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const patch: Partial<typeof issues.$inferInsert> = {
|
2026-02-25 08:38:37 -06:00
|
|
|
...issueData,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
updatedAt: new Date(),
|
|
|
|
|
};
|
|
|
|
|
|
2026-02-23 14:40:32 -06:00
|
|
|
const nextAssigneeAgentId =
|
2026-02-25 08:38:37 -06:00
|
|
|
issueData.assigneeAgentId !== undefined ? issueData.assigneeAgentId : existing.assigneeAgentId;
|
2026-02-23 14:40:32 -06:00
|
|
|
const nextAssigneeUserId =
|
2026-02-25 08:38:37 -06:00
|
|
|
issueData.assigneeUserId !== undefined ? issueData.assigneeUserId : existing.assigneeUserId;
|
2026-02-23 14:40:32 -06:00
|
|
|
|
|
|
|
|
if (nextAssigneeAgentId && nextAssigneeUserId) {
|
|
|
|
|
throw unprocessable("Issue can only have one assignee");
|
|
|
|
|
}
|
|
|
|
|
if (patch.status === "in_progress" && !nextAssigneeAgentId && !nextAssigneeUserId) {
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
throw unprocessable("in_progress issues require an assignee");
|
|
|
|
|
}
|
2026-02-25 08:38:37 -06:00
|
|
|
if (issueData.assigneeAgentId) {
|
|
|
|
|
await assertAssignableAgent(existing.companyId, issueData.assigneeAgentId);
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
Agent management: hire endpoint with permission gates and pending_approval status,
config revision tracking with rollback, agent duplicate route, permission CRUD.
Block pending_approval agents from auth, heartbeat, and assignments.
Approvals: revision request/resubmit flow, approval comments CRUD, issue-approval
linking, auto-wake agents on approval decisions with context snapshot.
Costs: per-agent breakdown, period filtering (month/week/day/all), cost by agent
list endpoint.
Adapters: agentConfigurationDoc on all adapters, /llms/agent-configuration.txt
reflection routes. Inject PAPERCLIP_APPROVAL_ID, PAPERCLIP_APPROVAL_STATUS,
PAPERCLIP_LINKED_ISSUE_IDS into adapter environments.
Sidebar badges endpoint for pending approval/inbox counts. Dashboard and company
settings extensions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 13:02:41 -06:00
|
|
|
}
|
2026-02-25 08:38:37 -06:00
|
|
|
if (issueData.assigneeUserId) {
|
|
|
|
|
await assertAssignableUser(existing.companyId, issueData.assigneeUserId);
|
2026-02-23 14:40:32 -06:00
|
|
|
}
|
2026-03-13 17:12:25 -05:00
|
|
|
const nextProjectId = issueData.projectId !== undefined ? issueData.projectId : existing.projectId;
|
|
|
|
|
const nextProjectWorkspaceId =
|
|
|
|
|
issueData.projectWorkspaceId !== undefined ? issueData.projectWorkspaceId : existing.projectWorkspaceId;
|
|
|
|
|
const nextExecutionWorkspaceId =
|
|
|
|
|
issueData.executionWorkspaceId !== undefined ? issueData.executionWorkspaceId : existing.executionWorkspaceId;
|
|
|
|
|
if (nextProjectWorkspaceId) {
|
|
|
|
|
await assertValidProjectWorkspace(existing.companyId, nextProjectId, nextProjectWorkspaceId);
|
|
|
|
|
}
|
|
|
|
|
if (nextExecutionWorkspaceId) {
|
|
|
|
|
await assertValidExecutionWorkspace(existing.companyId, nextProjectId, nextExecutionWorkspaceId);
|
|
|
|
|
}
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
applyStatusSideEffects(issueData.status, patch);
|
|
|
|
|
if (issueData.status && issueData.status !== "done") {
|
2026-02-19 09:09:40 -06:00
|
|
|
patch.completedAt = null;
|
|
|
|
|
}
|
2026-02-25 08:38:37 -06:00
|
|
|
if (issueData.status && issueData.status !== "cancelled") {
|
2026-02-19 09:09:40 -06:00
|
|
|
patch.cancelledAt = null;
|
|
|
|
|
}
|
2026-02-25 08:38:37 -06:00
|
|
|
if (issueData.status && issueData.status !== "in_progress") {
|
2026-02-20 15:48:22 -06:00
|
|
|
patch.checkoutRunId = null;
|
2026-04-03 10:03:43 +02:00
|
|
|
// Fix B: also clear the execution lock when leaving in_progress
|
|
|
|
|
patch.executionRunId = null;
|
2026-04-03 15:11:42 +02:00
|
|
|
patch.executionAgentNameKey = null;
|
2026-04-03 10:03:43 +02:00
|
|
|
patch.executionLockedAt = null;
|
2026-02-20 15:48:22 -06:00
|
|
|
}
|
2026-02-23 14:40:32 -06:00
|
|
|
if (
|
2026-02-25 08:38:37 -06:00
|
|
|
(issueData.assigneeAgentId !== undefined && issueData.assigneeAgentId !== existing.assigneeAgentId) ||
|
|
|
|
|
(issueData.assigneeUserId !== undefined && issueData.assigneeUserId !== existing.assigneeUserId)
|
2026-02-23 14:40:32 -06:00
|
|
|
) {
|
2026-02-20 15:48:22 -06:00
|
|
|
patch.checkoutRunId = null;
|
2026-04-03 10:03:43 +02:00
|
|
|
// Fix B: clear execution lock on reassignment, matching checkoutRunId clear
|
|
|
|
|
patch.executionRunId = null;
|
2026-04-03 15:11:42 +02:00
|
|
|
patch.executionAgentNameKey = null;
|
2026-04-03 10:03:43 +02:00
|
|
|
patch.executionLockedAt = null;
|
2026-02-20 15:48:22 -06:00
|
|
|
}
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
2026-04-07 17:07:10 -05:00
|
|
|
const runUpdate = async (tx: any) => {
|
2026-03-12 08:50:31 -05:00
|
|
|
const defaultCompanyGoal = await getDefaultCompanyGoal(tx, existing.companyId);
|
2026-03-24 08:11:09 -05:00
|
|
|
const [currentProjectGoalId, nextProjectGoalId] = await Promise.all([
|
|
|
|
|
getProjectDefaultGoalId(tx, existing.companyId, existing.projectId),
|
|
|
|
|
getProjectDefaultGoalId(
|
|
|
|
|
tx,
|
|
|
|
|
existing.companyId,
|
|
|
|
|
issueData.projectId !== undefined ? issueData.projectId : existing.projectId,
|
|
|
|
|
),
|
|
|
|
|
]);
|
2026-03-12 08:50:31 -05:00
|
|
|
patch.goalId = resolveNextIssueGoalId({
|
|
|
|
|
currentProjectId: existing.projectId,
|
|
|
|
|
currentGoalId: existing.goalId,
|
2026-03-24 08:11:09 -05:00
|
|
|
currentProjectGoalId,
|
2026-03-12 08:50:31 -05:00
|
|
|
projectId: issueData.projectId,
|
|
|
|
|
goalId: issueData.goalId,
|
2026-03-24 08:11:09 -05:00
|
|
|
projectGoalId: nextProjectGoalId,
|
2026-03-12 08:50:31 -05:00
|
|
|
defaultGoalId: defaultCompanyGoal?.id ?? null,
|
|
|
|
|
});
|
2026-02-25 08:38:37 -06:00
|
|
|
const updated = await tx
|
|
|
|
|
.update(issues)
|
|
|
|
|
.set(patch)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.returning()
|
2026-04-07 17:07:10 -05:00
|
|
|
.then((rows: Array<typeof issues.$inferSelect>) => rows[0] ?? null);
|
2026-02-25 08:38:37 -06:00
|
|
|
if (!updated) return null;
|
|
|
|
|
if (nextLabelIds !== undefined) {
|
|
|
|
|
await syncIssueLabels(updated.id, existing.companyId, nextLabelIds, tx);
|
|
|
|
|
}
|
2026-04-04 13:56:04 -05:00
|
|
|
if (blockedByIssueIds !== undefined) {
|
|
|
|
|
await syncBlockedByIssueIds(
|
|
|
|
|
updated.id,
|
|
|
|
|
existing.companyId,
|
|
|
|
|
blockedByIssueIds,
|
|
|
|
|
{
|
|
|
|
|
agentId: actorAgentId ?? null,
|
|
|
|
|
userId: actorUserId ?? null,
|
|
|
|
|
},
|
|
|
|
|
tx,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-02-25 08:38:37 -06:00
|
|
|
const [enriched] = await withIssueLabels(tx, [updated]);
|
|
|
|
|
return enriched;
|
2026-04-07 17:07:10 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return dbOrTx === db ? db.transaction(runUpdate) : runUpdate(dbOrTx);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
},
|
2026-02-16 13:31:58 -06:00
|
|
|
|
|
|
|
|
remove: (id: string) =>
|
2026-02-20 10:31:56 -06:00
|
|
|
db.transaction(async (tx) => {
|
|
|
|
|
const attachmentAssetIds = await tx
|
|
|
|
|
.select({ assetId: issueAttachments.assetId })
|
|
|
|
|
.from(issueAttachments)
|
|
|
|
|
.where(eq(issueAttachments.issueId, id));
|
2026-03-13 22:17:49 -05:00
|
|
|
const issueDocumentIds = await tx
|
|
|
|
|
.select({ documentId: issueDocuments.documentId })
|
|
|
|
|
.from(issueDocuments)
|
|
|
|
|
.where(eq(issueDocuments.issueId, id));
|
2026-02-20 10:31:56 -06:00
|
|
|
|
|
|
|
|
const removedIssue = await tx
|
|
|
|
|
.delete(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.returning()
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (removedIssue && attachmentAssetIds.length > 0) {
|
|
|
|
|
await tx
|
|
|
|
|
.delete(assets)
|
|
|
|
|
.where(inArray(assets.id, attachmentAssetIds.map((row) => row.assetId)));
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 22:17:49 -05:00
|
|
|
if (removedIssue && issueDocumentIds.length > 0) {
|
|
|
|
|
await tx
|
|
|
|
|
.delete(documents)
|
|
|
|
|
.where(inArray(documents.id, issueDocumentIds.map((row) => row.documentId)));
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
if (!removedIssue) return null;
|
|
|
|
|
const [enriched] = await withIssueLabels(tx, [removedIssue]);
|
|
|
|
|
return enriched;
|
2026-02-20 10:31:56 -06:00
|
|
|
}),
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
2026-02-20 15:48:22 -06:00
|
|
|
checkout: async (id: string, agentId: string, expectedStatuses: string[], checkoutRunId: string | null) => {
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
Agent management: hire endpoint with permission gates and pending_approval status,
config revision tracking with rollback, agent duplicate route, permission CRUD.
Block pending_approval agents from auth, heartbeat, and assignments.
Approvals: revision request/resubmit flow, approval comments CRUD, issue-approval
linking, auto-wake agents on approval decisions with context snapshot.
Costs: per-agent breakdown, period filtering (month/week/day/all), cost by agent
list endpoint.
Adapters: agentConfigurationDoc on all adapters, /llms/agent-configuration.txt
reflection routes. Inject PAPERCLIP_APPROVAL_ID, PAPERCLIP_APPROVAL_STATUS,
PAPERCLIP_LINKED_ISSUE_IDS into adapter environments.
Sidebar badges endpoint for pending approval/inbox counts. Dashboard and company
settings extensions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 13:02:41 -06:00
|
|
|
const issueCompany = await db
|
|
|
|
|
.select({ companyId: issues.companyId })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!issueCompany) throw notFound("Issue not found");
|
|
|
|
|
await assertAssignableAgent(issueCompany.companyId, agentId);
|
|
|
|
|
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
const now = new Date();
|
2026-04-03 10:03:43 +02:00
|
|
|
|
|
|
|
|
// Fix C: staleness detection — if executionRunId references a run that is no
|
|
|
|
|
// longer queued or running, clear it before applying the execution lock condition
|
|
|
|
|
// so a dead lock can't produce a spurious 409.
|
2026-04-03 15:11:42 +02:00
|
|
|
// Wrapped in a transaction with SELECT FOR UPDATE to make the read + clear atomic,
|
|
|
|
|
// matching the existing pattern in enqueueWakeup().
|
|
|
|
|
await db.transaction(async (tx) => {
|
|
|
|
|
await tx.execute(
|
|
|
|
|
sql`select id from issues where id = ${id} for update`,
|
|
|
|
|
);
|
|
|
|
|
const preCheckRow = await tx
|
|
|
|
|
.select({ executionRunId: issues.executionRunId })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!preCheckRow?.executionRunId) return;
|
|
|
|
|
const lockRun = await tx
|
2026-04-03 10:03:43 +02:00
|
|
|
.select({ id: heartbeatRuns.id, status: heartbeatRuns.status })
|
|
|
|
|
.from(heartbeatRuns)
|
|
|
|
|
.where(eq(heartbeatRuns.id, preCheckRow.executionRunId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!lockRun || (lockRun.status !== "queued" && lockRun.status !== "running")) {
|
2026-04-03 15:11:42 +02:00
|
|
|
await tx
|
2026-04-03 10:03:43 +02:00
|
|
|
.update(issues)
|
2026-04-03 15:11:42 +02:00
|
|
|
.set({ executionRunId: null, executionAgentNameKey: null, executionLockedAt: null, updatedAt: now })
|
2026-04-03 10:03:43 +02:00
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issues.id, id),
|
|
|
|
|
eq(issues.executionRunId, preCheckRow.executionRunId),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-04-03 15:11:42 +02:00
|
|
|
});
|
2026-04-03 10:03:43 +02:00
|
|
|
|
2026-02-20 15:48:22 -06:00
|
|
|
const sameRunAssigneeCondition = checkoutRunId
|
|
|
|
|
? and(
|
|
|
|
|
eq(issues.assigneeAgentId, agentId),
|
|
|
|
|
or(isNull(issues.checkoutRunId), eq(issues.checkoutRunId, checkoutRunId)),
|
|
|
|
|
)
|
|
|
|
|
: and(eq(issues.assigneeAgentId, agentId), isNull(issues.checkoutRunId));
|
|
|
|
|
const executionLockCondition = checkoutRunId
|
|
|
|
|
? or(isNull(issues.executionRunId), eq(issues.executionRunId, checkoutRunId))
|
|
|
|
|
: isNull(issues.executionRunId);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
const updated = await db
|
|
|
|
|
.update(issues)
|
|
|
|
|
.set({
|
|
|
|
|
assigneeAgentId: agentId,
|
2026-02-23 14:40:32 -06:00
|
|
|
assigneeUserId: null,
|
2026-02-20 15:48:22 -06:00
|
|
|
checkoutRunId,
|
|
|
|
|
executionRunId: checkoutRunId,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
status: "in_progress",
|
|
|
|
|
startedAt: now,
|
|
|
|
|
updatedAt: now,
|
|
|
|
|
})
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issues.id, id),
|
|
|
|
|
inArray(issues.status, expectedStatuses),
|
2026-02-20 15:48:22 -06:00
|
|
|
or(isNull(issues.assigneeAgentId), sameRunAssigneeCondition),
|
|
|
|
|
executionLockCondition,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.returning()
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
if (updated) {
|
|
|
|
|
const [enriched] = await withIssueLabels(db, [updated]);
|
|
|
|
|
return enriched;
|
|
|
|
|
}
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
|
|
|
|
const current = await db
|
|
|
|
|
.select({
|
|
|
|
|
id: issues.id,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
2026-02-20 15:48:22 -06:00
|
|
|
checkoutRunId: issues.checkoutRunId,
|
|
|
|
|
executionRunId: issues.executionRunId,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
})
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (!current) throw notFound("Issue not found");
|
|
|
|
|
|
2026-02-20 15:48:22 -06:00
|
|
|
if (
|
|
|
|
|
current.assigneeAgentId === agentId &&
|
|
|
|
|
current.status === "in_progress" &&
|
|
|
|
|
current.checkoutRunId == null &&
|
|
|
|
|
(current.executionRunId == null || current.executionRunId === checkoutRunId) &&
|
|
|
|
|
checkoutRunId
|
|
|
|
|
) {
|
|
|
|
|
const adopted = await db
|
|
|
|
|
.update(issues)
|
|
|
|
|
.set({
|
|
|
|
|
checkoutRunId,
|
|
|
|
|
executionRunId: checkoutRunId,
|
|
|
|
|
updatedAt: new Date(),
|
|
|
|
|
})
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(issues.id, id),
|
|
|
|
|
eq(issues.status, "in_progress"),
|
|
|
|
|
eq(issues.assigneeAgentId, agentId),
|
|
|
|
|
isNull(issues.checkoutRunId),
|
|
|
|
|
or(isNull(issues.executionRunId), eq(issues.executionRunId, checkoutRunId)),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.returning()
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (adopted) return adopted;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-21 08:23:44 -06:00
|
|
|
if (
|
|
|
|
|
checkoutRunId &&
|
|
|
|
|
current.assigneeAgentId === agentId &&
|
|
|
|
|
current.status === "in_progress" &&
|
|
|
|
|
current.checkoutRunId &&
|
|
|
|
|
current.checkoutRunId !== checkoutRunId
|
|
|
|
|
) {
|
|
|
|
|
const adopted = await adoptStaleCheckoutRun({
|
|
|
|
|
issueId: id,
|
|
|
|
|
actorAgentId: agentId,
|
|
|
|
|
actorRunId: checkoutRunId,
|
|
|
|
|
expectedCheckoutRunId: current.checkoutRunId,
|
|
|
|
|
});
|
2026-02-25 08:38:37 -06:00
|
|
|
if (adopted) {
|
2026-04-03 09:56:23 +09:00
|
|
|
const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!row) throw notFound("Issue not found");
|
2026-02-25 08:38:37 -06:00
|
|
|
const [enriched] = await withIssueLabels(db, [row]);
|
|
|
|
|
return enriched;
|
|
|
|
|
}
|
2026-02-21 08:23:44 -06:00
|
|
|
}
|
|
|
|
|
|
2026-02-20 15:48:22 -06:00
|
|
|
// If this run already owns it and it's in_progress, return it (no self-409)
|
|
|
|
|
if (
|
|
|
|
|
current.assigneeAgentId === agentId &&
|
|
|
|
|
current.status === "in_progress" &&
|
|
|
|
|
sameRunLock(current.checkoutRunId, checkoutRunId)
|
|
|
|
|
) {
|
2026-04-03 09:56:23 +09:00
|
|
|
const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!row) throw notFound("Issue not found");
|
2026-02-25 08:38:37 -06:00
|
|
|
const [enriched] = await withIssueLabels(db, [row]);
|
|
|
|
|
return enriched;
|
2026-02-17 20:46:12 -06:00
|
|
|
}
|
|
|
|
|
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
throw conflict("Issue checkout conflict", {
|
|
|
|
|
issueId: current.id,
|
|
|
|
|
status: current.status,
|
|
|
|
|
assigneeAgentId: current.assigneeAgentId,
|
2026-02-20 15:48:22 -06:00
|
|
|
checkoutRunId: current.checkoutRunId,
|
|
|
|
|
executionRunId: current.executionRunId,
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
assertCheckoutOwner: async (id: string, actorAgentId: string, actorRunId: string | null) => {
|
|
|
|
|
const current = await db
|
|
|
|
|
.select({
|
|
|
|
|
id: issues.id,
|
|
|
|
|
status: issues.status,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId,
|
|
|
|
|
checkoutRunId: issues.checkoutRunId,
|
|
|
|
|
})
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (!current) throw notFound("Issue not found");
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
current.status === "in_progress" &&
|
|
|
|
|
current.assigneeAgentId === actorAgentId &&
|
|
|
|
|
sameRunLock(current.checkoutRunId, actorRunId)
|
|
|
|
|
) {
|
2026-02-21 08:23:44 -06:00
|
|
|
return { ...current, adoptedFromRunId: null as string | null };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
actorRunId &&
|
|
|
|
|
current.status === "in_progress" &&
|
|
|
|
|
current.assigneeAgentId === actorAgentId &&
|
|
|
|
|
current.checkoutRunId &&
|
|
|
|
|
current.checkoutRunId !== actorRunId
|
|
|
|
|
) {
|
|
|
|
|
const adopted = await adoptStaleCheckoutRun({
|
|
|
|
|
issueId: id,
|
|
|
|
|
actorAgentId,
|
|
|
|
|
actorRunId,
|
|
|
|
|
expectedCheckoutRunId: current.checkoutRunId,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (adopted) {
|
|
|
|
|
return {
|
|
|
|
|
...adopted,
|
|
|
|
|
adoptedFromRunId: current.checkoutRunId,
|
|
|
|
|
};
|
|
|
|
|
}
|
2026-02-20 15:48:22 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw conflict("Issue run ownership conflict", {
|
|
|
|
|
issueId: current.id,
|
|
|
|
|
status: current.status,
|
|
|
|
|
assigneeAgentId: current.assigneeAgentId,
|
|
|
|
|
checkoutRunId: current.checkoutRunId,
|
|
|
|
|
actorAgentId,
|
|
|
|
|
actorRunId,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
|
2026-02-20 15:48:22 -06:00
|
|
|
release: async (id: string, actorAgentId?: string, actorRunId?: string | null) => {
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
const existing = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (!existing) return null;
|
|
|
|
|
if (actorAgentId && existing.assigneeAgentId && existing.assigneeAgentId !== actorAgentId) {
|
|
|
|
|
throw conflict("Only assignee can release issue");
|
|
|
|
|
}
|
2026-02-20 15:48:22 -06:00
|
|
|
if (
|
|
|
|
|
actorAgentId &&
|
|
|
|
|
existing.status === "in_progress" &&
|
|
|
|
|
existing.assigneeAgentId === actorAgentId &&
|
|
|
|
|
existing.checkoutRunId &&
|
|
|
|
|
!sameRunLock(existing.checkoutRunId, actorRunId ?? null)
|
|
|
|
|
) {
|
|
|
|
|
throw conflict("Only checkout run can release issue", {
|
|
|
|
|
issueId: existing.id,
|
|
|
|
|
assigneeAgentId: existing.assigneeAgentId,
|
|
|
|
|
checkoutRunId: existing.checkoutRunId,
|
|
|
|
|
actorRunId: actorRunId ?? null,
|
|
|
|
|
});
|
|
|
|
|
}
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
const updated = await db
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
.update(issues)
|
|
|
|
|
.set({
|
|
|
|
|
status: "todo",
|
|
|
|
|
assigneeAgentId: null,
|
2026-02-20 15:48:22 -06:00
|
|
|
checkoutRunId: null,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
updatedAt: new Date(),
|
|
|
|
|
})
|
|
|
|
|
.where(eq(issues.id, id))
|
|
|
|
|
.returning()
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
2026-02-25 08:38:37 -06:00
|
|
|
if (!updated) return null;
|
|
|
|
|
const [enriched] = await withIssueLabels(db, [updated]);
|
|
|
|
|
return enriched;
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
},
|
|
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
listLabels: (companyId: string) =>
|
|
|
|
|
db.select().from(labels).where(eq(labels.companyId, companyId)).orderBy(asc(labels.name), asc(labels.id)),
|
|
|
|
|
|
|
|
|
|
getLabelById: (id: string) =>
|
|
|
|
|
db
|
|
|
|
|
.select()
|
|
|
|
|
.from(labels)
|
|
|
|
|
.where(eq(labels.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null),
|
|
|
|
|
|
|
|
|
|
createLabel: async (companyId: string, data: Pick<typeof labels.$inferInsert, "name" | "color">) => {
|
|
|
|
|
const [created] = await db
|
|
|
|
|
.insert(labels)
|
|
|
|
|
.values({
|
|
|
|
|
companyId,
|
|
|
|
|
name: data.name.trim(),
|
|
|
|
|
color: data.color,
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
return created;
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
deleteLabel: async (id: string) =>
|
|
|
|
|
db
|
|
|
|
|
.delete(labels)
|
|
|
|
|
.where(eq(labels.id, id))
|
|
|
|
|
.returning()
|
|
|
|
|
.then((rows) => rows[0] ?? null),
|
|
|
|
|
|
2026-03-13 08:49:11 -05:00
|
|
|
listComments: async (
|
|
|
|
|
issueId: string,
|
|
|
|
|
opts?: {
|
|
|
|
|
afterCommentId?: string | null;
|
|
|
|
|
order?: "asc" | "desc";
|
|
|
|
|
limit?: number | null;
|
|
|
|
|
},
|
|
|
|
|
) => {
|
|
|
|
|
const order = opts?.order === "asc" ? "asc" : "desc";
|
|
|
|
|
const afterCommentId = opts?.afterCommentId?.trim() || null;
|
2026-03-13 10:18:00 -05:00
|
|
|
const limit =
|
|
|
|
|
opts?.limit && opts.limit > 0
|
|
|
|
|
? Math.min(Math.floor(opts.limit), MAX_ISSUE_COMMENT_PAGE_LIMIT)
|
|
|
|
|
: null;
|
2026-03-13 08:49:11 -05:00
|
|
|
|
|
|
|
|
const conditions = [eq(issueComments.issueId, issueId)];
|
|
|
|
|
if (afterCommentId) {
|
|
|
|
|
const anchor = await db
|
|
|
|
|
.select({
|
|
|
|
|
id: issueComments.id,
|
|
|
|
|
createdAt: issueComments.createdAt,
|
|
|
|
|
})
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(and(eq(issueComments.issueId, issueId), eq(issueComments.id, afterCommentId)))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (!anchor) return [];
|
|
|
|
|
conditions.push(
|
2026-03-13 10:18:00 -05:00
|
|
|
order === "asc"
|
|
|
|
|
? sql<boolean>`(
|
|
|
|
|
${issueComments.createdAt} > ${anchor.createdAt}
|
|
|
|
|
OR (${issueComments.createdAt} = ${anchor.createdAt} AND ${issueComments.id} > ${anchor.id})
|
|
|
|
|
)`
|
|
|
|
|
: sql<boolean>`(
|
|
|
|
|
${issueComments.createdAt} < ${anchor.createdAt}
|
|
|
|
|
OR (${issueComments.createdAt} = ${anchor.createdAt} AND ${issueComments.id} < ${anchor.id})
|
|
|
|
|
)`,
|
2026-03-13 08:49:11 -05:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const query = db
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
.select()
|
|
|
|
|
.from(issueComments)
|
2026-03-13 08:49:11 -05:00
|
|
|
.where(and(...conditions))
|
2026-03-13 10:18:00 -05:00
|
|
|
.orderBy(
|
|
|
|
|
order === "asc" ? asc(issueComments.createdAt) : desc(issueComments.createdAt),
|
|
|
|
|
order === "asc" ? asc(issueComments.id) : desc(issueComments.id),
|
|
|
|
|
);
|
2026-03-13 08:49:11 -05:00
|
|
|
|
|
|
|
|
const comments = limit ? await query.limit(limit) : await query;
|
2026-03-20 08:00:39 -05:00
|
|
|
const { censorUsernameInLogs } = await instanceSettings.getGeneral();
|
|
|
|
|
return comments.map((comment) => redactIssueComment(comment, censorUsernameInLogs));
|
2026-03-13 08:49:11 -05:00
|
|
|
},
|
|
|
|
|
|
|
|
|
|
getCommentCursor: async (issueId: string) => {
|
2026-03-13 14:53:30 -05:00
|
|
|
const [latest, countRow] = await Promise.all([
|
|
|
|
|
db
|
|
|
|
|
.select({
|
|
|
|
|
latestCommentId: issueComments.id,
|
|
|
|
|
latestCommentAt: issueComments.createdAt,
|
|
|
|
|
})
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(eq(issueComments.issueId, issueId))
|
|
|
|
|
.orderBy(desc(issueComments.createdAt), desc(issueComments.id))
|
|
|
|
|
.limit(1)
|
|
|
|
|
.then((rows) => rows[0] ?? null),
|
|
|
|
|
db
|
|
|
|
|
.select({
|
|
|
|
|
totalComments: sql<number>`count(*)::int`,
|
|
|
|
|
})
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(eq(issueComments.issueId, issueId))
|
|
|
|
|
.then((rows) => rows[0] ?? null),
|
|
|
|
|
]);
|
2026-03-13 08:49:11 -05:00
|
|
|
|
|
|
|
|
return {
|
2026-03-13 14:53:30 -05:00
|
|
|
totalComments: Number(countRow?.totalComments ?? 0),
|
2026-03-13 08:49:11 -05:00
|
|
|
latestCommentId: latest?.latestCommentId ?? null,
|
|
|
|
|
latestCommentAt: latest?.latestCommentAt ?? null,
|
|
|
|
|
};
|
|
|
|
|
},
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
2026-03-05 11:02:22 -06:00
|
|
|
getComment: (commentId: string) =>
|
2026-03-20 08:00:39 -05:00
|
|
|
instanceSettings.getGeneral().then(({ censorUsernameInLogs }) =>
|
|
|
|
|
db
|
2026-03-05 11:02:22 -06:00
|
|
|
.select()
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(eq(issueComments.id, commentId))
|
2026-03-11 22:17:21 -05:00
|
|
|
.then((rows) => {
|
|
|
|
|
const comment = rows[0] ?? null;
|
2026-03-20 08:00:39 -05:00
|
|
|
return comment ? redactIssueComment(comment, censorUsernameInLogs) : null;
|
|
|
|
|
})),
|
2026-03-05 11:02:22 -06:00
|
|
|
|
[codex] Improve issue detail and issue-list UX (#3678)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - A core part of that is the operator experience around reading issue
state, agent chat, and sub-task structure
> - The current branch had a long run of issue-detail and issue-list UX
fixes that all improve how humans follow and steer active work
> - Those changes mostly live in the UI/chat surface and should be
reviewed together instead of mixed with workspace/runtime work
> - This pull request packages the issue-detail, chat, markdown, and
sub-issue list improvements into one standalone change
> - The benefit is a cleaner, less jumpy, more reliable issue workflow
on desktop and mobile without coupling it to unrelated server/runtime
refactors
## What Changed
- Stabilized issue chat runtime wiring, optimistic comment handling,
queued-comment cancellation, and composer anchoring during live updates
- Fixed several issue-detail rendering and navigation regressions
including placeholder bleed, local polling scope, mobile inbox-to-issue
transitions, and visible refresh resets
- Improved markdown and rich-content handling with advisory image
normalization, editor fallback behavior, touch mention recovery, and
`issue:` quicklook links
- Refined sub-issue behavior with parent-derived defaults, current-user
inheritance fixes, empty-state cleanup, and a reusable issue-list
presentation for sub-issues
- Added targeted UI tests for the new issue-detail, chat scroll/message,
placeholder-data, markdown, and issue-list behaviors
## Verification
- `pnpm vitest run ui/src/components/IssueChatThread.test.tsx
ui/src/components/MarkdownEditor.test.tsx
ui/src/components/IssuesList.test.tsx
ui/src/context/LiveUpdatesProvider.test.tsx
ui/src/lib/issue-chat-messages.test.ts
ui/src/lib/issue-chat-scroll.test.ts
ui/src/lib/issue-detail-subissues.test.ts
ui/src/lib/query-placeholder-data.test.tsx
ui/src/hooks/usePaperclipIssueRuntime.test.tsx`
## Risks
- Medium: this branch touches the highest-traffic issue-detail UI paths,
so regressions would show up as chat/thread or sub-issue UX glitches
- The changes are UI-heavy and would benefit from reviewer screenshots
or a quick manual browser pass before merge
## Model Used
- OpenAI Codex coding agent (GPT-5-class runtime in Codex CLI; exact
deployed model ID is not exposed in this environment), reasoning
enabled, tool use and local code execution enabled
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-14 12:50:48 -05:00
|
|
|
removeComment: async (commentId: string) => {
|
|
|
|
|
const currentUserRedactionOptions = {
|
|
|
|
|
enabled: (await instanceSettings.getGeneral()).censorUsernameInLogs,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return db.transaction(async (tx) => {
|
|
|
|
|
const [comment] = await tx
|
|
|
|
|
.delete(issueComments)
|
|
|
|
|
.where(eq(issueComments.id, commentId))
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
if (!comment) return null;
|
|
|
|
|
|
|
|
|
|
await tx
|
|
|
|
|
.update(issues)
|
|
|
|
|
.set({ updatedAt: new Date() })
|
|
|
|
|
.where(eq(issues.id, comment.issueId));
|
|
|
|
|
|
|
|
|
|
return redactIssueComment(comment, currentUserRedactionOptions.enabled);
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
|
2026-04-02 09:11:49 -05:00
|
|
|
addComment: async (
|
|
|
|
|
issueId: string,
|
|
|
|
|
body: string,
|
|
|
|
|
actor: { agentId?: string; userId?: string; runId?: string | null },
|
|
|
|
|
) => {
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
const issue = await db
|
|
|
|
|
.select({ companyId: issues.companyId })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, issueId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (!issue) throw notFound("Issue not found");
|
|
|
|
|
|
2026-03-20 08:00:39 -05:00
|
|
|
const currentUserRedactionOptions = {
|
|
|
|
|
enabled: (await instanceSettings.getGeneral()).censorUsernameInLogs,
|
|
|
|
|
};
|
|
|
|
|
const redactedBody = redactCurrentUserText(body, currentUserRedactionOptions);
|
2026-03-02 16:55:37 -06:00
|
|
|
const [comment] = await db
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
.insert(issueComments)
|
|
|
|
|
.values({
|
|
|
|
|
companyId: issue.companyId,
|
|
|
|
|
issueId,
|
|
|
|
|
authorAgentId: actor.agentId ?? null,
|
|
|
|
|
authorUserId: actor.userId ?? null,
|
2026-04-02 09:11:49 -05:00
|
|
|
createdByRunId: actor.runId ?? null,
|
2026-03-11 22:17:21 -05:00
|
|
|
body: redactedBody,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
})
|
2026-03-02 16:55:37 -06:00
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
// Update issue's updatedAt so comment activity is reflected in recency sorting
|
|
|
|
|
await db
|
|
|
|
|
.update(issues)
|
|
|
|
|
.set({ updatedAt: new Date() })
|
|
|
|
|
.where(eq(issues.id, issueId));
|
|
|
|
|
|
2026-03-20 08:00:39 -05:00
|
|
|
return redactIssueComment(comment, currentUserRedactionOptions.enabled);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
},
|
|
|
|
|
|
2026-02-20 10:31:56 -06:00
|
|
|
createAttachment: async (input: {
|
|
|
|
|
issueId: string;
|
|
|
|
|
issueCommentId?: string | null;
|
|
|
|
|
provider: string;
|
|
|
|
|
objectKey: string;
|
|
|
|
|
contentType: string;
|
|
|
|
|
byteSize: number;
|
|
|
|
|
sha256: string;
|
|
|
|
|
originalFilename?: string | null;
|
|
|
|
|
createdByAgentId?: string | null;
|
|
|
|
|
createdByUserId?: string | null;
|
|
|
|
|
}) => {
|
|
|
|
|
const issue = await db
|
|
|
|
|
.select({ id: issues.id, companyId: issues.companyId })
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, input.issueId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!issue) throw notFound("Issue not found");
|
|
|
|
|
|
|
|
|
|
if (input.issueCommentId) {
|
|
|
|
|
const comment = await db
|
|
|
|
|
.select({ id: issueComments.id, companyId: issueComments.companyId, issueId: issueComments.issueId })
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(eq(issueComments.id, input.issueCommentId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!comment) throw notFound("Issue comment not found");
|
|
|
|
|
if (comment.companyId !== issue.companyId || comment.issueId !== issue.id) {
|
|
|
|
|
throw unprocessable("Attachment comment must belong to same issue and company");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return db.transaction(async (tx) => {
|
|
|
|
|
const [asset] = await tx
|
|
|
|
|
.insert(assets)
|
|
|
|
|
.values({
|
|
|
|
|
companyId: issue.companyId,
|
|
|
|
|
provider: input.provider,
|
|
|
|
|
objectKey: input.objectKey,
|
|
|
|
|
contentType: input.contentType,
|
|
|
|
|
byteSize: input.byteSize,
|
|
|
|
|
sha256: input.sha256,
|
|
|
|
|
originalFilename: input.originalFilename ?? null,
|
|
|
|
|
createdByAgentId: input.createdByAgentId ?? null,
|
|
|
|
|
createdByUserId: input.createdByUserId ?? null,
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
const [attachment] = await tx
|
|
|
|
|
.insert(issueAttachments)
|
|
|
|
|
.values({
|
|
|
|
|
companyId: issue.companyId,
|
|
|
|
|
issueId: issue.id,
|
|
|
|
|
assetId: asset.id,
|
|
|
|
|
issueCommentId: input.issueCommentId ?? null,
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
id: attachment.id,
|
|
|
|
|
companyId: attachment.companyId,
|
|
|
|
|
issueId: attachment.issueId,
|
|
|
|
|
issueCommentId: attachment.issueCommentId,
|
|
|
|
|
assetId: attachment.assetId,
|
|
|
|
|
provider: asset.provider,
|
|
|
|
|
objectKey: asset.objectKey,
|
|
|
|
|
contentType: asset.contentType,
|
|
|
|
|
byteSize: asset.byteSize,
|
|
|
|
|
sha256: asset.sha256,
|
|
|
|
|
originalFilename: asset.originalFilename,
|
|
|
|
|
createdByAgentId: asset.createdByAgentId,
|
|
|
|
|
createdByUserId: asset.createdByUserId,
|
|
|
|
|
createdAt: attachment.createdAt,
|
|
|
|
|
updatedAt: attachment.updatedAt,
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
listAttachments: async (issueId: string) =>
|
|
|
|
|
db
|
|
|
|
|
.select({
|
|
|
|
|
id: issueAttachments.id,
|
|
|
|
|
companyId: issueAttachments.companyId,
|
|
|
|
|
issueId: issueAttachments.issueId,
|
|
|
|
|
issueCommentId: issueAttachments.issueCommentId,
|
|
|
|
|
assetId: issueAttachments.assetId,
|
|
|
|
|
provider: assets.provider,
|
|
|
|
|
objectKey: assets.objectKey,
|
|
|
|
|
contentType: assets.contentType,
|
|
|
|
|
byteSize: assets.byteSize,
|
|
|
|
|
sha256: assets.sha256,
|
|
|
|
|
originalFilename: assets.originalFilename,
|
|
|
|
|
createdByAgentId: assets.createdByAgentId,
|
|
|
|
|
createdByUserId: assets.createdByUserId,
|
|
|
|
|
createdAt: issueAttachments.createdAt,
|
|
|
|
|
updatedAt: issueAttachments.updatedAt,
|
|
|
|
|
})
|
|
|
|
|
.from(issueAttachments)
|
|
|
|
|
.innerJoin(assets, eq(issueAttachments.assetId, assets.id))
|
|
|
|
|
.where(eq(issueAttachments.issueId, issueId))
|
|
|
|
|
.orderBy(desc(issueAttachments.createdAt)),
|
|
|
|
|
|
|
|
|
|
getAttachmentById: async (id: string) =>
|
|
|
|
|
db
|
|
|
|
|
.select({
|
|
|
|
|
id: issueAttachments.id,
|
|
|
|
|
companyId: issueAttachments.companyId,
|
|
|
|
|
issueId: issueAttachments.issueId,
|
|
|
|
|
issueCommentId: issueAttachments.issueCommentId,
|
|
|
|
|
assetId: issueAttachments.assetId,
|
|
|
|
|
provider: assets.provider,
|
|
|
|
|
objectKey: assets.objectKey,
|
|
|
|
|
contentType: assets.contentType,
|
|
|
|
|
byteSize: assets.byteSize,
|
|
|
|
|
sha256: assets.sha256,
|
|
|
|
|
originalFilename: assets.originalFilename,
|
|
|
|
|
createdByAgentId: assets.createdByAgentId,
|
|
|
|
|
createdByUserId: assets.createdByUserId,
|
|
|
|
|
createdAt: issueAttachments.createdAt,
|
|
|
|
|
updatedAt: issueAttachments.updatedAt,
|
|
|
|
|
})
|
|
|
|
|
.from(issueAttachments)
|
|
|
|
|
.innerJoin(assets, eq(issueAttachments.assetId, assets.id))
|
|
|
|
|
.where(eq(issueAttachments.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null),
|
|
|
|
|
|
|
|
|
|
removeAttachment: async (id: string) =>
|
|
|
|
|
db.transaction(async (tx) => {
|
|
|
|
|
const existing = await tx
|
|
|
|
|
.select({
|
|
|
|
|
id: issueAttachments.id,
|
|
|
|
|
companyId: issueAttachments.companyId,
|
|
|
|
|
issueId: issueAttachments.issueId,
|
|
|
|
|
issueCommentId: issueAttachments.issueCommentId,
|
|
|
|
|
assetId: issueAttachments.assetId,
|
|
|
|
|
provider: assets.provider,
|
|
|
|
|
objectKey: assets.objectKey,
|
|
|
|
|
contentType: assets.contentType,
|
|
|
|
|
byteSize: assets.byteSize,
|
|
|
|
|
sha256: assets.sha256,
|
|
|
|
|
originalFilename: assets.originalFilename,
|
|
|
|
|
createdByAgentId: assets.createdByAgentId,
|
|
|
|
|
createdByUserId: assets.createdByUserId,
|
|
|
|
|
createdAt: issueAttachments.createdAt,
|
|
|
|
|
updatedAt: issueAttachments.updatedAt,
|
|
|
|
|
})
|
|
|
|
|
.from(issueAttachments)
|
|
|
|
|
.innerJoin(assets, eq(issueAttachments.assetId, assets.id))
|
|
|
|
|
.where(eq(issueAttachments.id, id))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!existing) return null;
|
|
|
|
|
|
|
|
|
|
await tx.delete(issueAttachments).where(eq(issueAttachments.id, id));
|
|
|
|
|
await tx.delete(assets).where(eq(assets.id, existing.assetId));
|
|
|
|
|
return existing;
|
|
|
|
|
}),
|
|
|
|
|
|
2026-02-17 20:07:14 -06:00
|
|
|
findMentionedAgents: async (companyId: string, body: string) => {
|
|
|
|
|
const re = /\B@([^\s@,!?.]+)/g;
|
|
|
|
|
const tokens = new Set<string>();
|
|
|
|
|
let m: RegExpExecArray | null;
|
2026-03-20 16:38:55 +00:00
|
|
|
while ((m = re.exec(body)) !== null) {
|
|
|
|
|
const normalized = normalizeAgentMentionToken(m[1]);
|
|
|
|
|
if (normalized) tokens.add(normalized.toLowerCase());
|
|
|
|
|
}
|
2026-03-21 14:48:10 -05:00
|
|
|
|
|
|
|
|
const explicitAgentMentionIds = extractAgentMentionIds(body);
|
|
|
|
|
if (tokens.size === 0 && explicitAgentMentionIds.length === 0) return [];
|
2026-02-17 20:07:14 -06:00
|
|
|
const rows = await db.select({ id: agents.id, name: agents.name })
|
|
|
|
|
.from(agents).where(eq(agents.companyId, companyId));
|
2026-03-21 14:48:10 -05:00
|
|
|
const resolved = new Set<string>(explicitAgentMentionIds);
|
|
|
|
|
for (const agent of rows) {
|
|
|
|
|
if (tokens.has(agent.name.toLowerCase())) {
|
|
|
|
|
resolved.add(agent.id);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return [...resolved];
|
2026-02-17 20:07:14 -06:00
|
|
|
},
|
|
|
|
|
|
Sync/master post pap1497 followups 2026 04 15 (#3779)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - The board depends on issue, inbox, cost, and company-skill surfaces
to stay accurate and fast while agents are actively working
> - The PAP-1497 follow-up branch exposed a few rough edges in those
surfaces: stale active-run state on completed issues, missing creator
filters, oversized issue payload scans, and placeholder issue-route
parsing
> - Those gaps make the control plane harder to trust because operators
can see misleading run state, miss the right subset of work, or pay
extra query/render cost on large issue records
> - This pull request tightens those follow-ups across server and UI
code, and adds regression coverage for the affected paths
> - The benefit is a more reliable issue workflow, safer high-volume
cost aggregation, and clearer board/operator navigation
## What Changed
- Added the `v2026.415.0` release changelog entry.
- Fixed stale issue-run presentation after completion and reused the
shared issue-path parser so literal route placeholders no longer become
issue links.
- Added creator filters to the Issues page and Inbox, including
persisted filter-state normalization and regression coverage.
- Bounded issue detail/list project-mention scans and trimmed large
issue-list payload fields to keep issue reads lighter.
- Hardened company-skill list projection and cost/finance aggregation so
large markdown blobs and large summed values do not leak into list
responses or overflow 32-bit casts.
- Added targeted server/UI regression tests for company skills,
costs/finance, issue mention scanning, creator filters, inbox
normalization, and issue reference parsing.
## Verification
- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/issues-goal-context-routes.test.ts
server/src/__tests__/issues-service.test.ts ui/src/lib/inbox.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-reference.test.ts`
- `gh pr checks 3779`
Current pass set on the PR head: `policy`, `verify`, `e2e`,
`security/snyk (cryppadotta)`, `Greptile Review`
## Risks
- Creator filter options are derived from the currently loaded
issue/agent data, so very sparse result sets may not surface every
historical creator until they appear in the active dataset.
- Cost/finance aggregate casts now use `double precision`; that removes
the current overflow risk, but future schema changes should keep
large-value aggregation behavior under review.
- Issue detail mention scanning now skips comment-body scans on the
detail route, so any consumer that relied on comment-only project
mentions there would need to fetch them separately.
## Model Used
- OpenAI Codex, GPT-5-based coding agent with terminal tool use and
local code execution in the Paperclip workspace. Exact internal model
ID/context-window exposure is not surfaced in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 21:13:56 -05:00
|
|
|
findMentionedProjectIds: async (
|
|
|
|
|
issueId: string,
|
|
|
|
|
opts?: { includeCommentBodies?: boolean },
|
|
|
|
|
) => {
|
2026-03-02 13:31:58 -06:00
|
|
|
const issue = await db
|
|
|
|
|
.select({
|
|
|
|
|
companyId: issues.companyId,
|
|
|
|
|
title: issues.title,
|
|
|
|
|
description: issues.description,
|
|
|
|
|
})
|
|
|
|
|
.from(issues)
|
|
|
|
|
.where(eq(issues.id, issueId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
if (!issue) return [];
|
|
|
|
|
|
|
|
|
|
const mentionedIds = new Set<string>();
|
Sync/master post pap1497 followups 2026 04 15 (#3779)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - The board depends on issue, inbox, cost, and company-skill surfaces
to stay accurate and fast while agents are actively working
> - The PAP-1497 follow-up branch exposed a few rough edges in those
surfaces: stale active-run state on completed issues, missing creator
filters, oversized issue payload scans, and placeholder issue-route
parsing
> - Those gaps make the control plane harder to trust because operators
can see misleading run state, miss the right subset of work, or pay
extra query/render cost on large issue records
> - This pull request tightens those follow-ups across server and UI
code, and adds regression coverage for the affected paths
> - The benefit is a more reliable issue workflow, safer high-volume
cost aggregation, and clearer board/operator navigation
## What Changed
- Added the `v2026.415.0` release changelog entry.
- Fixed stale issue-run presentation after completion and reused the
shared issue-path parser so literal route placeholders no longer become
issue links.
- Added creator filters to the Issues page and Inbox, including
persisted filter-state normalization and regression coverage.
- Bounded issue detail/list project-mention scans and trimmed large
issue-list payload fields to keep issue reads lighter.
- Hardened company-skill list projection and cost/finance aggregation so
large markdown blobs and large summed values do not leak into list
responses or overflow 32-bit casts.
- Added targeted server/UI regression tests for company skills,
costs/finance, issue mention scanning, creator filters, inbox
normalization, and issue reference parsing.
## Verification
- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/issues-goal-context-routes.test.ts
server/src/__tests__/issues-service.test.ts ui/src/lib/inbox.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-reference.test.ts`
- `gh pr checks 3779`
Current pass set on the PR head: `policy`, `verify`, `e2e`,
`security/snyk (cryppadotta)`, `Greptile Review`
## Risks
- Creator filter options are derived from the currently loaded
issue/agent data, so very sparse result sets may not surface every
historical creator until they appear in the active dataset.
- Cost/finance aggregate casts now use `double precision`; that removes
the current overflow risk, but future schema changes should keep
large-value aggregation behavior under review.
- Issue detail mention scanning now skips comment-body scans on the
detail route, so any consumer that relied on comment-only project
mentions there would need to fetch them separately.
## Model Used
- OpenAI Codex, GPT-5-based coding agent with terminal tool use and
local code execution in the Paperclip workspace. Exact internal model
ID/context-window exposure is not surfaced in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 21:13:56 -05:00
|
|
|
for (const source of [issue.title, issue.description ?? ""]) {
|
2026-03-02 13:31:58 -06:00
|
|
|
for (const projectId of extractProjectMentionIds(source)) {
|
|
|
|
|
mentionedIds.add(projectId);
|
|
|
|
|
}
|
|
|
|
|
}
|
Sync/master post pap1497 followups 2026 04 15 (#3779)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies
> - The board depends on issue, inbox, cost, and company-skill surfaces
to stay accurate and fast while agents are actively working
> - The PAP-1497 follow-up branch exposed a few rough edges in those
surfaces: stale active-run state on completed issues, missing creator
filters, oversized issue payload scans, and placeholder issue-route
parsing
> - Those gaps make the control plane harder to trust because operators
can see misleading run state, miss the right subset of work, or pay
extra query/render cost on large issue records
> - This pull request tightens those follow-ups across server and UI
code, and adds regression coverage for the affected paths
> - The benefit is a more reliable issue workflow, safer high-volume
cost aggregation, and clearer board/operator navigation
## What Changed
- Added the `v2026.415.0` release changelog entry.
- Fixed stale issue-run presentation after completion and reused the
shared issue-path parser so literal route placeholders no longer become
issue links.
- Added creator filters to the Issues page and Inbox, including
persisted filter-state normalization and regression coverage.
- Bounded issue detail/list project-mention scans and trimmed large
issue-list payload fields to keep issue reads lighter.
- Hardened company-skill list projection and cost/finance aggregation so
large markdown blobs and large summed values do not leak into list
responses or overflow 32-bit casts.
- Added targeted server/UI regression tests for company skills,
costs/finance, issue mention scanning, creator filters, inbox
normalization, and issue reference parsing.
## Verification
- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/issues-goal-context-routes.test.ts
server/src/__tests__/issues-service.test.ts ui/src/lib/inbox.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-reference.test.ts`
- `gh pr checks 3779`
Current pass set on the PR head: `policy`, `verify`, `e2e`,
`security/snyk (cryppadotta)`, `Greptile Review`
## Risks
- Creator filter options are derived from the currently loaded
issue/agent data, so very sparse result sets may not surface every
historical creator until they appear in the active dataset.
- Cost/finance aggregate casts now use `double precision`; that removes
the current overflow risk, but future schema changes should keep
large-value aggregation behavior under review.
- Issue detail mention scanning now skips comment-body scans on the
detail route, so any consumer that relied on comment-only project
mentions there would need to fetch them separately.
## Model Used
- OpenAI Codex, GPT-5-based coding agent with terminal tool use and
local code execution in the Paperclip workspace. Exact internal model
ID/context-window exposure is not surfaced in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-15 21:13:56 -05:00
|
|
|
|
|
|
|
|
if (opts?.includeCommentBodies !== false) {
|
|
|
|
|
const comments = await db
|
|
|
|
|
.select({ body: issueComments.body })
|
|
|
|
|
.from(issueComments)
|
|
|
|
|
.where(eq(issueComments.issueId, issueId));
|
|
|
|
|
|
|
|
|
|
for (const comment of comments) {
|
|
|
|
|
for (const projectId of extractProjectMentionIds(comment.body)) {
|
|
|
|
|
mentionedIds.add(projectId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-02 13:31:58 -06:00
|
|
|
if (mentionedIds.size === 0) return [];
|
|
|
|
|
|
|
|
|
|
const rows = await db
|
|
|
|
|
.select({ id: projects.id })
|
|
|
|
|
.from(projects)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(projects.companyId, issue.companyId),
|
|
|
|
|
inArray(projects.id, [...mentionedIds]),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
const valid = new Set(rows.map((row) => row.id));
|
|
|
|
|
return [...mentionedIds].filter((projectId) => valid.has(projectId));
|
|
|
|
|
},
|
|
|
|
|
|
2026-02-17 20:07:14 -06:00
|
|
|
getAncestors: async (issueId: string) => {
|
2026-02-20 10:31:56 -06:00
|
|
|
const raw: Array<{
|
2026-02-20 16:04:05 -06:00
|
|
|
id: string; identifier: string | null; title: string; description: string | null;
|
2026-02-17 20:07:14 -06:00
|
|
|
status: string; priority: string;
|
|
|
|
|
assigneeAgentId: string | null; projectId: string | null; goalId: string | null;
|
|
|
|
|
}> = [];
|
|
|
|
|
const visited = new Set<string>([issueId]);
|
|
|
|
|
const start = await db.select().from(issues).where(eq(issues.id, issueId)).then(r => r[0] ?? null);
|
|
|
|
|
let currentId = start?.parentId ?? null;
|
2026-02-20 10:31:56 -06:00
|
|
|
while (currentId && !visited.has(currentId) && raw.length < 50) {
|
2026-02-17 20:07:14 -06:00
|
|
|
visited.add(currentId);
|
|
|
|
|
const parent = await db.select({
|
2026-02-20 16:04:05 -06:00
|
|
|
id: issues.id, identifier: issues.identifier, title: issues.title, description: issues.description,
|
2026-02-17 20:07:14 -06:00
|
|
|
status: issues.status, priority: issues.priority,
|
|
|
|
|
assigneeAgentId: issues.assigneeAgentId, projectId: issues.projectId,
|
|
|
|
|
goalId: issues.goalId, parentId: issues.parentId,
|
|
|
|
|
}).from(issues).where(eq(issues.id, currentId)).then(r => r[0] ?? null);
|
|
|
|
|
if (!parent) break;
|
2026-02-20 10:31:56 -06:00
|
|
|
raw.push({
|
2026-02-20 16:04:05 -06:00
|
|
|
id: parent.id, identifier: parent.identifier ?? null, title: parent.title, description: parent.description ?? null,
|
2026-02-17 20:07:14 -06:00
|
|
|
status: parent.status, priority: parent.priority,
|
|
|
|
|
assigneeAgentId: parent.assigneeAgentId ?? null,
|
|
|
|
|
projectId: parent.projectId ?? null, goalId: parent.goalId ?? null,
|
|
|
|
|
});
|
|
|
|
|
currentId = parent.parentId ?? null;
|
|
|
|
|
}
|
2026-02-20 10:31:56 -06:00
|
|
|
|
|
|
|
|
// Batch-fetch referenced projects and goals
|
|
|
|
|
const projectIds = [...new Set(raw.map(a => a.projectId).filter((id): id is string => id != null))];
|
|
|
|
|
const goalIds = [...new Set(raw.map(a => a.goalId).filter((id): id is string => id != null))];
|
|
|
|
|
|
2026-02-25 08:38:37 -06:00
|
|
|
const projectMap = new Map<string, {
|
|
|
|
|
id: string;
|
|
|
|
|
name: string;
|
|
|
|
|
description: string | null;
|
|
|
|
|
status: string;
|
|
|
|
|
goalId: string | null;
|
|
|
|
|
workspaces: Array<{
|
|
|
|
|
id: string;
|
|
|
|
|
companyId: string;
|
|
|
|
|
projectId: string;
|
|
|
|
|
name: string;
|
2026-02-25 21:35:33 -06:00
|
|
|
cwd: string | null;
|
2026-02-25 08:38:37 -06:00
|
|
|
repoUrl: string | null;
|
|
|
|
|
repoRef: string | null;
|
|
|
|
|
metadata: Record<string, unknown> | null;
|
|
|
|
|
isPrimary: boolean;
|
|
|
|
|
createdAt: Date;
|
|
|
|
|
updatedAt: Date;
|
|
|
|
|
}>;
|
|
|
|
|
primaryWorkspace: {
|
|
|
|
|
id: string;
|
|
|
|
|
companyId: string;
|
|
|
|
|
projectId: string;
|
|
|
|
|
name: string;
|
2026-02-25 21:35:33 -06:00
|
|
|
cwd: string | null;
|
2026-02-25 08:38:37 -06:00
|
|
|
repoUrl: string | null;
|
|
|
|
|
repoRef: string | null;
|
|
|
|
|
metadata: Record<string, unknown> | null;
|
|
|
|
|
isPrimary: boolean;
|
|
|
|
|
createdAt: Date;
|
|
|
|
|
updatedAt: Date;
|
|
|
|
|
} | null;
|
|
|
|
|
}>();
|
2026-02-20 10:31:56 -06:00
|
|
|
const goalMap = new Map<string, { id: string; title: string; description: string | null; level: string; status: string }>();
|
|
|
|
|
|
|
|
|
|
if (projectIds.length > 0) {
|
2026-02-25 08:38:37 -06:00
|
|
|
const workspaceRows = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(projectWorkspaces)
|
|
|
|
|
.where(inArray(projectWorkspaces.projectId, projectIds))
|
|
|
|
|
.orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id));
|
|
|
|
|
const workspaceMap = new Map<string, Array<(typeof workspaceRows)[number]>>();
|
|
|
|
|
for (const workspace of workspaceRows) {
|
|
|
|
|
const existing = workspaceMap.get(workspace.projectId);
|
|
|
|
|
if (existing) existing.push(workspace);
|
|
|
|
|
else workspaceMap.set(workspace.projectId, [workspace]);
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-20 10:31:56 -06:00
|
|
|
const rows = await db.select({
|
|
|
|
|
id: projects.id, name: projects.name, description: projects.description,
|
|
|
|
|
status: projects.status, goalId: projects.goalId,
|
|
|
|
|
}).from(projects).where(inArray(projects.id, projectIds));
|
|
|
|
|
for (const r of rows) {
|
2026-02-25 08:38:37 -06:00
|
|
|
const projectWorkspaceRows = workspaceMap.get(r.id) ?? [];
|
|
|
|
|
const workspaces = projectWorkspaceRows.map((workspace) => ({
|
|
|
|
|
id: workspace.id,
|
|
|
|
|
companyId: workspace.companyId,
|
|
|
|
|
projectId: workspace.projectId,
|
|
|
|
|
name: workspace.name,
|
|
|
|
|
cwd: workspace.cwd,
|
|
|
|
|
repoUrl: workspace.repoUrl ?? null,
|
|
|
|
|
repoRef: workspace.repoRef ?? null,
|
|
|
|
|
metadata: (workspace.metadata as Record<string, unknown> | null) ?? null,
|
|
|
|
|
isPrimary: workspace.isPrimary,
|
|
|
|
|
createdAt: workspace.createdAt,
|
|
|
|
|
updatedAt: workspace.updatedAt,
|
|
|
|
|
}));
|
|
|
|
|
const primaryWorkspace = workspaces.find((workspace) => workspace.isPrimary) ?? workspaces[0] ?? null;
|
|
|
|
|
projectMap.set(r.id, {
|
|
|
|
|
...r,
|
|
|
|
|
workspaces,
|
|
|
|
|
primaryWorkspace,
|
|
|
|
|
});
|
2026-02-20 10:31:56 -06:00
|
|
|
// Also collect goalIds from projects
|
|
|
|
|
if (r.goalId && !goalIds.includes(r.goalId)) goalIds.push(r.goalId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (goalIds.length > 0) {
|
|
|
|
|
const rows = await db.select({
|
|
|
|
|
id: goals.id, title: goals.title, description: goals.description,
|
|
|
|
|
level: goals.level, status: goals.status,
|
|
|
|
|
}).from(goals).where(inArray(goals.id, goalIds));
|
|
|
|
|
for (const r of rows) goalMap.set(r.id, r);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return raw.map(a => ({
|
|
|
|
|
...a,
|
|
|
|
|
project: a.projectId ? projectMap.get(a.projectId) ?? null : null,
|
|
|
|
|
goal: a.goalId ? goalMap.get(a.goalId) ?? null : null,
|
|
|
|
|
}));
|
2026-02-17 20:07:14 -06:00
|
|
|
},
|
2026-02-16 13:31:58 -06:00
|
|
|
};
|
|
|
|
|
}
|