@mastra/factory 0.26.0-alpha.2 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -7
- package/dist/boards/define-board.d.ts +19 -0
- package/dist/boards/define-board.d.ts.map +1 -1
- package/dist/boards/define-board.js +41 -9
- package/dist/boards/define-board.js.map +1 -1
- package/dist/boards/project-boards.d.ts +78 -0
- package/dist/boards/project-boards.d.ts.map +1 -0
- package/dist/boards/project-boards.js +194 -0
- package/dist/boards/project-boards.js.map +1 -0
- package/dist/boards/review.js +2 -2
- package/dist/boards/review.js.map +1 -1
- package/dist/boards/stored-board.d.ts +101 -0
- package/dist/boards/stored-board.d.ts.map +1 -0
- package/dist/boards/stored-board.js +139 -0
- package/dist/boards/stored-board.js.map +1 -0
- package/dist/boards/work.d.ts.map +1 -1
- package/dist/boards/work.js +6 -3
- package/dist/boards/work.js.map +1 -1
- package/dist/capabilities/intake.d.ts +6 -0
- package/dist/capabilities/intake.d.ts.map +1 -1
- package/dist/factory.d.ts +15 -2
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +49 -10
- package/dist/factory.js.map +1 -1
- package/dist/integrations/jira/binding-scope.d.ts +30 -0
- package/dist/integrations/jira/binding-scope.d.ts.map +1 -0
- package/dist/integrations/jira/binding-scope.js +50 -0
- package/dist/integrations/jira/binding-scope.js.map +1 -0
- package/dist/integrations/jira/claim.d.ts +12 -0
- package/dist/integrations/jira/claim.d.ts.map +1 -1
- package/dist/integrations/jira/claim.js +24 -1
- package/dist/integrations/jira/claim.js.map +1 -1
- package/dist/integrations/jira/intake-jql.d.ts +32 -0
- package/dist/integrations/jira/intake-jql.d.ts.map +1 -0
- package/dist/integrations/jira/intake-jql.js +57 -0
- package/dist/integrations/jira/intake-jql.js.map +1 -0
- package/dist/integrations/jira/integration.d.ts +4 -3
- package/dist/integrations/jira/integration.d.ts.map +1 -1
- package/dist/integrations/jira/integration.js +14 -21
- package/dist/integrations/jira/integration.js.map +1 -1
- package/dist/integrations/jira/routes.d.ts +3 -0
- package/dist/integrations/jira/routes.d.ts.map +1 -1
- package/dist/integrations/jira/routes.js +16 -29
- package/dist/integrations/jira/routes.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +8 -13
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/platform/jira/integration.d.ts +7 -1
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +26 -24
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/jira/routes.d.ts +3 -0
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
- package/dist/integrations/platform/jira/routes.js +17 -28
- package/dist/integrations/platform/jira/routes.js.map +1 -1
- package/dist/routes/attention-providers.d.ts +2 -1
- package/dist/routes/attention-providers.d.ts.map +1 -1
- package/dist/routes/attention-providers.js +3 -2
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/attention.d.ts +2 -1
- package/dist/routes/attention.d.ts.map +1 -1
- package/dist/routes/attention.js.map +1 -1
- package/dist/routes/boards.d.ts +30 -0
- package/dist/routes/boards.d.ts.map +1 -0
- package/dist/routes/boards.js +272 -0
- package/dist/routes/boards.js.map +1 -0
- package/dist/routes/contracts.d.ts +249 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +107 -35
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake.d.ts +15 -10
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +109 -22
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/projects.d.ts +3 -0
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +10 -1
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/surface.d.ts +10 -3
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +12 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/tenant-credentials.d.ts +9 -0
- package/dist/routes/tenant-credentials.d.ts.map +1 -1
- package/dist/routes/tenant-credentials.js +24 -2
- package/dist/routes/tenant-credentials.js.map +1 -1
- package/dist/routes/work-items.d.ts +3 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +64 -42
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +7 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +70 -34
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +3 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +11 -6
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/tools.d.ts +2 -1
- package/dist/rules/tools.d.ts.map +1 -1
- package/dist/rules/tools.js +2 -1
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +3 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +12 -12
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -0
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +6 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +110 -0
- package/dist/storage/domains/boards/base.d.ts.map +1 -0
- package/dist/storage/domains/boards/base.js +292 -0
- package/dist/storage/domains/boards/base.js.map +1 -0
- package/dist/storage/domains/boards/schemas.d.ts +11 -0
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -0
- package/dist/storage/domains/boards/schemas.js +106 -0
- package/dist/storage/domains/boards/schemas.js.map +1 -0
- package/dist/storage/domains/credentials/base.d.ts +4 -1
- package/dist/storage/domains/credentials/base.d.ts.map +1 -1
- package/dist/storage/domains/credentials/base.js +5 -2
- package/dist/storage/domains/credentials/base.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +86 -5
- package/dist/storage/domains/intake/base.d.ts.map +1 -1
- package/dist/storage/domains/intake/base.js +298 -59
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +2 -1
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +15 -10
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +14 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +39 -11
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/tools/read-tools.d.ts +3 -1
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +3 -2
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/session-tools.d.ts +3 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +2 -1
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/sessions-state-processor.d.ts +3 -1
- package/dist/tools/sessions-state-processor.d.ts.map +1 -1
- package/dist/tools/sessions-state-processor.js +2 -1
- package/dist/tools/sessions-state-processor.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts +3 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +3 -2
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/workspace.js +1 -1
- package/factory-skills/factory-plan/SKILL.md +1 -1
- package/factory-skills/factory-triage/SKILL.md +18 -7
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attention-providers.js","names":[],"sources":["../../src/routes/attention-providers.ts"],"sourcesContent":["import { boardForWorkItem } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { decisionRetryable, overtakenDecisionIds } from '../rules/decision-applicability.js';\n/**\n * Per-kind attention providers. Each kind owns its counts, its bounded page\n * scan, and its wire item shape; the route layer k-way merges provider pages\n * on `occurredAt desc` with one resumable cursor per kind.\n */\n\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport type {\n WorkItemCommentRow,\n WorkItemCommentsStorage,\n WorkItemMentionRow,\n} from '../storage/domains/comments/base.js';\nimport type {\n FactoryAttentionIdentity,\n FactoryAttentionKind,\n FactoryAttentionReceiptRecord,\n FactoryDeferredDecisionRecord,\n FactoryDispatchStatus,\n WorkItemRow,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport {\n factoryAttentionKey,\n factoryDecisionAttentionIdentity,\n factoryMentionAttentionIdentity,\n} from '../storage/domains/work-items/base.js';\n\nexport type FactoryAttentionView = 'open' | 'unread' | 'archived';\n\nexport interface AttentionScope {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n}\n\nexport interface AttentionStreamPosition {\n occurredAt: Date;\n id: string;\n}\n\nexport interface AttentionEntry {\n occurredAt: Date;\n /** Position resuming the provider's stream right after this entry. */\n resumeCursor: AttentionStreamPosition;\n item: Record<string, unknown>;\n}\n\nexport interface AttentionPageArgs {\n view: FactoryAttentionView;\n search?: string;\n before?: AttentionStreamPosition;\n limit: number;\n}\n\nexport interface AttentionPageResult {\n entries: AttentionEntry[];\n /** More rows behind the scan once every returned entry is consumed. */\n hasMore: boolean;\n /** Resume point for a scan-budget stop past the last returned entry. */\n continuation?: AttentionStreamPosition;\n}\n\nexport interface AttentionCounts {\n open: number;\n unread: number;\n}\n\nexport interface AttentionLatest {\n key: string;\n at: Date;\n unread: boolean;\n}\n\nexport interface AttentionProvider {\n kind: FactoryAttentionKind;\n counts(scope: AttentionScope): Promise<AttentionCounts>;\n latest(scope: AttentionScope): Promise<AttentionLatest | null>;\n page(scope: AttentionScope, args: AttentionPageArgs): Promise<AttentionPageResult>;\n markAllRead(\n scope: AttentionScope,\n args: { before?: AttentionStreamPosition; now: Date },\n ): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }>;\n}\n\nexport const SCAN_PAGE_SIZE = 50;\n// Receipt filtering is bounded per request; the response cursor resumes after the last scan.\nconst MAX_RECEIPT_SCAN_PAGES = 4;\n\ninterface ScanBatch<T> {\n rows: T[];\n /** Set only when the page budget stopped a scan that still had rows behind it. */\n continuation?: AttentionStreamPosition;\n}\n\n/**\n * One bounded keyset scan, shared by every provider read. Walks newest-first\n * from `before` until the stream runs dry or the page budget is spent; the\n * final batch of a budget stop carries the position to resume from.\n */\nexport async function* scanBatches<T>(\n fetchBatch: (before?: AttentionStreamPosition) => Promise<{ rows: T[]; hasMore: boolean }>,\n positionOf: (row: T) => AttentionStreamPosition,\n before?: AttentionStreamPosition,\n): AsyncGenerator<ScanBatch<T>> {\n let cursor = before;\n for (let scanned = 1; scanned <= MAX_RECEIPT_SCAN_PAGES; scanned += 1) {\n const { rows, hasMore } = await fetchBatch(cursor);\n const last = rows.at(-1);\n if (!last) return;\n const position = positionOf(last);\n yield { rows, ...(hasMore && scanned === MAX_RECEIPT_SCAN_PAGES ? { continuation: position } : {}) };\n if (!hasMore) return;\n cursor = position;\n }\n}\n\n/** Fills a page from the scan, stopping at `limit` entries or at the scan budget. */\nexport async function collectPage<T>(\n batches: AsyncGenerator<ScanBatch<T>>,\n limit: number,\n toEntries: (rows: T[]) => Promise<AttentionEntry[]>,\n): Promise<AttentionPageResult> {\n const entries: AttentionEntry[] = [];\n for await (const batch of batches) {\n for (const entry of await toEntries(batch.rows)) {\n if (entries.length === limit) return { entries, hasMore: true };\n entries.push(entry);\n }\n if (batch.continuation) return { entries, hasMore: true, continuation: batch.continuation };\n }\n return { entries, hasMore: false };\n}\n\n/** Marks every scanned batch read, reporting where a budget stop left off. */\nexport async function markScanRead<T>(\n batches: AsyncGenerator<ScanBatch<T>>,\n markBatch: (rows: T[]) => Promise<void>,\n): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }> {\n for await (const batch of batches) {\n await markBatch(batch.rows);\n if (batch.continuation) return { hasMore: true, continuation: batch.continuation };\n }\n return { hasMore: false };\n}\n\nexport function factoryDecisionType(decision: FactoryDeferredDecisionRecord): string {\n return typeof decision.decision.type === 'string' ? decision.decision.type.slice(0, 64) : 'unknown';\n}\n\nexport function matchesView(view: FactoryAttentionView, receipt: FactoryAttentionReceiptRecord | undefined): boolean {\n if (view === 'archived') return receipt?.state === 'archived';\n if (view === 'unread') return receipt === undefined;\n return receipt?.state !== 'archived';\n}\n\nfunction attentionTarget(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined) {\n if (!item) return { kind: 'rules' as const };\n const role = typeof decision.decision.role === 'string' ? decision.decision.role : undefined;\n const session = role ? item.sessions[role] : undefined;\n if (session) {\n return {\n kind: 'thread' as const,\n sessionId: session.sessionId,\n threadId: session.threadId,\n };\n }\n return {\n kind: 'work-item' as const,\n workItemId: item.id,\n board: boardForWorkItem(item),\n };\n}\n\n/** One deferred-decision status seen as attention: failures and parked runs differ only by this. */\nexport interface DecisionAttentionSpec {\n kind: FactoryAttentionKind;\n status: FactoryDispatchStatus;\n identity(decision: FactoryDeferredDecisionRecord): FactoryAttentionIdentity;\n occurredAt(decision: FactoryDeferredDecisionRecord): Date;\n title(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined): string;\n detail(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined): string;\n extra?(decision: FactoryDeferredDecisionRecord, context: { overtaken: boolean }): Record<string, unknown>;\n matches(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined, search: string): boolean;\n}\n\nexport class DecisionAttentionProvider implements AttentionProvider {\n readonly kind: FactoryAttentionKind;\n readonly #workItems: WorkItemsStorage;\n readonly #spec: DecisionAttentionSpec;\n readonly #boards: BoardRegistry;\n\n constructor(\n { workItems, boards }: { workItems: WorkItemsStorage; boards: BoardRegistry },\n spec: DecisionAttentionSpec,\n ) {\n this.#workItems = workItems;\n this.#boards = boards;\n this.#spec = spec;\n this.kind = spec.kind;\n }\n\n async counts(scope: AttentionScope): Promise<AttentionCounts> {\n const [total, receiptCount, archivedCount] = await Promise.all([\n this.#workItems.countDeferredDecisionsByStatuses({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n statuses: [this.#spec.status],\n }),\n this.#workItems.countAttentionReceipts({ ...receiptScope(scope), kind: this.kind }),\n this.#workItems.countAttentionReceipts({ ...receiptScope(scope), kind: this.kind, state: 'archived' }),\n ]);\n return {\n open: Math.max(0, total - archivedCount),\n unread: Math.max(0, total - receiptCount),\n };\n }\n\n async latest(scope: AttentionScope): Promise<AttentionLatest | null> {\n const page = await this.#workItems.listDecisionPageByStatus({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n status: this.#spec.status,\n limit: 1,\n });\n const newest = page.decisions[0];\n if (!newest) return null;\n const identity = this.#spec.identity(newest);\n const receipts = await this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: [identity],\n });\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n at: this.#spec.occurredAt(newest),\n unread: receipts.length === 0,\n };\n }\n\n #scan(scope: AttentionScope, before?: AttentionStreamPosition) {\n return scanBatches<FactoryDeferredDecisionRecord>(\n async cursor => {\n const page = await this.#workItems.listDecisionPageByStatus({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n status: this.#spec.status,\n before: cursor,\n limit: SCAN_PAGE_SIZE,\n });\n return { rows: page.decisions, hasMore: page.hasMore };\n },\n decision => ({ occurredAt: this.#spec.occurredAt(decision), id: decision.id }),\n before,\n );\n }\n\n async page(scope: AttentionScope, { view, search, before, limit }: AttentionPageArgs): Promise<AttentionPageResult> {\n return collectPage(this.#scan(scope, before), limit, async decisions => {\n const [receiptByKey, itemById, overtaken] = await Promise.all([\n this.#receiptsFor(scope, decisions),\n this.#linkedItems(scope, decisions),\n overtakenDecisionIds(this.#workItems, this.#boards, scope, decisions),\n ]);\n const entries: AttentionEntry[] = [];\n for (const decision of decisions) {\n const identity = this.#spec.identity(decision);\n const receipt = receiptByKey.get(factoryAttentionKey(scope.factoryProjectId, identity));\n if (!matchesView(view, receipt)) continue;\n const item = decision.workItemId ? itemById.get(decision.workItemId) : undefined;\n if (search && !this.#spec.matches(decision, item, search)) continue;\n const occurredAt = this.#spec.occurredAt(decision);\n entries.push({\n occurredAt,\n resumeCursor: { occurredAt, id: decision.id },\n item: {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n kind: this.kind,\n decisionId: decision.id,\n occurrence: identity.occurrence,\n workItemId: decision.workItemId,\n title: this.#spec.title(decision, item),\n detail: this.#spec.detail(decision, item),\n decisionType: factoryDecisionType(decision),\n ...this.#spec.extra?.(decision, { overtaken: overtaken.has(decision.id) }),\n occurredAt: occurredAt.toISOString(),\n read: receipt !== undefined,\n archived: receipt?.state === 'archived',\n target: attentionTarget(decision, item),\n },\n });\n }\n return entries;\n });\n }\n\n async #receiptsFor(\n scope: AttentionScope,\n decisions: FactoryDeferredDecisionRecord[],\n ): Promise<Map<string, FactoryAttentionReceiptRecord>> {\n const receipts = await this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: decisions.map(decision => this.#spec.identity(decision)),\n });\n return new Map(receipts.map(receipt => [factoryAttentionKey(scope.factoryProjectId, receipt), receipt]));\n }\n\n async #linkedItems(\n scope: AttentionScope,\n decisions: FactoryDeferredDecisionRecord[],\n ): Promise<Map<string, WorkItemRow>> {\n const items = await this.#workItems.listByIds({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n ids: decisions.flatMap(decision => (decision.workItemId ? [decision.workItemId] : [])),\n });\n return new Map(items.map(item => [item.id, item]));\n }\n\n async markAllRead(\n scope: AttentionScope,\n { before, now }: { before?: AttentionStreamPosition; now: Date },\n ): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }> {\n return markScanRead(this.#scan(scope, before), async decisions => {\n await this.#workItems.markAttentionReceiptsRead({\n ...receiptScope(scope),\n identities: decisions.map(decision => this.#spec.identity(decision)),\n now,\n });\n });\n }\n}\n\nexport const failedDecisionAttentionSpec: DecisionAttentionSpec = {\n kind: 'automation-failed',\n status: 'failed',\n identity: decision => factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence),\n occurredAt: decision => decision.completedAt ?? decision.updatedAt,\n title: (decision, item) => item?.title ?? factoryDispatchFailureMetadata(decision.failureCode).label,\n detail: decision => decision.lastError?.slice(0, 512) ?? factoryDispatchFailureMetadata(decision.failureCode).label,\n extra: (decision, { overtaken }) => ({\n failureCode: decision.failureCode,\n canRetry: decisionRetryable(decision, overtaken),\n }),\n matches: (decision, item, search) =>\n item?.title.toLowerCase().includes(search) === true ||\n decision.lastError?.toLowerCase().includes(search) === true ||\n factoryDecisionType(decision).toLowerCase().includes(search),\n};\n\ninterface ResolvedMention {\n mention: WorkItemMentionRow;\n comment: WorkItemCommentRow;\n item: WorkItemRow;\n identity: FactoryAttentionIdentity;\n receipt: FactoryAttentionReceiptRecord | undefined;\n}\n\nexport class MentionAttentionProvider implements AttentionProvider {\n readonly kind = 'mention' as const;\n readonly #workItems: WorkItemsStorage;\n readonly #comments: WorkItemCommentsStorage;\n\n constructor({ workItems, comments }: { workItems: WorkItemsStorage; comments: WorkItemCommentsStorage }) {\n this.#workItems = workItems;\n this.#comments = comments;\n }\n\n #scan(scope: AttentionScope, before?: AttentionStreamPosition) {\n return scanBatches<WorkItemMentionRow>(\n async cursor => {\n const rows = await this.#comments.listMentionsForUser({\n ...receiptScope(scope),\n ...(cursor ? { before: cursor } : {}),\n limit: SCAN_PAGE_SIZE + 1,\n });\n return { rows: rows.slice(0, SCAN_PAGE_SIZE), hasMore: rows.length > SCAN_PAGE_SIZE };\n },\n mention => ({ occurredAt: mention.occurredAt, id: mention.id }),\n before,\n );\n }\n\n /**\n * Mention rows joined to what the inbox needs to show one — dropping the\n * ones it cannot: a deleted comment, or a work item gone from the project.\n */\n async #resolve(scope: AttentionScope, mentions: WorkItemMentionRow[]): Promise<ResolvedMention[]> {\n const [receipts, comments, items] = await Promise.all([\n this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: mentions.map(mention => factoryMentionAttentionIdentity(mention.commentId)),\n }),\n this.#comments.listByIds({\n orgId: scope.orgId,\n ids: [...new Set(mentions.map(mention => mention.commentId))],\n }),\n this.#workItems.listByIds({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n ids: [...new Set(mentions.map(mention => mention.workItemId))],\n }),\n ]);\n const receiptByKey = new Map(\n receipts.map(receipt => [factoryAttentionKey(scope.factoryProjectId, receipt), receipt]),\n );\n const commentById = new Map(comments.map(comment => [comment.id, comment]));\n const itemById = new Map(items.map(item => [item.id, item]));\n\n const resolved: ResolvedMention[] = [];\n for (const mention of mentions) {\n const comment = commentById.get(mention.commentId);\n const item = itemById.get(mention.workItemId);\n if (!comment || comment.deletedAt || !item) continue;\n const identity = factoryMentionAttentionIdentity(mention.commentId);\n resolved.push({\n mention,\n comment,\n item,\n identity,\n receipt: receiptByKey.get(factoryAttentionKey(scope.factoryProjectId, identity)),\n });\n }\n return resolved;\n }\n\n /**\n * Derived from the same bounded scan as `page`, never from raw aggregates:\n * the badge must count exactly what the views can show, down to stopping at\n * the same scan budget. Aggregates would count orphan mention rows the list\n * can never display or clear.\n */\n async counts(scope: AttentionScope): Promise<AttentionCounts> {\n let open = 0;\n let unread = 0;\n for await (const batch of this.#scan(scope)) {\n for (const { receipt } of await this.#resolve(scope, batch.rows)) {\n if (receipt?.state !== 'archived') open += 1;\n if (receipt === undefined) unread += 1;\n }\n }\n return { open, unread };\n }\n\n async latest(scope: AttentionScope): Promise<AttentionLatest | null> {\n const mentions = await this.#comments.listMentionsForUser({ ...receiptScope(scope), limit: 10 });\n const newest = (await this.#resolve(scope, mentions))[0];\n if (!newest) return null;\n return {\n key: factoryAttentionKey(scope.factoryProjectId, newest.identity),\n at: newest.mention.occurredAt,\n unread: newest.receipt === undefined,\n };\n }\n\n async page(scope: AttentionScope, { view, search, before, limit }: AttentionPageArgs): Promise<AttentionPageResult> {\n return collectPage(this.#scan(scope, before), limit, async mentions => {\n const entries: AttentionEntry[] = [];\n for (const resolved of await this.#resolve(scope, mentions)) {\n if (!matchesView(view, resolved.receipt)) continue;\n if (search && !matchesMentionSearch(resolved, search)) continue;\n entries.push({\n occurredAt: resolved.mention.occurredAt,\n resumeCursor: { occurredAt: resolved.mention.occurredAt, id: resolved.mention.id },\n item: toMentionItem(scope, resolved),\n });\n }\n return entries;\n });\n }\n\n async markAllRead(\n scope: AttentionScope,\n { before, now }: { before?: AttentionStreamPosition; now: Date },\n ): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }> {\n return markScanRead(this.#scan(scope, before), async mentions => {\n await this.#workItems.markAttentionReceiptsRead({\n ...receiptScope(scope),\n identities: mentions.map(mention => factoryMentionAttentionIdentity(mention.commentId)),\n now,\n });\n });\n }\n}\n\nfunction matchesMentionSearch({ item, comment }: ResolvedMention, search: string): boolean {\n return (\n item.title.toLowerCase().includes(search) ||\n comment.body.toLowerCase().includes(search) ||\n comment.author.displayName?.toLowerCase().includes(search) === true\n );\n}\n\nfunction toMentionItem(scope: AttentionScope, { mention, comment, item, identity, receipt }: ResolvedMention) {\n const authorName = comment.author.displayName;\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n kind: 'mention' as const,\n commentId: mention.commentId,\n occurrence: 0,\n workItemId: mention.workItemId,\n title: item.title,\n detail: comment.body.slice(0, 512),\n authorId: comment.author.id,\n ...(authorName ? { authorName } : {}),\n occurredAt: mention.occurredAt.toISOString(),\n read: receipt !== undefined,\n archived: receipt?.state === 'archived',\n target: {\n kind: 'work-item' as const,\n workItemId: mention.workItemId,\n board: boardForWorkItem(item),\n commentId: mention.commentId,\n },\n };\n}\n\nexport function receiptScope(scope: AttentionScope): { orgId: string; factoryProjectId: string; userId: string } {\n return { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId, userId: scope.userId };\n}\n"],"mappings":";;;;;;;;;;;AAuFA,MAAa,iBAAiB;AAE9B,MAAM,yBAAyB;;;;;;AAa/B,gBAAuB,YACrB,YACA,YACA,QAC8B;CAC9B,IAAI,SAAS;CACb,KAAK,IAAI,UAAU,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GACF,CAAC;EACH,CAAC;CACH;AACF;AAEA,SAAS,qBAAqB,EAAE,MAAM,WAA4B,QAAyB;CACzF,OACE,KAAK,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,KACxC,QAAQ,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM,KAC1C,QAAQ,OAAO,aAAa,YAAY,CAAC,CAAC,SAAS,MAAM,MAAM;AAEnE;AAEA,SAAS,cAAc,OAAuB,EAAE,SAAS,SAAS,MAAM,UAAU,WAA4B;CAC5G,MAAM,aAAa,QAAQ,OAAO;CAClC,OAAO;EACL,KAAK,oBAAoB,MAAM,kBAAkB,QAAQ;EACzD,MAAM;EACN,WAAW,QAAQ;EACnB,YAAY;EACZ,YAAY,QAAQ;EACpB,OAAO,KAAK;EACZ,QAAQ,QAAQ,KAAK,MAAM,GAAG,GAAG;EACjC,UAAU,QAAQ,OAAO;EACzB,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACnC,YAAY,QAAQ,WAAW,YAAY;EAC3C,MAAM,YAAY,KAAA;EAClB,UAAU,SAAS,UAAU;EAC7B,QAAQ;GACN,MAAM;GACN,YAAY,QAAQ;GACpB,OAAO,iBAAiB,IAAI;GAC5B,WAAW,QAAQ;EACrB;CACF;AACF;AAEA,SAAgB,aAAa,OAAoF;CAC/G,OAAO;EAAE,OAAO,MAAM;EAAO,kBAAkB,MAAM;EAAkB,QAAQ,MAAM;CAAO;AAC9F"}
|
|
1
|
+
{"version":3,"file":"attention-providers.js","names":[],"sources":["../../src/routes/attention-providers.ts"],"sourcesContent":["import { boardForWorkItem } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { decisionRetryable, overtakenDecisionIds } from '../rules/decision-applicability.js';\n/**\n * Per-kind attention providers. Each kind owns its counts, its bounded page\n * scan, and its wire item shape; the route layer k-way merges provider pages\n * on `occurredAt desc` with one resumable cursor per kind.\n */\n\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport type {\n WorkItemCommentRow,\n WorkItemCommentsStorage,\n WorkItemMentionRow,\n} from '../storage/domains/comments/base.js';\nimport type {\n FactoryAttentionIdentity,\n FactoryAttentionKind,\n FactoryAttentionReceiptRecord,\n FactoryDeferredDecisionRecord,\n FactoryDispatchStatus,\n WorkItemRow,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport {\n factoryAttentionKey,\n factoryDecisionAttentionIdentity,\n factoryMentionAttentionIdentity,\n} from '../storage/domains/work-items/base.js';\n\nexport type FactoryAttentionView = 'open' | 'unread' | 'archived';\n\nexport interface AttentionScope {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n}\n\nexport interface AttentionStreamPosition {\n occurredAt: Date;\n id: string;\n}\n\nexport interface AttentionEntry {\n occurredAt: Date;\n /** Position resuming the provider's stream right after this entry. */\n resumeCursor: AttentionStreamPosition;\n item: Record<string, unknown>;\n}\n\nexport interface AttentionPageArgs {\n view: FactoryAttentionView;\n search?: string;\n before?: AttentionStreamPosition;\n limit: number;\n}\n\nexport interface AttentionPageResult {\n entries: AttentionEntry[];\n /** More rows behind the scan once every returned entry is consumed. */\n hasMore: boolean;\n /** Resume point for a scan-budget stop past the last returned entry. */\n continuation?: AttentionStreamPosition;\n}\n\nexport interface AttentionCounts {\n open: number;\n unread: number;\n}\n\nexport interface AttentionLatest {\n key: string;\n at: Date;\n unread: boolean;\n}\n\nexport interface AttentionProvider {\n kind: FactoryAttentionKind;\n counts(scope: AttentionScope): Promise<AttentionCounts>;\n latest(scope: AttentionScope): Promise<AttentionLatest | null>;\n page(scope: AttentionScope, args: AttentionPageArgs): Promise<AttentionPageResult>;\n markAllRead(\n scope: AttentionScope,\n args: { before?: AttentionStreamPosition; now: Date },\n ): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }>;\n}\n\nexport const SCAN_PAGE_SIZE = 50;\n// Receipt filtering is bounded per request; the response cursor resumes after the last scan.\nconst MAX_RECEIPT_SCAN_PAGES = 4;\n\ninterface ScanBatch<T> {\n rows: T[];\n /** Set only when the page budget stopped a scan that still had rows behind it. */\n continuation?: AttentionStreamPosition;\n}\n\n/**\n * One bounded keyset scan, shared by every provider read. Walks newest-first\n * from `before` until the stream runs dry or the page budget is spent; the\n * final batch of a budget stop carries the position to resume from.\n */\nexport async function* scanBatches<T>(\n fetchBatch: (before?: AttentionStreamPosition) => Promise<{ rows: T[]; hasMore: boolean }>,\n positionOf: (row: T) => AttentionStreamPosition,\n before?: AttentionStreamPosition,\n): AsyncGenerator<ScanBatch<T>> {\n let cursor = before;\n for (let scanned = 1; scanned <= MAX_RECEIPT_SCAN_PAGES; scanned += 1) {\n const { rows, hasMore } = await fetchBatch(cursor);\n const last = rows.at(-1);\n if (!last) return;\n const position = positionOf(last);\n yield { rows, ...(hasMore && scanned === MAX_RECEIPT_SCAN_PAGES ? { continuation: position } : {}) };\n if (!hasMore) return;\n cursor = position;\n }\n}\n\n/** Fills a page from the scan, stopping at `limit` entries or at the scan budget. */\nexport async function collectPage<T>(\n batches: AsyncGenerator<ScanBatch<T>>,\n limit: number,\n toEntries: (rows: T[]) => Promise<AttentionEntry[]>,\n): Promise<AttentionPageResult> {\n const entries: AttentionEntry[] = [];\n for await (const batch of batches) {\n for (const entry of await toEntries(batch.rows)) {\n if (entries.length === limit) return { entries, hasMore: true };\n entries.push(entry);\n }\n if (batch.continuation) return { entries, hasMore: true, continuation: batch.continuation };\n }\n return { entries, hasMore: false };\n}\n\n/** Marks every scanned batch read, reporting where a budget stop left off. */\nexport async function markScanRead<T>(\n batches: AsyncGenerator<ScanBatch<T>>,\n markBatch: (rows: T[]) => Promise<void>,\n): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }> {\n for await (const batch of batches) {\n await markBatch(batch.rows);\n if (batch.continuation) return { hasMore: true, continuation: batch.continuation };\n }\n return { hasMore: false };\n}\n\nexport function factoryDecisionType(decision: FactoryDeferredDecisionRecord): string {\n return typeof decision.decision.type === 'string' ? decision.decision.type.slice(0, 64) : 'unknown';\n}\n\nexport function matchesView(view: FactoryAttentionView, receipt: FactoryAttentionReceiptRecord | undefined): boolean {\n if (view === 'archived') return receipt?.state === 'archived';\n if (view === 'unread') return receipt === undefined;\n return receipt?.state !== 'archived';\n}\n\nfunction attentionTarget(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined) {\n if (!item) return { kind: 'rules' as const };\n const role = typeof decision.decision.role === 'string' ? decision.decision.role : undefined;\n const session = role ? item.sessions[role] : undefined;\n if (session) {\n return {\n kind: 'thread' as const,\n sessionId: session.sessionId,\n threadId: session.threadId,\n };\n }\n return {\n kind: 'work-item' as const,\n workItemId: item.id,\n board: boardForWorkItem(item),\n };\n}\n\n/** One deferred-decision status seen as attention: failures and parked runs differ only by this. */\nexport interface DecisionAttentionSpec {\n kind: FactoryAttentionKind;\n status: FactoryDispatchStatus;\n identity(decision: FactoryDeferredDecisionRecord): FactoryAttentionIdentity;\n occurredAt(decision: FactoryDeferredDecisionRecord): Date;\n title(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined): string;\n detail(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined): string;\n extra?(decision: FactoryDeferredDecisionRecord, context: { overtaken: boolean }): Record<string, unknown>;\n matches(decision: FactoryDeferredDecisionRecord, item: WorkItemRow | undefined, search: string): boolean;\n}\n\nexport class DecisionAttentionProvider implements AttentionProvider {\n readonly kind: FactoryAttentionKind;\n readonly #workItems: WorkItemsStorage;\n readonly #spec: DecisionAttentionSpec;\n readonly #boards: ProjectBoardSource;\n\n constructor(\n { workItems, boards }: { workItems: WorkItemsStorage; boards: BoardRegistry | ProjectBoardSource },\n spec: DecisionAttentionSpec,\n ) {\n this.#workItems = workItems;\n this.#boards = toBoardSource(boards);\n this.#spec = spec;\n this.kind = spec.kind;\n }\n\n async counts(scope: AttentionScope): Promise<AttentionCounts> {\n const [total, receiptCount, archivedCount] = await Promise.all([\n this.#workItems.countDeferredDecisionsByStatuses({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n statuses: [this.#spec.status],\n }),\n this.#workItems.countAttentionReceipts({ ...receiptScope(scope), kind: this.kind }),\n this.#workItems.countAttentionReceipts({ ...receiptScope(scope), kind: this.kind, state: 'archived' }),\n ]);\n return {\n open: Math.max(0, total - archivedCount),\n unread: Math.max(0, total - receiptCount),\n };\n }\n\n async latest(scope: AttentionScope): Promise<AttentionLatest | null> {\n const page = await this.#workItems.listDecisionPageByStatus({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n status: this.#spec.status,\n limit: 1,\n });\n const newest = page.decisions[0];\n if (!newest) return null;\n const identity = this.#spec.identity(newest);\n const receipts = await this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: [identity],\n });\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n at: this.#spec.occurredAt(newest),\n unread: receipts.length === 0,\n };\n }\n\n #scan(scope: AttentionScope, before?: AttentionStreamPosition) {\n return scanBatches<FactoryDeferredDecisionRecord>(\n async cursor => {\n const page = await this.#workItems.listDecisionPageByStatus({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n status: this.#spec.status,\n before: cursor,\n limit: SCAN_PAGE_SIZE,\n });\n return { rows: page.decisions, hasMore: page.hasMore };\n },\n decision => ({ occurredAt: this.#spec.occurredAt(decision), id: decision.id }),\n before,\n );\n }\n\n async page(scope: AttentionScope, { view, search, before, limit }: AttentionPageArgs): Promise<AttentionPageResult> {\n return collectPage(this.#scan(scope, before), limit, async decisions => {\n const [receiptByKey, itemById, overtaken] = await Promise.all([\n this.#receiptsFor(scope, decisions),\n this.#linkedItems(scope, decisions),\n this.#boards.load(scope).then(boards => overtakenDecisionIds(this.#workItems, boards, scope, decisions)),\n ]);\n const entries: AttentionEntry[] = [];\n for (const decision of decisions) {\n const identity = this.#spec.identity(decision);\n const receipt = receiptByKey.get(factoryAttentionKey(scope.factoryProjectId, identity));\n if (!matchesView(view, receipt)) continue;\n const item = decision.workItemId ? itemById.get(decision.workItemId) : undefined;\n if (search && !this.#spec.matches(decision, item, search)) continue;\n const occurredAt = this.#spec.occurredAt(decision);\n entries.push({\n occurredAt,\n resumeCursor: { occurredAt, id: decision.id },\n item: {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n kind: this.kind,\n decisionId: decision.id,\n occurrence: identity.occurrence,\n workItemId: decision.workItemId,\n title: this.#spec.title(decision, item),\n detail: this.#spec.detail(decision, item),\n decisionType: factoryDecisionType(decision),\n ...this.#spec.extra?.(decision, { overtaken: overtaken.has(decision.id) }),\n occurredAt: occurredAt.toISOString(),\n read: receipt !== undefined,\n archived: receipt?.state === 'archived',\n target: attentionTarget(decision, item),\n },\n });\n }\n return entries;\n });\n }\n\n async #receiptsFor(\n scope: AttentionScope,\n decisions: FactoryDeferredDecisionRecord[],\n ): Promise<Map<string, FactoryAttentionReceiptRecord>> {\n const receipts = await this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: decisions.map(decision => this.#spec.identity(decision)),\n });\n return new Map(receipts.map(receipt => [factoryAttentionKey(scope.factoryProjectId, receipt), receipt]));\n }\n\n async #linkedItems(\n scope: AttentionScope,\n decisions: FactoryDeferredDecisionRecord[],\n ): Promise<Map<string, WorkItemRow>> {\n const items = await this.#workItems.listByIds({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n ids: decisions.flatMap(decision => (decision.workItemId ? [decision.workItemId] : [])),\n });\n return new Map(items.map(item => [item.id, item]));\n }\n\n async markAllRead(\n scope: AttentionScope,\n { before, now }: { before?: AttentionStreamPosition; now: Date },\n ): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }> {\n return markScanRead(this.#scan(scope, before), async decisions => {\n await this.#workItems.markAttentionReceiptsRead({\n ...receiptScope(scope),\n identities: decisions.map(decision => this.#spec.identity(decision)),\n now,\n });\n });\n }\n}\n\nexport const failedDecisionAttentionSpec: DecisionAttentionSpec = {\n kind: 'automation-failed',\n status: 'failed',\n identity: decision => factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence),\n occurredAt: decision => decision.completedAt ?? decision.updatedAt,\n title: (decision, item) => item?.title ?? factoryDispatchFailureMetadata(decision.failureCode).label,\n detail: decision => decision.lastError?.slice(0, 512) ?? factoryDispatchFailureMetadata(decision.failureCode).label,\n extra: (decision, { overtaken }) => ({\n failureCode: decision.failureCode,\n canRetry: decisionRetryable(decision, overtaken),\n }),\n matches: (decision, item, search) =>\n item?.title.toLowerCase().includes(search) === true ||\n decision.lastError?.toLowerCase().includes(search) === true ||\n factoryDecisionType(decision).toLowerCase().includes(search),\n};\n\ninterface ResolvedMention {\n mention: WorkItemMentionRow;\n comment: WorkItemCommentRow;\n item: WorkItemRow;\n identity: FactoryAttentionIdentity;\n receipt: FactoryAttentionReceiptRecord | undefined;\n}\n\nexport class MentionAttentionProvider implements AttentionProvider {\n readonly kind = 'mention' as const;\n readonly #workItems: WorkItemsStorage;\n readonly #comments: WorkItemCommentsStorage;\n\n constructor({ workItems, comments }: { workItems: WorkItemsStorage; comments: WorkItemCommentsStorage }) {\n this.#workItems = workItems;\n this.#comments = comments;\n }\n\n #scan(scope: AttentionScope, before?: AttentionStreamPosition) {\n return scanBatches<WorkItemMentionRow>(\n async cursor => {\n const rows = await this.#comments.listMentionsForUser({\n ...receiptScope(scope),\n ...(cursor ? { before: cursor } : {}),\n limit: SCAN_PAGE_SIZE + 1,\n });\n return { rows: rows.slice(0, SCAN_PAGE_SIZE), hasMore: rows.length > SCAN_PAGE_SIZE };\n },\n mention => ({ occurredAt: mention.occurredAt, id: mention.id }),\n before,\n );\n }\n\n /**\n * Mention rows joined to what the inbox needs to show one — dropping the\n * ones it cannot: a deleted comment, or a work item gone from the project.\n */\n async #resolve(scope: AttentionScope, mentions: WorkItemMentionRow[]): Promise<ResolvedMention[]> {\n const [receipts, comments, items] = await Promise.all([\n this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: mentions.map(mention => factoryMentionAttentionIdentity(mention.commentId)),\n }),\n this.#comments.listByIds({\n orgId: scope.orgId,\n ids: [...new Set(mentions.map(mention => mention.commentId))],\n }),\n this.#workItems.listByIds({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n ids: [...new Set(mentions.map(mention => mention.workItemId))],\n }),\n ]);\n const receiptByKey = new Map(\n receipts.map(receipt => [factoryAttentionKey(scope.factoryProjectId, receipt), receipt]),\n );\n const commentById = new Map(comments.map(comment => [comment.id, comment]));\n const itemById = new Map(items.map(item => [item.id, item]));\n\n const resolved: ResolvedMention[] = [];\n for (const mention of mentions) {\n const comment = commentById.get(mention.commentId);\n const item = itemById.get(mention.workItemId);\n if (!comment || comment.deletedAt || !item) continue;\n const identity = factoryMentionAttentionIdentity(mention.commentId);\n resolved.push({\n mention,\n comment,\n item,\n identity,\n receipt: receiptByKey.get(factoryAttentionKey(scope.factoryProjectId, identity)),\n });\n }\n return resolved;\n }\n\n /**\n * Derived from the same bounded scan as `page`, never from raw aggregates:\n * the badge must count exactly what the views can show, down to stopping at\n * the same scan budget. Aggregates would count orphan mention rows the list\n * can never display or clear.\n */\n async counts(scope: AttentionScope): Promise<AttentionCounts> {\n let open = 0;\n let unread = 0;\n for await (const batch of this.#scan(scope)) {\n for (const { receipt } of await this.#resolve(scope, batch.rows)) {\n if (receipt?.state !== 'archived') open += 1;\n if (receipt === undefined) unread += 1;\n }\n }\n return { open, unread };\n }\n\n async latest(scope: AttentionScope): Promise<AttentionLatest | null> {\n const mentions = await this.#comments.listMentionsForUser({ ...receiptScope(scope), limit: 10 });\n const newest = (await this.#resolve(scope, mentions))[0];\n if (!newest) return null;\n return {\n key: factoryAttentionKey(scope.factoryProjectId, newest.identity),\n at: newest.mention.occurredAt,\n unread: newest.receipt === undefined,\n };\n }\n\n async page(scope: AttentionScope, { view, search, before, limit }: AttentionPageArgs): Promise<AttentionPageResult> {\n return collectPage(this.#scan(scope, before), limit, async mentions => {\n const entries: AttentionEntry[] = [];\n for (const resolved of await this.#resolve(scope, mentions)) {\n if (!matchesView(view, resolved.receipt)) continue;\n if (search && !matchesMentionSearch(resolved, search)) continue;\n entries.push({\n occurredAt: resolved.mention.occurredAt,\n resumeCursor: { occurredAt: resolved.mention.occurredAt, id: resolved.mention.id },\n item: toMentionItem(scope, resolved),\n });\n }\n return entries;\n });\n }\n\n async markAllRead(\n scope: AttentionScope,\n { before, now }: { before?: AttentionStreamPosition; now: Date },\n ): Promise<{ hasMore: boolean; continuation?: AttentionStreamPosition }> {\n return markScanRead(this.#scan(scope, before), async mentions => {\n await this.#workItems.markAttentionReceiptsRead({\n ...receiptScope(scope),\n identities: mentions.map(mention => factoryMentionAttentionIdentity(mention.commentId)),\n now,\n });\n });\n }\n}\n\nfunction matchesMentionSearch({ item, comment }: ResolvedMention, search: string): boolean {\n return (\n item.title.toLowerCase().includes(search) ||\n comment.body.toLowerCase().includes(search) ||\n comment.author.displayName?.toLowerCase().includes(search) === true\n );\n}\n\nfunction toMentionItem(scope: AttentionScope, { mention, comment, item, identity, receipt }: ResolvedMention) {\n const authorName = comment.author.displayName;\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n kind: 'mention' as const,\n commentId: mention.commentId,\n occurrence: 0,\n workItemId: mention.workItemId,\n title: item.title,\n detail: comment.body.slice(0, 512),\n authorId: comment.author.id,\n ...(authorName ? { authorName } : {}),\n occurredAt: mention.occurredAt.toISOString(),\n read: receipt !== undefined,\n archived: receipt?.state === 'archived',\n target: {\n kind: 'work-item' as const,\n workItemId: mention.workItemId,\n board: boardForWorkItem(item),\n commentId: mention.commentId,\n },\n };\n}\n\nexport function receiptScope(scope: AttentionScope): { orgId: string; factoryProjectId: string; userId: string } {\n return { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId, userId: scope.userId };\n}\n"],"mappings":";;;;;;;;;;;;AAyFA,MAAa,iBAAiB;AAE9B,MAAM,yBAAyB;;;;;;AAa/B,gBAAuB,YACrB,YACA,YACA,QAC8B;CAC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AAW,0BAA0B;IAC9C,GAAG,aAAa,KAAK;IACrB,YAAY,SAAS,KAAI,YAAW,gCAAgC,QAAQ,SAAS,CAAC;IACtF;GACF,CAAC;EACH,CAAC;CACH;AACF;AAEA,SAAS,qBAAqB,EAAE,MAAM,WAA4B,QAAyB;CACzF,OACE,KAAK,MAAM,YAAY,CAAC,CAAC,SAAS,MAAM,KACxC,QAAQ,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM,KAC1C,QAAQ,OAAO,aAAa,YAAY,CAAC,CAAC,SAAS,MAAM,MAAM;AAEnE;AAEA,SAAS,cAAc,OAAuB,EAAE,SAAS,SAAS,MAAM,UAAU,WAA4B;CAC5G,MAAM,aAAa,QAAQ,OAAO;CAClC,OAAO;EACL,KAAK,oBAAoB,MAAM,kBAAkB,QAAQ;EACzD,MAAM;EACN,WAAW,QAAQ;EACnB,YAAY;EACZ,YAAY,QAAQ;EACpB,OAAO,KAAK;EACZ,QAAQ,QAAQ,KAAK,MAAM,GAAG,GAAG;EACjC,UAAU,QAAQ,OAAO;EACzB,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACnC,YAAY,QAAQ,WAAW,YAAY;EAC3C,MAAM,YAAY,KAAA;EAClB,UAAU,SAAS,UAAU;EAC7B,QAAQ;GACN,MAAM;GACN,YAAY,QAAQ;GACpB,OAAO,iBAAiB,IAAI;GAC5B,WAAW,QAAQ;EACrB;CACF;AACF;AAEA,SAAgB,aAAa,OAAoF;CAC/G,OAAO;EAAE,OAAO,MAAM;EAAO,kBAAkB,MAAM;EAAkB,QAAQ,MAAM;CAAO;AAC9F"}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import type { ApiRoute } from '@mastra/core/server';
|
|
7
7
|
import type { BoardRegistry } from '../boards/index.js';
|
|
8
|
+
import type { ProjectBoardSource } from '../boards/project-boards.js';
|
|
8
9
|
import type { LiveSessions } from '../session/live-sessions.js';
|
|
9
10
|
import type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';
|
|
10
11
|
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
@@ -12,7 +13,7 @@ import type { AttentionScope } from './attention-providers.js';
|
|
|
12
13
|
export { factoryDecisionType } from './attention-providers.js';
|
|
13
14
|
interface AttentionRouteDependencies {
|
|
14
15
|
workItems: WorkItemsStorage;
|
|
15
|
-
boards: BoardRegistry;
|
|
16
|
+
boards: BoardRegistry | ProjectBoardSource;
|
|
16
17
|
comments: WorkItemCommentsStorage;
|
|
17
18
|
liveSessions: Pick<LiveSessions, 'parked' | 'parkedIn'>;
|
|
18
19
|
resolveProject(context: unknown): Promise<AttentionScope | {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attention.d.ts","sourceRoot":"","sources":["../../src/routes/attention.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"attention.d.ts","sourceRoot":"","sources":["../../src/routes/attention.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEtE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AACnF,OAAO,KAAK,EAGV,gBAAgB,EACjB,MAAM,uCAAuC,CAAC;AAK/C,OAAO,KAAK,EAGV,cAAc,EAEf,MAAM,0BAA0B,CAAC;AAQlC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAE/D,UAAU,0BAA0B;IAClC,SAAS,EAAE,gBAAgB,CAAC;IAC5B,MAAM,EAAE,aAAa,GAAG,kBAAkB,CAAC;IAC3C,QAAQ,EAAE,uBAAuB,CAAC;IAClC,YAAY,EAAE,IAAI,CAAC,YAAY,EAAE,QAAQ,GAAG,UAAU,CAAC,CAAC;IACxD,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,GAAG;QAAE,QAAQ,EAAE,QAAQ,CAAA;KAAE,CAAC,CAAC;CACpF;AA0HD,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,0BAA0B,GAAG,QAAQ,EAAE,CA2HzF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attention.js","names":[],"sources":["../../src/routes/attention.ts"],"sourcesContent":["/**\n * Attention routes: k-way merge of the per-kind providers on `occurredAt desc`.\n * The wire cursor is a per-kind map — each kind's stream resumes independently,\n * `null` meaning \"not started yet\", an absent kind meaning \"exhausted\".\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { BoardRegistry } from '../boards/index.js';\n\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';\nimport type {\n FactoryAttentionKind,\n FactoryAttentionReceiptAction,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { factoryAttentionKey } from '../storage/domains/work-items/base.js';\nimport { ActivityAttentionProvider } from './attention-activity.js';\nimport { ParkedRunAttentionProvider } from './attention-parked.js';\nimport { proposedDecisionAttentionSpec } from './attention-proposed.js';\nimport type {\n AttentionPageResult,\n AttentionProvider,\n AttentionScope,\n AttentionStreamPosition,\n} from './attention-providers.js';\nimport {\n DecisionAttentionProvider,\n failedDecisionAttentionSpec,\n MentionAttentionProvider,\n} from './attention-providers.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\n\nexport { factoryDecisionType } from './attention-providers.js';\n\ninterface AttentionRouteDependencies {\n workItems: WorkItemsStorage;\n boards: BoardRegistry;\n comments: WorkItemCommentsStorage;\n liveSessions: Pick<LiveSessions, 'parked' | 'parkedIn'>;\n resolveProject(context: unknown): Promise<AttentionScope | { response: Response }>;\n}\n\ntype AttentionCursorMap = Map<FactoryAttentionKind, AttentionStreamPosition | undefined>;\n\nfunction encodeAttentionCursor(cursors: AttentionCursorMap): string {\n const wire: Record<string, [string, string] | null> = {};\n for (const [kind, position] of cursors) {\n wire[kind] = position ? [position.occurredAt.toISOString(), position.id] : null;\n }\n return Buffer.from(JSON.stringify(wire), 'utf8').toString('base64url');\n}\n\ninterface MergedAttentionPage {\n items: Array<Record<string, unknown>>;\n hasMore: boolean;\n nextCursor?: string;\n}\n\n/**\n * Take the newest `limit` entries across provider pages. Each kind's next\n * cursor is the resume position of its last consumed entry; a kind consumed to\n * the end inherits the provider's own continuation.\n */\nfunction mergeAttentionPages(\n pages: Array<{\n kind: FactoryAttentionKind;\n incoming: AttentionStreamPosition | undefined;\n result: AttentionPageResult;\n }>,\n limit: number,\n): MergedAttentionPage {\n const consumed = new Map(pages.map(page => [page.kind, 0]));\n const items: Array<Record<string, unknown>> = [];\n while (items.length < limit) {\n let best: { kind: FactoryAttentionKind; at: number } | undefined;\n for (const page of pages) {\n const next = page.result.entries[consumed.get(page.kind) ?? 0];\n if (!next) continue;\n const at = next.occurredAt.getTime();\n if (!best || at > best.at) best = { kind: page.kind, at };\n }\n if (!best) break;\n const index = consumed.get(best.kind) ?? 0;\n const entry = pages.find(page => page.kind === best.kind)?.result.entries[index];\n if (!entry) break;\n items.push(entry.item);\n consumed.set(best.kind, index + 1);\n }\n\n const nextCursors: AttentionCursorMap = new Map();\n let hasMore = false;\n for (const page of pages) {\n const used = consumed.get(page.kind) ?? 0;\n const entries = page.result.entries;\n if (used < entries.length) {\n hasMore = true;\n const lastConsumed = used > 0 ? entries[used - 1] : undefined;\n nextCursors.set(page.kind, lastConsumed ? lastConsumed.resumeCursor : page.incoming);\n continue;\n }\n if (page.result.hasMore) {\n hasMore = true;\n nextCursors.set(page.kind, page.result.continuation ?? entries.at(-1)?.resumeCursor ?? page.incoming);\n }\n }\n return {\n items,\n hasMore,\n ...(hasMore && nextCursors.size > 0 ? { nextCursor: encodeAttentionCursor(nextCursors) } : {}),\n };\n}\n\nfunction receiptRoute(\n dependencies: AttentionRouteDependencies,\n verb: 'read' | 'archive' | 'restore',\n action: FactoryAttentionReceiptAction,\n): ApiRoute {\n const contract =\n verb === 'read'\n ? FACTORY_ROUTE_CONTRACTS.attentionRead\n : verb === 'archive'\n ? FACTORY_ROUTE_CONTRACTS.attentionArchive\n : FACTORY_ROUTE_CONTRACTS.attentionRestore;\n return registerApiRoute(contract.path, {\n method: contract.method,\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const parsedPath = contract.pathSchema.safeParse({\n id: resolved.factoryProjectId,\n kind: context.req.param('kind'),\n sourceId: context.req.param('sourceId'),\n occurrence: context.req.param('occurrence'),\n });\n if (!parsedPath.success) return context.json({ error: 'invalid_attention_item' }, 422);\n const { kind, sourceId, occurrence } = parsedPath.data;\n const stillParked =\n kind !== 'agent-waiting' || dependencies.liveSessions.parked(sourceId)?.suspendedAt === occurrence;\n if (!stillParked) return context.json({ error: 'attention_item_not_current' }, 409);\n await dependencies.workItems.ensureReady();\n const receipt = await dependencies.workItems.setAttentionReceipt({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n userId: resolved.userId,\n identity: { kind, sourceId, occurrence },\n action,\n now: new Date(),\n });\n if (!receipt) return context.json({ error: 'attention_item_not_current' }, 409);\n return context.json({\n receipt: {\n key: factoryAttentionKey(resolved.factoryProjectId, receipt),\n state: receipt.state,\n readAt: receipt.readAt.toISOString(),\n archivedAt: receipt.archivedAt?.toISOString() ?? null,\n },\n });\n },\n });\n}\n\nexport function buildAttentionRoutes(dependencies: AttentionRouteDependencies): ApiRoute[] {\n const { workItems, boards, comments, liveSessions } = dependencies;\n const providers: AttentionProvider[] = [\n new DecisionAttentionProvider({ workItems, boards }, failedDecisionAttentionSpec),\n new DecisionAttentionProvider({ workItems, boards }, proposedDecisionAttentionSpec),\n new MentionAttentionProvider({ workItems, comments }),\n new ActivityAttentionProvider({ workItems, comments }),\n new ParkedRunAttentionProvider({ workItems, liveSessions }),\n ];\n\n return [\n registerApiRoute(FACTORY_ROUTE_CONTRACTS.attentionList.path, {\n method: FACTORY_ROUTE_CONTRACTS.attentionList.method,\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const query = FACTORY_ROUTE_CONTRACTS.attentionList.querySchema.safeParse({\n view: context.req.query('view'),\n kind: context.req.queries('kind'),\n before: context.req.query('before'),\n limit: context.req.query('limit'),\n search: context.req.query('search'),\n });\n if (!query.success) {\n const field = query.error.issues[0]?.path[0];\n return context.json(\n {\n error:\n field === 'kind'\n ? 'invalid_attention_kind'\n : field === 'before'\n ? 'invalid_cursor'\n : 'invalid_attention_view',\n },\n 400,\n );\n }\n const { view, before, search, limit } = query.data;\n const kinds = query.data.kind ?? providers.map(provider => provider.kind);\n await workItems.ensureReady();\n await comments.ensureReady();\n\n const active = providers.filter(\n provider => kinds.includes(provider.kind) && (!before || before.has(provider.kind)),\n );\n\n const [summaries, pages] = await Promise.all([\n Promise.all(\n providers.map(async provider => ({\n kind: provider.kind,\n counts: await provider.counts(resolved),\n latest: await provider.latest(resolved),\n })),\n ),\n Promise.all(\n active.map(async provider => ({\n kind: provider.kind,\n incoming: before?.get(provider.kind),\n result: await provider.page(resolved, {\n view,\n ...(search ? { search } : {}),\n before: before?.get(provider.kind),\n limit,\n }),\n })),\n ),\n ]);\n\n const merged = mergeAttentionPages(pages, limit);\n\n return context.json({\n items: merged.items,\n kinds: Object.fromEntries(\n summaries.map(summary => [\n summary.kind,\n {\n ...summary.counts,\n latest: summary.latest ? { ...summary.latest, at: summary.latest.at.toISOString() } : null,\n },\n ]),\n ),\n hasMore: merged.hasMore,\n ...(merged.nextCursor ? { nextCursor: merged.nextCursor } : {}),\n });\n },\n }),\n registerApiRoute(FACTORY_ROUTE_CONTRACTS.attentionReadAll.path, {\n method: FACTORY_ROUTE_CONTRACTS.attentionReadAll.method,\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const query = FACTORY_ROUTE_CONTRACTS.attentionReadAll.querySchema.safeParse({\n before: context.req.query('before'),\n });\n if (!query.success) return context.json({ error: 'invalid_cursor' }, 400);\n const { before } = query.data;\n await workItems.ensureReady();\n await comments.ensureReady();\n\n const now = new Date();\n const active = providers.filter(provider => !before || before.has(provider.kind));\n const nextCursors: AttentionCursorMap = new Map();\n let hasMore = false;\n for (const provider of active) {\n const result = await provider.markAllRead(resolved, { before: before?.get(provider.kind), now });\n if (result.hasMore) {\n hasMore = true;\n if (result.continuation) nextCursors.set(provider.kind, result.continuation);\n }\n }\n return context.json({\n ok: true,\n hasMore,\n ...(hasMore && nextCursors.size > 0 ? { nextCursor: encodeAttentionCursor(nextCursors) } : {}),\n });\n },\n }),\n receiptRoute(dependencies, 'read', 'read'),\n receiptRoute(dependencies, 'archive', 'archive'),\n receiptRoute(dependencies, 'restore', 'restore'),\n ];\n}\n"],"mappings":";;;;;;;;AA8CA,SAAS,sBAAsB,SAAqC;CAClE,MAAM,OAAgD,CAAC;CACvD,KAAK,MAAM,CAAC,MAAM,aAAa,SAC7B,KAAK,QAAQ,WAAW,CAAC,SAAS,WAAW,YAAY,GAAG,SAAS,EAAE,IAAI;CAE7E,OAAO,OAAO,KAAK,KAAK,UAAU,IAAI,GAAG,MAAM,CAAC,CAAC,SAAS,WAAW;AACvE;;;;;;AAaA,SAAS,oBACP,OAKA,OACqB;CACrB,MAAM,WAAW,IAAI,IAAI,MAAM,KAAI,SAAQ,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC;CAC1D,MAAM,QAAwC,CAAC;CAC/C,OAAO,MAAM,SAAS,O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AY,CAAC,UAAU,OAAO,IAAI,SAAS,IAAI,CAAC;IAChF,MAAM,8BAAkC,IAAI,IAAI;IAChD,IAAI,UAAU;IACd,KAAK,MAAM,YAAY,QAAQ;KAC7B,MAAM,SAAS,MAAM,SAAS,YAAY,UAAU;MAAE,QAAQ,QAAQ,IAAI,SAAS,IAAI;MAAG;KAAI,CAAC;KAC/F,IAAI,OAAO,SAAS;MAClB,UAAU;MACV,IAAI,OAAO,cAAc,YAAY,IAAI,SAAS,MAAM,OAAO,YAAY;KAC7E;IACF;IACA,OAAO,QAAQ,KAAK;KAClB,IAAI;KACJ;KACA,GAAI,WAAW,YAAY,OAAO,IAAI,EAAE,YAAY,sBAAsB,WAAW,EAAE,IAAI,CAAC;IAC9F,CAAC;GACH;EACF,CAAC;EACD,aAAa,cAAc,QAAQ,MAAM;EACzC,aAAa,cAAc,WAAW,SAAS;EAC/C,aAAa,cAAc,WAAW,SAAS;CACjD;AACF"}
|
|
1
|
+
{"version":3,"file":"attention.js","names":[],"sources":["../../src/routes/attention.ts"],"sourcesContent":["/**\n * Attention routes: k-way merge of the per-kind providers on `occurredAt desc`.\n * The wire cursor is a per-kind map — each kind's stream resumes independently,\n * `null` meaning \"not started yet\", an absent kind meaning \"exhausted\".\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\n\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';\nimport type {\n FactoryAttentionKind,\n FactoryAttentionReceiptAction,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { factoryAttentionKey } from '../storage/domains/work-items/base.js';\nimport { ActivityAttentionProvider } from './attention-activity.js';\nimport { ParkedRunAttentionProvider } from './attention-parked.js';\nimport { proposedDecisionAttentionSpec } from './attention-proposed.js';\nimport type {\n AttentionPageResult,\n AttentionProvider,\n AttentionScope,\n AttentionStreamPosition,\n} from './attention-providers.js';\nimport {\n DecisionAttentionProvider,\n failedDecisionAttentionSpec,\n MentionAttentionProvider,\n} from './attention-providers.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\n\nexport { factoryDecisionType } from './attention-providers.js';\n\ninterface AttentionRouteDependencies {\n workItems: WorkItemsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n comments: WorkItemCommentsStorage;\n liveSessions: Pick<LiveSessions, 'parked' | 'parkedIn'>;\n resolveProject(context: unknown): Promise<AttentionScope | { response: Response }>;\n}\n\ntype AttentionCursorMap = Map<FactoryAttentionKind, AttentionStreamPosition | undefined>;\n\nfunction encodeAttentionCursor(cursors: AttentionCursorMap): string {\n const wire: Record<string, [string, string] | null> = {};\n for (const [kind, position] of cursors) {\n wire[kind] = position ? [position.occurredAt.toISOString(), position.id] : null;\n }\n return Buffer.from(JSON.stringify(wire), 'utf8').toString('base64url');\n}\n\ninterface MergedAttentionPage {\n items: Array<Record<string, unknown>>;\n hasMore: boolean;\n nextCursor?: string;\n}\n\n/**\n * Take the newest `limit` entries across provider pages. Each kind's next\n * cursor is the resume position of its last consumed entry; a kind consumed to\n * the end inherits the provider's own continuation.\n */\nfunction mergeAttentionPages(\n pages: Array<{\n kind: FactoryAttentionKind;\n incoming: AttentionStreamPosition | undefined;\n result: AttentionPageResult;\n }>,\n limit: number,\n): MergedAttentionPage {\n const consumed = new Map(pages.map(page => [page.kind, 0]));\n const items: Array<Record<string, unknown>> = [];\n while (items.length < limit) {\n let best: { kind: FactoryAttentionKind; at: number } | undefined;\n for (const page of pages) {\n const next = page.result.entries[consumed.get(page.kind) ?? 0];\n if (!next) continue;\n const at = next.occurredAt.getTime();\n if (!best || at > best.at) best = { kind: page.kind, at };\n }\n if (!best) break;\n const index = consumed.get(best.kind) ?? 0;\n const entry = pages.find(page => page.kind === best.kind)?.result.entries[index];\n if (!entry) break;\n items.push(entry.item);\n consumed.set(best.kind, index + 1);\n }\n\n const nextCursors: AttentionCursorMap = new Map();\n let hasMore = false;\n for (const page of pages) {\n const used = consumed.get(page.kind) ?? 0;\n const entries = page.result.entries;\n if (used < entries.length) {\n hasMore = true;\n const lastConsumed = used > 0 ? entries[used - 1] : undefined;\n nextCursors.set(page.kind, lastConsumed ? lastConsumed.resumeCursor : page.incoming);\n continue;\n }\n if (page.result.hasMore) {\n hasMore = true;\n nextCursors.set(page.kind, page.result.continuation ?? entries.at(-1)?.resumeCursor ?? page.incoming);\n }\n }\n return {\n items,\n hasMore,\n ...(hasMore && nextCursors.size > 0 ? { nextCursor: encodeAttentionCursor(nextCursors) } : {}),\n };\n}\n\nfunction receiptRoute(\n dependencies: AttentionRouteDependencies,\n verb: 'read' | 'archive' | 'restore',\n action: FactoryAttentionReceiptAction,\n): ApiRoute {\n const contract =\n verb === 'read'\n ? FACTORY_ROUTE_CONTRACTS.attentionRead\n : verb === 'archive'\n ? FACTORY_ROUTE_CONTRACTS.attentionArchive\n : FACTORY_ROUTE_CONTRACTS.attentionRestore;\n return registerApiRoute(contract.path, {\n method: contract.method,\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const parsedPath = contract.pathSchema.safeParse({\n id: resolved.factoryProjectId,\n kind: context.req.param('kind'),\n sourceId: context.req.param('sourceId'),\n occurrence: context.req.param('occurrence'),\n });\n if (!parsedPath.success) return context.json({ error: 'invalid_attention_item' }, 422);\n const { kind, sourceId, occurrence } = parsedPath.data;\n const stillParked =\n kind !== 'agent-waiting' || dependencies.liveSessions.parked(sourceId)?.suspendedAt === occurrence;\n if (!stillParked) return context.json({ error: 'attention_item_not_current' }, 409);\n await dependencies.workItems.ensureReady();\n const receipt = await dependencies.workItems.setAttentionReceipt({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n userId: resolved.userId,\n identity: { kind, sourceId, occurrence },\n action,\n now: new Date(),\n });\n if (!receipt) return context.json({ error: 'attention_item_not_current' }, 409);\n return context.json({\n receipt: {\n key: factoryAttentionKey(resolved.factoryProjectId, receipt),\n state: receipt.state,\n readAt: receipt.readAt.toISOString(),\n archivedAt: receipt.archivedAt?.toISOString() ?? null,\n },\n });\n },\n });\n}\n\nexport function buildAttentionRoutes(dependencies: AttentionRouteDependencies): ApiRoute[] {\n const { workItems, boards, comments, liveSessions } = dependencies;\n const providers: AttentionProvider[] = [\n new DecisionAttentionProvider({ workItems, boards }, failedDecisionAttentionSpec),\n new DecisionAttentionProvider({ workItems, boards }, proposedDecisionAttentionSpec),\n new MentionAttentionProvider({ workItems, comments }),\n new ActivityAttentionProvider({ workItems, comments }),\n new ParkedRunAttentionProvider({ workItems, liveSessions }),\n ];\n\n return [\n registerApiRoute(FACTORY_ROUTE_CONTRACTS.attentionList.path, {\n method: FACTORY_ROUTE_CONTRACTS.attentionList.method,\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const query = FACTORY_ROUTE_CONTRACTS.attentionList.querySchema.safeParse({\n view: context.req.query('view'),\n kind: context.req.queries('kind'),\n before: context.req.query('before'),\n limit: context.req.query('limit'),\n search: context.req.query('search'),\n });\n if (!query.success) {\n const field = query.error.issues[0]?.path[0];\n return context.json(\n {\n error:\n field === 'kind'\n ? 'invalid_attention_kind'\n : field === 'before'\n ? 'invalid_cursor'\n : 'invalid_attention_view',\n },\n 400,\n );\n }\n const { view, before, search, limit } = query.data;\n const kinds = query.data.kind ?? providers.map(provider => provider.kind);\n await workItems.ensureReady();\n await comments.ensureReady();\n\n const active = providers.filter(\n provider => kinds.includes(provider.kind) && (!before || before.has(provider.kind)),\n );\n\n const [summaries, pages] = await Promise.all([\n Promise.all(\n providers.map(async provider => ({\n kind: provider.kind,\n counts: await provider.counts(resolved),\n latest: await provider.latest(resolved),\n })),\n ),\n Promise.all(\n active.map(async provider => ({\n kind: provider.kind,\n incoming: before?.get(provider.kind),\n result: await provider.page(resolved, {\n view,\n ...(search ? { search } : {}),\n before: before?.get(provider.kind),\n limit,\n }),\n })),\n ),\n ]);\n\n const merged = mergeAttentionPages(pages, limit);\n\n return context.json({\n items: merged.items,\n kinds: Object.fromEntries(\n summaries.map(summary => [\n summary.kind,\n {\n ...summary.counts,\n latest: summary.latest ? { ...summary.latest, at: summary.latest.at.toISOString() } : null,\n },\n ]),\n ),\n hasMore: merged.hasMore,\n ...(merged.nextCursor ? { nextCursor: merged.nextCursor } : {}),\n });\n },\n }),\n registerApiRoute(FACTORY_ROUTE_CONTRACTS.attentionReadAll.path, {\n method: FACTORY_ROUTE_CONTRACTS.attentionReadAll.method,\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const query = FACTORY_ROUTE_CONTRACTS.attentionReadAll.querySchema.safeParse({\n before: context.req.query('before'),\n });\n if (!query.success) return context.json({ error: 'invalid_cursor' }, 400);\n const { before } = query.data;\n await workItems.ensureReady();\n await comments.ensureReady();\n\n const now = new Date();\n const active = providers.filter(provider => !before || before.has(provider.kind));\n const nextCursors: AttentionCursorMap = new Map();\n let hasMore = false;\n for (const provider of active) {\n const result = await provider.markAllRead(resolved, { before: before?.get(provider.kind), now });\n if (result.hasMore) {\n hasMore = true;\n if (result.continuation) nextCursors.set(provider.kind, result.continuation);\n }\n }\n return context.json({\n ok: true,\n hasMore,\n ...(hasMore && nextCursors.size > 0 ? { nextCursor: encodeAttentionCursor(nextCursors) } : {}),\n });\n },\n }),\n receiptRoute(dependencies, 'read', 'read'),\n receiptRoute(dependencies, 'archive', 'archive'),\n receiptRoute(dependencies, 'restore', 'restore'),\n ];\n}\n"],"mappings":";;;;;;;;AA+CA,SAAS,sBAAsB,SAAqC;CAClE,MAAM,OAAgD,CAAC;CACvD,KAAK,MAAM,CAAC,MAAM,aAAa,SAC7B,KAAK,QAAQ,WAAW,CAAC,SAAS,WAAW,YAAY,GAAG,SAAS,EAAE,IAAI;CAE7E,OAAO,OAAO,KAAK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ACpC,CAAC;IACD,IAAI,CAAC,MAAM,SAAS,OAAO,QAAQ,KAAK,EAAE,OAAO,iBAAiB,GAAG,GAAG;IACxE,MAAM,EAAE,WAAW,MAAM;IACzB,MAAM,UAAU,YAAY;IAC5B,MAAM,SAAS,YAAY;IAE3B,MAAM,sBAAM,IAAI,KAAK;IACrB,MAAM,SAAS,UAAU,QAAO,aAAY,CAAC,UAAU,OAAO,IAAI,SAAS,IAAI,CAAC;IAChF,MAAM,8BAAkC,IAAI,IAAI;IAChD,IAAI,UAAU;IACd,KAAK,MAAM,YAAY,QAAQ;KAC7B,MAAM,SAAS,MAAM,SAAS,YAAY,UAAU;MAAE,QAAQ,QAAQ,IAAI,SAAS,IAAI;MAAG;KAAI,CAAC;KAC/F,IAAI,OAAO,SAAS;MAClB,UAAU;MACV,IAAI,OAAO,cAAc,YAAY,IAAI,SAAS,MAAM,OAAO,YAAY;KAC7E;IACF;IACA,OAAO,QAAQ,KAAK;KAClB,IAAI;KACJ;KACA,GAAI,WAAW,YAAY,OAAO,IAAI,EAAE,YAAY,sBAAsB,WAAW,EAAE,IAAI,CAAC;IAC9F,CAAC;GACH;EACF,CAAC;EACD,aAAa,cAAc,QAAQ,MAAM;EACzC,aAAa,cAAc,WAAW,SAAS;EAC/C,aAAa,cAAc,WAAW,SAAS;CACjD;AACF"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mastra `apiRoutes` for managing a project's stored boards.
|
|
3
|
+
*
|
|
4
|
+
* Reads need project membership; writes need an organization admin in tenant mode. Built-in and
|
|
5
|
+
* app boards are defined in code and read-only here. Every write to a stored board is checked
|
|
6
|
+
* against the rules `defineBoard()` enforces and the cards sitting on it, then invalidates the
|
|
7
|
+
* project's board cache.
|
|
8
|
+
*/
|
|
9
|
+
import type { ApiRoute } from '@mastra/core/server';
|
|
10
|
+
import type { ProjectBoardCache } from '../boards/project-boards.js';
|
|
11
|
+
import type { AuditEmitter } from '../storage/domains/audit/domain.js';
|
|
12
|
+
import type { StoredBoardsStorage } from '../storage/domains/boards/base.js';
|
|
13
|
+
import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';
|
|
14
|
+
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
15
|
+
import type { RouteDependencies } from './route.js';
|
|
16
|
+
import { Route } from './route.js';
|
|
17
|
+
export interface BoardRoutesDeps extends RouteDependencies {
|
|
18
|
+
audit: AuditEmitter;
|
|
19
|
+
projects: FactoryProjectsStorage;
|
|
20
|
+
/** Read to refuse edits that would strand cards. */
|
|
21
|
+
workItems: Pick<WorkItemsStorage, 'list'>;
|
|
22
|
+
storage: StoredBoardsStorage;
|
|
23
|
+
/** The per-project boards: the read-only code boards, skills, and the cache to invalidate. */
|
|
24
|
+
boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills'>;
|
|
25
|
+
}
|
|
26
|
+
export declare class BoardRoutes extends Route<BoardRoutesDeps> {
|
|
27
|
+
#private;
|
|
28
|
+
routes(): ApiRoute[];
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=boards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"boards.d.ts","sourceRoot":"","sources":["../../src/routes/boards.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAKrE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAEvE,OAAO,KAAK,EAIV,mBAAmB,EAEpB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,MAAM,WAAW,eAAgB,SAAQ,iBAAiB;IACxD,KAAK,EAAE,YAAY,CAAC;IACpB,QAAQ,EAAE,sBAAsB,CAAC;IACjC,oDAAoD;IACpD,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAC1C,OAAO,EAAE,mBAAmB,CAAC;IAC7B,8FAA8F;IAC9F,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,UAAU,GAAG,YAAY,GAAG,cAAc,GAAG,YAAY,CAAC,CAAC;CAC5F;AAwBD,qBAAa,WAAY,SAAQ,KAAK,CAAC,eAAe,CAAC;;IA2LrD,MAAM,IAAI,QAAQ,EAAE,CAkEnB;CACF"}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { boardForWorkItem } from "../boards/semantics.js";
|
|
2
|
+
import { createBoardRegistry } from "../boards/registry.js";
|
|
3
|
+
import { findBoardSkillProblems } from "../skills/app-skills.js";
|
|
4
|
+
import { boardDefinitionOf, compileStoredBoard, storedBoardInputSchema } from "../boards/stored-board.js";
|
|
5
|
+
import { FACTORY_ROUTE_CONTRACTS } from "./contracts.js";
|
|
6
|
+
import { Route } from "./route.js";
|
|
7
|
+
import { StoredBoardError } from "../storage/domains/boards/base.js";
|
|
8
|
+
import { registerApiRoute } from "@mastra/core/server";
|
|
9
|
+
// src/routes/boards.ts
|
|
10
|
+
/** A response the handler returns as is: a refusal or an error. */
|
|
11
|
+
var Refusal = class {
|
|
12
|
+
status;
|
|
13
|
+
body;
|
|
14
|
+
constructor(status, body) {
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.body = body;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
function loose(context) {
|
|
20
|
+
return context;
|
|
21
|
+
}
|
|
22
|
+
function issueMessage(issues) {
|
|
23
|
+
return issues.map((issue) => issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message).join("; ");
|
|
24
|
+
}
|
|
25
|
+
const UNKNOWN_SKILL = "but no such skill exists";
|
|
26
|
+
var BoardRoutes = class extends Route {
|
|
27
|
+
async #resolve(c) {
|
|
28
|
+
const { auth, projects } = this.deps;
|
|
29
|
+
await auth.ensureUser(c);
|
|
30
|
+
const tenant = auth.tenant(c);
|
|
31
|
+
if (!tenant) throw new Refusal(401, { error: "unauthorized" });
|
|
32
|
+
if (!tenant.orgId) throw new Refusal(403, {
|
|
33
|
+
error: "organization_required",
|
|
34
|
+
message: "Boards belong to an organization."
|
|
35
|
+
});
|
|
36
|
+
const parsed = FACTORY_ROUTE_CONTRACTS.boardCatalog.pathSchema.safeParse({ id: c.req.param("id") });
|
|
37
|
+
if (!parsed.success) throw new Refusal(404, { error: "Project not found" });
|
|
38
|
+
await projects.ensureReady();
|
|
39
|
+
if (!await projects.get({
|
|
40
|
+
orgId: tenant.orgId,
|
|
41
|
+
id: parsed.data.id
|
|
42
|
+
})) throw new Refusal(404, { error: "Project not found" });
|
|
43
|
+
return {
|
|
44
|
+
orgId: tenant.orgId,
|
|
45
|
+
userId: tenant.userId,
|
|
46
|
+
factoryProjectId: parsed.data.id
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
async #requireAdmin(c, scope) {
|
|
50
|
+
const { auth } = this.deps;
|
|
51
|
+
if (auth.enabled() && !await auth.isOrganizationAdmin(c, scope.orgId)) throw new Refusal(403, {
|
|
52
|
+
error: "organization_admin_required",
|
|
53
|
+
message: "Organization administrator access is required to change boards."
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
async #body(c) {
|
|
57
|
+
try {
|
|
58
|
+
return await c.req.json();
|
|
59
|
+
} catch {
|
|
60
|
+
throw new Refusal(400, {
|
|
61
|
+
error: "invalid_request",
|
|
62
|
+
message: "Invalid JSON body."
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
#boardKey(c) {
|
|
67
|
+
const parsed = FACTORY_ROUTE_CONTRACTS.boardGet.pathSchema.safeParse({
|
|
68
|
+
id: c.req.param("id"),
|
|
69
|
+
boardKey: c.req.param("boardKey")
|
|
70
|
+
});
|
|
71
|
+
if (!parsed.success) throw new Refusal(404, { error: "board_not_found" });
|
|
72
|
+
return parsed.data.boardKey;
|
|
73
|
+
}
|
|
74
|
+
/** Built-in and app boards come from code; they can't be created over, edited or deleted here. */
|
|
75
|
+
#refuseCodeBoard(key) {
|
|
76
|
+
if (!this.deps.boards.codeRegistry.has(key)) return;
|
|
77
|
+
throw new Refusal(409, {
|
|
78
|
+
error: "code_board",
|
|
79
|
+
message: `Board "${key}" is defined in code and can't be edited here.`
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
async #existing(scope, key) {
|
|
83
|
+
const row = await this.deps.storage.get(scope, key);
|
|
84
|
+
if (!row) throw new Refusal(404, {
|
|
85
|
+
error: "board_not_found",
|
|
86
|
+
message: `Board "${key}" does not exist.`
|
|
87
|
+
});
|
|
88
|
+
return row;
|
|
89
|
+
}
|
|
90
|
+
/** Validates a definition the way `defineBoard()` does, plus the skills its runners name. */
|
|
91
|
+
#validate(input) {
|
|
92
|
+
const parsed = storedBoardInputSchema.safeParse(input);
|
|
93
|
+
if (!parsed.success) throw new Refusal(422, {
|
|
94
|
+
error: "invalid_board",
|
|
95
|
+
message: issueMessage(parsed.error.issues)
|
|
96
|
+
});
|
|
97
|
+
const board = compileStoredBoard(parsed.data);
|
|
98
|
+
const unknown = findBoardSkillProblems(createBoardRegistry({
|
|
99
|
+
boards: [board],
|
|
100
|
+
includeDefaultBoards: false
|
|
101
|
+
}), this.deps.boards.codeSkills).filter((problem) => problem.includes(UNKNOWN_SKILL));
|
|
102
|
+
if (unknown.length > 0) throw new Refusal(422, {
|
|
103
|
+
error: "unknown_skill",
|
|
104
|
+
message: unknown.join(" ")
|
|
105
|
+
});
|
|
106
|
+
return parsed.data;
|
|
107
|
+
}
|
|
108
|
+
/** The cards on a board, and how many sit in each phase. */
|
|
109
|
+
async #occupancy(scope, key) {
|
|
110
|
+
const phases = /* @__PURE__ */ new Map();
|
|
111
|
+
let cards = 0;
|
|
112
|
+
for (const item of await this.deps.workItems.list(scope)) {
|
|
113
|
+
if (boardForWorkItem(item) !== key) continue;
|
|
114
|
+
cards++;
|
|
115
|
+
for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
cards,
|
|
119
|
+
phases
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** Refuses a change that removes, or changes the kind of, a phase cards sit in. */
|
|
123
|
+
async #checkPhasesFree(scope, row, next) {
|
|
124
|
+
const kinds = new Map(next.map((phase) => [phase.key, phase.kind]));
|
|
125
|
+
const changed = row.phases.filter((phase) => kinds.get(phase.key) !== phase.kind).map((phase) => phase.key);
|
|
126
|
+
if (changed.length === 0) return;
|
|
127
|
+
const occupancy = (await this.#occupancy(scope, row.key)).phases;
|
|
128
|
+
const inUse = Object.fromEntries(changed.flatMap((key) => occupancy.get(key) ? [[key, occupancy.get(key)]] : []));
|
|
129
|
+
if (Object.keys(inUse).length === 0) return;
|
|
130
|
+
throw new Refusal(409, {
|
|
131
|
+
error: "phase_in_use",
|
|
132
|
+
message: `Cards sit in ${Object.entries(inUse).map(([key, count]) => `"${key}" (${count})`).join(", ")}; move them before removing those phases or changing their kind.`,
|
|
133
|
+
phases: inUse
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
async #respond(c, scope, key, status = 200) {
|
|
137
|
+
const project = await this.deps.boards.describe(scope);
|
|
138
|
+
const details = project.details.get(key);
|
|
139
|
+
const code = this.deps.boards.codeRegistry.get(key);
|
|
140
|
+
if (code) {
|
|
141
|
+
const { description, ...definition } = boardDefinitionOf(code);
|
|
142
|
+
return c.json({ board: {
|
|
143
|
+
...definition,
|
|
144
|
+
description: description ?? null,
|
|
145
|
+
revision: null,
|
|
146
|
+
source: details?.source ?? "app",
|
|
147
|
+
editable: false,
|
|
148
|
+
problems: details?.problems ?? []
|
|
149
|
+
} }, status);
|
|
150
|
+
}
|
|
151
|
+
const row = await this.deps.storage.get(scope, key);
|
|
152
|
+
if (!row) return c.json({
|
|
153
|
+
error: "board_not_found",
|
|
154
|
+
message: `Board "${key}" does not exist.`
|
|
155
|
+
}, 404);
|
|
156
|
+
const loadProblems = project.problems.filter((problem) => problem.startsWith(`Board '${key}' could not be loaded:`));
|
|
157
|
+
return c.json({ board: {
|
|
158
|
+
key: row.key,
|
|
159
|
+
name: row.name,
|
|
160
|
+
description: row.description,
|
|
161
|
+
phases: row.phases.map(({ position: _position, ...phase }) => phase),
|
|
162
|
+
revision: row.revision,
|
|
163
|
+
source: "stored",
|
|
164
|
+
editable: true,
|
|
165
|
+
problems: [...details?.problems ?? [], ...loadProblems]
|
|
166
|
+
} }, status);
|
|
167
|
+
}
|
|
168
|
+
async #audit(c, scope, action, board) {
|
|
169
|
+
await this.deps.audit.emit({
|
|
170
|
+
context: c,
|
|
171
|
+
input: {
|
|
172
|
+
action: `factory.board.${action}`,
|
|
173
|
+
factoryProjectId: scope.factoryProjectId,
|
|
174
|
+
targets: [{
|
|
175
|
+
type: "board",
|
|
176
|
+
id: board.key,
|
|
177
|
+
name: board.name
|
|
178
|
+
}]
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
#route(contract, handle) {
|
|
183
|
+
return registerApiRoute(contract.path, {
|
|
184
|
+
method: contract.method,
|
|
185
|
+
requiresAuth: false,
|
|
186
|
+
handler: async (c) => {
|
|
187
|
+
const context = loose(c);
|
|
188
|
+
try {
|
|
189
|
+
return await handle(context);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (error instanceof Refusal) return context.json(error.body, error.status);
|
|
192
|
+
if (error instanceof StoredBoardError) return context.json({
|
|
193
|
+
error: error.code,
|
|
194
|
+
message: error.message
|
|
195
|
+
}, error.code === "board_not_found" ? 404 : 409);
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
routes() {
|
|
202
|
+
const { storage, boards } = this.deps;
|
|
203
|
+
const contracts = FACTORY_ROUTE_CONTRACTS;
|
|
204
|
+
return [
|
|
205
|
+
this.#route(contracts.boardGet, async (c) => {
|
|
206
|
+
const scope = await this.#resolve(c);
|
|
207
|
+
return this.#respond(c, scope, this.#boardKey(c));
|
|
208
|
+
}),
|
|
209
|
+
this.#route(contracts.boardCreate, async (c) => {
|
|
210
|
+
const scope = await this.#resolve(c);
|
|
211
|
+
await this.#requireAdmin(c, scope);
|
|
212
|
+
const input = this.#validate(await this.#body(c));
|
|
213
|
+
this.#refuseCodeBoard(input.key);
|
|
214
|
+
await storage.create(scope, input, scope.userId);
|
|
215
|
+
boards.invalidate(scope);
|
|
216
|
+
await this.#audit(c, scope, "created", input);
|
|
217
|
+
return this.#respond(c, scope, input.key, 201);
|
|
218
|
+
}),
|
|
219
|
+
this.#route(contracts.boardReplace, async (c) => {
|
|
220
|
+
const scope = await this.#resolve(c);
|
|
221
|
+
const key = this.#boardKey(c);
|
|
222
|
+
await this.#requireAdmin(c, scope);
|
|
223
|
+
this.#refuseCodeBoard(key);
|
|
224
|
+
const parsed = contracts.boardReplace.bodySchema.safeParse(await this.#body(c));
|
|
225
|
+
if (!parsed.success) throw new Refusal(422, {
|
|
226
|
+
error: "invalid_board",
|
|
227
|
+
message: issueMessage(parsed.error.issues)
|
|
228
|
+
});
|
|
229
|
+
const { expectedRevision, ...definition } = parsed.data;
|
|
230
|
+
const row = await this.#existing(scope, key);
|
|
231
|
+
const input = this.#validate({
|
|
232
|
+
key,
|
|
233
|
+
...definition
|
|
234
|
+
});
|
|
235
|
+
await this.#checkPhasesFree(scope, row, input.phases);
|
|
236
|
+
const { key: _key, ...replacement } = input;
|
|
237
|
+
await storage.replace(scope, key, replacement, {
|
|
238
|
+
expectedRevision,
|
|
239
|
+
actor: scope.userId
|
|
240
|
+
});
|
|
241
|
+
boards.invalidate(scope);
|
|
242
|
+
await this.#audit(c, scope, "updated", input);
|
|
243
|
+
return this.#respond(c, scope, key);
|
|
244
|
+
}),
|
|
245
|
+
this.#route(contracts.boardDelete, async (c) => {
|
|
246
|
+
const scope = await this.#resolve(c);
|
|
247
|
+
const key = this.#boardKey(c);
|
|
248
|
+
await this.#requireAdmin(c, scope);
|
|
249
|
+
this.#refuseCodeBoard(key);
|
|
250
|
+
const parsed = contracts.boardDelete.querySchema.safeParse({ expectedRevision: c.req.query("expectedRevision") });
|
|
251
|
+
if (!parsed.success) throw new Refusal(422, {
|
|
252
|
+
error: "invalid_request",
|
|
253
|
+
message: issueMessage(parsed.error.issues)
|
|
254
|
+
});
|
|
255
|
+
const row = await this.#existing(scope, key);
|
|
256
|
+
const { cards } = await this.#occupancy(scope, key);
|
|
257
|
+
if (cards > 0) throw new Refusal(409, {
|
|
258
|
+
error: "board_in_use",
|
|
259
|
+
message: `Board "${key}" still has cards; move or delete them first.`,
|
|
260
|
+
cards
|
|
261
|
+
});
|
|
262
|
+
await storage.delete(scope, key, { expectedRevision: parsed.data.expectedRevision });
|
|
263
|
+
boards.invalidate(scope);
|
|
264
|
+
await this.#audit(c, scope, "deleted", row);
|
|
265
|
+
return c.body(null, 204);
|
|
266
|
+
})
|
|
267
|
+
];
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
export { BoardRoutes };
|
|
271
|
+
|
|
272
|
+
//# sourceMappingURL=boards.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"boards.js","names":[],"sources":["../../src/routes/boards.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for managing a project's stored boards.\n *\n * Reads need project membership; writes need an organization admin in tenant mode. Built-in and\n * app boards are defined in code and read-only here. Every write to a stored board is checked\n * against the rules `defineBoard()` enforces and the cards sitting on it, then invalidates the\n * project's board cache.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport type { z } from 'zod';\n\nimport type { ProjectBoardCache } from '../boards/project-boards.js';\nimport { createBoardRegistry } from '../boards/registry.js';\nimport { boardForWorkItem } from '../boards/semantics.js';\nimport { boardDefinitionOf, compileStoredBoard, storedBoardInputSchema } from '../boards/stored-board.js';\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredPhaseInput,\n} from '../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\nimport type { RouteDependencies } from './route.js';\nimport { Route } from './route.js';\n\nexport interface BoardRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n projects: FactoryProjectsStorage;\n /** Read to refuse edits that would strand cards. */\n workItems: Pick<WorkItemsStorage, 'list'>;\n storage: StoredBoardsStorage;\n /** The per-project boards: the read-only code boards, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills'>;\n}\n\ntype Resolved = StoredBoardScope & { userId: string };\n\n/** A response the handler returns as is: a refusal or an error. */\nclass Refusal {\n constructor(\n readonly status: 400 | 401 | 403 | 404 | 409 | 422,\n readonly body: Record<string, unknown>,\n ) {}\n}\n\nfunction loose(context: unknown): Context {\n return context as Context;\n}\n\nfunction issueMessage(issues: readonly z.core.$ZodIssue[]): string {\n return issues\n .map(issue => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n .join('; ');\n}\n\nconst UNKNOWN_SKILL = 'but no such skill exists';\n\nexport class BoardRoutes extends Route<BoardRoutesDeps> {\n async #resolve(c: Context): Promise<Resolved> {\n const { auth, projects } = this.deps;\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) throw new Refusal(401, { error: 'unauthorized' });\n if (!tenant.orgId) {\n throw new Refusal(403, { error: 'organization_required', message: 'Boards belong to an organization.' });\n }\n const parsed = FACTORY_ROUTE_CONTRACTS.boardCatalog.pathSchema.safeParse({ id: c.req.param('id') });\n if (!parsed.success) throw new Refusal(404, { error: 'Project not found' });\n await projects.ensureReady();\n if (!(await projects.get({ orgId: tenant.orgId, id: parsed.data.id }))) {\n throw new Refusal(404, { error: 'Project not found' });\n }\n return { orgId: tenant.orgId, userId: tenant.userId, factoryProjectId: parsed.data.id };\n }\n\n async #requireAdmin(c: Context, scope: Resolved): Promise<void> {\n const { auth } = this.deps;\n if (auth.enabled() && !(await auth.isOrganizationAdmin(c, scope.orgId))) {\n throw new Refusal(403, {\n error: 'organization_admin_required',\n message: 'Organization administrator access is required to change boards.',\n });\n }\n }\n\n async #body(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n throw new Refusal(400, { error: 'invalid_request', message: 'Invalid JSON body.' });\n }\n }\n\n #boardKey(c: Context): string {\n const parsed = FACTORY_ROUTE_CONTRACTS.boardGet.pathSchema.safeParse({\n id: c.req.param('id'),\n boardKey: c.req.param('boardKey'),\n });\n if (!parsed.success) throw new Refusal(404, { error: 'board_not_found' });\n return parsed.data.boardKey;\n }\n\n /** Built-in and app boards come from code; they can't be created over, edited or deleted here. */\n #refuseCodeBoard(key: string): void {\n if (!this.deps.boards.codeRegistry.has(key)) return;\n throw new Refusal(409, {\n error: 'code_board',\n message: `Board \"${key}\" is defined in code and can't be edited here.`,\n });\n }\n\n async #existing(scope: Resolved, key: string) {\n const row = await this.deps.storage.get(scope, key);\n if (!row) throw new Refusal(404, { error: 'board_not_found', message: `Board \"${key}\" does not exist.` });\n return row;\n }\n\n /** Validates a definition the way `defineBoard()` does, plus the skills its runners name. */\n #validate(input: unknown): StoredBoardInput {\n const parsed = storedBoardInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n const board = compileStoredBoard(parsed.data);\n const problems = findBoardSkillProblems(\n createBoardRegistry({ boards: [board], includeDefaultBoards: false }),\n this.deps.boards.codeSkills,\n );\n const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL));\n if (unknown.length > 0) throw new Refusal(422, { error: 'unknown_skill', message: unknown.join(' ') });\n return parsed.data;\n }\n\n /** The cards on a board, and how many sit in each phase. */\n async #occupancy(scope: Resolved, key: string): Promise<{ cards: number; phases: Map<string, number> }> {\n const phases = new Map<string, number>();\n let cards = 0;\n for (const item of await this.deps.workItems.list(scope)) {\n if (boardForWorkItem(item) !== key) continue;\n cards++;\n for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);\n }\n return { cards, phases };\n }\n\n /** Refuses a change that removes, or changes the kind of, a phase cards sit in. */\n async #checkPhasesFree(scope: Resolved, row: StoredBoardRecord, next: readonly StoredPhaseInput[]): Promise<void> {\n const kinds = new Map(next.map(phase => [phase.key, phase.kind]));\n const changed = row.phases.filter(phase => kinds.get(phase.key) !== phase.kind).map(phase => phase.key);\n if (changed.length === 0) return;\n const occupancy = (await this.#occupancy(scope, row.key)).phases;\n const inUse = Object.fromEntries(changed.flatMap(key => (occupancy.get(key) ? [[key, occupancy.get(key)!]] : [])));\n if (Object.keys(inUse).length === 0) return;\n throw new Refusal(409, {\n error: 'phase_in_use',\n message: `Cards sit in ${Object.entries(inUse)\n .map(([key, count]) => `\"${key}\" (${count})`)\n .join(', ')}; move them before removing those phases or changing their kind.`,\n phases: inUse,\n });\n }\n\n async #respond(c: Context, scope: Resolved, key: string, status: 200 | 201 = 200) {\n const project = await this.deps.boards.describe(scope);\n const details = project.details.get(key);\n const code = this.deps.boards.codeRegistry.get(key);\n if (code) {\n const { description, ...definition } = boardDefinitionOf(code);\n return c.json(\n {\n board: {\n ...definition,\n description: description ?? null,\n revision: null,\n source: details?.source ?? 'app',\n editable: false,\n problems: details?.problems ?? [],\n },\n },\n status,\n );\n }\n const row = await this.deps.storage.get(scope, key);\n if (!row) return c.json({ error: 'board_not_found', message: `Board \"${key}\" does not exist.` }, 404);\n // A board that failed to load is missing from the details; its error is a project problem.\n const loadProblems = project.problems.filter(problem => problem.startsWith(`Board '${key}' could not be loaded:`));\n return c.json(\n {\n board: {\n key: row.key,\n name: row.name,\n description: row.description,\n phases: row.phases.map(({ position: _position, ...phase }) => phase),\n revision: row.revision,\n source: 'stored',\n editable: true,\n problems: [...(details?.problems ?? []), ...loadProblems],\n },\n },\n status,\n );\n }\n\n async #audit(\n c: Context,\n scope: Resolved,\n action: 'created' | 'updated' | 'deleted',\n board: { key: string; name: string },\n ) {\n await this.deps.audit.emit({\n context: c,\n input: {\n action: `factory.board.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'board', id: board.key, name: board.name }],\n },\n });\n }\n\n #route(\n contract: { path: string; method: 'GET' | 'POST' | 'PATCH' | 'DELETE' },\n handle: (c: Context) => Promise<Response>,\n ): ApiRoute {\n return registerApiRoute(contract.path, {\n method: contract.method,\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n try {\n return await handle(context);\n } catch (error) {\n if (error instanceof Refusal) return context.json(error.body, error.status);\n if (error instanceof StoredBoardError) {\n return context.json(\n { error: error.code, message: error.message },\n error.code === 'board_not_found' ? 404 : 409,\n );\n }\n throw error;\n }\n },\n });\n }\n\n routes(): ApiRoute[] {\n const { storage, boards } = this.deps;\n const contracts = FACTORY_ROUTE_CONTRACTS;\n return [\n this.#route(contracts.boardGet, async c => {\n const scope = await this.#resolve(c);\n return this.#respond(c, scope, this.#boardKey(c));\n }),\n\n this.#route(contracts.boardCreate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const input = this.#validate(await this.#body(c));\n this.#refuseCodeBoard(input.key);\n await storage.create(scope, input, scope.userId);\n boards.invalidate(scope);\n await this.#audit(c, scope, 'created', input);\n return this.#respond(c, scope, input.key, 201);\n }),\n\n this.#route(contracts.boardReplace, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n this.#refuseCodeBoard(key);\n const parsed = contracts.boardReplace.bodySchema.safeParse(await this.#body(c));\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n const { expectedRevision, ...definition } = parsed.data;\n const row = await this.#existing(scope, key);\n const input = this.#validate({ key, ...definition });\n await this.#checkPhasesFree(scope, row, input.phases);\n const { key: _key, ...replacement } = input;\n await storage.replace(scope, key, replacement, { expectedRevision, actor: scope.userId });\n boards.invalidate(scope);\n await this.#audit(c, scope, 'updated', input);\n return this.#respond(c, scope, key);\n }),\n\n this.#route(contracts.boardDelete, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n this.#refuseCodeBoard(key);\n const parsed = contracts.boardDelete.querySchema.safeParse({\n expectedRevision: c.req.query('expectedRevision'),\n });\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(parsed.error.issues) });\n }\n const row = await this.#existing(scope, key);\n const { cards } = await this.#occupancy(scope, key);\n if (cards > 0) {\n throw new Refusal(409, {\n error: 'board_in_use',\n message: `Board \"${key}\" still has cards; move or delete them first.`,\n cards,\n });\n }\n await storage.delete(scope, key, { expectedRevision: parsed.data.expectedRevision });\n boards.invalidate(scope);\n await this.#audit(c, scope, 'deleted', row);\n return c.body(null, 204);\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;;AA+CA,IAAM,UAAN,MAAc;CAED;CACA;CAFX,YACE,QACA,MACA;EAFS,KAAA,SAAA;EACA,KAAA,OAAA;CACR;AACL;AAEA,SAAS,MAAM,SAA2B;CACxC,OAAO;AACT;AAEA,SAAS,aAAa,QAA6C;CACjE,OAAO,OACJ,KAAI,UAAU,MAAM,KAAK,SAAS,IAAI,GAAG,MAAM,KAAK,KAAK,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