@mastra/factory 0.12.0-alpha.0 → 0.12.0-alpha.2
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/CHANGELOG.md +45 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +6 -1
- package/dist/factory.js.map +1 -1
- package/dist/feed-events.d.ts +13 -0
- package/dist/feed-events.d.ts.map +1 -0
- package/dist/feed-events.js +25 -0
- package/dist/feed-events.js.map +1 -0
- package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +22 -14
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +1 -1
- package/dist/integrations/github/rules.d.ts +6 -0
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +58 -12
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +1 -1
- package/dist/integrations/platform/github/event-worker.js +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -1
- package/dist/routes/attention-activity.d.ts +24 -0
- package/dist/routes/attention-activity.d.ts.map +1 -0
- package/dist/routes/attention-activity.js +143 -0
- package/dist/routes/attention-activity.js.map +1 -0
- package/dist/routes/attention-providers.d.ts +31 -1
- package/dist/routes/attention-providers.d.ts.map +1 -1
- package/dist/routes/attention-providers.js +4 -4
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/attention.d.ts.map +1 -1
- package/dist/routes/attention.js +39 -11
- package/dist/routes/attention.js.map +1 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +4 -3
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +11 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/defaults.d.ts.map +1 -1
- package/dist/rules/defaults.js +20 -8
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +24 -10
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +2 -3
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/transition-service.d.ts +2 -2
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +33 -12
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +27 -1
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +37 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +3 -1
- package/dist/rules/validation.js.map +1 -1
- package/dist/storage/domains/comments/activity.d.ts +40 -0
- package/dist/storage/domains/comments/activity.d.ts.map +1 -0
- package/dist/storage/domains/comments/activity.js +94 -0
- package/dist/storage/domains/comments/activity.js.map +1 -0
- package/dist/storage/domains/comments/base.d.ts +13 -1
- package/dist/storage/domains/comments/base.d.ts.map +1 -1
- package/dist/storage/domains/comments/base.js +41 -3
- package/dist/storage/domains/comments/base.js.map +1 -1
- package/dist/storage/domains/comments/domain.d.ts +4 -1
- package/dist/storage/domains/comments/domain.d.ts.map +1 -1
- package/dist/storage/domains/comments/domain.js +17 -5
- package/dist/storage/domains/comments/domain.js.map +1 -1
- package/dist/storage/domains/comments/parse.d.ts +1 -0
- package/dist/storage/domains/comments/parse.d.ts.map +1 -1
- package/dist/storage/domains/comments/parse.js +2 -2
- package/dist/storage/domains/comments/parse.js.map +1 -1
- package/dist/storage/domains/comments/routes.d.ts +2 -0
- package/dist/storage/domains/comments/routes.d.ts.map +1 -1
- package/dist/storage/domains/comments/routes.js +49 -3
- package/dist/storage/domains/comments/routes.js.map +1 -1
- package/dist/storage/domains/comments/schema.d.ts +1 -0
- package/dist/storage/domains/comments/schema.d.ts.map +1 -1
- package/dist/storage/domains/comments/schema.js +45 -1
- package/dist/storage/domains/comments/schema.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +18 -3
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +95 -38
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/package.json +6 -6
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { factoryActivityAttentionIdentity, factoryAttentionKey } from "../storage/domains/work-items/base.js";
|
|
2
|
+
import { collectPage, markScanRead, matchesView, receiptScope, scanBatches, workItemBoard } from "./attention-providers.js";
|
|
3
|
+
//#region src/routes/attention-activity.ts
|
|
4
|
+
var ActivityAttentionProvider = class {
|
|
5
|
+
kind = "activity";
|
|
6
|
+
#workItems;
|
|
7
|
+
#comments;
|
|
8
|
+
constructor({ workItems, comments }) {
|
|
9
|
+
this.#workItems = workItems;
|
|
10
|
+
this.#comments = comments;
|
|
11
|
+
}
|
|
12
|
+
#scan(scope, before) {
|
|
13
|
+
return scanBatches(async (cursor) => {
|
|
14
|
+
const rows = await this.#comments.listActivityForUser({
|
|
15
|
+
...receiptScope(scope),
|
|
16
|
+
...cursor ? { before: cursor } : {},
|
|
17
|
+
limit: 51
|
|
18
|
+
});
|
|
19
|
+
return {
|
|
20
|
+
rows: rows.slice(0, 50),
|
|
21
|
+
hasMore: rows.length > 50
|
|
22
|
+
};
|
|
23
|
+
}, (activity) => ({
|
|
24
|
+
occurredAt: activity.occurredAt,
|
|
25
|
+
id: activity.id
|
|
26
|
+
}), before);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A vanished work item drops the row; a deleted latest comment does not —
|
|
30
|
+
* the entry still reports that the discussion moved, with the body replaced.
|
|
31
|
+
*/
|
|
32
|
+
async #resolve(scope, rows) {
|
|
33
|
+
const [receipts, comments, items] = await Promise.all([
|
|
34
|
+
this.#workItems.listAttentionReceipts({
|
|
35
|
+
...receiptScope(scope),
|
|
36
|
+
identities: rows.map((row) => factoryActivityAttentionIdentity(row.workItemId, row.occurrence))
|
|
37
|
+
}),
|
|
38
|
+
this.#comments.listByIds({
|
|
39
|
+
orgId: scope.orgId,
|
|
40
|
+
ids: [...new Set(rows.map((row) => row.latestCommentId))]
|
|
41
|
+
}),
|
|
42
|
+
this.#workItems.listByIds({
|
|
43
|
+
orgId: scope.orgId,
|
|
44
|
+
factoryProjectId: scope.factoryProjectId,
|
|
45
|
+
ids: [...new Set(rows.map((row) => row.workItemId))]
|
|
46
|
+
})
|
|
47
|
+
]);
|
|
48
|
+
const receiptByKey = new Map(receipts.map((receipt) => [factoryAttentionKey(scope.factoryProjectId, receipt), receipt]));
|
|
49
|
+
const commentById = new Map(comments.map((comment) => [comment.id, comment]));
|
|
50
|
+
const itemById = new Map(items.map((item) => [item.id, item]));
|
|
51
|
+
const resolved = [];
|
|
52
|
+
for (const activity of rows) {
|
|
53
|
+
const item = itemById.get(activity.workItemId);
|
|
54
|
+
if (!item) continue;
|
|
55
|
+
const identity = factoryActivityAttentionIdentity(activity.workItemId, activity.occurrence);
|
|
56
|
+
resolved.push({
|
|
57
|
+
activity,
|
|
58
|
+
item,
|
|
59
|
+
comment: commentById.get(activity.latestCommentId),
|
|
60
|
+
identity,
|
|
61
|
+
receipt: receiptByKey.get(factoryAttentionKey(scope.factoryProjectId, identity))
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return resolved;
|
|
65
|
+
}
|
|
66
|
+
async counts(scope) {
|
|
67
|
+
let open = 0;
|
|
68
|
+
let unread = 0;
|
|
69
|
+
for await (const batch of this.#scan(scope)) for (const { receipt } of await this.#resolve(scope, batch.rows)) {
|
|
70
|
+
if (receipt?.state !== "archived") open += 1;
|
|
71
|
+
if (receipt === void 0) unread += 1;
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
open,
|
|
75
|
+
unread
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Always null: `latestOccurrence*` drives the notification sound, and this tier stays silent. */
|
|
79
|
+
async latest() {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
async page(scope, { view, search, before, limit }) {
|
|
83
|
+
return collectPage(this.#scan(scope, before), limit, async (rows) => {
|
|
84
|
+
const entries = [];
|
|
85
|
+
for (const resolved of await this.#resolve(scope, rows)) {
|
|
86
|
+
if (!matchesView(view, resolved.receipt)) continue;
|
|
87
|
+
if (search && !matchesActivitySearch(resolved, search)) continue;
|
|
88
|
+
entries.push({
|
|
89
|
+
occurredAt: resolved.activity.occurredAt,
|
|
90
|
+
resumeCursor: {
|
|
91
|
+
occurredAt: resolved.activity.occurredAt,
|
|
92
|
+
id: resolved.activity.id
|
|
93
|
+
},
|
|
94
|
+
item: toActivityItem(scope, resolved)
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return entries;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
async markAllRead(scope, { before, now }) {
|
|
101
|
+
return markScanRead(this.#scan(scope, before), async (rows) => {
|
|
102
|
+
await this.#workItems.markAttentionReceiptsRead({
|
|
103
|
+
...receiptScope(scope),
|
|
104
|
+
identities: rows.map((row) => factoryActivityAttentionIdentity(row.workItemId, row.occurrence)),
|
|
105
|
+
now
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
function activityDetail({ comment }) {
|
|
111
|
+
if (!comment || comment.deletedAt) return "Comment removed";
|
|
112
|
+
return comment.body.slice(0, 512);
|
|
113
|
+
}
|
|
114
|
+
function matchesActivitySearch(resolved, search) {
|
|
115
|
+
return resolved.item.title.toLowerCase().includes(search) || activityDetail(resolved).toLowerCase().includes(search) || resolved.activity.latestAuthorName?.toLowerCase().includes(search) === true;
|
|
116
|
+
}
|
|
117
|
+
function toActivityItem(scope, resolved) {
|
|
118
|
+
const { activity, item, identity, receipt } = resolved;
|
|
119
|
+
return {
|
|
120
|
+
key: factoryAttentionKey(scope.factoryProjectId, identity),
|
|
121
|
+
kind: "activity",
|
|
122
|
+
commentId: activity.latestCommentId,
|
|
123
|
+
occurrence: activity.occurrence,
|
|
124
|
+
workItemId: activity.workItemId,
|
|
125
|
+
title: item.title,
|
|
126
|
+
detail: activityDetail(resolved),
|
|
127
|
+
authorId: activity.latestAuthorId,
|
|
128
|
+
...activity.latestAuthorName ? { authorName: activity.latestAuthorName } : {},
|
|
129
|
+
occurredAt: activity.occurredAt.toISOString(),
|
|
130
|
+
read: receipt !== void 0,
|
|
131
|
+
archived: receipt?.state === "archived",
|
|
132
|
+
target: {
|
|
133
|
+
kind: "work-item",
|
|
134
|
+
workItemId: activity.workItemId,
|
|
135
|
+
board: workItemBoard(item),
|
|
136
|
+
commentId: activity.latestCommentId
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
//#endregion
|
|
141
|
+
export { ActivityAttentionProvider };
|
|
142
|
+
|
|
143
|
+
//# sourceMappingURL=attention-activity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attention-activity.js","names":["#workItems","#comments","#resolve","#scan"],"sources":["../../src/routes/attention-activity.ts"],"sourcesContent":["/** Projects `activity.ts` fan-out rows. Below the badge: the sidebar counts mentions and failures only. */\n\nimport type {\n WorkItemActivityRow,\n WorkItemCommentRow,\n WorkItemCommentsStorage,\n} from '../storage/domains/comments/base.js';\nimport type {\n FactoryAttentionIdentity,\n FactoryAttentionReceiptRecord,\n WorkItemRow,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { factoryActivityAttentionIdentity, factoryAttentionKey } from '../storage/domains/work-items/base.js';\nimport type {\n AttentionCounts,\n AttentionEntry,\n AttentionLatest,\n AttentionPageArgs,\n AttentionPageResult,\n AttentionProvider,\n AttentionScope,\n AttentionStreamPosition,\n} from './attention-providers.js';\nimport {\n collectPage,\n markScanRead,\n matchesView,\n receiptScope,\n SCAN_PAGE_SIZE,\n scanBatches,\n workItemBoard,\n} from './attention-providers.js';\n\ninterface ResolvedActivity {\n activity: WorkItemActivityRow;\n item: WorkItemRow;\n comment: WorkItemCommentRow | undefined;\n identity: FactoryAttentionIdentity;\n receipt: FactoryAttentionReceiptRecord | undefined;\n}\n\nexport class ActivityAttentionProvider implements AttentionProvider {\n readonly kind = 'activity' 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<WorkItemActivityRow>(\n async cursor => {\n const rows = await this.#comments.listActivityForUser({\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 activity => ({ occurredAt: activity.occurredAt, id: activity.id }),\n before,\n );\n }\n\n /**\n * A vanished work item drops the row; a deleted latest comment does not —\n * the entry still reports that the discussion moved, with the body replaced.\n */\n async #resolve(scope: AttentionScope, rows: WorkItemActivityRow[]): Promise<ResolvedActivity[]> {\n const [receipts, comments, items] = await Promise.all([\n this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: rows.map(row => factoryActivityAttentionIdentity(row.workItemId, row.occurrence)),\n }),\n this.#comments.listByIds({\n orgId: scope.orgId,\n ids: [...new Set(rows.map(row => row.latestCommentId))],\n }),\n this.#workItems.listByIds({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n ids: [...new Set(rows.map(row => row.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: ResolvedActivity[] = [];\n for (const activity of rows) {\n const item = itemById.get(activity.workItemId);\n if (!item) continue;\n const identity = factoryActivityAttentionIdentity(activity.workItemId, activity.occurrence);\n resolved.push({\n activity,\n item,\n comment: commentById.get(activity.latestCommentId),\n identity,\n receipt: receiptByKey.get(factoryAttentionKey(scope.factoryProjectId, identity)),\n });\n }\n return resolved;\n }\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 /** Always null: `latestOccurrence*` drives the notification sound, and this tier stays silent. */\n async latest(): Promise<AttentionLatest | null> {\n return null;\n }\n\n async page(scope: AttentionScope, { view, search, before, limit }: AttentionPageArgs): Promise<AttentionPageResult> {\n return collectPage(this.#scan(scope, before), limit, async rows => {\n const entries: AttentionEntry[] = [];\n for (const resolved of await this.#resolve(scope, rows)) {\n if (!matchesView(view, resolved.receipt)) continue;\n if (search && !matchesActivitySearch(resolved, search)) continue;\n entries.push({\n occurredAt: resolved.activity.occurredAt,\n resumeCursor: { occurredAt: resolved.activity.occurredAt, id: resolved.activity.id },\n item: toActivityItem(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 rows => {\n await this.#workItems.markAttentionReceiptsRead({\n ...receiptScope(scope),\n identities: rows.map(row => factoryActivityAttentionIdentity(row.workItemId, row.occurrence)),\n now,\n });\n });\n }\n}\n\nfunction activityDetail({ comment }: ResolvedActivity): string {\n if (!comment || comment.deletedAt) return 'Comment removed';\n return comment.body.slice(0, 512);\n}\n\nfunction matchesActivitySearch(resolved: ResolvedActivity, search: string): boolean {\n return (\n resolved.item.title.toLowerCase().includes(search) ||\n activityDetail(resolved).toLowerCase().includes(search) ||\n resolved.activity.latestAuthorName?.toLowerCase().includes(search) === true\n );\n}\n\nfunction toActivityItem(scope: AttentionScope, resolved: ResolvedActivity) {\n const { activity, item, identity, receipt } = resolved;\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n kind: 'activity' as const,\n commentId: activity.latestCommentId,\n occurrence: activity.occurrence,\n workItemId: activity.workItemId,\n title: item.title,\n detail: activityDetail(resolved),\n authorId: activity.latestAuthorId,\n ...(activity.latestAuthorName ? { authorName: activity.latestAuthorName } : {}),\n occurredAt: activity.occurredAt.toISOString(),\n read: receipt !== undefined,\n archived: receipt?.state === 'archived',\n target: {\n kind: 'work-item' as const,\n workItemId: activity.workItemId,\n board: workItemBoard(item),\n commentId: activity.latestCommentId,\n },\n };\n}\n"],"mappings":";;;AA0CA,IAAa,4BAAb,MAAoE;CAClE,OAAgB;CAChB;CACA;CAEA,YAAY,EAAE,WAAW,YAAgF;EACvG,KAAKA,aAAa;EAClB,KAAKC,YAAY;CACnB;CAEA,MAAM,OAAuB,QAAkC;EAC7D,OAAO,YACL,OAAM,WAAU;GACd,MAAM,OAAO,MAAM,KAAKA,UAAU,oBAAoB;IACpD,GAAG,aAAa,KAAK;IACrB,GAAI,SAAS,EAAE,QAAQ,OAAO,IAAI,CAAC;IACnC,OAAA;GACF,CAAC;GACD,OAAO;IAAE,MAAM,KAAK,MAAM,GAAA,EAAiB;IAAG,SAAS,KAAK,SAAA;GAAwB;EACtF,IACA,cAAa;GAAE,YAAY,SAAS;GAAY,IAAI,SAAS;EAAG,IAChE,MACF;CACF;;;;;CAMA,MAAMC,SAAS,OAAuB,MAA0D;EAC9F,MAAM,CAAC,UAAU,UAAU,SAAS,MAAM,QAAQ,IAAI;GACpD,KAAKF,WAAW,sBAAsB;IACpC,GAAG,aAAa,KAAK;IACrB,YAAY,KAAK,KAAI,QAAO,iCAAiC,IAAI,YAAY,IAAI,UAAU,CAAC;GAC9F,CAAC;GACD,KAAKC,UAAU,UAAU;IACvB,OAAO,MAAM;IACb,KAAK,CAAC,GAAG,IAAI,IAAI,KAAK,KAAI,QAAO,IAAI,eAAe,CAAC,CAAC;GACxD,CAAC;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AQ;EAC/B,UAAU,SAAS;EACnB,GAAI,SAAS,mBAAmB,EAAE,YAAY,SAAS,iBAAiB,IAAI,CAAC;EAC7E,YAAY,SAAS,WAAW,YAAY;EAC5C,MAAM,YAAY,KAAA;EAClB,UAAU,SAAS,UAAU;EAC7B,QAAQ;GACN,MAAM;GACN,YAAY,SAAS;GACrB,OAAO,cAAc,IAAI;GACzB,WAAW,SAAS;EACtB;CACF;AACF"}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* on `occurredAt desc` with one resumable cursor per kind.
|
|
5
5
|
*/
|
|
6
6
|
import type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';
|
|
7
|
-
import type { FactoryAttentionKind, FactoryDeferredDecisionRecord, WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
7
|
+
import type { FactoryAttentionKind, FactoryAttentionReceiptRecord, FactoryDeferredDecisionRecord, WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
8
8
|
export type FactoryAttentionView = 'open' | 'unread' | 'archived';
|
|
9
9
|
export interface AttentionScope {
|
|
10
10
|
orgId: string;
|
|
@@ -56,7 +56,31 @@ export interface AttentionProvider {
|
|
|
56
56
|
continuation?: AttentionStreamPosition;
|
|
57
57
|
}>;
|
|
58
58
|
}
|
|
59
|
+
export declare const SCAN_PAGE_SIZE = 50;
|
|
60
|
+
interface ScanBatch<T> {
|
|
61
|
+
rows: T[];
|
|
62
|
+
/** Set only when the page budget stopped a scan that still had rows behind it. */
|
|
63
|
+
continuation?: AttentionStreamPosition;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* One bounded keyset scan, shared by every provider read. Walks newest-first
|
|
67
|
+
* from `before` until the stream runs dry or the page budget is spent; the
|
|
68
|
+
* final batch of a budget stop carries the position to resume from.
|
|
69
|
+
*/
|
|
70
|
+
export declare function scanBatches<T>(fetchBatch: (before?: AttentionStreamPosition) => Promise<{
|
|
71
|
+
rows: T[];
|
|
72
|
+
hasMore: boolean;
|
|
73
|
+
}>, positionOf: (row: T) => AttentionStreamPosition, before?: AttentionStreamPosition): AsyncGenerator<ScanBatch<T>>;
|
|
74
|
+
/** Fills a page from the scan, stopping at `limit` entries or at the scan budget. */
|
|
75
|
+
export declare function collectPage<T>(batches: AsyncGenerator<ScanBatch<T>>, limit: number, toEntries: (rows: T[]) => Promise<AttentionEntry[]>): Promise<AttentionPageResult>;
|
|
76
|
+
/** Marks every scanned batch read, reporting where a budget stop left off. */
|
|
77
|
+
export declare function markScanRead<T>(batches: AsyncGenerator<ScanBatch<T>>, markBatch: (rows: T[]) => Promise<void>): Promise<{
|
|
78
|
+
hasMore: boolean;
|
|
79
|
+
continuation?: AttentionStreamPosition;
|
|
80
|
+
}>;
|
|
59
81
|
export declare function factoryDecisionType(decision: FactoryDeferredDecisionRecord): string;
|
|
82
|
+
export declare function matchesView(view: FactoryAttentionView, receipt: FactoryAttentionReceiptRecord | undefined): boolean;
|
|
83
|
+
export declare function workItemBoard(item: WorkItemRow): 'review' | 'work';
|
|
60
84
|
export declare class AutomationFailedAttentionProvider implements AttentionProvider {
|
|
61
85
|
#private;
|
|
62
86
|
readonly kind: "automation-failed";
|
|
@@ -98,4 +122,10 @@ export declare class MentionAttentionProvider implements AttentionProvider {
|
|
|
98
122
|
continuation?: AttentionStreamPosition;
|
|
99
123
|
}>;
|
|
100
124
|
}
|
|
125
|
+
export declare function receiptScope(scope: AttentionScope): {
|
|
126
|
+
orgId: string;
|
|
127
|
+
factoryProjectId: string;
|
|
128
|
+
userId: string;
|
|
129
|
+
};
|
|
130
|
+
export {};
|
|
101
131
|
//# sourceMappingURL=attention-providers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attention-providers.d.ts","sourceRoot":"","sources":["../../src/routes/attention-providers.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAEV,uBAAuB,EAExB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAEV,oBAAoB,
|
|
1
|
+
{"version":3,"file":"attention-providers.d.ts","sourceRoot":"","sources":["../../src/routes/attention-providers.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAEV,uBAAuB,EAExB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAEV,oBAAoB,EACpB,6BAA6B,EAC7B,6BAA6B,EAC7B,WAAW,EACX,gBAAgB,EACjB,MAAM,uCAAuC,CAAC;AAO/C,MAAM,MAAM,oBAAoB,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,CAAC;AAElE,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,IAAI,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,cAAc;IAC7B,UAAU,EAAE,IAAI,CAAC;IACjB,sEAAsE;IACtE,YAAY,EAAE,uBAAuB,CAAC;IACtC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC/B;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,oBAAoB,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,uBAAuB,CAAC;IACjC,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,uEAAuE;IACvE,OAAO,EAAE,OAAO,CAAC;IACjB,wEAAwE;IACxE,YAAY,CAAC,EAAE,uBAAuB,CAAC;CACxC;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,EAAE,EAA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it: 50
|
|
146
146
|
});
|
|
147
147
|
return {
|
|
148
148
|
rows: page.decisions,
|
|
@@ -216,8 +216,8 @@ var MentionAttentionProvider = class {
|
|
|
216
216
|
limit: 51
|
|
217
217
|
});
|
|
218
218
|
return {
|
|
219
|
-
rows: rows.slice(0,
|
|
220
|
-
hasMore: rows.length >
|
|
219
|
+
rows: rows.slice(0, 50),
|
|
220
|
+
hasMore: rows.length > 50
|
|
221
221
|
};
|
|
222
222
|
}, (mention) => ({
|
|
223
223
|
occurredAt: mention.occurredAt,
|
|
@@ -379,6 +379,6 @@ function receiptScope(scope) {
|
|
|
379
379
|
};
|
|
380
380
|
}
|
|
381
381
|
//#endregion
|
|
382
|
-
export { AutomationFailedAttentionProvider, MentionAttentionProvider, factoryDecisionType };
|
|
382
|
+
export { AutomationFailedAttentionProvider, MentionAttentionProvider, SCAN_PAGE_SIZE, collectPage, factoryDecisionType, markScanRead, matchesView, receiptScope, scanBatches, workItemBoard };
|
|
383
383
|
|
|
384
384
|
//# sourceMappingURL=attention-providers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attention-providers.js","names":["#workItems","#scan","#receiptsFor","#linkedItems","#comments","#resolve"],"sources":["../../src/routes/attention-providers.ts"],"sourcesContent":["/**\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 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\nconst 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 */\nasync 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. */\nasync 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. */\nasync 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\nfunction failureOccurredAt(decision: FactoryDeferredDecisionRecord): Date {\n return decision.completedAt ?? decision.updatedAt;\n}\n\nfunction 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: workItemBoard(item),\n };\n}\n\nfunction workItemBoard(item: WorkItemRow): 'review' | 'work' {\n const review = item.externalSource?.integrationId === 'github' && item.externalSource.type === 'pull-request';\n return review ? 'review' : 'work';\n}\n\nexport class AutomationFailedAttentionProvider implements AttentionProvider {\n readonly kind = 'automation-failed' as const;\n readonly #workItems: WorkItemsStorage;\n\n constructor({ workItems }: { workItems: WorkItemsStorage }) {\n this.#workItems = workItems;\n }\n\n async counts(scope: AttentionScope): Promise<AttentionCounts> {\n const [failedCount, receiptCount, archivedCount] = await Promise.all([\n this.#workItems.countDeferredDecisionsByStatuses({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n statuses: ['failed'],\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, failedCount - archivedCount),\n unread: Math.max(0, failedCount - receiptCount),\n };\n }\n\n async latest(scope: AttentionScope): Promise<AttentionLatest | null> {\n const page = await this.#workItems.listFailedDecisionPage({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n limit: 1,\n });\n const newest = page.decisions[0];\n if (!newest) return null;\n const identity = factoryDecisionAttentionIdentity(newest.id, newest.failureOccurrence);\n const receipts = await this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: [identity],\n });\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n at: failureOccurredAt(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.listFailedDecisionPage({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n before: cursor,\n limit: SCAN_PAGE_SIZE,\n });\n return { rows: page.decisions, hasMore: page.hasMore };\n },\n decision => ({ occurredAt: failureOccurredAt(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] = await Promise.all([\n this.#receiptsFor(scope, decisions),\n this.#linkedItems(scope, decisions),\n ]);\n const entries: AttentionEntry[] = [];\n for (const decision of decisions) {\n const identity = factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence);\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 && !matchesFailureSearch(decision, item, search)) continue;\n entries.push({\n occurredAt: failureOccurredAt(decision),\n resumeCursor: { occurredAt: failureOccurredAt(decision), id: decision.id },\n item: toFailureItem(scope, decision, item, receipt),\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 => factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence)),\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 =>\n factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence),\n ),\n now,\n });\n });\n }\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 matchesFailureSearch(\n decision: FactoryDeferredDecisionRecord,\n item: WorkItemRow | undefined,\n search: string,\n): boolean {\n return (\n item?.title.toLowerCase().includes(search) === true ||\n decision.lastError?.toLowerCase().includes(search) === true ||\n factoryDecisionType(decision).toLowerCase().includes(search)\n );\n}\n\nfunction toFailureItem(\n scope: AttentionScope,\n decision: FactoryDeferredDecisionRecord,\n item: WorkItemRow | undefined,\n receipt: FactoryAttentionReceiptRecord | undefined,\n) {\n const failure = factoryDispatchFailureMetadata(decision.failureCode);\n const identity = factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence);\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n kind: 'automation-failed' as const,\n decisionId: decision.id,\n occurrence: decision.failureOccurrence,\n workItemId: decision.workItemId,\n title: item?.title ?? failure.label,\n detail: decision.lastError?.slice(0, 512) ?? failure.label,\n decisionType: factoryDecisionType(decision),\n failureCode: decision.failureCode,\n canRetry: failure.canRetry,\n occurredAt: failureOccurredAt(decision).toISOString(),\n read: receipt !== undefined,\n archived: receipt?.state === 'archived',\n target: attentionTarget(decision, item),\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: workItemBoard(item),\n commentId: mention.commentId,\n },\n };\n}\n\nfunction receiptScope(scope: AttentionScope): { orgId: string; factoryProjectId: string; userId: string } {\n return { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId, userId: scope.userId };\n}\n"],"mappings":";;;;;;;;AAmFA,MAAM,iBAAiB;AAEvB,MAAM,yBAAyB;;;;;;AAa/B,gBAAgB,YACd,YACA,YACA,QAC8B;CAC9B,IAAI,SAAS;CACb,KAAK,IAAI,UAAU,GAAG,WAAW,wBAAwB,WAAW,GAAG;EACrE,MAAM,EAAE,MAAM,YAAY,MAAM,WAAW,MAAM;EACjD,MAAM,OAAO,KAAK,GAAG,EAAE;EACvB,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,WAAW,IAAI;EAChC,MAAM;GAAE;GAAM,GAAI,WAAW,YAAY,yBAAyB,EAAE,cAAc,SAAS,IAAI,CAAC;EAAG;EACnG,IAAI,CAAC,SAAS;EACd,SAAS;CACX;AACF;;AAGA,eAAe,YACb,SACA,OACA,WAC8B;CAC9B,MAAM,UAA4B,CAAC;CACnC,WAAW,MAAM,SAAS,SAAS;EACjC,KAAK,MAAM,SAAS,MAAM,UAAU,MAAM,IAAI,GAAG;GAC/C,IAAI,QAAQ,WAAW,OAAO,OAAO;IAAE;IAAS,SAAS;GAAK;GAC9D,QAAQ,KAAK,KAAK;EACpB;EACA,IAAI,MAAM,cAAc,OAAO;GAAE;GAAS,SAAS;GAAM,cAAc,MAAM;EAAa;CAC5F;CACA,OAAO;EAAE;EAAS,SAAS;CAAM;AACnC;;AAGA,eAAe,aACb,SACA,WACuE;CACvE,WAAW,MAAM,SAAS,SAAS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ems","#scan","#receiptsFor","#linkedItems","#comments","#resolve"],"sources":["../../src/routes/attention-providers.ts"],"sourcesContent":["/**\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 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\nfunction failureOccurredAt(decision: FactoryDeferredDecisionRecord): Date {\n return decision.completedAt ?? decision.updatedAt;\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: workItemBoard(item),\n };\n}\n\nexport function workItemBoard(item: WorkItemRow): 'review' | 'work' {\n const review = item.externalSource?.integrationId === 'github' && item.externalSource.type === 'pull-request';\n return review ? 'review' : 'work';\n}\n\nexport class AutomationFailedAttentionProvider implements AttentionProvider {\n readonly kind = 'automation-failed' as const;\n readonly #workItems: WorkItemsStorage;\n\n constructor({ workItems }: { workItems: WorkItemsStorage }) {\n this.#workItems = workItems;\n }\n\n async counts(scope: AttentionScope): Promise<AttentionCounts> {\n const [failedCount, receiptCount, archivedCount] = await Promise.all([\n this.#workItems.countDeferredDecisionsByStatuses({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n statuses: ['failed'],\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, failedCount - archivedCount),\n unread: Math.max(0, failedCount - receiptCount),\n };\n }\n\n async latest(scope: AttentionScope): Promise<AttentionLatest | null> {\n const page = await this.#workItems.listFailedDecisionPage({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n limit: 1,\n });\n const newest = page.decisions[0];\n if (!newest) return null;\n const identity = factoryDecisionAttentionIdentity(newest.id, newest.failureOccurrence);\n const receipts = await this.#workItems.listAttentionReceipts({\n ...receiptScope(scope),\n identities: [identity],\n });\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n at: failureOccurredAt(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.listFailedDecisionPage({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n before: cursor,\n limit: SCAN_PAGE_SIZE,\n });\n return { rows: page.decisions, hasMore: page.hasMore };\n },\n decision => ({ occurredAt: failureOccurredAt(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] = await Promise.all([\n this.#receiptsFor(scope, decisions),\n this.#linkedItems(scope, decisions),\n ]);\n const entries: AttentionEntry[] = [];\n for (const decision of decisions) {\n const identity = factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence);\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 && !matchesFailureSearch(decision, item, search)) continue;\n entries.push({\n occurredAt: failureOccurredAt(decision),\n resumeCursor: { occurredAt: failureOccurredAt(decision), id: decision.id },\n item: toFailureItem(scope, decision, item, receipt),\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 => factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence)),\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 =>\n factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence),\n ),\n now,\n });\n });\n }\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 matchesFailureSearch(\n decision: FactoryDeferredDecisionRecord,\n item: WorkItemRow | undefined,\n search: string,\n): boolean {\n return (\n item?.title.toLowerCase().includes(search) === true ||\n decision.lastError?.toLowerCase().includes(search) === true ||\n factoryDecisionType(decision).toLowerCase().includes(search)\n );\n}\n\nfunction toFailureItem(\n scope: AttentionScope,\n decision: FactoryDeferredDecisionRecord,\n item: WorkItemRow | undefined,\n receipt: FactoryAttentionReceiptRecord | undefined,\n) {\n const failure = factoryDispatchFailureMetadata(decision.failureCode);\n const identity = factoryDecisionAttentionIdentity(decision.id, decision.failureOccurrence);\n return {\n key: factoryAttentionKey(scope.factoryProjectId, identity),\n kind: 'automation-failed' as const,\n decisionId: decision.id,\n occurrence: decision.failureOccurrence,\n workItemId: decision.workItemId,\n title: item?.title ?? failure.label,\n detail: decision.lastError?.slice(0, 512) ?? failure.label,\n decisionType: factoryDecisionType(decision),\n failureCode: decision.failureCode,\n canRetry: failure.canRetry,\n occurredAt: failureOccurredAt(decision).toISOString(),\n read: receipt !== undefined,\n archived: receipt?.state === 'archived',\n target: attentionTarget(decision, item),\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: workItemBoard(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":";;;;;;;;AAmFA,MAAa,iBAAiB;AAE9B,MAAM,yBAAyB;;;;;;AAa/B,gBAAuB,YACrB,YACA,YACA,QAC8B;CAC9B,IAAI,SAAS;CACb,KAAK,IAAI,UAAU,GAAG,WAAW,wBAAwB,WAAW,GAAG;EACrE,MAAM,EAAE,MAAM,YAAY,MAAM,WAAW,MAAM;EACjD,MAAM,OAAO,KAAK,GAAG,EAAE;EACvB,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,WAAW,IAAI;EAChC,MAAM;GAAE;GA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,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,cAAc,IAAI;GACzB,WAAW,QAAQ;EACrB;CACF;AACF;AAEA,SAAgB,aAAa,OAAoF;CAC/G,OAAO;EAAE,OAAO,MAAM;EAAO,kBAAkB,MAAM;EAAkB,QAAQ,MAAM;CAAO;AAC9F"}
|
|
@@ -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;AAGpD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AACnF,OAAO,KAAK,EAGV,gBAAgB,EACjB,MAAM,uCAAuC,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;AAGpD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AACnF,OAAO,KAAK,EAGV,gBAAgB,EACjB,MAAM,uCAAuC,CAAC;AAG/C,OAAO,KAAK,EAIV,cAAc,EAGf,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAM/D,UAAU,0BAA0B;IAClC,SAAS,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,EAAE,uBAAuB,CAAC;IAClC,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,GAAG;QAAE,QAAQ,EAAE,QAAQ,CAAA;KAAE,CAAC,CAAC;CACpF;AAmMD,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,0BAA0B,GAAG,QAAQ,EAAE,CA8HzF"}
|
package/dist/routes/attention.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { factoryAttentionKey } from "../storage/domains/work-items/base.js";
|
|
2
2
|
import { AutomationFailedAttentionProvider, MentionAttentionProvider, factoryDecisionType } from "./attention-providers.js";
|
|
3
|
+
import { ActivityAttentionProvider } from "./attention-activity.js";
|
|
3
4
|
import { registerApiRoute } from "@mastra/core/server";
|
|
4
5
|
//#region src/routes/attention.ts
|
|
5
6
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
@@ -15,7 +16,17 @@ function parseAttentionLimit(raw) {
|
|
|
15
16
|
return Math.max(1, Math.min(MAX_PAGE_SIZE, parsed));
|
|
16
17
|
}
|
|
17
18
|
function isAttentionKind(value) {
|
|
18
|
-
return value === "automation-failed" || value === "mention";
|
|
19
|
+
return value === "automation-failed" || value === "mention" || value === "activity";
|
|
20
|
+
}
|
|
21
|
+
/** Kinds the sidebar badge and the notification sound answer to. */
|
|
22
|
+
const BADGE_KINDS = /* @__PURE__ */ new Set(["automation-failed", "mention"]);
|
|
23
|
+
function parseAttentionTier(raw) {
|
|
24
|
+
if (raw === void 0) return "all";
|
|
25
|
+
return raw === "badge" || raw === "activity" ? raw : void 0;
|
|
26
|
+
}
|
|
27
|
+
function kindInTier(tier, kind) {
|
|
28
|
+
if (tier === "all") return true;
|
|
29
|
+
return tier === "badge" ? BADGE_KINDS.has(kind) : !BADGE_KINDS.has(kind);
|
|
19
30
|
}
|
|
20
31
|
function encodeAttentionCursor(cursors) {
|
|
21
32
|
const wire = {};
|
|
@@ -153,10 +164,17 @@ function receiptRoute(dependencies, verb, action) {
|
|
|
153
164
|
}
|
|
154
165
|
function buildAttentionRoutes(dependencies) {
|
|
155
166
|
const { workItems, comments } = dependencies;
|
|
156
|
-
const providers = [
|
|
157
|
-
workItems,
|
|
158
|
-
|
|
159
|
-
|
|
167
|
+
const providers = [
|
|
168
|
+
new AutomationFailedAttentionProvider({ workItems }),
|
|
169
|
+
new MentionAttentionProvider({
|
|
170
|
+
workItems,
|
|
171
|
+
comments
|
|
172
|
+
}),
|
|
173
|
+
new ActivityAttentionProvider({
|
|
174
|
+
workItems,
|
|
175
|
+
comments
|
|
176
|
+
})
|
|
177
|
+
];
|
|
160
178
|
return [
|
|
161
179
|
registerApiRoute("/web/factory/projects/:id/attention", {
|
|
162
180
|
method: "GET",
|
|
@@ -166,6 +184,8 @@ function buildAttentionRoutes(dependencies) {
|
|
|
166
184
|
if ("response" in resolved) return resolved.response;
|
|
167
185
|
const view = parseAttentionView(context.req.query("view"));
|
|
168
186
|
if (view === void 0) return context.json({ error: "invalid_attention_view" }, 400);
|
|
187
|
+
const tier = parseAttentionTier(context.req.query("tier"));
|
|
188
|
+
if (tier === void 0) return context.json({ error: "invalid_attention_tier" }, 400);
|
|
169
189
|
const cursorRaw = context.req.query("before");
|
|
170
190
|
const before = parseAttentionCursor(cursorRaw);
|
|
171
191
|
if (cursorRaw && !before) return context.json({ error: "invalid_cursor" }, 400);
|
|
@@ -173,15 +193,18 @@ function buildAttentionRoutes(dependencies) {
|
|
|
173
193
|
await comments.ensureReady();
|
|
174
194
|
const search = context.req.query("search")?.trim().toLowerCase().slice(0, 200);
|
|
175
195
|
const limit = parseAttentionLimit(context.req.query("limit"));
|
|
176
|
-
const active = providers.filter((provider) => !before || before.has(provider.kind));
|
|
177
|
-
const [approvalCount,
|
|
196
|
+
const active = providers.filter((provider) => kindInTier(tier, provider.kind) && (!before || before.has(provider.kind)));
|
|
197
|
+
const [approvalCount, summaries, pages] = await Promise.all([
|
|
178
198
|
workItems.countDeferredDecisionsByStatuses({
|
|
179
199
|
orgId: resolved.orgId,
|
|
180
200
|
factoryProjectId: resolved.factoryProjectId,
|
|
181
201
|
statuses: ["proposed"]
|
|
182
202
|
}),
|
|
183
|
-
Promise.all(providers.map((provider) =>
|
|
184
|
-
|
|
203
|
+
Promise.all(providers.map(async (provider) => ({
|
|
204
|
+
kind: provider.kind,
|
|
205
|
+
counts: await provider.counts(resolved),
|
|
206
|
+
latest: await provider.latest(resolved)
|
|
207
|
+
}))),
|
|
185
208
|
Promise.all(active.map(async (provider) => ({
|
|
186
209
|
kind: provider.kind,
|
|
187
210
|
incoming: before?.get(provider.kind),
|
|
@@ -193,8 +216,12 @@ function buildAttentionRoutes(dependencies) {
|
|
|
193
216
|
})
|
|
194
217
|
})))
|
|
195
218
|
]);
|
|
196
|
-
const
|
|
197
|
-
const
|
|
219
|
+
const badge = summaries.filter((summary) => BADGE_KINDS.has(summary.kind));
|
|
220
|
+
const activity = summaries.filter((summary) => !BADGE_KINDS.has(summary.kind));
|
|
221
|
+
const sum = (rows, field) => rows.reduce((total, row) => total + row.counts[field], 0);
|
|
222
|
+
const openCount = sum(badge, "open") + approvalCount;
|
|
223
|
+
const unreadCount = sum(badge, "unread");
|
|
224
|
+
const latests = badge.map((summary) => summary.latest);
|
|
198
225
|
const unreadLatests = latests.filter((latest) => latest?.unread ?? false);
|
|
199
226
|
const latest = unreadLatests.length > 0 ? newestLatest(unreadLatests) : newestLatest(latests);
|
|
200
227
|
const merged = mergeAttentionPages(pages, limit);
|
|
@@ -204,6 +231,7 @@ function buildAttentionRoutes(dependencies) {
|
|
|
204
231
|
approvalCount,
|
|
205
232
|
badgeCount: unreadCount + approvalCount,
|
|
206
233
|
unreadCount,
|
|
234
|
+
activityUnreadCount: sum(activity, "unread"),
|
|
207
235
|
latestOccurrenceKey: latest?.key ?? null,
|
|
208
236
|
latestOccurrenceAt: latest?.at.toISOString() ?? null,
|
|
209
237
|
latestOccurrenceUnread: latest?.unread ?? false,
|
|
@@ -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';\n\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 type {\n AttentionLatest,\n AttentionPageResult,\n AttentionProvider,\n AttentionScope,\n AttentionStreamPosition,\n FactoryAttentionView,\n} from './attention-providers.js';\nimport { AutomationFailedAttentionProvider, MentionAttentionProvider } from './attention-providers.js';\n\nexport { factoryDecisionType } from './attention-providers.js';\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DEFAULT_PAGE_SIZE = 25;\nconst MAX_PAGE_SIZE = 50;\n\ninterface AttentionRouteDependencies {\n workItems: WorkItemsStorage;\n comments: WorkItemCommentsStorage;\n resolveProject(context: unknown): Promise<AttentionScope | { response: Response }>;\n}\n\ntype AttentionCursorMap = Map<FactoryAttentionKind, AttentionStreamPosition | undefined>;\n\nfunction parseAttentionView(raw: string | undefined): FactoryAttentionView | undefined {\n if (!raw || raw === 'open') return 'open';\n if (raw === 'unread' || raw === 'archived') return raw;\n return undefined;\n}\n\nfunction parseAttentionLimit(raw: string | undefined): number {\n const parsed = raw ? Number.parseInt(raw, 10) : DEFAULT_PAGE_SIZE;\n if (!Number.isFinite(parsed)) return DEFAULT_PAGE_SIZE;\n return Math.max(1, Math.min(MAX_PAGE_SIZE, parsed));\n}\n\nfunction isAttentionKind(value: string): value is FactoryAttentionKind {\n return value === 'automation-failed' || value === 'mention';\n}\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\nfunction parseStreamPosition(value: unknown): AttentionStreamPosition | undefined {\n if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== 'string' || typeof value[1] !== 'string') {\n return undefined;\n }\n const occurredAt = new Date(value[0]);\n if (Number.isNaN(occurredAt.getTime()) || !UUID_RE.test(value[1])) return undefined;\n return { occurredAt, id: value[1] };\n}\n\nfunction parseAttentionCursor(raw: string | undefined): AttentionCursorMap | undefined {\n if (!raw) return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));\n // Cursors minted before the inbox merged kinds are a bare position over the\n // only stream there was. Held by anyone mid-list when this deploys, so they\n // resume that stream rather than 400: mentions arrive on their next load.\n if (Array.isArray(decoded)) {\n const legacy = parseStreamPosition(decoded);\n return legacy ? new Map([['automation-failed', legacy]]) : undefined;\n }\n if (!decoded || typeof decoded !== 'object') return undefined;\n const cursors: AttentionCursorMap = new Map();\n for (const [kind, value] of Object.entries(decoded)) {\n if (!isAttentionKind(kind)) return undefined;\n if (value === null) {\n cursors.set(kind, undefined);\n continue;\n }\n const position = parseStreamPosition(value);\n if (!position) return undefined;\n cursors.set(kind, position);\n }\n return cursors.size > 0 ? cursors : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction parseOccurrence(raw: string | undefined): number | undefined {\n if (!raw || !/^(0|[1-9]\\d*)$/.test(raw)) return undefined;\n const occurrence = Number(raw);\n return Number.isSafeInteger(occurrence) ? occurrence : undefined;\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 newestLatest(latests: Array<AttentionLatest | null>): AttentionLatest | null {\n let newest: AttentionLatest | null = null;\n for (const latest of latests) {\n if (!latest) continue;\n if (!newest || latest.at.getTime() > newest.at.getTime()) newest = latest;\n }\n return newest;\n}\n\nfunction receiptRoute(\n dependencies: AttentionRouteDependencies,\n verb: 'read' | 'archive' | 'restore',\n action: FactoryAttentionReceiptAction,\n): ApiRoute {\n return registerApiRoute(`/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/${verb}`, {\n method: 'POST',\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const kind = context.req.param('kind');\n const sourceId = context.req.param('sourceId');\n const occurrence = parseOccurrence(context.req.param('occurrence'));\n if (!kind || !isAttentionKind(kind) || !sourceId || !UUID_RE.test(sourceId) || occurrence === undefined) {\n return context.json({ error: 'invalid_attention_item' }, 422);\n }\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, comments } = dependencies;\n const providers: AttentionProvider[] = [\n new AutomationFailedAttentionProvider({ workItems }),\n new MentionAttentionProvider({ workItems, comments }),\n ];\n\n return [\n registerApiRoute('/web/factory/projects/:id/attention', {\n method: 'GET',\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const view = parseAttentionView(context.req.query('view'));\n if (view === undefined) return context.json({ error: 'invalid_attention_view' }, 400);\n const cursorRaw = context.req.query('before');\n const before = parseAttentionCursor(cursorRaw);\n if (cursorRaw && !before) return context.json({ error: 'invalid_cursor' }, 400);\n await workItems.ensureReady();\n await comments.ensureReady();\n\n const search = context.req.query('search')?.trim().toLowerCase().slice(0, 200);\n const limit = parseAttentionLimit(context.req.query('limit'));\n const active = providers.filter(provider => !before || before.has(provider.kind));\n\n const [approvalCount, counts, latests, pages] = await Promise.all([\n workItems.countDeferredDecisionsByStatuses({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n statuses: ['proposed'],\n }),\n Promise.all(providers.map(provider => provider.counts(resolved))),\n Promise.all(providers.map(provider => provider.latest(resolved))),\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 openCount = counts.reduce((sum, count) => sum + count.open, 0) + approvalCount;\n const unreadCount = counts.reduce((sum, count) => sum + count.unread, 0);\n // An unread item must never be masked by a newer already-read one of\n // another kind — the streams are independent.\n const unreadLatests = latests.filter(latest => latest?.unread ?? false);\n const latest = unreadLatests.length > 0 ? newestLatest(unreadLatests) : newestLatest(latests);\n const merged = mergeAttentionPages(pages, limit);\n\n return context.json({\n items: merged.items,\n openCount,\n approvalCount,\n badgeCount: unreadCount + approvalCount,\n unreadCount,\n latestOccurrenceKey: latest?.key ?? null,\n latestOccurrenceAt: latest?.at.toISOString() ?? null,\n latestOccurrenceUnread: latest?.unread ?? false,\n hasMore: merged.hasMore,\n ...(merged.nextCursor ? { nextCursor: merged.nextCursor } : {}),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/attention/read-all', {\n method: 'POST',\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const cursorRaw = context.req.query('before');\n const before = parseAttentionCursor(cursorRaw);\n if (cursorRaw && !before) return context.json({ error: 'invalid_cursor' }, 400);\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":";;;;AA4BA,MAAM,UAAU;AAChB,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAUtB,SAAS,mBAAmB,KAA2D;CACrF,IAAI,CAAC,OAAO,QAAQ,QAAQ,OAAO;CACnC,IAAI,QAAQ,YAAY,QAAQ,YAAY,OAAO;AAErD;AAEA,SAAS,oBAAoB,KAAiC;CAC5D,MAAM,SAAS,MAAM,OAAO,SAAS,KAAK,EAAE,IAAI;CAChD,IAAI,CAAC,OAAO,SAAS,MAAM,GAAG,OAAO;CACrC,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,eAAe,MAAM,CAAC;AACpD;AAEA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,UAAU,uBAAuB,UAAU;AACpD;AAEA,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;AAEA,SAAS,oBAAoB,OAAqD;CAChF,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,KAAK,OAAO,MAAM,OAAO,YAAY,OAAO,MAAM,OAAO,UACrG;CAEF,MAAM,aAAa,IAAI,KAAK,MAAM,EAAE;CACpC,IAAI,OAAO,MAAM,WAAW,QAAQ,CAAC,KAAK,CAAC,QAAQ,KAAK,MAAM,EAAE,GAAG,OAAO,KAAA;CAC1E,OAAO;EAAE;EAAY,IAAI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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';\n\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 type {\n AttentionLatest,\n AttentionPageResult,\n AttentionProvider,\n AttentionScope,\n AttentionStreamPosition,\n FactoryAttentionView,\n} from './attention-providers.js';\nimport { AutomationFailedAttentionProvider, MentionAttentionProvider } from './attention-providers.js';\n\nexport { factoryDecisionType } from './attention-providers.js';\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DEFAULT_PAGE_SIZE = 25;\nconst MAX_PAGE_SIZE = 50;\n\ninterface AttentionRouteDependencies {\n workItems: WorkItemsStorage;\n comments: WorkItemCommentsStorage;\n resolveProject(context: unknown): Promise<AttentionScope | { response: Response }>;\n}\n\ntype AttentionCursorMap = Map<FactoryAttentionKind, AttentionStreamPosition | undefined>;\n\nfunction parseAttentionView(raw: string | undefined): FactoryAttentionView | undefined {\n if (!raw || raw === 'open') return 'open';\n if (raw === 'unread' || raw === 'archived') return raw;\n return undefined;\n}\n\nfunction parseAttentionLimit(raw: string | undefined): number {\n const parsed = raw ? Number.parseInt(raw, 10) : DEFAULT_PAGE_SIZE;\n if (!Number.isFinite(parsed)) return DEFAULT_PAGE_SIZE;\n return Math.max(1, Math.min(MAX_PAGE_SIZE, parsed));\n}\n\nfunction isAttentionKind(value: string): value is FactoryAttentionKind {\n return value === 'automation-failed' || value === 'mention' || value === 'activity';\n}\n\n/** Kinds the sidebar badge and the notification sound answer to. */\nconst BADGE_KINDS: ReadonlySet<FactoryAttentionKind> = new Set(['automation-failed', 'mention']);\n\ntype AttentionTier = 'all' | 'badge' | 'activity';\n\nfunction parseAttentionTier(raw: string | undefined): AttentionTier | undefined {\n if (raw === undefined) return 'all';\n return raw === 'badge' || raw === 'activity' ? raw : undefined;\n}\n\nfunction kindInTier(tier: AttentionTier, kind: FactoryAttentionKind): boolean {\n if (tier === 'all') return true;\n return tier === 'badge' ? BADGE_KINDS.has(kind) : !BADGE_KINDS.has(kind);\n}\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\nfunction parseStreamPosition(value: unknown): AttentionStreamPosition | undefined {\n if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== 'string' || typeof value[1] !== 'string') {\n return undefined;\n }\n const occurredAt = new Date(value[0]);\n if (Number.isNaN(occurredAt.getTime()) || !UUID_RE.test(value[1])) return undefined;\n return { occurredAt, id: value[1] };\n}\n\nfunction parseAttentionCursor(raw: string | undefined): AttentionCursorMap | undefined {\n if (!raw) return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));\n // Cursors minted before the inbox merged kinds are a bare position over the\n // only stream there was. Held by anyone mid-list when this deploys, so they\n // resume that stream rather than 400: mentions arrive on their next load.\n if (Array.isArray(decoded)) {\n const legacy = parseStreamPosition(decoded);\n return legacy ? new Map([['automation-failed', legacy]]) : undefined;\n }\n if (!decoded || typeof decoded !== 'object') return undefined;\n const cursors: AttentionCursorMap = new Map();\n for (const [kind, value] of Object.entries(decoded)) {\n if (!isAttentionKind(kind)) return undefined;\n if (value === null) {\n cursors.set(kind, undefined);\n continue;\n }\n const position = parseStreamPosition(value);\n if (!position) return undefined;\n cursors.set(kind, position);\n }\n return cursors.size > 0 ? cursors : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction parseOccurrence(raw: string | undefined): number | undefined {\n if (!raw || !/^(0|[1-9]\\d*)$/.test(raw)) return undefined;\n const occurrence = Number(raw);\n return Number.isSafeInteger(occurrence) ? occurrence : undefined;\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 newestLatest(latests: Array<AttentionLatest | null>): AttentionLatest | null {\n let newest: AttentionLatest | null = null;\n for (const latest of latests) {\n if (!latest) continue;\n if (!newest || latest.at.getTime() > newest.at.getTime()) newest = latest;\n }\n return newest;\n}\n\nfunction receiptRoute(\n dependencies: AttentionRouteDependencies,\n verb: 'read' | 'archive' | 'restore',\n action: FactoryAttentionReceiptAction,\n): ApiRoute {\n return registerApiRoute(`/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/${verb}`, {\n method: 'POST',\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const kind = context.req.param('kind');\n const sourceId = context.req.param('sourceId');\n const occurrence = parseOccurrence(context.req.param('occurrence'));\n if (!kind || !isAttentionKind(kind) || !sourceId || !UUID_RE.test(sourceId) || occurrence === undefined) {\n return context.json({ error: 'invalid_attention_item' }, 422);\n }\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, comments } = dependencies;\n const providers: AttentionProvider[] = [\n new AutomationFailedAttentionProvider({ workItems }),\n new MentionAttentionProvider({ workItems, comments }),\n new ActivityAttentionProvider({ workItems, comments }),\n ];\n\n return [\n registerApiRoute('/web/factory/projects/:id/attention', {\n method: 'GET',\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const view = parseAttentionView(context.req.query('view'));\n if (view === undefined) return context.json({ error: 'invalid_attention_view' }, 400);\n // `tier` scopes the item list only; the counts always describe every\n // tier, so the badge popover can page badge kinds without losing the\n // activity numbers.\n const tier = parseAttentionTier(context.req.query('tier'));\n if (tier === undefined) return context.json({ error: 'invalid_attention_tier' }, 400);\n const cursorRaw = context.req.query('before');\n const before = parseAttentionCursor(cursorRaw);\n if (cursorRaw && !before) return context.json({ error: 'invalid_cursor' }, 400);\n await workItems.ensureReady();\n await comments.ensureReady();\n\n const search = context.req.query('search')?.trim().toLowerCase().slice(0, 200);\n const limit = parseAttentionLimit(context.req.query('limit'));\n const active = providers.filter(\n provider => kindInTier(tier, provider.kind) && (!before || before.has(provider.kind)),\n );\n\n const [approvalCount, summaries, pages] = await Promise.all([\n workItems.countDeferredDecisionsByStatuses({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n statuses: ['proposed'],\n }),\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 // The badge tier and the activity tier are counted apart: activity\n // leaking into `latests` would ring the notification sound on every\n // teammate comment.\n const badge = summaries.filter(summary => BADGE_KINDS.has(summary.kind));\n const activity = summaries.filter(summary => !BADGE_KINDS.has(summary.kind));\n const sum = (rows: typeof summaries, field: 'open' | 'unread') =>\n rows.reduce((total, row) => total + row.counts[field], 0);\n const openCount = sum(badge, 'open') + approvalCount;\n const unreadCount = sum(badge, 'unread');\n // An unread item must never be masked by a newer already-read one of\n // another kind — the streams are independent.\n const latests = badge.map(summary => summary.latest);\n const unreadLatests = latests.filter(latest => latest?.unread ?? false);\n const latest = unreadLatests.length > 0 ? newestLatest(unreadLatests) : newestLatest(latests);\n const merged = mergeAttentionPages(pages, limit);\n\n return context.json({\n items: merged.items,\n openCount,\n approvalCount,\n badgeCount: unreadCount + approvalCount,\n unreadCount,\n activityUnreadCount: sum(activity, 'unread'),\n latestOccurrenceKey: latest?.key ?? null,\n latestOccurrenceAt: latest?.at.toISOString() ?? null,\n latestOccurrenceUnread: latest?.unread ?? false,\n hasMore: merged.hasMore,\n ...(merged.nextCursor ? { nextCursor: merged.nextCursor } : {}),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/attention/read-all', {\n method: 'POST',\n requiresAuth: false,\n handler: async context => {\n const resolved = await dependencies.resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const cursorRaw = context.req.query('before');\n const before = parseAttentionCursor(cursorRaw);\n if (cursorRaw && !before) return context.json({ error: 'invalid_cursor' }, 400);\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":";;;;;AA6BA,MAAM,UAAU;AAChB,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAUtB,SAAS,mBAAmB,KAA2D;CACrF,IAAI,CAAC,OAAO,QAAQ,QAAQ,OAAO;CACnC,IAAI,QAAQ,YAAY,QAAQ,YAAY,OAAO;AAErD;AAEA,SAAS,oBAAoB,KAAiC;CAC5D,MAAM,SAAS,MAAM,OAAO,SAAS,KAAK,EAAE,IAAI;CAChD,IAAI,CAAC,OAAO,SAAS,MAAM,GAAG,OAAO;CACrC,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,eAAe,MAAM,CAAC;AACpD;AAEA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,UAAU,uBAAuB,UAAU,aAAa,UAAU;AAC3E;;AAGA,MAAM,8BAAiD,IAAI,IAAI,CAAC,qBAAqB,SAAS,CAAC;AAI/F,SAAS,mBAAmB,KAAoD;CAC9E,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,OAAO,QAAQ,WAAW,QAAQ,aAAa,MAAM,KAAA;AACvD;AAEA,SAAS,WAAW,MAAqB,MAAqC;CAC5E,IAAI,SAAS,OAAO,OAAO;CAC3B,OAAO,SAAS,UAAU,YAAY,IAAI,IAAI,IAAI,CAAC,YAAY,IAAI,IAAI;AACzE;AAEA,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,WA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