@mastra/factory 0.30.0-alpha.3 → 0.30.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/boards/phase-runner.d.ts +2 -0
- package/dist/boards/phase-runner.d.ts.map +1 -1
- package/dist/boards/phase-runner.js +1 -1
- package/dist/boards/phase-runner.js.map +1 -1
- package/dist/factory.js.map +1 -1
- package/dist/integrations/slack/chat-tools.d.ts.map +1 -1
- package/dist/integrations/slack/chat-tools.js +62 -0
- package/dist/integrations/slack/chat-tools.js.map +1 -1
- package/dist/mcp/routes.d.ts.map +1 -1
- package/dist/mcp/routes.js +6 -5
- package/dist/mcp/routes.js.map +1 -1
- package/dist/routes/contracts.d.ts +1 -1
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +9 -3
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/work-item-selection.d.ts +2 -2
- package/dist/routes/work-item-selection.js +7 -7
- package/dist/routes/work-item-selection.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +2 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/phase-goal.d.ts +4 -0
- package/dist/rules/phase-goal.d.ts.map +1 -1
- package/dist/rules/phase-goal.js +6 -3
- package/dist/rules/phase-goal.js.map +1 -1
- package/dist/rules/transition-service.d.ts +2 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +44 -14
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +28 -0
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +6 -10
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/reports.d.ts +3 -0
- package/dist/tools/reports.d.ts.map +1 -1
- package/dist/tools/reports.js +7 -2
- package/dist/tools/reports.js.map +1 -1
- package/dist/work-items/board-phases.js +4 -4
- package/dist/work-items/board-phases.js.map +1 -1
- package/dist/work-items/card-facts.d.ts +3 -2
- package/dist/work-items/card-facts.d.ts.map +1 -1
- package/dist/work-items/card-facts.js +2 -2
- package/dist/work-items/card-facts.js.map +1 -1
- package/dist/work-items/card-number.d.ts +11 -2
- package/dist/work-items/card-number.d.ts.map +1 -1
- package/dist/work-items/card-number.js +2 -1
- package/dist/work-items/card-number.js.map +1 -1
- package/dist/work-items/card-reference.d.ts +2 -0
- package/dist/work-items/card-reference.d.ts.map +1 -1
- package/dist/work-items/card-reference.js +2 -1
- package/dist/work-items/card-reference.js.map +1 -1
- package/dist/work-items/card-search.d.ts +5 -0
- package/dist/work-items/card-search.d.ts.map +1 -0
- package/dist/work-items/card-search.js +19 -0
- package/dist/work-items/card-search.js.map +1 -0
- package/dist/work-items/search-terms.d.ts +75 -0
- package/dist/work-items/search-terms.d.ts.map +1 -0
- package/dist/work-items/search-terms.js +93 -0
- package/dist/work-items/search-terms.js.map +1 -0
- package/dist/work-items/search-words.d.ts +5 -2
- package/dist/work-items/search-words.d.ts.map +1 -1
- package/dist/work-items/search-words.js +7 -4
- package/dist/work-items/search-words.js.map +1 -1
- package/package.json +5 -5
- package/dist/work-items/card-search-text.d.ts +0 -4
- package/dist/work-items/card-search-text.d.ts.map +0 -1
- package/dist/work-items/card-search-text.js +0 -15
- package/dist/work-items/card-search-text.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read-tools.d.ts","sourceRoot":"","sources":["../../src/tools/read-tools.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AASxB,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,oBAAoB,CAAC;AAExE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBA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mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,gBAAgB,EAAE,YAAY,CAAC,GAAG,IAAI,CAAC,CAAC;IACvE,sFAAsF;IACtF,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC,YAAY,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG,SAAS,CAAC;CAC5E;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAE1D;AAQD,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,GAAG,MAAM,CAEhE;AAED;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,aAU3B,CAAC;AAEJ;;;GAGG;AACH,wBAAsB,YAAY,CAChC,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,YAAY,GAAG,eAAe,CAAC,EACjE,KAAK,EAAE,IAAI,CAAC,gBAAgB,EAAE,OAAO,GAAG,kBAAkB,CAAC,EAC3D,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAsBtB;AAoCD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,KAAK,CAEnD;AAiGD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,gBAAgB,EAAE,IAAI,EAAE,2BAA2B,GAAG,gBAAgB,CA8NnH"}
|
package/dist/tools/read-tools.js
CHANGED
|
@@ -7,8 +7,10 @@ import { parkedRunLabel } from "../routes/attention-parked.js";
|
|
|
7
7
|
import { decisionRetryable, overtakenDecisionIds } from "../rules/decision-applicability.js";
|
|
8
8
|
import { factoryDispatchFailureMetadata } from "../rules/dispatch-errors.js";
|
|
9
9
|
import { needsApproval } from "../rules/types.js";
|
|
10
|
+
import { cardFacts } from "../work-items/card-facts.js";
|
|
10
11
|
import { workItemNumber } from "../work-items/card-number.js";
|
|
11
|
-
import { cardCarries, isCardFor, isSourceReference
|
|
12
|
+
import { cardCarries, isCardFor, isSourceReference } from "../work-items/card-reference.js";
|
|
13
|
+
import { matchesSearch, searchTerms } from "../work-items/search-terms.js";
|
|
12
14
|
import { sessionActivity } from "./deliver.js";
|
|
13
15
|
import { createTool } from "@mastra/core/tools";
|
|
14
16
|
import { z } from "zod";
|
|
@@ -153,7 +155,7 @@ function isHeld(boards, item) {
|
|
|
153
155
|
return !item.stageHistory.some((entry) => entry.stage !== triage && board.isWorking(entry.stage));
|
|
154
156
|
}
|
|
155
157
|
const listInputSchema = z.object({
|
|
156
|
-
query: z.string().trim().min(1).max(200).optional().describe("
|
|
158
|
+
query: z.string().trim().min(1).max(200).optional().describe("What the board's search box takes: case-insensitive words of the title, a whole card number like \"#123\", a key (ENG-42, owner/repo#123), a branch or card id, or the link of an issue or pull request, which finds the cards tracking it, a pull request attached to its issue's card included."),
|
|
157
159
|
stage: z.string().min(1).max(64).optional().describe("Only items in this stage, by its key as items list it (e.g. \"intake\" or \"planning\"); a board's review stage key can differ from its name."),
|
|
158
160
|
board: z.string().min(1).max(64).optional().describe("Only items on this board, by its key, e.g. \"work\"."),
|
|
159
161
|
role: z.string().min(1).max(64).optional().describe("Only items that have a session for this role."),
|
|
@@ -187,15 +189,9 @@ function createFactoryReadTools(scope, deps) {
|
|
|
187
189
|
const stage = workItemStage(item);
|
|
188
190
|
byStage[stage] = (byStage[stage] ?? 0) + 1;
|
|
189
191
|
}
|
|
190
|
-
const
|
|
191
|
-
const sourceQuery = input.query && numberQuery === void 0 && sourceKeyFromReference(input.query) !== null ? input.query : void 0;
|
|
192
|
-
const text = input.query?.toLowerCase();
|
|
192
|
+
const terms = searchTerms(input.query ?? "");
|
|
193
193
|
const matches = items.filter((item) => {
|
|
194
|
-
if (
|
|
195
|
-
if (workItemNumber(item) !== Number(numberQuery)) return false;
|
|
196
|
-
} else if (sourceQuery !== void 0) {
|
|
197
|
-
if (!cardCarries(item, sourceQuery)) return false;
|
|
198
|
-
} else if (text && !item.title.toLowerCase().includes(text)) return false;
|
|
194
|
+
if (!matchesSearch(cardFacts(item).search, terms)) return false;
|
|
199
195
|
if (input.stage && !item.stages.includes(input.stage)) return false;
|
|
200
196
|
if (input.board && boardForWorkItem(item) !== input.board) return false;
|
|
201
197
|
if (input.role && !item.sessions[input.role]) return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read-tools.js","names":[],"sources":["../../src/tools/read-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport {\n awaitsAcceptance,\n boardFlow,\n boardForWorkItem,\n pullRequestSourceNumber,\n pullRequestSources,\n} from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factorySessionUrl, factoryWorkItemUrl } from '../links.js';\nimport { parkedRunLabel } from '../routes/attention-parked.js';\nimport { decisionRetryable, overtakenDecisionIds } from '../rules/decision-applicability.js';\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport { needsApproval } from '../rules/types.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { AuditStorage } from '../storage/domains/audit/base.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryRunBindingRecord,\n Card,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { cardCarries, isCardFor, isSourceReference, sourceKeyFromReference } from '../work-items/card-reference.js';\nimport { sessionActivity } from './deliver.js';\nimport type { FactorySessionActivity } from './deliver.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport const MAX_TEXT = 600;\nexport const MAX_ERROR = 400;\nexport const MAX_LIST = 50;\nconst DEFAULT_LIST = 25;\n\nexport interface FactoryReadToolDependencies {\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'getForProject'\n | 'listRunBindings'\n | 'listDeferredDecisions'\n | 'listByIds'\n | 'listDecisionsForEvaluations'\n | 'listWorkItemSubscribers'\n | 'listSessionSubscriptions'\n >;\n audit: Pick<AuditStorage, 'list'>;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The live controller, for whether a session is mid-run and when it last moved; absent before the mount is up. */\n messaging?: () => Promise<Pick<FactoryMessaging, 'controller'> | null>;\n /** Which live sessions are parked on a tool prompt; absent before the mount is up. */\n liveSessions?: () => Pick<LiveSessions, 'parked' | 'parkedIn'> | undefined;\n}\n\nexport function truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\nfunction iso(value: Date | string | null | undefined): string | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isFinite(date.getTime()) ? date.toISOString() : null;\n}\n\nexport function workItemStage(item: Pick<Card, 'stages'>): string {\n return item.stages.join('+');\n}\n\n/**\n * A work item id, its card number, or the issue or pull request it tracks, as people paste it: a\n * link, `owner/repo#123`, `group/project!7` or a tracker key like `ENG-42`. Anything else can't\n * name an item.\n */\nexport const workItemRefSchema = z\n .string()\n .trim()\n .max(512)\n .refine(ref => z.string().uuid().safeParse(ref).success || /^#?\\d+$/.test(ref) || isSourceReference(ref), {\n message:\n 'Use a work item id (UUID), its number like \"#123\", or the link or owner/repo#123 of the issue or pull request it tracks.',\n })\n .describe(\n 'Work item id, its number like \"#123\", or the issue or pull request it tracks: its link, owner/repo#123, or a key like ENG-42. With several repositories, prefer the link: a bare number can belong to more than one.',\n );\n\n/**\n * Resolve a ref validated by `workItemRefSchema` to an item in this Factory only. A link or\n * shorthand finds the card of that issue or pull request, else the card it is attached to.\n */\nexport async function findWorkItem(\n workItems: Pick<WorkItemsStorage, 'listShared' | 'getForProject'>,\n scope: Pick<FactoryToolScope, 'orgId' | 'factoryProjectId'>,\n ref: string,\n): Promise<Card | null> {\n const trimmed = ref.trim();\n if (z.string().uuid().safeParse(trimmed).success) {\n return workItems.getForProject(scope.orgId, scope.factoryProjectId, trimmed);\n }\n const number = /^#?(\\d+)$/.exec(trimmed)?.[1];\n if (number === undefined) return findBySource(await workItems.listShared(scope), trimmed);\n const items = await workItems.listShared(scope);\n const matches = items.filter(item => workItemNumber(item) === Number(number));\n // Issue and PR numbers share a space on GitHub; prefer the issue's card.\n const workCards = matches.filter(item => item.externalSource?.type !== 'pull-request');\n // Hand-filed card numbers and issue numbers from several repositories can repeat; refuse to guess.\n refuseAmbiguous(number, workCards);\n const match = workCards[0] ?? matches[0];\n if (match) return structuredClone(match);\n // A pull request attached to an issue's card is found through that card. Pull request numbers\n // repeat across repositories too.\n const carriers = items.filter(item =>\n pullRequestSources(item).some(source => pullRequestSourceNumber(source) === Number(number)),\n );\n refuseAmbiguous(number, carriers);\n return carriers[0] ? structuredClone(carriers[0]) : null;\n}\n\nfunction findBySource(items: readonly Card[], ref: string): Card | null {\n // The issue's or pull request's own card first, then a card it is attached to (a pull request on its issue's card).\n for (const tier of [items.filter(item => isCardFor(item, ref)), items.filter(item => cardCarries(item, ref))]) {\n refuseAmbiguous(ref, tier);\n if (tier[0]) return structuredClone(tier[0]);\n }\n return null;\n}\n\nfunction refuseAmbiguous(ref: string, items: readonly Card[]): void {\n if (items.length <= 1) return;\n const candidates = items\n .map(item => `${item.id} (${item.title}, ${boardForWorkItem(item)} › ${workItemStage(item)})`)\n .join(', ');\n const label = /^\\d+$/.test(ref) ? `#${ref}` : ref;\n throw new Error(`${label} matches more than one work item; use its id instead: ${candidates}.`);\n}\n\n/** The stage the card is in and where its board lets it go next, as the board shows its move buttons. */\nfunction boardMoves(board: InstalledBoard | undefined, item: Card) {\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n const phase = board && stage !== undefined && Object.hasOwn(board.phases, stage) ? board.phases[stage] : undefined;\n if (!board || !phase || stage === undefined) return null;\n return {\n board: { key: board.id, name: board.name },\n stage: { key: stage, name: phase.name, kind: phase.kind },\n // A working stage runs its skill again when the card is moved to the stage it is in.\n canRerun: phase.kind === 'working',\n next: phase.nextPhases\n .filter(key => Object.hasOwn(board.phases, key))\n .map(key => ({ key, name: board.phases[key]!.name, kind: board.phases[key]!.kind })),\n };\n}\n\nexport function workItemNotFound(ref: string): Error {\n return new Error(`No work item ${ref} was found in this Factory.`);\n}\n\nfunction activeWorker(bindings: FactoryRunBindingRecord[], itemId: string) {\n const binding = bindings.find(candidate => candidate.workItemId === itemId && candidate.status === 'active');\n return binding ? { role: binding.role, sessionId: binding.sessionId } : null;\n}\n\n/** The card on its Factory board; null when the server has no public URL configured. */\nfunction workItemUrl(item: Card) {\n return (\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n workItemId: item.id,\n }) ?? null\n );\n}\n\nfunction summarizeItem(item: Card, bindings: FactoryRunBindingRecord[]) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n board: boardForWorkItem(item),\n stage: workItemStage(item),\n url: workItemUrl(item),\n activeWorker: activeWorker(bindings, item.id),\n requestedBy: item.createdBy,\n updatedAt: iso(item.updatedAt),\n };\n}\n\nfunction summarizeDecision(decision: FactoryDeferredDecisionRecord, overtaken = false) {\n const type = typeof decision.decision.type === 'string' ? decision.decision.type : 'decision';\n const role = typeof decision.decision.role === 'string' ? decision.decision.role : null;\n return {\n id: decision.id,\n workItemId: decision.workItemId,\n type,\n role,\n status: decision.status,\n attempts: decision.attempts,\n failureCode: decision.failureCode,\n failureLabel: decision.failureCode ? factoryDispatchFailureMetadata(decision.failureCode).label : null,\n canRetry: decisionRetryable(decision, overtaken),\n error: decision.lastError ? truncate(decision.lastError, MAX_ERROR) : null,\n approvedBy: decision.approvedBy,\n updatedAt: iso(decision.updatedAt),\n };\n}\n\n/**\n * Held: a card triage left resting (or whose source asks for approval), until a person moves it\n * on. A card that has been past triage since (parked by self-review, or dragged back) resumes\n * instead, matching the board's held state.\n */\nfunction isHeld(boards: BoardRegistry, item: Card): boolean {\n const board = boards.get(boardForWorkItem(item));\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n if (!board || !stage || board.phaseKind(stage) !== 'resting') return false;\n if (needsApproval(item, phase => awaitsAcceptance(board, phase))) return true;\n const triage = boardFlow(board).triage;\n const triageRole = triage ? board.roleForPhase(triage) : undefined;\n if (!triageRole || item.sessions[triageRole] === undefined) return false;\n return !item.stageHistory.some(entry => entry.stage !== triage && board.isWorking(entry.stage));\n}\n\nconst listInputSchema = z\n .object({\n query: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe(\n 'Case-insensitive text in the title, an exact card number like \"#123\", or the link, owner/repo#123 or key (ENG-42) of an issue or pull request, which finds the cards tracking it.',\n ),\n stage: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Only items in this stage, by its key as items list it (e.g. \"intake\" or \"planning\"); a board\\'s review stage key can differ from its name.',\n ),\n board: z.string().min(1).max(64).optional().describe('Only items on this board, by its key, e.g. \"work\".'),\n role: z.string().min(1).max(64).optional().describe('Only items that have a session for this role.'),\n active: z.boolean().optional().describe('true: only items with an agent working now; false: only idle items.'),\n requestedBy: z.literal('me').optional().describe('\"me\": only items you filed.'),\n subscribed: z\n .boolean()\n .optional()\n .describe('true: only items this session follows; false: only items it does not.'),\n limit: z.number().int().min(1).max(MAX_LIST).optional().describe(`Default ${DEFAULT_LIST}, max ${MAX_LIST}.`),\n })\n .strict();\n\nexport function createFactoryReadTools(scope: FactoryToolScope, deps: FactoryReadToolDependencies): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n return {\n factory_list_work_items: createTool({\n id: 'factory_list_work_items',\n description:\n \"List this Factory's work items, newest activity first, with counts per stage for the whole Factory. Filter by text or #number, stage, board, role, whether an agent is working on it, items you filed, or items this session follows. Check here for an existing item before filing a new one.\",\n inputSchema: listInputSchema,\n execute: async input => {\n const [items, bindings, followed] = await Promise.all([\n deps.workItems.listShared(project),\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId),\n input.subscribed === undefined\n ? undefined\n : deps.workItems.listSessionSubscriptions({ ...project, sessionId: scope.sessionId }),\n ]);\n const followedIds = new Set(followed?.map(subscription => subscription.workItemId));\n const byStage: Record<string, number> = {};\n for (const item of items) {\n const stage = workItemStage(item);\n byStage[stage] = (byStage[stage] ?? 0) + 1;\n }\n const numberQuery = input.query ? /^#(\\d+)$/.exec(input.query)?.[1] : undefined;\n // A pasted link or owner/repo#123 finds the cards tracking that issue or pull request, not titles.\n const sourceQuery =\n input.query && numberQuery === undefined && sourceKeyFromReference(input.query) !== null\n ? input.query\n : undefined;\n const text = input.query?.toLowerCase();\n const matches = items\n .filter(item => {\n if (numberQuery !== undefined) {\n if (workItemNumber(item) !== Number(numberQuery)) return false;\n } else if (sourceQuery !== undefined) {\n if (!cardCarries(item, sourceQuery)) return false;\n } else if (text && !item.title.toLowerCase().includes(text)) return false;\n if (input.stage && !item.stages.includes(input.stage)) return false;\n if (input.board && boardForWorkItem(item) !== input.board) return false;\n if (input.role && !item.sessions[input.role]) return false;\n if (input.active !== undefined && (activeWorker(bindings, item.id) !== null) !== input.active) return false;\n if (input.requestedBy === 'me' && item.createdBy !== scope.userId) return false;\n if (input.subscribed !== undefined && followedIds.has(item.id) !== input.subscribed) return false;\n return true;\n })\n .sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());\n const limit = input.limit ?? DEFAULT_LIST;\n return {\n counts: { total: items.length, byStage },\n items: matches.slice(0, limit).map(item => summarizeItem(item, bindings)),\n truncated: matches.length > limit,\n };\n },\n }),\n\n factory_inspect_work_item: createTool({\n id: 'factory_inspect_work_item',\n description:\n 'Everything the Factory knows about one work item: its description, the stages its board lets it move to next, stage history, sessions by role (with whether each is mid-run and when its thread last moved), decisions with errors, recent audit events, labels, linked items and the sessions following it. Use it to explain why an item is where it is, and to pick the stage key factory_transition_work_item takes.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await findWorkItem(deps.workItems, scope, workItem);\n if (!item) throw workItemNotFound(workItem);\n const [bindings, decisions, audit, all, subscribers] = await Promise.all([\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, item.id),\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, { workItemId: item.id }),\n deps.audit.list({ ...project, limit: 200 }),\n deps.workItems.listShared(project),\n deps.workItems.listWorkItemSubscribers({ orgId: scope.orgId, workItemId: item.id }),\n ]);\n const itemDecisions = decisions.slice(-MAX_LIST);\n const boards = await toBoardSource(deps.boards).load(project);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n boards,\n project,\n itemDecisions.filter(decision => decision.status === 'failed'),\n );\n const labels = Array.isArray(item.workItem.labels)\n ? item.workItem.labels.filter((label): label is string => typeof label === 'string').slice(0, MAX_LIST)\n : [];\n const parent = item.parentWorkItemId\n ? all.find(candidate => candidate.id === item.parentWorkItemId)\n : undefined;\n const children = all.filter(candidate => candidate.parentWorkItemId === item.id);\n const controller = (await deps.messaging?.())?.controller;\n const activity = async (sessionId: string, threadId: string): Promise<FactorySessionActivity | null> =>\n controller ? sessionActivity(controller, sessionId, threadId) : null;\n const sessions = await Promise.all(\n Object.entries(item.sessions).map(async ([role, ref]) => ({\n role,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n url:\n factorySessionUrl({\n factoryProjectId: item.factoryProjectId,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n }) ?? null,\n startedBy: ref.startedBy,\n active: bindings.some(\n binding => binding.role === role && binding.sessionId === ref.sessionId && binding.status === 'active',\n ),\n // `running` with an old `lastActivityAt` is a stuck run; `running` with a recent one is a long one.\n ...((await activity(ref.sessionId, ref.threadId)) ?? { running: null, lastActivityAt: null }),\n })),\n );\n return {\n item: {\n ...summarizeItem(item, bindings),\n description: item.description,\n source: item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual',\n sourceUrl: typeof item.workItem.url === 'string' ? item.workItem.url : null,\n revision: item.revision,\n },\n moves: boardMoves(boards.get(boardForWorkItem(item)), item),\n labels,\n stageHistory: item.stageHistory.slice(-MAX_LIST).map(entry => ({\n stage: entry.stage,\n enteredAt: entry.enteredAt,\n exitedAt: entry.exitedAt ?? null,\n by: entry.by,\n })),\n sessions,\n decisions: itemDecisions.map(decision => summarizeDecision(decision, overtaken.has(decision.id))),\n audit: audit.events\n .filter(event => event.targets.some(target => target.type === 'work_item' && target.id === item.id))\n .slice(0, 25)\n .map(event => ({\n action: event.action,\n actorId: event.actorId,\n actorType: event.actorType,\n occurredAt: iso(event.occurredAt),\n })),\n parent: parent ? summarizeItem(parent, bindings) : null,\n children: children.slice(0, MAX_LIST).map(child => summarizeItem(child, bindings)),\n subscribers: subscribers.slice(0, MAX_LIST).map(subscription => ({\n sessionId: subscription.sessionId,\n reason: subscription.reason,\n isCaller: subscription.sessionId === scope.sessionId,\n })),\n };\n },\n }),\n\n factory_list_attention: createTool({\n id: 'factory_list_attention',\n description:\n 'What in this Factory needs a person: failed decisions grouped by failure code and error (one incident per group), proposals waiting for approval, runs parked on a tool prompt (a plan to review, a question to answer) while still in flight, and Work cards triage left in Intake for a person to move on.',\n inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_LIST).optional() }).strict(),\n execute: async ({ limit = DEFAULT_LIST }) => {\n const [decisions, items] = await Promise.all([\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {\n statuses: ['failed', 'proposed'],\n }),\n deps.workItems.listShared(project),\n ]);\n const itemsById = new Map(items.map(item => [item.id, item]));\n const failed = decisions.filter(decision => decision.status === 'failed');\n const groups = new Map<\n string,\n { failureCode: string; error: string; decisions: FactoryDeferredDecisionRecord[] }\n >();\n for (const decision of failed) {\n const error = truncate(decision.lastError ?? '', MAX_ERROR);\n const key = `${decision.failureCode ?? 'unknown'}|${error}`;\n const group = groups.get(key) ?? { failureCode: decision.failureCode ?? 'unknown', error, decisions: [] };\n group.decisions.push(decision);\n groups.set(key, group);\n }\n const ref = (workItemId: string | null) => {\n const item = workItemId ? itemsById.get(workItemId) : undefined;\n return {\n workItemId,\n number: item ? workItemNumber(item) : null,\n title: item ? truncate(item.title, MAX_TEXT) : null,\n url: item ? workItemUrl(item) : null,\n };\n };\n const allIncidents = [...groups.values()].sort((a, b) => b.decisions.length - a.decisions.length);\n const incidents = allIncidents\n .slice(0, limit)\n .map(group => ({ ...group, shown: group.decisions.slice(0, limit) }));\n // Check exactly the decisions this call returns, so every canRetry is real.\n const boards = await toBoardSource(deps.boards).load(project);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n boards,\n project,\n incidents.flatMap(group => group.shown),\n );\n const proposals = decisions.filter(decision => decision.status === 'proposed');\n const held = items.filter(item => isHeld(boards, item));\n const waiting = (deps.liveSessions?.()?.parkedIn(scope.factoryProjectId) ?? []).sort(\n (a, b) => a.run.suspendedAt - b.run.suspendedAt,\n );\n return {\n incidents: incidents.map(group => ({\n failureCode: group.failureCode,\n failureLabel: factoryDispatchFailureMetadata(group.decisions[0]!.failureCode).label,\n error: group.error,\n count: group.decisions.length,\n decisions: group.shown.map(decision => ({\n id: decision.id,\n ...ref(decision.workItemId),\n attempts: decision.attempts,\n canRetry: decisionRetryable(decision, overtaken.has(decision.id)),\n })),\n })),\n proposals: proposals\n .slice(0, limit)\n .map(decision => ({ ...summarizeDecision(decision), ...ref(decision.workItemId) })),\n waiting: waiting.slice(0, limit).map(({ sessionId, run }) => ({\n sessionId,\n toolName: run.toolName,\n label: parkedRunLabel(run.toolName),\n waitingSince: new Date(run.suspendedAt).toISOString(),\n })),\n held: held.slice(0, limit).map(item => ({\n ...ref(item.id),\n stage: workItemStage(item),\n })),\n truncated:\n allIncidents.length > limit ||\n incidents.some(group => group.shown.length < group.decisions.length) ||\n proposals.length > limit ||\n waiting.length > limit ||\n held.length > limit,\n };\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,MAAa,WAAW;AACxB,MAAa,YAAY;AACz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EAAE;KACpF,SAAS,QAAQ,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,WAAW,WAAW;MAC5D;MACA,UAAU,IAAI;MACd,OAAO,eAAe,IAAI,QAAQ;MAClC,cAAc,IAAI,KAAK,IAAI,WAAW,CAAC,CAAC,YAAY;KACtD,EAAE;KACF,MAAM,KAAK,MAAM,GAAG,KAAK,CAAC,CAAC,KAAI,UAAS;MACtC,GAAG,IAAI,KAAK,EAAE;MACd,OAAO,cAAc,IAAI;KAC3B,EAAE;KACF,WACE,aAAa,SAAS,SACtB,UAAU,MAAK,UAAS,MAAM,MAAM,SAAS,MAAM,UAAU,MAAM,KACnE,UAAU,SAAS,SACnB,QAAQ,SAAS,SACjB,KAAK,SAAS;IAClB;GACF;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"read-tools.js","names":[],"sources":["../../src/tools/read-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport {\n awaitsAcceptance,\n boardFlow,\n boardForWorkItem,\n pullRequestSourceNumber,\n pullRequestSources,\n} from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factorySessionUrl, factoryWorkItemUrl } from '../links.js';\nimport { parkedRunLabel } from '../routes/attention-parked.js';\nimport { decisionRetryable, overtakenDecisionIds } from '../rules/decision-applicability.js';\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport { needsApproval } from '../rules/types.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { AuditStorage } from '../storage/domains/audit/base.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryRunBindingRecord,\n Card,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { cardFacts } from '../work-items/card-facts.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { cardCarries, isCardFor, isSourceReference } from '../work-items/card-reference.js';\nimport { matchesSearch, searchTerms } from '../work-items/search-terms.js';\nimport { sessionActivity } from './deliver.js';\nimport type { FactorySessionActivity } from './deliver.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport const MAX_TEXT = 600;\nexport const MAX_ERROR = 400;\nexport const MAX_LIST = 50;\nconst DEFAULT_LIST = 25;\n\nexport interface FactoryReadToolDependencies {\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'getForProject'\n | 'listRunBindings'\n | 'listDeferredDecisions'\n | 'listByIds'\n | 'listDecisionsForEvaluations'\n | 'listWorkItemSubscribers'\n | 'listSessionSubscriptions'\n >;\n audit: Pick<AuditStorage, 'list'>;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The live controller, for whether a session is mid-run and when it last moved; absent before the mount is up. */\n messaging?: () => Promise<Pick<FactoryMessaging, 'controller'> | null>;\n /** Which live sessions are parked on a tool prompt; absent before the mount is up. */\n liveSessions?: () => Pick<LiveSessions, 'parked' | 'parkedIn'> | undefined;\n}\n\nexport function truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\nfunction iso(value: Date | string | null | undefined): string | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isFinite(date.getTime()) ? date.toISOString() : null;\n}\n\nexport function workItemStage(item: Pick<Card, 'stages'>): string {\n return item.stages.join('+');\n}\n\n/**\n * A work item id, its card number, or the issue or pull request it tracks, as people paste it: a\n * link, `owner/repo#123`, `group/project!7` or a tracker key like `ENG-42`. Anything else can't\n * name an item.\n */\nexport const workItemRefSchema = z\n .string()\n .trim()\n .max(512)\n .refine(ref => z.string().uuid().safeParse(ref).success || /^#?\\d+$/.test(ref) || isSourceReference(ref), {\n message:\n 'Use a work item id (UUID), its number like \"#123\", or the link or owner/repo#123 of the issue or pull request it tracks.',\n })\n .describe(\n 'Work item id, its number like \"#123\", or the issue or pull request it tracks: its link, owner/repo#123, or a key like ENG-42. With several repositories, prefer the link: a bare number can belong to more than one.',\n );\n\n/**\n * Resolve a ref validated by `workItemRefSchema` to an item in this Factory only. A link or\n * shorthand finds the card of that issue or pull request, else the card it is attached to.\n */\nexport async function findWorkItem(\n workItems: Pick<WorkItemsStorage, 'listShared' | 'getForProject'>,\n scope: Pick<FactoryToolScope, 'orgId' | 'factoryProjectId'>,\n ref: string,\n): Promise<Card | null> {\n const trimmed = ref.trim();\n if (z.string().uuid().safeParse(trimmed).success) {\n return workItems.getForProject(scope.orgId, scope.factoryProjectId, trimmed);\n }\n const number = /^#?(\\d+)$/.exec(trimmed)?.[1];\n if (number === undefined) return findBySource(await workItems.listShared(scope), trimmed);\n const items = await workItems.listShared(scope);\n const matches = items.filter(item => workItemNumber(item) === Number(number));\n // Issue and PR numbers share a space on GitHub; prefer the issue's card.\n const workCards = matches.filter(item => item.externalSource?.type !== 'pull-request');\n // Hand-filed card numbers and issue numbers from several repositories can repeat; refuse to guess.\n refuseAmbiguous(number, workCards);\n const match = workCards[0] ?? matches[0];\n if (match) return structuredClone(match);\n // A pull request attached to an issue's card is found through that card. Pull request numbers\n // repeat across repositories too.\n const carriers = items.filter(item =>\n pullRequestSources(item).some(source => pullRequestSourceNumber(source) === Number(number)),\n );\n refuseAmbiguous(number, carriers);\n return carriers[0] ? structuredClone(carriers[0]) : null;\n}\n\nfunction findBySource(items: readonly Card[], ref: string): Card | null {\n // The issue's or pull request's own card first, then a card it is attached to (a pull request on its issue's card).\n for (const tier of [items.filter(item => isCardFor(item, ref)), items.filter(item => cardCarries(item, ref))]) {\n refuseAmbiguous(ref, tier);\n if (tier[0]) return structuredClone(tier[0]);\n }\n return null;\n}\n\nfunction refuseAmbiguous(ref: string, items: readonly Card[]): void {\n if (items.length <= 1) return;\n const candidates = items\n .map(item => `${item.id} (${item.title}, ${boardForWorkItem(item)} › ${workItemStage(item)})`)\n .join(', ');\n const label = /^\\d+$/.test(ref) ? `#${ref}` : ref;\n throw new Error(`${label} matches more than one work item; use its id instead: ${candidates}.`);\n}\n\n/** The stage the card is in and where its board lets it go next, as the board shows its move buttons. */\nfunction boardMoves(board: InstalledBoard | undefined, item: Card) {\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n const phase = board && stage !== undefined && Object.hasOwn(board.phases, stage) ? board.phases[stage] : undefined;\n if (!board || !phase || stage === undefined) return null;\n return {\n board: { key: board.id, name: board.name },\n stage: { key: stage, name: phase.name, kind: phase.kind },\n // A working stage runs its skill again when the card is moved to the stage it is in.\n canRerun: phase.kind === 'working',\n next: phase.nextPhases\n .filter(key => Object.hasOwn(board.phases, key))\n .map(key => ({ key, name: board.phases[key]!.name, kind: board.phases[key]!.kind })),\n };\n}\n\nexport function workItemNotFound(ref: string): Error {\n return new Error(`No work item ${ref} was found in this Factory.`);\n}\n\nfunction activeWorker(bindings: FactoryRunBindingRecord[], itemId: string) {\n const binding = bindings.find(candidate => candidate.workItemId === itemId && candidate.status === 'active');\n return binding ? { role: binding.role, sessionId: binding.sessionId } : null;\n}\n\n/** The card on its Factory board; null when the server has no public URL configured. */\nfunction workItemUrl(item: Card) {\n return (\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n workItemId: item.id,\n }) ?? null\n );\n}\n\nfunction summarizeItem(item: Card, bindings: FactoryRunBindingRecord[]) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n board: boardForWorkItem(item),\n stage: workItemStage(item),\n url: workItemUrl(item),\n activeWorker: activeWorker(bindings, item.id),\n requestedBy: item.createdBy,\n updatedAt: iso(item.updatedAt),\n };\n}\n\nfunction summarizeDecision(decision: FactoryDeferredDecisionRecord, overtaken = false) {\n const type = typeof decision.decision.type === 'string' ? decision.decision.type : 'decision';\n const role = typeof decision.decision.role === 'string' ? decision.decision.role : null;\n return {\n id: decision.id,\n workItemId: decision.workItemId,\n type,\n role,\n status: decision.status,\n attempts: decision.attempts,\n failureCode: decision.failureCode,\n failureLabel: decision.failureCode ? factoryDispatchFailureMetadata(decision.failureCode).label : null,\n canRetry: decisionRetryable(decision, overtaken),\n error: decision.lastError ? truncate(decision.lastError, MAX_ERROR) : null,\n approvedBy: decision.approvedBy,\n updatedAt: iso(decision.updatedAt),\n };\n}\n\n/**\n * Held: a card triage left resting (or whose source asks for approval), until a person moves it\n * on. A card that has been past triage since (parked by self-review, or dragged back) resumes\n * instead, matching the board's held state.\n */\nfunction isHeld(boards: BoardRegistry, item: Card): boolean {\n const board = boards.get(boardForWorkItem(item));\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n if (!board || !stage || board.phaseKind(stage) !== 'resting') return false;\n if (needsApproval(item, phase => awaitsAcceptance(board, phase))) return true;\n const triage = boardFlow(board).triage;\n const triageRole = triage ? board.roleForPhase(triage) : undefined;\n if (!triageRole || item.sessions[triageRole] === undefined) return false;\n return !item.stageHistory.some(entry => entry.stage !== triage && board.isWorking(entry.stage));\n}\n\nconst listInputSchema = z\n .object({\n query: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe(\n 'What the board\\'s search box takes: case-insensitive words of the title, a whole card number like \"#123\", a key (ENG-42, owner/repo#123), a branch or card id, or the link of an issue or pull request, which finds the cards tracking it, a pull request attached to its issue\\'s card included.',\n ),\n stage: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Only items in this stage, by its key as items list it (e.g. \"intake\" or \"planning\"); a board\\'s review stage key can differ from its name.',\n ),\n board: z.string().min(1).max(64).optional().describe('Only items on this board, by its key, e.g. \"work\".'),\n role: z.string().min(1).max(64).optional().describe('Only items that have a session for this role.'),\n active: z.boolean().optional().describe('true: only items with an agent working now; false: only idle items.'),\n requestedBy: z.literal('me').optional().describe('\"me\": only items you filed.'),\n subscribed: z\n .boolean()\n .optional()\n .describe('true: only items this session follows; false: only items it does not.'),\n limit: z.number().int().min(1).max(MAX_LIST).optional().describe(`Default ${DEFAULT_LIST}, max ${MAX_LIST}.`),\n })\n .strict();\n\nexport function createFactoryReadTools(scope: FactoryToolScope, deps: FactoryReadToolDependencies): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n return {\n factory_list_work_items: createTool({\n id: 'factory_list_work_items',\n description:\n \"List this Factory's work items, newest activity first, with counts per stage for the whole Factory. Filter by text or #number, stage, board, role, whether an agent is working on it, items you filed, or items this session follows. Check here for an existing item before filing a new one.\",\n inputSchema: listInputSchema,\n execute: async input => {\n const [items, bindings, followed] = await Promise.all([\n deps.workItems.listShared(project),\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId),\n input.subscribed === undefined\n ? undefined\n : deps.workItems.listSessionSubscriptions({ ...project, sessionId: scope.sessionId }),\n ]);\n const followedIds = new Set(followed?.map(subscription => subscription.workItemId));\n const byStage: Record<string, number> = {};\n for (const item of items) {\n const stage = workItemStage(item);\n byStage[stage] = (byStage[stage] ?? 0) + 1;\n }\n // The board's search, with what it computed of each card.\n const terms = searchTerms(input.query ?? '');\n const matches = items\n .filter(item => {\n if (!matchesSearch(cardFacts(item).search, terms)) return false;\n if (input.stage && !item.stages.includes(input.stage)) return false;\n if (input.board && boardForWorkItem(item) !== input.board) return false;\n if (input.role && !item.sessions[input.role]) return false;\n if (input.active !== undefined && (activeWorker(bindings, item.id) !== null) !== input.active) return false;\n if (input.requestedBy === 'me' && item.createdBy !== scope.userId) return false;\n if (input.subscribed !== undefined && followedIds.has(item.id) !== input.subscribed) return false;\n return true;\n })\n .sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());\n const limit = input.limit ?? DEFAULT_LIST;\n return {\n counts: { total: items.length, byStage },\n items: matches.slice(0, limit).map(item => summarizeItem(item, bindings)),\n truncated: matches.length > limit,\n };\n },\n }),\n\n factory_inspect_work_item: createTool({\n id: 'factory_inspect_work_item',\n description:\n 'Everything the Factory knows about one work item: its description, the stages its board lets it move to next, stage history, sessions by role (with whether each is mid-run and when its thread last moved), decisions with errors, recent audit events, labels, linked items and the sessions following it. Use it to explain why an item is where it is, and to pick the stage key factory_transition_work_item takes.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await findWorkItem(deps.workItems, scope, workItem);\n if (!item) throw workItemNotFound(workItem);\n const [bindings, decisions, audit, all, subscribers] = await Promise.all([\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, item.id),\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, { workItemId: item.id }),\n deps.audit.list({ ...project, limit: 200 }),\n deps.workItems.listShared(project),\n deps.workItems.listWorkItemSubscribers({ orgId: scope.orgId, workItemId: item.id }),\n ]);\n const itemDecisions = decisions.slice(-MAX_LIST);\n const boards = await toBoardSource(deps.boards).load(project);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n boards,\n project,\n itemDecisions.filter(decision => decision.status === 'failed'),\n );\n const labels = Array.isArray(item.workItem.labels)\n ? item.workItem.labels.filter((label): label is string => typeof label === 'string').slice(0, MAX_LIST)\n : [];\n const parent = item.parentWorkItemId\n ? all.find(candidate => candidate.id === item.parentWorkItemId)\n : undefined;\n const children = all.filter(candidate => candidate.parentWorkItemId === item.id);\n const controller = (await deps.messaging?.())?.controller;\n const activity = async (sessionId: string, threadId: string): Promise<FactorySessionActivity | null> =>\n controller ? sessionActivity(controller, sessionId, threadId) : null;\n const sessions = await Promise.all(\n Object.entries(item.sessions).map(async ([role, ref]) => ({\n role,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n url:\n factorySessionUrl({\n factoryProjectId: item.factoryProjectId,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n }) ?? null,\n startedBy: ref.startedBy,\n active: bindings.some(\n binding => binding.role === role && binding.sessionId === ref.sessionId && binding.status === 'active',\n ),\n // `running` with an old `lastActivityAt` is a stuck run; `running` with a recent one is a long one.\n ...((await activity(ref.sessionId, ref.threadId)) ?? { running: null, lastActivityAt: null }),\n })),\n );\n return {\n item: {\n ...summarizeItem(item, bindings),\n description: item.description,\n source: item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual',\n sourceUrl: typeof item.workItem.url === 'string' ? item.workItem.url : null,\n revision: item.revision,\n },\n moves: boardMoves(boards.get(boardForWorkItem(item)), item),\n labels,\n stageHistory: item.stageHistory.slice(-MAX_LIST).map(entry => ({\n stage: entry.stage,\n enteredAt: entry.enteredAt,\n exitedAt: entry.exitedAt ?? null,\n by: entry.by,\n })),\n sessions,\n decisions: itemDecisions.map(decision => summarizeDecision(decision, overtaken.has(decision.id))),\n audit: audit.events\n .filter(event => event.targets.some(target => target.type === 'work_item' && target.id === item.id))\n .slice(0, 25)\n .map(event => ({\n action: event.action,\n actorId: event.actorId,\n actorType: event.actorType,\n occurredAt: iso(event.occurredAt),\n })),\n parent: parent ? summarizeItem(parent, bindings) : null,\n children: children.slice(0, MAX_LIST).map(child => summarizeItem(child, bindings)),\n subscribers: subscribers.slice(0, MAX_LIST).map(subscription => ({\n sessionId: subscription.sessionId,\n reason: subscription.reason,\n isCaller: subscription.sessionId === scope.sessionId,\n })),\n };\n },\n }),\n\n factory_list_attention: createTool({\n id: 'factory_list_attention',\n description:\n 'What in this Factory needs a person: failed decisions grouped by failure code and error (one incident per group), proposals waiting for approval, runs parked on a tool prompt (a plan to review, a question to answer) while still in flight, and Work cards triage left in Intake for a person to move on.',\n inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_LIST).optional() }).strict(),\n execute: async ({ limit = DEFAULT_LIST }) => {\n const [decisions, items] = await Promise.all([\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {\n statuses: ['failed', 'proposed'],\n }),\n deps.workItems.listShared(project),\n ]);\n const itemsById = new Map(items.map(item => [item.id, item]));\n const failed = decisions.filter(decision => decision.status === 'failed');\n const groups = new Map<\n string,\n { failureCode: string; error: string; decisions: FactoryDeferredDecisionRecord[] }\n >();\n for (const decision of failed) {\n const error = truncate(decision.lastError ?? '', MAX_ERROR);\n const key = `${decision.failureCode ?? 'unknown'}|${error}`;\n const group = groups.get(key) ?? { failureCode: decision.failureCode ?? 'unknown', error, decisions: [] };\n group.decisions.push(decision);\n groups.set(key, group);\n }\n const ref = (workItemId: string | null) => {\n const item = workItemId ? itemsById.get(workItemId) : undefined;\n return {\n workItemId,\n number: item ? workItemNumber(item) : null,\n title: item ? truncate(item.title, MAX_TEXT) : null,\n url: item ? workItemUrl(item) : null,\n };\n };\n const allIncidents = [...groups.values()].sort((a, b) => b.decisions.length - a.decisions.length);\n const incidents = allIncidents\n .slice(0, limit)\n .map(group => ({ ...group, shown: group.decisions.slice(0, limit) }));\n // Check exactly the decisions this call returns, so every canRetry is real.\n const boards = await toBoardSource(deps.boards).load(project);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n boards,\n project,\n incidents.flatMap(group => group.shown),\n );\n const proposals = decisions.filter(decision => decision.status === 'proposed');\n const held = items.filter(item => isHeld(boards, item));\n const waiting = (deps.liveSessions?.()?.parkedIn(scope.factoryProjectId) ?? []).sort(\n (a, b) => a.run.suspendedAt - b.run.suspendedAt,\n );\n return {\n incidents: incidents.map(group => ({\n failureCode: group.failureCode,\n failureLabel: factoryDispatchFailureMetadata(group.decisions[0]!.failureCode).label,\n error: group.error,\n count: group.decisions.length,\n decisions: group.shown.map(decision => ({\n id: decision.id,\n ...ref(decision.workItemId),\n attempts: decision.attempts,\n canRetry: decisionRetryable(decision, overtaken.has(decision.id)),\n })),\n })),\n proposals: proposals\n .slice(0, limit)\n .map(decision => ({ ...summarizeDecision(decision), ...ref(decision.workItemId) })),\n waiting: waiting.slice(0, limit).map(({ sessionId, run }) => ({\n sessionId,\n toolName: run.toolName,\n label: parkedRunLabel(run.toolName),\n waitingSince: new Date(run.suspendedAt).toISOString(),\n })),\n held: held.slice(0, limit).map(item => ({\n ...ref(item.id),\n stage: workItemStage(item),\n })),\n truncated:\n allIncidents.length > limit ||\n incidents.some(group => group.shown.length < group.decis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F,MAAM,KAAK,MAAM,GAAG,KAAK,CAAC,CAAC,KAAI,UAAS;MACtC,GAAG,IAAI,KAAK,EAAE;MACd,OAAO,cAAc,IAAI;KAC3B,EAAE;KACF,WACE,aAAa,SAAS,SACtB,UAAU,MAAK,UAAS,MAAM,MAAM,SAAS,MAAM,UAAU,MAAM,KACnE,UAAU,SAAS,SACnB,QAAQ,SAAS,SACjB,KAAK,SAAS;IAClB;GACF;EACF,CAAC;CACH;AACF"}
|
package/dist/tools/reports.d.ts
CHANGED
|
@@ -134,6 +134,9 @@ export interface FactoryStageChange {
|
|
|
134
134
|
workItemId: string;
|
|
135
135
|
fromStage: string | undefined;
|
|
136
136
|
toStage: string;
|
|
137
|
+
/** The boards the move left and entered. Named in the notice when they differ. */
|
|
138
|
+
fromBoard?: string;
|
|
139
|
+
toBoard?: string;
|
|
137
140
|
}
|
|
138
141
|
/**
|
|
139
142
|
* Tells a work item's subscribers it moved, at `low` priority. Only sessions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reports.d.ts","sourceRoot":"","sources":["../../src/tools/reports.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EACV,oBAAoB,EACpB,oBAAoB,EACpB,2BAA2B,EAC5B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAG9E,OAAO,KAAK,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAEjF,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,CAAC;AAE7E,4GAA4G;AAC5G,eAAO,MAAM,oBAAoB,EAAE,MAAM,CACvC,mBAAmB,GAAG,QAAQ,EAC9B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,oBAAoB,CAAC;I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,EAAE,yBAAyB,GAAG,4BAA4B,CA8BzG;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,yBAAyB,GAAG,uBAAuB,CA2CtG"}
|
package/dist/tools/reports.js
CHANGED
|
@@ -242,7 +242,8 @@ function createStageChangeNotifier({ workItems, reporting }) {
|
|
|
242
242
|
const resolved = await reporting();
|
|
243
243
|
if (!resolved) return;
|
|
244
244
|
const { label, ref } = await workItemReference(workItems, change);
|
|
245
|
-
const
|
|
245
|
+
const movedBoards = change.fromBoard !== void 0 && change.toBoard !== void 0 && change.fromBoard !== change.toBoard;
|
|
246
|
+
const summary = movedBoards ? change.fromStage ? `${label} moved from ${change.fromStage} on the ${change.fromBoard} board to ${change.toStage} on the ${change.toBoard} board.` : `${label} moved to ${change.toStage} on the ${change.toBoard} board.` : change.fromStage ? `${label} moved from ${change.fromStage} to ${change.toStage}.` : `${label} moved to ${change.toStage}.`;
|
|
246
247
|
const notification = {
|
|
247
248
|
kind: "stage",
|
|
248
249
|
priority: "low",
|
|
@@ -253,7 +254,11 @@ function createStageChangeNotifier({ workItems, reporting }) {
|
|
|
253
254
|
attributes: {
|
|
254
255
|
"work-item": ref,
|
|
255
256
|
...change.fromStage ? { "from-stage": change.fromStage } : {},
|
|
256
|
-
"to-stage": change.toStage
|
|
257
|
+
"to-stage": change.toStage,
|
|
258
|
+
...movedBoards ? {
|
|
259
|
+
"from-board": change.fromBoard,
|
|
260
|
+
"to-board": change.toBoard
|
|
261
|
+
} : {}
|
|
257
262
|
}
|
|
258
263
|
};
|
|
259
264
|
for (const subscriber of subscribers) try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reports.js","names":[],"sources":["../../src/tools/reports.ts"],"sourcesContent":["/**\n * Reports from sessions doing the work back to whoever follows it: a side\n * session's origin, or every subscriber of a work item. The agent reports with\n * `factory_message_origin`; when a run ends without one, the run-end backstop\n * sends it, so each run produces exactly one final report per recipient.\n */\n\nimport type {\n NotificationPriority,\n NotificationsStorage,\n SendNotificationSignalInput,\n} from '@mastra/core/notifications';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { FACTORY_SESSION_NOTIFICATION_SOURCE } from './deliver.js';\nimport type { FactoryDeliveryResult, FactoryDeliveryTarget } from './deliver.js';\n\nexport type FactoryReportStatus = 'progress' | 'blocked' | 'done' | 'failed';\n\n/** How each report status travels. Final reports never coalesce, so a later report can't overwrite them. */\nexport const FACTORY_REPORT_FORMS: Record<\n FactoryReportStatus | 'report',\n { kind: string; priority: NotificationPriority; coalesce: boolean }\n> = {\n failed: { kind: 'failed', priority: 'urgent', coalesce: false },\n blocked: { kind: 'blocked', priority: 'urgent', coalesce: false },\n done: { kind: 'done', priority: 'high', coalesce: false },\n progress: { kind: 'progress', priority: 'low', coalesce: true },\n // Not `message`: only messages can be answered, so a report can't start a reply loop.\n report: { kind: 'report', priority: 'high', coalesce: false },\n};\n\n/** How many recent `factory-session` notifications on a recipient thread the final-report check reads. */\nconst FINAL_REPORT_SCAN = 100;\n\nexport interface FactoryReportSender {\n sessionId: string;\n threadId: string;\n userId: string;\n}\n\nexport type FactoryReportDeliver = (\n target: FactoryDeliveryTarget,\n notification: Omit<SendNotificationSignalInput, 'source'>,\n options?: { onlyIfLive?: boolean },\n) => Promise<FactoryDeliveryResult>;\n\nexport interface FactoryReporting {\n deliver: FactoryReportDeliver;\n notifications: Pick<NotificationsStorage, 'listNotifications'>;\n}\n\n/**\n * Whether `senderSessionId` already put a report of one of `kinds` on the\n * recipient thread since `since`. Reads the durable notifications store, so it\n * holds across restarts. `listNotifications` has no time filter: records come\n * newest-updated first, and the scan stops at the first one last updated\n * before `since` (nothing after it can have been created later).\n */\nexport async function hasFinalReport(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n since,\n kinds,\n agentOnly = false,\n }: {\n senderSessionId: string;\n recipientThreadId: string;\n since: Date;\n kinds: readonly string[];\n /** Ignore reports Factory sent on the session's behalf (the backstop). */\n agentOnly?: boolean;\n },\n): Promise<boolean> {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n for (const record of records) {\n if (record.updatedAt < since) break;\n if (\n record.attributes?.['from-session'] === senderSessionId &&\n !(agentOnly && record.attributes?.backstop === 'true') &&\n // A reply carrying a final status counts like the report itself.\n (kinds.includes(record.kind) ||\n (record.kind === 'reply' &&\n typeof record.attributes?.status === 'string' &&\n kinds.includes(record.attributes.status))) &&\n record.createdAt >= since\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** The newest report `senderSessionId` put on the recipient thread. */\nasync function lastReport(\n notifications: FactoryReporting['notifications'],\n { senderSessionId, recipientThreadId }: { senderSessionId: string; recipientThreadId: string },\n) {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n return records\n .filter(record => record.attributes?.['from-session'] === senderSessionId)\n .reduce<(typeof records)[number] | undefined>(\n (newest, record) => (!newest || reportedAt(record) > reportedAt(newest) ? record : newest),\n undefined,\n );\n}\n\n/**\n * When a report last said something. `updatedAt` also moves when a report is\n * read, so it only counts once a later report has coalesced into this one;\n * otherwise the report says what it said when it was created.\n */\nfunction reportedAt(record: { createdAt: Date; updatedAt: Date; coalescedCount?: number }): Date {\n return (record.coalescedCount ?? 1) > 1 ? record.updatedAt : record.createdAt;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread is\n * already this exact `failed` backstop. A session stuck failing the same way\n * (a run that dies before the model, restarted over and over) then reports\n * once, not once per attempt; any other report in between resets it.\n */\nexport async function repeatsLastFailure(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n summary,\n }: { senderSessionId: string; recipientThreadId: string; summary: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, { senderSessionId, recipientThreadId });\n return last?.kind === 'failed' && last.attributes?.backstop === 'true' && last.summary === summary;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread\n * already says it is done. A session woken again after it finished (a PR it\n * subscribed to gets comments, reviews and CI results) ends each of those runs\n * with nothing new to say, so the follower hears \"finished\" once, not per wake.\n */\nasync function alreadyReportedDone(\n notifications: FactoryReporting['notifications'],\n target: { senderSessionId: string; recipientThreadId: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, target);\n return last?.kind === 'done' || (last?.kind === 'reply' && last.attributes?.status === 'done');\n}\n\nexport function reportNotification({\n sender,\n status,\n message,\n attributes = {},\n}: {\n sender: FactoryReportSender;\n status?: FactoryReportStatus;\n message: string;\n attributes?: Record<string, string>;\n}): Omit<SendNotificationSignalInput, 'source'> {\n const form = FACTORY_REPORT_FORMS[status ?? 'report'];\n return {\n kind: form.kind,\n priority: form.priority,\n // The whole text: a notification's summary is all the recipient's agent ever sees, even\n // through notification_inbox (which hides payloads), so a cut-off report loses its verdict.\n summary: message,\n payload: { message },\n sourceId: sender.sessionId,\n ...(form.coalesce ? { coalesceKey: `factory-session:${sender.sessionId}:${form.kind}` } : {}),\n attributes: {\n ...attributes,\n ...(status ? { status } : {}),\n // Last, so nothing above can claim another sender.\n 'from-session': sender.sessionId,\n 'from-thread': sender.threadId,\n 'from-user': sender.userId,\n },\n };\n}\n\n/** Everyone following a work item, except the session doing the reporting. */\nexport async function workItemReportRecipients(\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers'>,\n { orgId, workItemId, senderSessionId }: { orgId: string; workItemId: string; senderSessionId: string },\n): Promise<FactoryDeliveryTarget[]> {\n const subscribers = await workItems.listWorkItemSubscribers({ orgId, workItemId });\n return subscribers\n .filter(subscriber => subscriber.sessionId !== senderSessionId)\n .map(subscriber => ({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }));\n}\n\n/** How reports name an item: `#n`, else its quoted title, else its id. */\nasync function workItemReference(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n { orgId, factoryProjectId, workItemId }: { orgId: string; factoryProjectId: string; workItemId: string },\n): Promise<{ label: string; ref: string }> {\n const item = await workItems.getForProject(orgId, factoryProjectId, workItemId);\n const number = item ? workItemNumber(item) : null;\n if (number !== null) return { label: `#${number}`, ref: `#${number}` };\n return { label: item ? `\"${item.title}\"` : workItemId, ref: workItemId };\n}\n\n/** Attributes that say which item and role a worker's report is about. */\nexport async function workItemReportAttributes(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n {\n orgId,\n factoryProjectId,\n workItemId,\n role,\n }: { orgId: string; factoryProjectId: string; workItemId: string; role: string },\n): Promise<{ label: string; attributes: Record<string, string> }> {\n const { label, ref } = await workItemReference(workItems, { orgId, factoryProjectId, workItemId });\n return { label, attributes: { 'work-item': ref, role } };\n}\n\nexport type FactoryRunOutcome =\n | { status: 'done' }\n | { status: 'failed'; reason: string; failureCode?: string }\n | {\n status: 'blocked';\n toolName?: string;\n toolCallId?: string;\n /** The call waits for a person to allow it. */\n approval?: boolean;\n /** The tool paused itself, and a yes or no from a follower is all it needs. */\n decision?: boolean;\n };\n\n/** `waiting`: the session is waiting for an answer, so a later run owes the final report. */\nexport interface FactoryRunEndResult {\n waiting: boolean;\n deliveries?: FactoryDeliveryResult[];\n}\n\n/**\n * The run-end backstop: send `outcome` to each recipient that hasn't had a\n * final report from this sender since the run started. An agent's own `done`\n * or `failed` report wins. A run that completes after the agent's own\n * `blocked` sends nothing: the agent ended its turn to wait for an answer, and\n * its `done` comes from a later run. A `failed` backstop still goes out after an\n * earlier `blocked`.\n */\nexport async function sendRunEndReport(\n reporting: FactoryReporting,\n {\n sender,\n recipients,\n since,\n outcome,\n subject,\n attributes = {},\n }: {\n sender: FactoryReportSender;\n recipients: FactoryDeliveryTarget[];\n since: Date;\n outcome: FactoryRunOutcome;\n /** Who finished, e.g. \"The work session for #12\". */\n subject: string;\n attributes?: Record<string, string>;\n },\n): Promise<FactoryRunEndResult> {\n const kinds = outcome.status === 'blocked' ? ['blocked'] : ['done', 'failed'];\n const message =\n outcome.status === 'done'\n ? `${subject} finished.`\n : outcome.status === 'failed'\n ? `${subject} failed${outcome.failureCode ? ` (${outcome.failureCode})` : ''}: ${outcome.reason}`\n : outcome.approval\n ? `${subject} is waiting for someone to approve ${outcome.toolName ?? 'a tool call'} in that session.`\n : `${subject} is waiting${outcome.toolName ? ` on ${outcome.toolName}` : ''} and needs an answer.${\n outcome.decision && outcome.toolCallId\n ? ` Approve or decline it with factory_answer_approval (sessionId \"${sender.sessionId}\", toolCallId \"${outcome.toolCallId}\").`\n : ''\n }`;\n const notification = reportNotification({\n sender,\n status: outcome.status,\n message,\n attributes: {\n ...attributes,\n backstop: 'true',\n ...(outcome.status === 'failed' && outcome.failureCode ? { 'failure-code': outcome.failureCode } : {}),\n ...(outcome.status === 'blocked' && outcome.toolName ? { 'parked-tool': outcome.toolName } : {}),\n ...(outcome.status === 'blocked' && outcome.toolCallId ? { 'tool-call-id': outcome.toolCallId } : {}),\n ...(outcome.status === 'blocked' && (outcome.approval || outcome.decision) ? { 'waiting-for': 'approval' } : {}),\n },\n });\n const report = (recipient: FactoryDeliveryTarget, reportKinds: string[], agentOnly = false) =>\n hasFinalReport(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n since,\n kinds: reportKinds,\n agentOnly,\n });\n let waiting = outcome.status === 'blocked';\n const deliveries: FactoryDeliveryResult[] = [];\n for (const recipient of recipients) {\n // Only the agent's own reports count: an earlier run's backstop lands after this\n // run's window opened. A reply already told that follower how a finished run went.\n if (await report(recipient, outcome.status === 'done' ? [...kinds, 'reply'] : kinds, true)) continue;\n // Only the agent's own `blocked` means it ended its turn to wait; a backstop `blocked` from a parked run doesn't.\n if (outcome.status === 'done' && (await report(recipient, ['blocked'], true))) {\n waiting = true;\n continue;\n }\n if (\n outcome.status === 'done' &&\n (await alreadyReportedDone(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n }))\n ) {\n continue;\n }\n if (\n outcome.status === 'failed' &&\n (await repeatsLastFailure(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n summary: message,\n }))\n ) {\n continue;\n }\n deliveries.push(await reporting.deliver(recipient, notification));\n }\n return { waiting, deliveries };\n}\n\nexport interface FactoryRunEndInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n sender: FactoryReportSender;\n since: Date;\n outcome: FactoryRunOutcome;\n}\n\nexport type FactoryRunEndReporter = (input: FactoryRunEndInput) => Promise<FactoryRunEndResult>;\n\n/** The backstop for a work-item run: reports to the item's subscribers. Failures are logged, never thrown. */\nexport function createWorkItemRunEndReporter({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n /** Resolved per report: the controller exists only once the mount is up. */\n reporting: () => Promise<FactoryReporting | null>;\n}): FactoryRunEndReporter {\n return async input => {\n try {\n const resolved = await reporting();\n if (!resolved) return { waiting: false };\n const recipients = await workItemReportRecipients(workItems, {\n orgId: input.orgId,\n workItemId: input.workItemId,\n senderSessionId: input.sender.sessionId,\n });\n if (recipients.length === 0) return { waiting: false };\n const { label, attributes } = await workItemReportAttributes(workItems, input);\n return await sendRunEndReport(resolved, {\n sender: input.sender,\n recipients,\n since: input.since,\n outcome: input.outcome,\n subject: `The ${input.role} session for ${label}`,\n attributes,\n });\n } catch (error) {\n console.warn('[Factory reports] Unable to send the run-end report.', error);\n return { waiting: false };\n }\n };\n}\n\nexport interface FactoryStageChange {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n}\n\n/**\n * Tells a work item's subscribers it moved, at `low` priority. Only sessions\n * already live hear it: a stage change never brings a session online; an\n * offline subscriber sees the stage in its state signal on its next turn.\n */\nexport function createStageChangeNotifier({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n reporting: () => Promise<FactoryReporting | null>;\n}): (change: FactoryStageChange) => Promise<void> {\n return async change => {\n const subscribers = await workItems.listWorkItemSubscribers({\n orgId: change.orgId,\n workItemId: change.workItemId,\n });\n if (subscribers.length === 0) return;\n const resolved = await reporting();\n if (!resolved) return;\n const { label, ref } = await workItemReference(workItems, change);\n const summary = change.fromStage\n ? `${label} moved from ${change.fromStage} to ${change.toStage}.`\n : `${label} moved to ${change.toStage}.`;\n const notification: Omit<SendNotificationSignalInput, 'source'> = {\n kind: 'stage',\n priority: 'low',\n summary,\n payload: { message: summary },\n sourceId: change.workItemId,\n coalesceKey: `factory-stage:${change.workItemId}`,\n attributes: {\n 'work-item': ref,\n ...(change.fromStage ? { 'from-stage': change.fromStage } : {}),\n 'to-stage': change.toStage,\n },\n };\n for (const subscriber of subscribers) {\n try {\n await resolved.deliver({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }, notification, {\n onlyIfLive: true,\n });\n } catch (error) {\n console.warn(`[Factory reports] Unable to tell ${subscriber.sessionId} that ${label} moved.`, error);\n }\n }\n };\n}\n\n/** Reports one run end of a session; the thread is the one the run used. */\nexport type FactorySessionRunEndReporter = (input: {\n sessionId: string;\n threadId: string | null;\n outcome: FactoryRunOutcome;\n since: Date;\n}) => Promise<void>;\n\n/** A tool call a session's run is holding until someone approves or declines it. */\nexport interface FactoryApprovalRequest {\n sessionId: string;\n threadId: string | null;\n toolName: string;\n toolCallId: string;\n args: unknown;\n}\n\nexport type FactoryApprovalNotifier = (request: FactoryApprovalRequest) => Promise<void>;\n\ninterface SessionReportDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<\n WorkItemsStorage,\n 'findActiveRunBindingForSession' | 'findRunBindingBySession' | 'listWorkItemSubscribers' | 'getForProject'\n >;\n reporting: () => Promise<FactoryReporting | null>;\n}\n\n/** How much of a gated call's arguments an approval notice quotes. */\nconst APPROVAL_ARGS_LENGTH = 3000;\n\n/**\n * Who hears from a session: a work session (one with an active run binding)\n * reports to its item's followers, a side session to the session that started\n * it. Any other session (a person's own) has nobody to tell.\n */\nasync function sessionAudience(\n { sessions, workItems }: Omit<SessionReportDependencies, 'reporting'>,\n sessionId: string,\n threadId: string | null,\n /** When the run started: a binding revoked since then (the run moved its card to a finished stage) still counts. */\n since?: Date,\n): Promise<\n | {\n kind: 'work-item';\n binding: NonNullable<Awaited<ReturnType<WorkItemsStorage['findActiveRunBindingForSession']>>>;\n sender: FactoryReportSender;\n }\n | {\n kind: 'origin';\n sender: FactoryReportSender;\n recipient: FactoryDeliveryTarget;\n subject: string;\n /** Set while the origin has muted this side session's reports (approval notices still go through). */\n mutedAt: Date | null;\n }\n | null\n> {\n const row = await sessions.getBySessionId(sessionId);\n if (!row?.factoryProjectId) return null;\n let binding = await workItems.findActiveRunBindingForSession({\n orgId: row.orgId,\n factoryProjectId: row.factoryProjectId,\n sessionId: row.sessionId,\n });\n if (!binding && since && threadId) {\n // The binding records the memory resource the run used: the Factory's, its\n // own id for a run kept on its own resource, or its owner's for a person's\n // session the run started in.\n for (const resourceId of new Set([row.factoryProjectId, row.sessionId, row.userId])) {\n const latest = await workItems.findRunBindingBySession({\n factoryProjectId: row.factoryProjectId,\n threadId,\n resourceId,\n sessionId: row.sessionId,\n });\n if (latest?.orgId === row.orgId && latest.revokedAt && latest.revokedAt >= since) {\n binding = latest;\n break;\n }\n }\n }\n if (binding) {\n return {\n kind: 'work-item',\n binding,\n sender: { sessionId: row.sessionId, threadId: binding.threadId, userId: row.userId },\n };\n }\n if (!row.originSessionId || !row.originThreadId || !threadId) return null;\n return {\n kind: 'origin',\n sender: { sessionId: row.sessionId, threadId, userId: row.userId },\n recipient: { sessionId: row.originSessionId, threadId: row.originThreadId },\n subject: `The side session \"${row.title ?? row.sessionId}\"`,\n mutedAt: row.originMutedAt ?? null,\n };\n}\n\n/** Reports each run end of a work or side session to whoever follows it. */\nexport function createSessionRunEndReporter(deps: SessionReportDependencies): FactorySessionRunEndReporter {\n const workItemRunEnd = createWorkItemRunEndReporter(deps);\n return async ({ sessionId, threadId, outcome, since }) => {\n const audience = await sessionAudience(deps, sessionId, threadId, since);\n if (!audience) return;\n if (audience.kind === 'work-item') {\n const { binding, sender } = audience;\n await workItemRunEnd({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n sender,\n since,\n outcome,\n });\n return;\n }\n // A muted origin still hears when the session is blocked: nothing else would tell it the session is waiting.\n if (audience.mutedAt && outcome.status !== 'blocked') return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n await sendRunEndReport(resolved, {\n sender: audience.sender,\n recipients: [audience.recipient],\n since,\n outcome,\n subject: audience.subject,\n });\n };\n}\n\n/**\n * Tells whoever follows a session, urgently, the moment its run holds a tool\n * call for approval. The run stays open on the gate, so no run end would say\n * so; the notice names the session and call so a follower can answer it with\n * `factory_answer_approval`.\n */\nexport function createSessionApprovalNotifier(deps: SessionReportDependencies): FactoryApprovalNotifier {\n return async ({ sessionId, threadId, toolName, toolCallId, args }) => {\n const audience = await sessionAudience(deps, sessionId, threadId);\n if (!audience) return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n let subject: string;\n let recipients: FactoryDeliveryTarget[];\n let attributes: Record<string, string> = {};\n if (audience.kind === 'work-item') {\n const { binding } = audience;\n recipients = await workItemReportRecipients(deps.workItems, {\n orgId: binding.orgId,\n workItemId: binding.workItemId,\n senderSessionId: audience.sender.sessionId,\n });\n const named = await workItemReportAttributes(deps.workItems, binding);\n subject = `The ${binding.role} session for ${named.label}`;\n attributes = named.attributes;\n } else {\n recipients = [audience.recipient];\n subject = audience.subject;\n }\n if (recipients.length === 0) return;\n const argsText = JSON.stringify(args ?? {}) ?? '{}';\n const quoted = argsText.length > APPROVAL_ARGS_LENGTH ? `${argsText.slice(0, APPROVAL_ARGS_LENGTH)}…` : argsText;\n const message = [\n `${subject} is waiting for approval to run ${toolName} with ${quoted}.`,\n `Answer it with factory_answer_approval (sessionId \"${audience.sender.sessionId}\", toolCallId \"${toolCallId}\"), or open that session to approve or decline it there.`,\n ].join(' ');\n const notification = {\n ...reportNotification({\n sender: audience.sender,\n message,\n attributes: { ...attributes, 'waiting-for': 'approval', 'tool-name': toolName, 'tool-call-id': toolCallId },\n }),\n kind: 'approval',\n priority: 'urgent' as const,\n // One notice per held call, even if the gate is announced again.\n dedupeKey: `factory-approval:${toolCallId}`,\n };\n for (const recipient of recipients) await resolved.deliver(recipient, notification);\n };\n}\n"],"mappings":";;;;AAsBA,MAAa,uBAGT;CACF,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAU,UAAU;CAAM;CAC9D,SAAS;EAAE,MAAM;EAAW,UAAU;EAAU,UAAU;CAAM;CAChE,MAAM;EAAE,MAAM;EAAQ,UAAU;EAAQ,UAAU;CAAM;CACxD,UAAU;EAAE,MAAM;EAAY,UAAU;EAAO,UAAU;CAAK;CAE9D,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAQ,UAAU;CAAM;AAC9D;;AAGA,MAAM,oBAAoB;;;;;;;;AA0B1B,eAAsB,eACpB,eACA,EACE,iBACA,mBACA,OACA,OACA,YAAY,SASI;CAClB,MAAM,UAAU,MAAM,cAAc,kBAAkB;EACpD,UAAU;EACV,QAAQ;EACR,OAAO;CACT,CAAC;CACD,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,YAAY,OAAO;EAC9B,IACE,OAAO,aAAa,oBAAoB,mBACxC,EAAE,aAAa,OAAO,YAAY,aAAa,YAE9C,MAAM,SAAS,OAAO,IAAI,KACxB,OAAO,SAAS,WACf,OAAO,OAAO,YAAY,WAAW,YACrC,MAAM,SAAS,OAAO,WAAW,MAAM,MAC3C,OAAO,aAAa,OAEpB,OAAO;CAEX;CACA,OAAO;AACT;;AAGA,eAAe,WACb,eACA,EAAE,iBAAiB,qBACnB;CAMA,QAAO,MALe,cAAc,kBAAkB;EACp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,SAAS,MAAM,GAAG,oBAAoB,EAAE,KAAK;EACxG,MAAM,UAAU,CACd,GAAG,QAAQ,kCAAkC,SAAS,QAAQ,OAAO,IACrE,sDAAsD,SAAS,OAAO,UAAU,iBAAiB,WAAW,yDAC9G,CAAC,CAAC,KAAK,GAAG;EACV,MAAM,eAAe;GACnB,GAAG,mBAAmB;IACpB,QAAQ,SAAS;IACjB;IACA,YAAY;KAAE,GAAG;KAAY,eAAe;KAAY,aAAa;KAAU,gBAAgB;IAAW;GAC5G,CAAC;GACD,MAAM;GACN,UAAU;GAEV,WAAW,oBAAoB;EACjC;EACA,KAAK,MAAM,aAAa,YAAY,MAAM,SAAS,QAAQ,WAAW,YAAY;CACpF;AACF"}
|
|
1
|
+
{"version":3,"file":"reports.js","names":[],"sources":["../../src/tools/reports.ts"],"sourcesContent":["/**\n * Reports from sessions doing the work back to whoever follows it: a side\n * session's origin, or every subscriber of a work item. The agent reports with\n * `factory_message_origin`; when a run ends without one, the run-end backstop\n * sends it, so each run produces exactly one final report per recipient.\n */\n\nimport type {\n NotificationPriority,\n NotificationsStorage,\n SendNotificationSignalInput,\n} from '@mastra/core/notifications';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { FACTORY_SESSION_NOTIFICATION_SOURCE } from './deliver.js';\nimport type { FactoryDeliveryResult, FactoryDeliveryTarget } from './deliver.js';\n\nexport type FactoryReportStatus = 'progress' | 'blocked' | 'done' | 'failed';\n\n/** How each report status travels. Final reports never coalesce, so a later report can't overwrite them. */\nexport const FACTORY_REPORT_FORMS: Record<\n FactoryReportStatus | 'report',\n { kind: string; priority: NotificationPriority; coalesce: boolean }\n> = {\n failed: { kind: 'failed', priority: 'urgent', coalesce: false },\n blocked: { kind: 'blocked', priority: 'urgent', coalesce: false },\n done: { kind: 'done', priority: 'high', coalesce: false },\n progress: { kind: 'progress', priority: 'low', coalesce: true },\n // Not `message`: only messages can be answered, so a report can't start a reply loop.\n report: { kind: 'report', priority: 'high', coalesce: false },\n};\n\n/** How many recent `factory-session` notifications on a recipient thread the final-report check reads. */\nconst FINAL_REPORT_SCAN = 100;\n\nexport interface FactoryReportSender {\n sessionId: string;\n threadId: string;\n userId: string;\n}\n\nexport type FactoryReportDeliver = (\n target: FactoryDeliveryTarget,\n notification: Omit<SendNotificationSignalInput, 'source'>,\n options?: { onlyIfLive?: boolean },\n) => Promise<FactoryDeliveryResult>;\n\nexport interface FactoryReporting {\n deliver: FactoryReportDeliver;\n notifications: Pick<NotificationsStorage, 'listNotifications'>;\n}\n\n/**\n * Whether `senderSessionId` already put a report of one of `kinds` on the\n * recipient thread since `since`. Reads the durable notifications store, so it\n * holds across restarts. `listNotifications` has no time filter: records come\n * newest-updated first, and the scan stops at the first one last updated\n * before `since` (nothing after it can have been created later).\n */\nexport async function hasFinalReport(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n since,\n kinds,\n agentOnly = false,\n }: {\n senderSessionId: string;\n recipientThreadId: string;\n since: Date;\n kinds: readonly string[];\n /** Ignore reports Factory sent on the session's behalf (the backstop). */\n agentOnly?: boolean;\n },\n): Promise<boolean> {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n for (const record of records) {\n if (record.updatedAt < since) break;\n if (\n record.attributes?.['from-session'] === senderSessionId &&\n !(agentOnly && record.attributes?.backstop === 'true') &&\n // A reply carrying a final status counts like the report itself.\n (kinds.includes(record.kind) ||\n (record.kind === 'reply' &&\n typeof record.attributes?.status === 'string' &&\n kinds.includes(record.attributes.status))) &&\n record.createdAt >= since\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** The newest report `senderSessionId` put on the recipient thread. */\nasync function lastReport(\n notifications: FactoryReporting['notifications'],\n { senderSessionId, recipientThreadId }: { senderSessionId: string; recipientThreadId: string },\n) {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n return records\n .filter(record => record.attributes?.['from-session'] === senderSessionId)\n .reduce<(typeof records)[number] | undefined>(\n (newest, record) => (!newest || reportedAt(record) > reportedAt(newest) ? record : newest),\n undefined,\n );\n}\n\n/**\n * When a report last said something. `updatedAt` also moves when a report is\n * read, so it only counts once a later report has coalesced into this one;\n * otherwise the report says what it said when it was created.\n */\nfunction reportedAt(record: { createdAt: Date; updatedAt: Date; coalescedCount?: number }): Date {\n return (record.coalescedCount ?? 1) > 1 ? record.updatedAt : record.createdAt;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread is\n * already this exact `failed` backstop. A session stuck failing the same way\n * (a run that dies before the model, restarted over and over) then reports\n * once, not once per attempt; any other report in between resets it.\n */\nexport async function repeatsLastFailure(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n summary,\n }: { senderSessionId: string; recipientThreadId: string; summary: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, { senderSessionId, recipientThreadId });\n return last?.kind === 'failed' && last.attributes?.backstop === 'true' && last.summary === summary;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread\n * already says it is done. A session woken again after it finished (a PR it\n * subscribed to gets comments, reviews and CI results) ends each of those runs\n * with nothing new to say, so the follower hears \"finished\" once, not per wake.\n */\nasync function alreadyReportedDone(\n notifications: FactoryReporting['notifications'],\n target: { senderSessionId: string; recipientThreadId: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, target);\n return last?.kind === 'done' || (last?.kind === 'reply' && last.attributes?.status === 'done');\n}\n\nexport function reportNotification({\n sender,\n status,\n message,\n attributes = {},\n}: {\n sender: FactoryReportSender;\n status?: FactoryReportStatus;\n message: string;\n attributes?: Record<string, string>;\n}): Omit<SendNotificationSignalInput, 'source'> {\n const form = FACTORY_REPORT_FORMS[status ?? 'report'];\n return {\n kind: form.kind,\n priority: form.priority,\n // The whole text: a notification's summary is all the recipient's agent ever sees, even\n // through notification_inbox (which hides payloads), so a cut-off report loses its verdict.\n summary: message,\n payload: { message },\n sourceId: sender.sessionId,\n ...(form.coalesce ? { coalesceKey: `factory-session:${sender.sessionId}:${form.kind}` } : {}),\n attributes: {\n ...attributes,\n ...(status ? { status } : {}),\n // Last, so nothing above can claim another sender.\n 'from-session': sender.sessionId,\n 'from-thread': sender.threadId,\n 'from-user': sender.userId,\n },\n };\n}\n\n/** Everyone following a work item, except the session doing the reporting. */\nexport async function workItemReportRecipients(\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers'>,\n { orgId, workItemId, senderSessionId }: { orgId: string; workItemId: string; senderSessionId: string },\n): Promise<FactoryDeliveryTarget[]> {\n const subscribers = await workItems.listWorkItemSubscribers({ orgId, workItemId });\n return subscribers\n .filter(subscriber => subscriber.sessionId !== senderSessionId)\n .map(subscriber => ({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }));\n}\n\n/** How reports name an item: `#n`, else its quoted title, else its id. */\nasync function workItemReference(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n { orgId, factoryProjectId, workItemId }: { orgId: string; factoryProjectId: string; workItemId: string },\n): Promise<{ label: string; ref: string }> {\n const item = await workItems.getForProject(orgId, factoryProjectId, workItemId);\n const number = item ? workItemNumber(item) : null;\n if (number !== null) return { label: `#${number}`, ref: `#${number}` };\n return { label: item ? `\"${item.title}\"` : workItemId, ref: workItemId };\n}\n\n/** Attributes that say which item and role a worker's report is about. */\nexport async function workItemReportAttributes(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n {\n orgId,\n factoryProjectId,\n workItemId,\n role,\n }: { orgId: string; factoryProjectId: string; workItemId: string; role: string },\n): Promise<{ label: string; attributes: Record<string, string> }> {\n const { label, ref } = await workItemReference(workItems, { orgId, factoryProjectId, workItemId });\n return { label, attributes: { 'work-item': ref, role } };\n}\n\nexport type FactoryRunOutcome =\n | { status: 'done' }\n | { status: 'failed'; reason: string; failureCode?: string }\n | {\n status: 'blocked';\n toolName?: string;\n toolCallId?: string;\n /** The call waits for a person to allow it. */\n approval?: boolean;\n /** The tool paused itself, and a yes or no from a follower is all it needs. */\n decision?: boolean;\n };\n\n/** `waiting`: the session is waiting for an answer, so a later run owes the final report. */\nexport interface FactoryRunEndResult {\n waiting: boolean;\n deliveries?: FactoryDeliveryResult[];\n}\n\n/**\n * The run-end backstop: send `outcome` to each recipient that hasn't had a\n * final report from this sender since the run started. An agent's own `done`\n * or `failed` report wins. A run that completes after the agent's own\n * `blocked` sends nothing: the agent ended its turn to wait for an answer, and\n * its `done` comes from a later run. A `failed` backstop still goes out after an\n * earlier `blocked`.\n */\nexport async function sendRunEndReport(\n reporting: FactoryReporting,\n {\n sender,\n recipients,\n since,\n outcome,\n subject,\n attributes = {},\n }: {\n sender: FactoryReportSender;\n recipients: FactoryDeliveryTarget[];\n since: Date;\n outcome: FactoryRunOutcome;\n /** Who finished, e.g. \"The work session for #12\". */\n subject: string;\n attributes?: Record<string, string>;\n },\n): Promise<FactoryRunEndResult> {\n const kinds = outcome.status === 'blocked' ? ['blocked'] : ['done', 'failed'];\n const message =\n outcome.status === 'done'\n ? `${subject} finished.`\n : outcome.status === 'failed'\n ? `${subject} failed${outcome.failureCode ? ` (${outcome.failureCode})` : ''}: ${outcome.reason}`\n : outcome.approval\n ? `${subject} is waiting for someone to approve ${outcome.toolName ?? 'a tool call'} in that session.`\n : `${subject} is waiting${outcome.toolName ? ` on ${outcome.toolName}` : ''} and needs an answer.${\n outcome.decision && outcome.toolCallId\n ? ` Approve or decline it with factory_answer_approval (sessionId \"${sender.sessionId}\", toolCallId \"${outcome.toolCallId}\").`\n : ''\n }`;\n const notification = reportNotification({\n sender,\n status: outcome.status,\n message,\n attributes: {\n ...attributes,\n backstop: 'true',\n ...(outcome.status === 'failed' && outcome.failureCode ? { 'failure-code': outcome.failureCode } : {}),\n ...(outcome.status === 'blocked' && outcome.toolName ? { 'parked-tool': outcome.toolName } : {}),\n ...(outcome.status === 'blocked' && outcome.toolCallId ? { 'tool-call-id': outcome.toolCallId } : {}),\n ...(outcome.status === 'blocked' && (outcome.approval || outcome.decision) ? { 'waiting-for': 'approval' } : {}),\n },\n });\n const report = (recipient: FactoryDeliveryTarget, reportKinds: string[], agentOnly = false) =>\n hasFinalReport(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n since,\n kinds: reportKinds,\n agentOnly,\n });\n let waiting = outcome.status === 'blocked';\n const deliveries: FactoryDeliveryResult[] = [];\n for (const recipient of recipients) {\n // Only the agent's own reports count: an earlier run's backstop lands after this\n // run's window opened. A reply already told that follower how a finished run went.\n if (await report(recipient, outcome.status === 'done' ? [...kinds, 'reply'] : kinds, true)) continue;\n // Only the agent's own `blocked` means it ended its turn to wait; a backstop `blocked` from a parked run doesn't.\n if (outcome.status === 'done' && (await report(recipient, ['blocked'], true))) {\n waiting = true;\n continue;\n }\n if (\n outcome.status === 'done' &&\n (await alreadyReportedDone(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n }))\n ) {\n continue;\n }\n if (\n outcome.status === 'failed' &&\n (await repeatsLastFailure(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n summary: message,\n }))\n ) {\n continue;\n }\n deliveries.push(await reporting.deliver(recipient, notification));\n }\n return { waiting, deliveries };\n}\n\nexport interface FactoryRunEndInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n sender: FactoryReportSender;\n since: Date;\n outcome: FactoryRunOutcome;\n}\n\nexport type FactoryRunEndReporter = (input: FactoryRunEndInput) => Promise<FactoryRunEndResult>;\n\n/** The backstop for a work-item run: reports to the item's subscribers. Failures are logged, never thrown. */\nexport function createWorkItemRunEndReporter({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n /** Resolved per report: the controller exists only once the mount is up. */\n reporting: () => Promise<FactoryReporting | null>;\n}): FactoryRunEndReporter {\n return async input => {\n try {\n const resolved = await reporting();\n if (!resolved) return { waiting: false };\n const recipients = await workItemReportRecipients(workItems, {\n orgId: input.orgId,\n workItemId: input.workItemId,\n senderSessionId: input.sender.sessionId,\n });\n if (recipients.length === 0) return { waiting: false };\n const { label, attributes } = await workItemReportAttributes(workItems, input);\n return await sendRunEndReport(resolved, {\n sender: input.sender,\n recipients,\n since: input.since,\n outcome: input.outcome,\n subject: `The ${input.role} session for ${label}`,\n attributes,\n });\n } catch (error) {\n console.warn('[Factory reports] Unable to send the run-end report.', error);\n return { waiting: false };\n }\n };\n}\n\nexport interface FactoryStageChange {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n /** The boards the move left and entered. Named in the notice when they differ. */\n fromBoard?: string;\n toBoard?: string;\n}\n\n/**\n * Tells a work item's subscribers it moved, at `low` priority. Only sessions\n * already live hear it: a stage change never brings a session online; an\n * offline subscriber sees the stage in its state signal on its next turn.\n */\nexport function createStageChangeNotifier({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n reporting: () => Promise<FactoryReporting | null>;\n}): (change: FactoryStageChange) => Promise<void> {\n return async change => {\n const subscribers = await workItems.listWorkItemSubscribers({\n orgId: change.orgId,\n workItemId: change.workItemId,\n });\n if (subscribers.length === 0) return;\n const resolved = await reporting();\n if (!resolved) return;\n const { label, ref } = await workItemReference(workItems, change);\n // On another board a phase of the same name is a different phase: a board change names both\n // boards so the notice never reads as staying put.\n const movedBoards =\n change.fromBoard !== undefined && change.toBoard !== undefined && change.fromBoard !== change.toBoard;\n const summary = movedBoards\n ? change.fromStage\n ? `${label} moved from ${change.fromStage} on the ${change.fromBoard} board to ${change.toStage} on the ${change.toBoard} board.`\n : `${label} moved to ${change.toStage} on the ${change.toBoard} board.`\n : change.fromStage\n ? `${label} moved from ${change.fromStage} to ${change.toStage}.`\n : `${label} moved to ${change.toStage}.`;\n const notification: Omit<SendNotificationSignalInput, 'source'> = {\n kind: 'stage',\n priority: 'low',\n summary,\n payload: { message: summary },\n sourceId: change.workItemId,\n coalesceKey: `factory-stage:${change.workItemId}`,\n attributes: {\n 'work-item': ref,\n ...(change.fromStage ? { 'from-stage': change.fromStage } : {}),\n 'to-stage': change.toStage,\n ...(movedBoards ? { 'from-board': change.fromBoard!, 'to-board': change.toBoard! } : {}),\n },\n };\n for (const subscriber of subscribers) {\n try {\n await resolved.deliver({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }, notification, {\n onlyIfLive: true,\n });\n } catch (error) {\n console.warn(`[Factory reports] Unable to tell ${subscriber.sessionId} that ${label} moved.`, error);\n }\n }\n };\n}\n\n/** Reports one run end of a session; the thread is the one the run used. */\nexport type FactorySessionRunEndReporter = (input: {\n sessionId: string;\n threadId: string | null;\n outcome: FactoryRunOutcome;\n since: Date;\n}) => Promise<void>;\n\n/** A tool call a session's run is holding until someone approves or declines it. */\nexport interface FactoryApprovalRequest {\n sessionId: string;\n threadId: string | null;\n toolName: string;\n toolCallId: string;\n args: unknown;\n}\n\nexport type FactoryApprovalNotifier = (request: FactoryApprovalRequest) => Promise<void>;\n\ninterface SessionReportDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<\n WorkItemsStorage,\n 'findActiveRunBindingForSession' | 'findRunBindingBySession' | 'listWorkItemSubscribers' | 'getForProject'\n >;\n reporting: () => Promise<FactoryReporting | null>;\n}\n\n/** How much of a gated call's arguments an approval notice quotes. */\nconst APPROVAL_ARGS_LENGTH = 3000;\n\n/**\n * Who hears from a session: a work session (one with an active run binding)\n * reports to its item's followers, a side session to the session that started\n * it. Any other session (a person's own) has nobody to tell.\n */\nasync function sessionAudience(\n { sessions, workItems }: Omit<SessionReportDependencies, 'reporting'>,\n sessionId: string,\n threadId: string | null,\n /** When the run started: a binding revoked since then (the run moved its card to a finished stage) still counts. */\n since?: Date,\n): Promise<\n | {\n kind: 'work-item';\n binding: NonNullable<Awaited<ReturnType<WorkItemsStorage['findActiveRunBindingForSession']>>>;\n sender: FactoryReportSender;\n }\n | {\n kind: 'origin';\n sender: FactoryReportSender;\n recipient: FactoryDeliveryTarget;\n subject: string;\n /** Set while the origin has muted this side session's reports (approval notices still go through). */\n mutedAt: Date | null;\n }\n | null\n> {\n const row = await sessions.getBySessionId(sessionId);\n if (!row?.factoryProjectId) return null;\n let binding = await workItems.findActiveRunBindingForSession({\n orgId: row.orgId,\n factoryProjectId: row.factoryProjectId,\n sessionId: row.sessionId,\n });\n if (!binding && since && threadId) {\n // The binding records the memory resource the run used: the Factory's, its\n // own id for a run kept on its own resource, or its owner's for a person's\n // session the run started in.\n for (const resourceId of new Set([row.factoryProjectId, row.sessionId, row.userId])) {\n const latest = await workItems.findRunBindingBySession({\n factoryProjectId: row.factoryProjectId,\n threadId,\n resourceId,\n sessionId: row.sessionId,\n });\n if (latest?.orgId === row.orgId && latest.revokedAt && latest.revokedAt >= since) {\n binding = latest;\n break;\n }\n }\n }\n if (binding) {\n return {\n kind: 'work-item',\n binding,\n sender: { sessionId: row.sessionId, threadId: binding.threadId, userId: row.userId },\n };\n }\n if (!row.originSessionId || !row.originThreadId || !threadId) return null;\n return {\n kind: 'origin',\n sender: { sessionId: row.sessionId, threadId, userId: row.userId },\n recipient: { sessionId: row.originSessionId, threadId: row.originThreadId },\n subject: `The side session \"${row.title ?? row.sessionId}\"`,\n mutedAt: row.originMutedAt ?? null,\n };\n}\n\n/** Reports each run end of a work or side session to whoever follows it. */\nexport function createSessionRunEndReporter(deps: SessionReportDependencies): FactorySessionRunEndReporter {\n const workItemRunEnd = createWorkItemRunEndReporter(deps);\n return async ({ sessionId, threadId, outcome, since }) => {\n const audience = await sessionAudience(deps, sessionId, threadId, since);\n if (!audience) return;\n if (audience.kind === 'work-item') {\n const { binding, sender } = audience;\n await workItemRunEnd({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n sender,\n since,\n outcome,\n });\n return;\n }\n // A muted origin still hears when the session is blocked: nothing else would tell it the session is waiting.\n if (audience.mutedAt && outcome.status !== 'blocked') return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n await sendRunEndReport(resolved, {\n sender: audience.sender,\n recipients: [audience.recipient],\n since,\n outcome,\n subject: audience.subject,\n });\n };\n}\n\n/**\n * Tells whoever follows a session, urgently, the moment its run holds a tool\n * call for approval. The run stays open on the gate, so no run end would say\n * so; the notice names the session and call so a follower can answer it with\n * `factory_answer_approval`.\n */\nexport function createSessionApprovalNotifier(deps: SessionReportDependencies): FactoryApprovalNotifier {\n return async ({ sessionId, threadId, toolName, toolCallId, args }) => {\n const audience = await sessionAudience(deps, sessionId, threadId);\n if (!audience) return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n let subject: string;\n let recipients: FactoryDeliveryTarget[];\n let attributes: Record<string, string> = {};\n if (audience.kind === 'work-item') {\n const { binding } = audience;\n recipients = await workItemReportRecipients(deps.workItems, {\n orgId: binding.orgId,\n workItemId: binding.workItemId,\n senderSessionId: audience.sender.sessionId,\n });\n const named = await workItemReportAttributes(deps.workItems, binding);\n subject = `The ${binding.role} session for ${named.label}`;\n attributes = named.attributes;\n } else {\n recipients = [audience.recipient];\n subject = audience.subject;\n }\n if (recipients.length === 0) return;\n const argsText = JSON.stringify(args ?? {}) ?? '{}';\n const quoted = argsText.length > APPROVAL_ARGS_LENGTH ? `${argsText.slice(0, APPROVAL_ARGS_LENGTH)}…` : argsText;\n const message = [\n `${subject} is waiting for approval to run ${toolName} with ${quoted}.`,\n `Answer it with factory_answer_approval (sessionId \"${audience.sender.sessionId}\", toolCallId \"${toolCallId}\"), or open that session to approve or decline it there.`,\n ].join(' ');\n const notification = {\n ...reportNotification({\n sender: audience.sender,\n message,\n attributes: { ...attributes, 'waiting-for': 'approval', 'tool-name': toolName, 'tool-call-id': toolCallId },\n }),\n kind: 'approval',\n priority: 'urgent' as const,\n // One notice per held call, even if the gate is announced again.\n dedupeKey: `factory-approval:${toolCallId}`,\n };\n for (const recipient of recipients) await resolved.deliver(recipient, notification);\n };\n}\n"],"mappings":";;;;AAsBA,MAAa,uBAGT;CACF,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAU,UAAU;CAAM;CAC9D,SAAS;EAAE,MAAM;EAAW,UAAU;EAAU,UAAU;CAAM;CAChE,MAAM;EAAE,MAAM;EAAQ,UAAU;EAAQ,UAAU;CAAM;CACxD,UAAU;EAAE,MAAM;EAAY,UAAU;EAAO,UAAU;CAAK;CAE9D,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAQ,UAAU;CAAM;AAC9D;;AAGA,MAAM,oBAAoB;;;;;;;;AA0B1B,eAAsB,eACpB,eACA,EACE,iBACA,mBACA,OACA,OACA,YAAY,SASI;CAClB,MAAM,UAAU,MAAM,cAAc,kBAAkB;EACpD,UAAU;EACV,QAAQ;EACR,OAAO;CACT,CAAC;CACD,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,YAAY,OAAO;EAC9B,IACE,OAAO,aAAa,oBAAoB,mBACxC,EAAE,aAAa,OAAO,YAAY,aAAa,YAE9C,MAAM,SAAS,OAAO,IAAI,KACxB,OAAO,SAAS,WACf,OAAO,OAAO,YAAY,WAAW,YACrC,MAAM,SAAS,OAAO,WAAW,MAAM,MAC3C,OAAO,aAAa,OAEpB,OAAO;CAEX;CACA,OAAO;AACT;;AAGA,eAAe,WACb,eACA,EAAE,iBAAiB,qBACnB;CAMA,QAAO,MALe,cAAc,kBAAkB;EACpD,UAAU;EACV,QAAQ;EACR,OAAO;CACT,CAAC,EAAA,CAEE,QAAO,WAAU,OAAO,aAAa,oBAAoB,eAAe,CAAC,CACzE,QACE,QAAQ,WAAY,CAAC,UAAU,WAAW,MAAM,IAAI,WAAW,MAAM,IAAI,SAAS,QACnF,KAAA,CACF;AACJ;;;;;;AAOA,SAAS,WA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AAG;EAC7B,MAAM,WAAW,KAAK,UAAU,QAAQ,CAAC,CAAC,KAAK;EAC/C,MAAM,SAAS,SAAS,SAAS,uBAAuB,GAAG,SAAS,MAAM,GAAG,oBAAoB,EAAE,KAAK;EACxG,MAAM,UAAU,CACd,GAAG,QAAQ,kCAAkC,SAAS,QAAQ,OAAO,IACrE,sDAAsD,SAAS,OAAO,UAAU,iBAAiB,WAAW,yDAC9G,CAAC,CAAC,KAAK,GAAG;EACV,MAAM,eAAe;GACnB,GAAG,mBAAmB;IACpB,QAAQ,SAAS;IACjB;IACA,YAAY;KAAE,GAAG;KAAY,eAAe;KAAY,aAAa;KAAU,gBAAgB;IAAW;GAC5G,CAAC;GACD,MAAM;GACN,UAAU;GAEV,WAAW,oBAAoB;EACjC;EACA,KAAK,MAAM,aAAa,YAAY,MAAM,SAAS,QAAQ,WAAW,YAAY;CACpF;AACF"}
|
|
@@ -4,7 +4,7 @@ import { hasEveryLabel } from "./card-labels.js";
|
|
|
4
4
|
import { BOARD_PERSON_FIELDS, matchesPeople } from "./card-people.js";
|
|
5
5
|
import { matchesSourceFilters } from "./card-source-filters.js";
|
|
6
6
|
import { relatedCardsIn } from "./list-related-cards.js";
|
|
7
|
-
import {
|
|
7
|
+
import { matchesSearch, searchTerms } from "./search-terms.js";
|
|
8
8
|
// src/work-items/board-phases.ts
|
|
9
9
|
/**
|
|
10
10
|
* What one board view shows: for each phase of the board, the cards a reader lists and how many
|
|
@@ -70,14 +70,14 @@ function ordered(held, sort) {
|
|
|
70
70
|
}
|
|
71
71
|
/** Whether the view's search and filters keep a card; undefined when the view has none. */
|
|
72
72
|
function viewMatcher(view) {
|
|
73
|
-
const
|
|
73
|
+
const terms = searchTerms(view.q ?? "");
|
|
74
74
|
const bySource = view.source.size > 0 || view.linearProject.size > 0;
|
|
75
75
|
const byLabel = view.label.size > 0;
|
|
76
76
|
const byPeople = BOARD_PERSON_FIELDS.some((field) => view[field].size > 0);
|
|
77
|
-
if (
|
|
77
|
+
if (terms.length === 0 && !bySource && !byLabel && !byPeople) return void 0;
|
|
78
78
|
return (card) => {
|
|
79
79
|
const facts = cardFacts(card);
|
|
80
|
-
return
|
|
80
|
+
return matchesSearch(facts.search, terms) && (!bySource || matchesSourceFilters(facts, view)) && (!byLabel || hasEveryLabel(facts.labels, view.label)) && (!byPeople || matchesPeople(facts.relations, view));
|
|
81
81
|
};
|
|
82
82
|
}
|
|
83
83
|
const EVERY_CARD = [() => true];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"board-phases.js","names":[],"sources":["../../src/work-items/board-phases.ts"],"sourcesContent":["/**\n * What one board view shows: for each phase of the board, the cards a reader lists and how many\n * match. The phases route answers with it, and the browser's tests run it in place of the server,\n * so it reads plain values only.\n */\n\nimport { boardForWorkItem } from '../boards/semantics.js';\nimport type { BoardPhasesQuery, BoardPhasesResponse } from '../routes/contracts.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { cardFacts } from './card-facts.js';\nimport { hasEveryLabel } from './card-labels.js';\nimport { BOARD_PERSON_FIELDS, matchesPeople } from './card-people.js';\nimport { matchesSourceFilters } from './card-source-filters.js';\nimport { relatedCardsIn } from './list-related-cards.js';\nimport { hasEveryWord, searchWords } from './search-words.js';\n\n/** The board whose phases are read: its id and its phases in declaration order. */\nexport interface PhasesBoard {\n id: string;\n phases: readonly string[];\n}\n\n/** The view, as the phases route parses it. `cards` is the route's own: bodies are not computed here. */\nexport type BoardPhasesView = Omit<BoardPhasesQuery, 'cards'>;\n\nexport interface BoardPhases {\n /** The answer, without what only the route knows: session states and card bodies. */\n body: Pick<BoardPhasesResponse, 'phases' | 'item' | 'related' | 'relatedTotal' | 'boardTotal' | 'matchingTotal'>;\n /** Every card `body` names: the listed ones, the asked one, then the related ones. */\n named: Card[];\n}\n\n/** A card in one phase. */\ninterface Placed {\n card: Card;\n /** When the card last entered the phase; when it was created, for a card the phase holds without an entry. */\n at: string;\n /** Who made that entry. */\n by: string | undefined;\n}\n\ninterface PhaseCards {\n phase: string;\n /** Latest entry first. */\n recent: Placed[];\n newest?: Placed[];\n oldest?: Placed[];\n}\n\ninterface BoardIndex {\n /** The board's cards, each once. */\n cards: Card[];\n phases: PhaseCards[];\n /** A card once for each phase it is listed under beyond its first. */\n repeats: Card[];\n}\n\n// One index per list version and board: `listShared` returns the same array until a card changes.\nconst boardsByList = new WeakMap<readonly Card[], Map<string, BoardIndex>>();\n\n/** The phases that list the card: each of the board's phases it is in, or the first one when it is in none. */\nfunction cardPhases(card: Card, phases: readonly string[]): readonly string[] {\n const held = phases.filter(phase => card.stages.includes(phase));\n return held.length > 0 ? held : phases.slice(0, 1);\n}\n\nfunction placed(card: Card, phase: string): Placed {\n let latest: Card['stageHistory'][number] | undefined;\n for (const entry of card.stageHistory) {\n if (entry.stage === phase && (!latest || entry.enteredAt > latest.enteredAt)) latest = entry;\n }\n return { card, at: latest?.enteredAt ?? card.createdAt.toISOString(), by: latest?.by };\n}\n\nfunction descending(left: string, right: string): number {\n return left < right ? 1 : left > right ? -1 : 0;\n}\n\n// Cards that entered at the same instant keep one order on every read.\nfunction byRecent(left: Placed, right: Placed): number {\n return descending(left.at, right.at) || descending(left.card.id, right.card.id);\n}\n\nfunction byCreation(direction: 1 | -1): (left: Placed, right: Placed) => number {\n return (left, right) =>\n direction * (left.card.createdAt.getTime() - right.card.createdAt.getTime()) ||\n descending(left.card.id, right.card.id);\n}\n\nfunction boardIndex(list: readonly Card[], board: PhasesBoard): BoardIndex {\n let boards = boardsByList.get(list);\n if (!boards) boardsByList.set(list, (boards = new Map()));\n // The phases are part of the key: an edited board keeps its id.\n const key = [board.id, ...board.phases].join('\\n');\n let index = boards.get(key);\n if (index) return index;\n\n const byPhase = new Map(board.phases.map((phase): [string, Placed[]] => [phase, []]));\n const cards: Card[] = [];\n const repeats: Card[] = [];\n for (const card of list) {\n if (boardForWorkItem(card) !== board.id) continue;\n cards.push(card);\n cardPhases(card, board.phases).forEach((phase, nth) => {\n byPhase.get(phase)?.push(placed(card, phase));\n if (nth > 0) repeats.push(card);\n });\n }\n index = {\n cards,\n phases: [...byPhase].map(([phase, entries]) => ({ phase, recent: entries.sort(byRecent) })),\n repeats,\n };\n boards.set(key, index);\n return index;\n}\n\nfunction ordered(held: PhaseCards, sort: BoardPhasesView['sort']): readonly Placed[] {\n if (sort === 'created-newest') return (held.newest ??= held.recent.toSorted(byCreation(-1)));\n if (sort === 'created-oldest') return (held.oldest ??= held.recent.toSorted(byCreation(1)));\n return held.recent;\n}\n\n/** Whether the view's search and filters keep a card; undefined when the view has none. */\nfunction viewMatcher(view: BoardPhasesView): ((card: Card) => boolean) | undefined {\n const words = searchWords(view.q ?? '');\n const bySource = view.source.size > 0 || view.linearProject.size > 0;\n const byLabel = view.label.size > 0;\n const byPeople = BOARD_PERSON_FIELDS.some(field => view[field].size > 0);\n if (words.length === 0 && !bySource && !byLabel && !byPeople) return undefined;\n return card => {\n const facts = cardFacts(card);\n return (\n hasEveryWord(facts.text, words) &&\n (!bySource || matchesSourceFilters(facts, view)) &&\n (!byLabel || hasEveryLabel(facts.labels, view.label)) &&\n (!byPeople || matchesPeople(facts.relations, view))\n );\n };\n}\n\nconst EVERY_CARD: ReadonlyArray<(entry: Placed) => boolean> = [() => true];\n\n/**\n * The phases of `board` as `view` shows them to `userId`, read from the project's whole `list`.\n * A window for a phase the board does not have deepens nothing: a reader may still hold a\n * phase deeper after the board lost that phase, and keeps its board. `version` names the body the\n * caller sends for a card: the caller knows that body, this module does not.\n */\nexport function boardPhases(\n list: readonly Card[],\n board: PhasesBoard,\n view: BoardPhasesView,\n userId: string,\n version: (card: Card) => string,\n): BoardPhases {\n const stamp = (card: Card) => ({ id: card.id, version: version(card) });\n const index = boardIndex(list, board);\n const matches = viewMatcher(view);\n // `recent-mine` is `recent` read twice: the cards the reader last moved here, then the others.\n const passes =\n view.sort === 'recent-mine'\n ? [(entry: Placed) => entry.by === userId, (entry: Placed) => entry.by !== userId]\n : EVERY_CARD;\n const item = view.item === undefined ? undefined : index.cards.find(card => card.id === view.item);\n const shown = item && (!matches || matches(item)) ? cardPhases(item, board.phases) : [];\n const places: Array<{ phase: string; position: number }> = [];\n\n const listed = new Set<Card>();\n let matchingTotal = 0;\n const phases = index.phases.map(held => {\n const all = ordered(held, view.sort);\n const size = view.window.get(held.phase) ?? view.limit;\n // The asked card is found, not listed down to: the answer is no larger for a card that lies deep.\n let sought = shown.includes(held.phase) ? item : undefined;\n const cards: Card[] = [];\n let total = 0;\n scan: for (const pass of passes) {\n for (const entry of all) {\n if (!pass(entry) || (matches && !matches(entry.card))) continue;\n if (entry.card === sought) {\n places.push({ phase: held.phase, position: total });\n sought = undefined;\n }\n total += 1;\n if (cards.length < size) {\n cards.push(entry.card);\n listed.add(entry.card);\n } else if (!matches && !sought) {\n // Nothing is filtered out, so the rest need not be read to count them.\n break scan;\n }\n }\n }\n if (!matches) total = all.length;\n matchingTotal += total;\n return { phase: held.phase, total, cards: cards.map(stamp) };\n });\n for (const card of index.repeats) {\n if (!matches || matches(card)) matchingTotal -= 1;\n }\n // Its body is the reader's to show whether or not a phase lists it.\n if (item) listed.add(item);\n\n const relatedTo = relatedCardsIn(list);\n const related = new Set<Card>();\n const everyRelated = new Set<Card>();\n for (const card of listed) {\n // One card may be the parent of thousands: each names its first `limit`, and the total counts the rest.\n let named = 0;\n for (const other of relatedTo(card)) {\n if (listed.has(other)) continue;\n everyRelated.add(other);\n if (named < view.limit) {\n related.add(other);\n named += 1;\n }\n }\n }\n return {\n body: {\n phases,\n ...(item ? { item: { ...stamp(item), places } } : {}),\n related: [...related].map(stamp),\n relatedTotal: everyRelated.size,\n boardTotal: index.cards.length,\n matchingTotal,\n },\n named: [...listed, ...related],\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA0DA,MAAM,+BAAe,IAAI,QAAkD;;AAG3E,SAAS,WAAW,MAAY,QAA8C;CAC5E,MAAM,OAAO,OAAO,QAAO,UAAS,KAAK,OAAO,SAAS,KAAK,CAAC;CAC/D,OAAO,K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O,MAAM,IAAI,KAAK;EAAE;CAC7D,CAAC;CACD,KAAK,MAAM,QAAQ,MAAM,SACvB,IAAI,CAAC,WAAW,QAAQ,IAAI,GAAG,iBAAiB;CAGlD,IAAI,MAAM,OAAO,IAAI,IAAI;CAEzB,MAAM,YAAY,eAAe,IAAI;CACrC,MAAM,0BAAU,IAAI,IAAU;CAC9B,MAAM,+BAAe,IAAI,IAAU;CACnC,KAAK,MAAM,QAAQ,QAAQ;EAEzB,IAAI,QAAQ;EACZ,KAAK,MAAM,SAAS,UAAU,IAAI,GAAG;GACnC,IAAI,OAAO,IAAI,KAAK,GAAG;GACvB,aAAa,IAAI,KAAK;GACtB,IAAI,QAAQ,KAAK,OAAO;IACtB,QAAQ,IAAI,KAAK;IACjB,SAAS;GACX;EACF;CACF;CACA,OAAO;EACL,MAAM;GACJ;GACA,GAAI,OAAO,EAAE,MAAM;IAAE,GAAG,MAAM,IAAI;IAAG;GAAO,EAAE,IAAI,CAAC;GACnD,SAAS,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,KAAK;GAC/B,cAAc,aAAa;GAC3B,YAAY,MAAM,MAAM;GACxB;EACF;EACA,OAAO,CAAC,GAAG,QAAQ,GAAG,OAAO;CAC/B;AACF"}
|
|
1
|
+
{"version":3,"file":"board-phases.js","names":[],"sources":["../../src/work-items/board-phases.ts"],"sourcesContent":["/**\n * What one board view shows: for each phase of the board, the cards a reader lists and how many\n * match. The phases route answers with it, and the browser's tests run it in place of the server,\n * so it reads plain values only.\n */\n\nimport { boardForWorkItem } from '../boards/semantics.js';\nimport type { BoardPhasesQuery, BoardPhasesResponse } from '../routes/contracts.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { cardFacts } from './card-facts.js';\nimport { hasEveryLabel } from './card-labels.js';\nimport { BOARD_PERSON_FIELDS, matchesPeople } from './card-people.js';\nimport { matchesSourceFilters } from './card-source-filters.js';\nimport { relatedCardsIn } from './list-related-cards.js';\nimport { matchesSearch, searchTerms } from './search-terms.js';\n\n/** The board whose phases are read: its id and its phases in declaration order. */\nexport interface PhasesBoard {\n id: string;\n phases: readonly string[];\n}\n\n/** The view, as the phases route parses it. `cards` is the route's own: bodies are not computed here. */\nexport type BoardPhasesView = Omit<BoardPhasesQuery, 'cards'>;\n\nexport interface BoardPhases {\n /** The answer, without what only the route knows: session states and card bodies. */\n body: Pick<BoardPhasesResponse, 'phases' | 'item' | 'related' | 'relatedTotal' | 'boardTotal' | 'matchingTotal'>;\n /** Every card `body` names: the listed ones, the asked one, then the related ones. */\n named: Card[];\n}\n\n/** A card in one phase. */\ninterface Placed {\n card: Card;\n /** When the card last entered the phase; when it was created, for a card the phase holds without an entry. */\n at: string;\n /** Who made that entry. */\n by: string | undefined;\n}\n\ninterface PhaseCards {\n phase: string;\n /** Latest entry first. */\n recent: Placed[];\n newest?: Placed[];\n oldest?: Placed[];\n}\n\ninterface BoardIndex {\n /** The board's cards, each once. */\n cards: Card[];\n phases: PhaseCards[];\n /** A card once for each phase it is listed under beyond its first. */\n repeats: Card[];\n}\n\n// One index per list version and board: `listShared` returns the same array until a card changes.\nconst boardsByList = new WeakMap<readonly Card[], Map<string, BoardIndex>>();\n\n/** The phases that list the card: each of the board's phases it is in, or the first one when it is in none. */\nfunction cardPhases(card: Card, phases: readonly string[]): readonly string[] {\n const held = phases.filter(phase => card.stages.includes(phase));\n return held.length > 0 ? held : phases.slice(0, 1);\n}\n\nfunction placed(card: Card, phase: string): Placed {\n let latest: Card['stageHistory'][number] | undefined;\n for (const entry of card.stageHistory) {\n if (entry.stage === phase && (!latest || entry.enteredAt > latest.enteredAt)) latest = entry;\n }\n return { card, at: latest?.enteredAt ?? card.createdAt.toISOString(), by: latest?.by };\n}\n\nfunction descending(left: string, right: string): number {\n return left < right ? 1 : left > right ? -1 : 0;\n}\n\n// Cards that entered at the same instant keep one order on every read.\nfunction byRecent(left: Placed, right: Placed): number {\n return descending(left.at, right.at) || descending(left.card.id, right.card.id);\n}\n\nfunction byCreation(direction: 1 | -1): (left: Placed, right: Placed) => number {\n return (left, right) =>\n direction * (left.card.createdAt.getTime() - right.card.createdAt.getTime()) ||\n descending(left.card.id, right.card.id);\n}\n\nfunction boardIndex(list: readonly Card[], board: PhasesBoard): BoardIndex {\n let boards = boardsByList.get(list);\n if (!boards) boardsByList.set(list, (boards = new Map()));\n // The phases are part of the key: an edited board keeps its id.\n const key = [board.id, ...board.phases].join('\\n');\n let index = boards.get(key);\n if (index) return index;\n\n const byPhase = new Map(board.phases.map((phase): [string, Placed[]] => [phase, []]));\n const cards: Card[] = [];\n const repeats: Card[] = [];\n for (const card of list) {\n if (boardForWorkItem(card) !== board.id) continue;\n cards.push(card);\n cardPhases(card, board.phases).forEach((phase, nth) => {\n byPhase.get(phase)?.push(placed(card, phase));\n if (nth > 0) repeats.push(card);\n });\n }\n index = {\n cards,\n phases: [...byPhase].map(([phase, entries]) => ({ phase, recent: entries.sort(byRecent) })),\n repeats,\n };\n boards.set(key, index);\n return index;\n}\n\nfunction ordered(held: PhaseCards, sort: BoardPhasesView['sort']): readonly Placed[] {\n if (sort === 'created-newest') return (held.newest ??= held.recent.toSorted(byCreation(-1)));\n if (sort === 'created-oldest') return (held.oldest ??= held.recent.toSorted(byCreation(1)));\n return held.recent;\n}\n\n/** Whether the view's search and filters keep a card; undefined when the view has none. */\nfunction viewMatcher(view: BoardPhasesView): ((card: Card) => boolean) | undefined {\n const terms = searchTerms(view.q ?? '');\n const bySource = view.source.size > 0 || view.linearProject.size > 0;\n const byLabel = view.label.size > 0;\n const byPeople = BOARD_PERSON_FIELDS.some(field => view[field].size > 0);\n if (terms.length === 0 && !bySource && !byLabel && !byPeople) return undefined;\n return card => {\n const facts = cardFacts(card);\n return (\n matchesSearch(facts.search, terms) &&\n (!bySource || matchesSourceFilters(facts, view)) &&\n (!byLabel || hasEveryLabel(facts.labels, view.label)) &&\n (!byPeople || matchesPeople(facts.relations, view))\n );\n };\n}\n\nconst EVERY_CARD: ReadonlyArray<(entry: Placed) => boolean> = [() => true];\n\n/**\n * The phases of `board` as `view` shows them to `userId`, read from the project's whole `list`.\n * A window for a phase the board does not have deepens nothing: a reader may still hold a\n * phase deeper after the board lost that phase, and keeps its board. `version` names the body the\n * caller sends for a card: the caller knows that body, this module does not.\n */\nexport function boardPhases(\n list: readonly Card[],\n board: PhasesBoard,\n view: BoardPhasesView,\n userId: string,\n version: (card: Card) => string,\n): BoardPhases {\n const stamp = (card: Card) => ({ id: card.id, version: version(card) });\n const index = boardIndex(list, board);\n const matches = viewMatcher(view);\n // `recent-mine` is `recent` read twice: the cards the reader last moved here, then the others.\n const passes =\n view.sort === 'recent-mine'\n ? [(entry: Placed) => entry.by === userId, (entry: Placed) => entry.by !== userId]\n : EVERY_CARD;\n const item = view.item === undefined ? undefined : index.cards.find(card => card.id === view.item);\n const shown = item && (!matches || matches(item)) ? cardPhases(item, board.phases) : [];\n const places: Array<{ phase: string; position: number }> = [];\n\n const listed = new Set<Card>();\n let matchingTotal = 0;\n const phases = index.phases.map(held => {\n const all = ordered(held, view.sort);\n const size = view.window.get(held.phase) ?? view.limit;\n // The asked card is found, not listed down to: the answer is no larger for a card that lies deep.\n let sought = shown.includes(held.phase) ? item : undefined;\n const cards: Card[] = [];\n let total = 0;\n scan: for (const pass of passes) {\n for (const entry of all) {\n if (!pass(entry) || (matches && !matches(entry.card))) continue;\n if (entry.card === sought) {\n places.push({ phase: held.phase, position: total });\n sought = undefined;\n }\n total += 1;\n if (cards.length < size) {\n cards.push(entry.card);\n listed.add(entry.card);\n } else if (!matches && !sought) {\n // Nothing is filtered out, so the rest need not be read to count them.\n break scan;\n }\n }\n }\n if (!matches) total = all.length;\n matchingTotal += total;\n return { phase: held.phase, total, cards: cards.map(stamp) };\n });\n for (const card of index.repeats) {\n if (!matches || matches(card)) matchingTotal -= 1;\n }\n // Its body is the reader's to show whether or not a phase lists it.\n if (item) listed.add(item);\n\n const relatedTo = relatedCardsIn(list);\n const related = new Set<Card>();\n const everyRelated = new Set<Card>();\n for (const card of listed) {\n // One card may be the parent of thousands: each names its first `limit`, and the total counts the rest.\n let named = 0;\n for (const other of relatedTo(card)) {\n if (listed.has(other)) continue;\n everyRelated.add(other);\n if (named < view.limit) {\n related.add(other);\n named += 1;\n }\n }\n }\n return {\n body: {\n phases,\n ...(item ? { item: { ...stamp(item), places } } : {}),\n related: [...related].map(stamp),\n relatedTotal: everyRelated.size,\n boardTotal: index.cards.length,\n matchingTotal,\n },\n named: [...listed, ...related],\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA0DA,MAAM,+BAAe,IAAI,QAAkD;;AAG3E,SAAS,WAAW,MAAY,QAA8C;CAC5E,MAAM,OAAO,OAAO,QAAO,UAAS,KAAK,OAAO,SAAS,KAAK,CAAC;CAC/D,OAAO,KAAK,SAAS,IAAI,OAAO,OAAO,MAAM,GAAG,CAAC;AACnD;AAEA,SAAS,OAAO,MAAY,OAAuB;CACjD,IAAI;CACJ,KAAK,MAAM,SAAS,KAAK,cACvB,IAAI,MAAM,UAAU,UAAU,CAAC,UAAU,MAAM,YAAY,OAAO,YAAY,SAAS;CAEzF,OAAO;EAAE;EAAM,IAAI,QAAQ,aAAa,KAAK,UAAU,YAAY;EAAG,IAAI,QAAQ;CAAG;AACvF;AAEA,SAAS,WAAW,MAAc,OAAuB;CACvD,OAAO,OAAO,QAAQ,IAAI,OAAO,QAAQ,KAAK;AAChD;AAGA,SAAS,SAAS,MAAc,OAAuB;CACrD,OAAO,WAAW,KAAK,IAAI,MAAM,EAAE,KAAK,WAAW,KAAK,KAAK,IAAI,MAAM,KAAK,EAAE;AAChF;AAEA,SAAS,WAAW,WAA4D;CAC9E,QAAQ,MAAM,UACZ,aAAa,KAAK,KAAK,UAAU,QAAQ,IAAI,MAAM,KAAK,UAAU,QAAQ,MAC1E,WAAW,KAAK,KAAK,IAAI,MAAM,KAAK,EAAE;AAC1C;AAEA,SAAS,WAAW,MAAuB,OAAgC;CACzE,IAAI,SAAS,aAAa,IAAI,IAAI;CAClC,IAAI,CAAC,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"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Card } from '../storage/domains/work-items/base.js';
|
|
2
2
|
import type { BoardRelations, ProviderPerson, ProviderPersonRole } from './card-people.js';
|
|
3
3
|
import type { SourceFacts } from './card-source-filters.js';
|
|
4
|
+
import type { SearchableCard } from './search-terms.js';
|
|
4
5
|
/** What a board view's search and filters read of a card. */
|
|
5
6
|
export interface CardFacts extends SourceFacts {
|
|
6
7
|
hasPullRequest: boolean;
|
|
@@ -11,8 +12,8 @@ export interface CardFacts extends SourceFacts {
|
|
|
11
12
|
relations: BoardRelations;
|
|
12
13
|
/** The Factory users who created the card, moved it or started a session on it. */
|
|
13
14
|
humanActorIds: readonly string[];
|
|
14
|
-
/**
|
|
15
|
-
|
|
15
|
+
/** What a search reads of the card, lowercased, so a search lowercases only its own words. */
|
|
16
|
+
search: SearchableCard;
|
|
16
17
|
}
|
|
17
18
|
/**
|
|
18
19
|
* What the card's source says of it. A card no provider filed has no source: its facts are its
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"card-facts.d.ts","sourceRoot":"","sources":["../../src/work-items/card-facts.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAKlE,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"card-facts.d.ts","sourceRoot":"","sources":["../../src/work-items/card-facts.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAKlE,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,6DAA6D;AAC7D,MAAM,WAAW,SAAU,SAAQ,WAAW;IAC5C,cAAc,EAAE,OAAO,CAAC;IACxB,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5B,0CAA0C;IAC1C,MAAM,EAAE,MAAM,CAAC,kBAAkB,EAAE,cAAc,EAAE,CAAC,CAAC;IACrD,kGAAkG;IAClG,SAAS,EAAE,cAAc,CAAC;IAC1B,mFAAmF;IACnF,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,8FAA8F;IAC9F,MAAM,EAAE,cAAc,CAAC;CACxB;AAKD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CASpF;AAgBD,0EAA0E;AAC1E,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,CA6B/C"}
|
|
@@ -3,7 +3,7 @@ import { isHumanActorId } from "../storage/domains/audit/actors.js";
|
|
|
3
3
|
import { workItemBranchSource } from "../work-item-branch.js";
|
|
4
4
|
import { metadataLabels } from "./card-labels.js";
|
|
5
5
|
import { factoryParticipantId, providerPeople } from "./card-people.js";
|
|
6
|
-
import {
|
|
6
|
+
import { cardSearch } from "./card-search.js";
|
|
7
7
|
// src/work-items/card-facts.ts
|
|
8
8
|
const factsByCard = /* @__PURE__ */ new WeakMap();
|
|
9
9
|
/**
|
|
@@ -65,7 +65,7 @@ function cardFacts(card) {
|
|
|
65
65
|
"review-requested": new Set(people["review-requested"].map((person) => person.id))
|
|
66
66
|
},
|
|
67
67
|
humanActorIds: actorIds,
|
|
68
|
-
|
|
68
|
+
search: cardSearch(card)
|
|
69
69
|
};
|
|
70
70
|
factsByCard.set(card, facts);
|
|
71
71
|
return facts;
|