@mastra/factory 0.28.0-alpha.5 → 0.28.0-alpha.6
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 +52 -28
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +5 -5
- package/dist/auth.js.map +1 -1
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +6 -7
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/index.d.ts +1 -1
- package/dist/boards/index.d.ts.map +1 -1
- package/dist/boards/index.js +2 -2
- package/dist/boards/project-boards.d.ts +30 -4
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +71 -19
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/boards/registry.d.ts +7 -1
- package/dist/boards/registry.d.ts.map +1 -1
- package/dist/boards/registry.js +16 -3
- package/dist/boards/registry.js.map +1 -1
- package/dist/boards/semantics.d.ts +5 -4
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +5 -4
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/work-migrations.d.ts +4 -3
- package/dist/boards/work-migrations.d.ts.map +1 -1
- package/dist/boards/work-migrations.js +6 -5
- package/dist/boards/work-migrations.js.map +1 -1
- package/dist/boards/work-seeds.d.ts +9 -0
- package/dist/boards/work-seeds.d.ts.map +1 -0
- package/dist/boards/work-seeds.js +56 -0
- package/dist/boards/work-seeds.js.map +1 -0
- package/dist/boards/work.d.ts +2 -2
- package/dist/boards/work.d.ts.map +1 -1
- package/dist/boards/work.js +0 -16
- package/dist/boards/work.js.map +1 -1
- package/dist/factory.d.ts +8 -4
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +30 -58
- package/dist/factory.js.map +1 -1
- package/dist/feed-events.d.ts +2 -3
- package/dist/feed-events.d.ts.map +1 -1
- package/dist/feed-events.js +4 -5
- package/dist/feed-events.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/integrations/base.d.ts +0 -11
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.js +1 -1
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/slack/integration.d.ts +0 -2
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +0 -5
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/slack.d.ts +3 -18
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +3 -74
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/links.d.ts +1 -2
- package/dist/links.d.ts.map +1 -1
- package/dist/links.js +1 -2
- package/dist/links.js.map +1 -1
- package/dist/routes/attention-providers.d.ts +0 -25
- package/dist/routes/attention-providers.d.ts.map +1 -1
- package/dist/routes/attention-providers.js +2 -150
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/attention.d.ts +0 -2
- package/dist/routes/attention.d.ts.map +1 -1
- package/dist/routes/attention.js +2 -13
- package/dist/routes/attention.js.map +1 -1
- package/dist/routes/contracts.d.ts +6 -14
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +4 -2
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/feed-events.d.ts +15 -0
- package/dist/routes/feed-events.d.ts.map +1 -0
- package/dist/routes/feed-events.js +68 -0
- package/dist/routes/feed-events.js.map +1 -0
- package/dist/routes/knowledge.js +1 -1
- package/dist/routes/projects.d.ts +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +1 -1
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/surface.d.ts +0 -7
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +1 -5
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts +0 -3
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +0 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +0 -3
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +5 -7
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +0 -4
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +15 -1
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +21 -5
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/channel-identity/base.d.ts +0 -4
- package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
- package/dist/storage/domains/channel-identity/base.js +0 -7
- package/dist/storage/domains/channel-identity/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +6 -8
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +9 -84
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +3 -3
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +10 -10
- package/dist/storage/domains/work-items/cards.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -2
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.js +8 -8
- package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
- package/dist/tools/read-tools.d.ts +0 -2
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +3 -14
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts +0 -3
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +8 -18
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +3 -2
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/description-context.d.ts +5 -0
- package/dist/work-items/description-context.d.ts.map +1 -0
- package/dist/work-items/description-context.js +17 -0
- package/dist/work-items/description-context.js.map +1 -0
- package/dist/work-items/split-migration.d.ts.map +1 -1
- package/dist/work-items/split-migration.js +1 -6
- package/dist/work-items/split-migration.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +3 -3
- package/factory-skills/factory-rereview/SKILL.md +2 -2
- package/factory-skills/factory-review/SKILL.md +2 -2
- package/factory-skills/factory-triage/SKILL.md +3 -2
- package/package.json +6 -6
- package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
- package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
- package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
- package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
- package/dist/integrations/slack/emoji.d.ts +0 -3
- package/dist/integrations/slack/emoji.d.ts.map +0 -1
- package/dist/integrations/slack/emoji.js +0 -11
- package/dist/integrations/slack/emoji.js.map +0 -1
- package/dist/integrations/slack/feed-publisher.d.ts +0 -26
- package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
- package/dist/integrations/slack/feed-publisher.js +0 -43
- package/dist/integrations/slack/feed-publisher.js.map +0 -1
- package/dist/routes/attention-activity.d.ts +0 -23
- package/dist/routes/attention-activity.d.ts.map +0 -1
- package/dist/routes/attention-activity.js +0 -154
- package/dist/routes/attention-activity.js.map +0 -1
- package/dist/storage/domains/comments/activity.d.ts +0 -40
- package/dist/storage/domains/comments/activity.d.ts.map +0 -1
- package/dist/storage/domains/comments/activity.js +0 -93
- package/dist/storage/domains/comments/activity.js.map +0 -1
- package/dist/storage/domains/comments/actor.d.ts +0 -51
- package/dist/storage/domains/comments/actor.d.ts.map +0 -1
- package/dist/storage/domains/comments/actor.js +0 -37
- package/dist/storage/domains/comments/actor.js.map +0 -1
- package/dist/storage/domains/comments/base.d.ts +0 -245
- package/dist/storage/domains/comments/base.d.ts.map +0 -1
- package/dist/storage/domains/comments/base.js +0 -539
- package/dist/storage/domains/comments/base.js.map +0 -1
- package/dist/storage/domains/comments/domain.d.ts +0 -135
- package/dist/storage/domains/comments/domain.d.ts.map +0 -1
- package/dist/storage/domains/comments/domain.js +0 -284
- package/dist/storage/domains/comments/domain.js.map +0 -1
- package/dist/storage/domains/comments/feed-context.d.ts +0 -22
- package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
- package/dist/storage/domains/comments/feed-context.js +0 -88
- package/dist/storage/domains/comments/feed-context.js.map +0 -1
- package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
- package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
- package/dist/storage/domains/comments/feed-sync.js +0 -1
- package/dist/storage/domains/comments/parse.d.ts +0 -23
- package/dist/storage/domains/comments/parse.d.ts.map +0 -1
- package/dist/storage/domains/comments/parse.js +0 -89
- package/dist/storage/domains/comments/parse.js.map +0 -1
- package/dist/storage/domains/comments/routes.d.ts +0 -24
- package/dist/storage/domains/comments/routes.d.ts.map +0 -1
- package/dist/storage/domains/comments/routes.js +0 -301
- package/dist/storage/domains/comments/routes.js.map +0 -1
- package/dist/storage/domains/comments/schema.d.ts +0 -5
- package/dist/storage/domains/comments/schema.d.ts.map +0 -1
- package/dist/storage/domains/comments/schema.js +0 -178
- package/dist/storage/domains/comments/schema.js.map +0 -1
- package/dist/storage/domains/comments/wire.d.ts +0 -40
- package/dist/storage/domains/comments/wire.d.ts.map +0 -1
- package/dist/storage/domains/comments/wire.js +0 -36
- package/dist/storage/domains/comments/wire.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"board-writes.js","names":[],"sources":["../../src/boards/board-writes.ts"],"sourcesContent":["/**\n * Writes to a project's stored boards, shared by the boards API and `MastraFactory#upsertBoard()`.\n *\n * Every write is checked against the rules `defineBoard()` enforces, the skills its runners name,\n * the code behaviour of a code board's copy, and the cards sitting on the board. It then\n * invalidates the project's board cache and records an audit event.\n */\n\nimport type { z } from 'zod';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredPhaseInput,\n} from '../storage/domains/boards/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport { codeBoardOf } from './define-board.js';\nimport type { ProjectBoardCache } from './project-boards.js';\nimport { createBoardRegistry } from './registry.js';\nimport { boardForWorkItem } from './semantics.js';\nimport {\n codeBehaviourConflicts,\n compileStoredBoard,\n sameBoardDefinition,\n storedBoardInputSchema,\n} from './stored-board.js';\nimport { workBoard } from './work.js';\n\nexport interface BoardWritesDeps {\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;\n /** Read to refuse edits that would strand cards. */\n workItems: Pick<WorkItemsStorage, 'list'>;\n}\n\n/** Who writes: stored as the board's author, and the audit event's actor. */\nexport interface BoardWriter {\n id: string;\n audit(input: EmitAuditInput): Promise<void>;\n}\n\n/** A refused board write. `status` and `body` are what the boards API answers with. */\nexport class BoardWriteError extends Error {\n override name = 'BoardWriteError';\n constructor(\n readonly status: 404 | 409 | 422,\n readonly body: { error: string; message?: string } & Record<string, unknown>,\n ) {\n super(body.message ?? body.error);\n }\n\n get code(): string {\n return this.body.error;\n }\n}\n\nexport function issueMessage(issues: readonly z.core.$ZodIssue[]): string {\n return issues\n .map(issue => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n .join('; ');\n}\n\nconst UNKNOWN_SKILL = 'but no such skill exists';\nconst UPSERT_ATTEMPTS = 3;\n\n/** Storage refusals (a stale revision, a missing or existing board) as board write errors. */\nasync function stored<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (error instanceof StoredBoardError) {\n throw new BoardWriteError(error.code === 'board_not_found' ? 404 : 409, {\n error: error.code,\n message: error.message,\n });\n }\n throw error;\n }\n}\n\n/**\n * The retired Review board's key is never written: a project still using it is served it from\n * code, and a board under its key elsewhere would take over the cards stored there.\n */\nfunction refuseReservedBoard(key: string): void {\n if (key !== LEGACY_REVIEW_BOARD) return;\n throw new BoardWriteError(409, {\n error: 'reserved_board',\n message: `Board \"${key}\" is reserved for the retired Review board.`,\n });\n}\n\nexport class BoardWrites {\n constructor(private readonly deps: BoardWritesDeps) {}\n\n /**\n * Code boards can't be created over, and Work can't be deleted while its code handlers run by its\n * key; the retired Review board's key can't be used at all.\n */\n refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void {\n refuseReservedBoard(key);\n const { boards } = this.deps;\n const code = boards.codeRegistry.get(key);\n if (!code) return;\n const stored = boards.seedFor(key) !== undefined;\n if (action === 'edit' && stored) return;\n if (action === 'delete' && stored && codeBoardOf(code) !== workBoard) return;\n throw new BoardWriteError(409, {\n error: 'code_board',\n message:\n action === 'delete' && stored\n ? `Board \"${key}\" is defined in code and can't be deleted; reset it to its default instead.`\n : `Board \"${key}\" is defined in code and can't be ${action === 'create' ? 'created over' : 'changed'} here.`,\n });\n }\n\n async existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord> {\n const row = await this.deps.storage.get(scope, key);\n if (!row) throw new BoardWriteError(404, { error: 'board_not_found', message: `Board \"${key}\" does not exist.` });\n return row;\n }\n\n /**\n * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code\n * board's copy is also checked against the code behaviour of its board and phase keys.\n */\n validate(input: unknown): StoredBoardInput {\n const { boards } = this.deps;\n const parsed = storedBoardInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new BoardWriteError(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n refuseReservedBoard(parsed.data.key);\n const code = boards.seedFor(parsed.data.key) && boards.codeRegistry.get(parsed.data.key);\n if (code) {\n const conflicts = codeBehaviourConflicts(parsed.data, code);\n if (conflicts.length > 0) {\n throw new BoardWriteError(422, { error: 'code_behaviour', message: conflicts.join(' '), conflicts });\n }\n }\n const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data);\n const problems = findBoardSkillProblems(\n createBoardRegistry({ boards: [board], includeDefaultBoards: false }),\n boards.codeSkills,\n );\n const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL));\n if (unknown.length > 0) throw new BoardWriteError(422, { error: 'unknown_skill', message: unknown.join(' ') });\n return parsed.data;\n }\n\n /** Creates a board under a key no code board uses. */\n async create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise<StoredBoardRecord> {\n const key = (input as { key?: unknown } | null)?.key;\n if (typeof key === 'string') this.refuseCodeBoard(key, 'create');\n const board = this.validate(input);\n const row = await stored(() => this.deps.storage.create(scope, board, writer.id));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return row;\n }\n\n /**\n * Stores a validated board in a project, after its first load stored Factory's boards: creates\n * it when the project has none under its key, and otherwise replaces the project's board, edited\n * or not, at its current revision, with the same checks as an edit. A write that loses a race\n * with another one rereads and tries again.\n */\n async upsert(\n scope: StoredBoardScope,\n board: StoredBoardInput,\n writer: BoardWriter,\n ): Promise<'inserted' | 'updated' | 'unchanged'> {\n refuseReservedBoard(board.key);\n const { storage, boards } = this.deps;\n await boards.describe(scope);\n for (let attempt = 1; ; attempt++) {\n const row = await storage.get(scope, board.key);\n try {\n if (!row) {\n if (!(await storage.insertIfMissing(scope, board, writer.id))) {\n throw new BoardWriteError(409, {\n error: 'revision_mismatch',\n message: `Board \"${board.key}\" was stored by another write; try again.`,\n });\n }\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return 'inserted';\n }\n const { key, ...definition } = board;\n const { written } = await this.replace(scope, key, definition, { expectedRevision: row.revision, writer });\n return written ? 'updated' : 'unchanged';\n } catch (error) {\n const lost =\n error instanceof BoardWriteError && (error.code === 'revision_mismatch' || error.code === 'board_not_found');\n if (!lost || attempt >= UPSERT_ATTEMPTS) throw error;\n }\n }\n }\n\n /**\n * Replaces a board's definition at `expectedRevision`. Saving it unchanged writes nothing;\n * `written` says whether anything was stored.\n */\n async replace(\n scope: StoredBoardScope,\n key: string,\n definition: Omit<StoredBoardInput, 'key'>,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<{ row: StoredBoardRecord; written: boolean }> {\n const { storage, boards } = this.deps;\n this.refuseCodeBoard(key, 'edit');\n const seed = boards.seedFor(key);\n // The project's first load stores Factory's boards.\n if (seed) await boards.describe(scope);\n const row = await this.existing(scope, key);\n const input = this.validate({ key, ...definition });\n if (row.revision === expectedRevision && sameBoardDefinition(row, input)) {\n return { row, written: false };\n }\n await this.#checkPhasesFree(scope, row, input.phases);\n const { key: _key, ...replacement } = input;\n const replaced = await stored(() =>\n storage.replace(scope, key, replacement, { expectedRevision, actor: writer.id }),\n );\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'updated', input);\n return { row: replaced, written: true };\n }\n\n /** Deletes a stored board that no card sits on. */\n async remove(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<void> {\n this.refuseCodeBoard(key, 'delete');\n // The project's first load stores Factory's boards.\n if (this.deps.boards.seedFor(key)) await this.deps.boards.describe(scope);\n const row = await this.existing(scope, key);\n const { cards } = await this.#occupancy(scope, key);\n if (cards > 0) {\n throw new BoardWriteError(409, {\n error: 'board_in_use',\n message: `Board \"${key}\" still has cards; move or delete them first.`,\n cards,\n });\n }\n await stored(() => this.deps.storage.delete(scope, key, { expectedRevision }));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'deleted', row);\n }\n\n /** Rewrites a board Factory stores to Factory's current definition of it, at the next revision. */\n async reset(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<StoredBoardRecord> {\n const { storage, boards } = this.deps;\n const seed = boards.seedFor(key);\n if (!seed) {\n this.refuseCodeBoard(key, 'edit');\n await this.existing(scope, key);\n throw new BoardWriteError(409, {\n error: 'not_code_board',\n message: `Board \"${key}\" was created in this project and has no default to reset to.`,\n });\n }\n await boards.describe(scope);\n const row = await this.existing(scope, key);\n await this.#checkPhasesFree(scope, row, seed.phases);\n const reset = await stored(() => storage.resetTo(scope, key, seed, { expectedRevision, actor: writer.id }));\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'reset', row);\n return reset;\n }\n\n /** The cards on a board, and how many sit in each phase. */\n async #occupancy(scope: StoredBoardScope, key: string): Promise<{ cards: number; phases: Map<string, number> }> {\n const phases = new Map<string, number>();\n let cards = 0;\n for (const item of await this.deps.workItems.list(scope)) {\n if (boardForWorkItem(item) !== key) continue;\n cards++;\n for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);\n }\n return { cards, phases };\n }\n\n /** Refuses a change that removes, or changes the kind of, a phase cards sit in. */\n async #checkPhasesFree(\n scope: StoredBoardScope,\n row: StoredBoardRecord,\n next: readonly StoredPhaseInput[],\n ): Promise<void> {\n const kinds = new Map(next.map(phase => [phase.key, phase.kind]));\n const changed = row.phases.filter(phase => kinds.get(phase.key) !== phase.kind).map(phase => phase.key);\n if (changed.length === 0) return;\n const occupancy = (await this.#occupancy(scope, row.key)).phases;\n const inUse = Object.fromEntries(changed.flatMap(key => (occupancy.get(key) ? [[key, occupancy.get(key)!]] : [])));\n if (Object.keys(inUse).length === 0) return;\n throw new BoardWriteError(409, {\n error: 'phase_in_use',\n message: `Cards sit in ${Object.entries(inUse)\n .map(([key, count]) => `\"${key}\" (${count})`)\n .join(', ')}; move them before removing those phases or changing their kind.`,\n phases: inUse,\n });\n }\n\n async #audit(\n scope: StoredBoardScope,\n writer: BoardWriter,\n action: 'created' | 'updated' | 'deleted' | 'reset',\n board: { key: string; name: string },\n ): Promise<void> {\n await writer.audit({\n action: `factory.board.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'board', id: board.key, name: board.name }],\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAiDA,IAAa,kBAAb,cAAqC,MAAM;CAG9B;CACA;CAHX,OAAgB;CAChB,YACE,QACA,MACA;EACA,MAAM,KAAK,WAAW,KAAK,KAAK;EAHvB,KAAA,SAAA;EACA,KAAA,OAAA;CAGX;CAEA,IAAI,OAAe;EACjB,OAAO,KAAK,KAAK;CACnB;AACF;AAEA,SAAgB,aAAa,QAA6C;CACxE,OAAO,OACJ,KAAI,UAAU,MAAM,KAAK,SAAS,IAAI,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,IAAI,MAAM,YAAY,MAAM,OAAQ,CAAC,CACnG,KAAK,IAAI;AACd;AAEA,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;AAGxB,eAAe,OAAU,OAAqC;CAC5D,IAAI;EACF,OAAO,MAAM,MAAM;CACrB,SAAS,OAAO;EACd,IAAI,iBAAiB,kBACnB,MAAM,IAAI,gBAAgB,MAAM,SAAS,oBAAoB,MAAM,KAAK;GACtE,OAAO,MAAM;GACb,SAAS,MAAM;EACjB,CAAC;EAEH,MAAM;CACR;AACF;;;;;AAMA,SAAS,oBAAoB,KAAmB;CAC9C,IAAI,QAAA,UAA6B;CACjC,MAAM,IAAI,gBAAgB,KAAK;EAC7B,OAAO;EACP,SAAS,UAAU,IAAI;CACzB,CAAC;AACH;AAEA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,MAAwC;EAAvB,KAAA,OAAA;CAAwB;;;;;CAMrD,gBAAgB,KAAa,QAA4C;EACvE,oBAAoB,GAAG;EAC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,IAAI,IAAI,KAAK,KAAI,UAAS,CAAC,MAAM,KAAK,MAAM,IAAI,CAAC,CAAC;EAChE,MAAM,UAAU,IAAI,OAAO,QAAO,UAAS,MAAM,IAAI,MAAM,GAAG,MAAM,MAAM,IAAI,CAAC,CAAC,KAAI,UAAS,MAAM,GAAG;EACtG,IAAI,QAAQ,WAAW,GAAG;EAC1B,MAAM,aAAa,MAAM,KAAK,WAAW,OAAO,IAAI,GAAG,EAAA,CAAG;EAC1D,MAAM,QAAQ,OAAO,YAAY,QAAQ,SAAQ,QAAQ,UAAU,IAAI,GAAG,IAAI,CAAC,CAAC,KAAK,UAAU,IAAI,GAAG,CAAE,CAAC,IAAI,CAAC,CAAE,CAAC;EACjH,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG;EACrC,MAAM,IAAI,gBAAgB,KAAK;GAC7B,OAAO;GACP,SAAS,gBAAgB,OAAO,QAAQ,KAAK,CAAC,CAC3C,KAAK,CAAC,KAAK,WAAW,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC,CAC5C,KAAK,IAAI,EAAE;GACd,QAAQ;EACV,CAAC;CACH;CAEA,MAAM,OACJ,OACA,QACA,QACA,OACe;EACf,MAAM,OAAO,MAAM;GACjB,QAAQ,iBAAiB;GACzB,kBAAkB,MAAM;GACxB,SAAS,CAAC;IAAE,MAAM;IAAS,IAAI,MAAM;IAAK,MAAM,MAAM;GAAK,CAAC;EAC9D,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"board-writes.js","names":[],"sources":["../../src/boards/board-writes.ts"],"sourcesContent":["/**\n * Writes to a project's stored boards, shared by the boards API and `MastraFactory#upsertBoard()`.\n *\n * Every write is checked against the rules `defineBoard()` enforces, the skills its runners name,\n * the code behaviour of a code board's copy, and the cards sitting on the board. It then\n * invalidates the project's board cache and records an audit event.\n */\n\nimport type { z } from 'zod';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredPhaseInput,\n} from '../storage/domains/boards/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport { codeBoardOf } from './define-board.js';\nimport type { ProjectBoardCache } from './project-boards.js';\nimport { boardRegistryOf } from './registry.js';\nimport { boardForWorkItem } from './semantics.js';\nimport {\n codeBehaviourConflicts,\n compileStoredBoard,\n sameBoardDefinition,\n storedBoardInputSchema,\n} from './stored-board.js';\nimport { workBoard } from './work.js';\n\nexport interface BoardWritesDeps {\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;\n /** Read to refuse edits that would strand cards. */\n workItems: Pick<WorkItemsStorage, 'list'>;\n}\n\n/** Who writes: stored as the board's author, and the audit event's actor. */\nexport interface BoardWriter {\n id: string;\n audit(input: EmitAuditInput): Promise<void>;\n}\n\n/** A refused board write. `status` and `body` are what the boards API answers with. */\nexport class BoardWriteError extends Error {\n override name = 'BoardWriteError';\n constructor(\n readonly status: 404 | 409 | 422,\n readonly body: { error: string; message?: string } & Record<string, unknown>,\n ) {\n super(body.message ?? body.error);\n }\n\n get code(): string {\n return this.body.error;\n }\n}\n\nexport function issueMessage(issues: readonly z.core.$ZodIssue[]): string {\n return issues\n .map(issue => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n .join('; ');\n}\n\nconst UNKNOWN_SKILL = 'but no such skill exists';\nconst UPSERT_ATTEMPTS = 3;\n\n/** Storage refusals (a stale revision, a missing or existing board) as board write errors. */\nasync function stored<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (error instanceof StoredBoardError) {\n throw new BoardWriteError(error.code === 'board_not_found' ? 404 : 409, {\n error: error.code,\n message: error.message,\n });\n }\n throw error;\n }\n}\n\n/**\n * The retired Review board's key is never written: a project still using it is served it from\n * code, and a board under its key elsewhere would take over the cards stored there.\n */\nfunction refuseReservedBoard(key: string): void {\n if (key !== LEGACY_REVIEW_BOARD) return;\n throw new BoardWriteError(409, {\n error: 'reserved_board',\n message: `Board \"${key}\" is reserved for the retired Review board.`,\n });\n}\n\nexport class BoardWrites {\n constructor(private readonly deps: BoardWritesDeps) {}\n\n /**\n * Code boards can't be created over, and Work can't be deleted while its code handlers run by its\n * key; the retired Review board's key can't be used at all.\n */\n refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void {\n refuseReservedBoard(key);\n const { boards } = this.deps;\n const code = boards.codeRegistry.get(key);\n if (!code) return;\n const stored = boards.seedFor(key) !== undefined;\n if (action === 'edit' && stored) return;\n if (action === 'delete' && stored && codeBoardOf(code) !== workBoard) return;\n throw new BoardWriteError(409, {\n error: 'code_board',\n message:\n action === 'delete' && stored\n ? `Board \"${key}\" is defined in code and can't be deleted; reset it to its default instead.`\n : `Board \"${key}\" is defined in code and can't be ${action === 'create' ? 'created over' : 'changed'} here.`,\n });\n }\n\n async existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord> {\n const row = await this.deps.storage.get(scope, key);\n if (!row) throw new BoardWriteError(404, { error: 'board_not_found', message: `Board \"${key}\" does not exist.` });\n return row;\n }\n\n /**\n * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code\n * board's copy is also checked against the code behaviour of its board and phase keys.\n */\n validate(input: unknown): StoredBoardInput {\n const { boards } = this.deps;\n const parsed = storedBoardInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new BoardWriteError(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n refuseReservedBoard(parsed.data.key);\n const code = boards.seedFor(parsed.data.key) && boards.codeRegistry.get(parsed.data.key);\n if (code) {\n const conflicts = codeBehaviourConflicts(parsed.data, code);\n if (conflicts.length > 0) {\n throw new BoardWriteError(422, { error: 'code_behaviour', message: conflicts.join(' '), conflicts });\n }\n }\n const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data);\n const problems = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills);\n const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL));\n if (unknown.length > 0) throw new BoardWriteError(422, { error: 'unknown_skill', message: unknown.join(' ') });\n return parsed.data;\n }\n\n /** Creates a board under a key no code board uses. */\n async create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise<StoredBoardRecord> {\n const key = (input as { key?: unknown } | null)?.key;\n if (typeof key === 'string') this.refuseCodeBoard(key, 'create');\n const board = this.validate(input);\n // Factory stores its boards only into a project that has none, so they go in first.\n await this.deps.boards.describe(scope);\n const row = await stored(() => this.deps.storage.create(scope, board, writer.id));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return row;\n }\n\n /**\n * Stores a validated board in a project, after its first load stored Factory's boards: creates\n * it when the project has none under its key, and otherwise replaces the project's board, edited\n * or not, at its current revision, with the same checks as an edit. A write that loses a race\n * with another one rereads and tries again.\n */\n async upsert(\n scope: StoredBoardScope,\n board: StoredBoardInput,\n writer: BoardWriter,\n ): Promise<'inserted' | 'updated' | 'unchanged'> {\n refuseReservedBoard(board.key);\n const { storage, boards } = this.deps;\n await boards.describe(scope);\n for (let attempt = 1; ; attempt++) {\n const row = await storage.get(scope, board.key);\n try {\n if (!row) {\n if (!(await storage.insertIfMissing(scope, board, writer.id))) {\n throw new BoardWriteError(409, {\n error: 'revision_mismatch',\n message: `Board \"${board.key}\" was stored by another write; try again.`,\n });\n }\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return 'inserted';\n }\n const { key, ...definition } = board;\n const { written } = await this.replace(scope, key, definition, { expectedRevision: row.revision, writer });\n return written ? 'updated' : 'unchanged';\n } catch (error) {\n const lost =\n error instanceof BoardWriteError && (error.code === 'revision_mismatch' || error.code === 'board_not_found');\n if (!lost || attempt >= UPSERT_ATTEMPTS) throw error;\n }\n }\n }\n\n /**\n * Replaces a board's definition at `expectedRevision`. Saving it unchanged writes nothing;\n * `written` says whether anything was stored.\n */\n async replace(\n scope: StoredBoardScope,\n key: string,\n definition: Omit<StoredBoardInput, 'key'>,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<{ row: StoredBoardRecord; written: boolean }> {\n const { storage, boards } = this.deps;\n this.refuseCodeBoard(key, 'edit');\n const seed = boards.seedFor(key);\n // The project's first load stores Factory's boards.\n if (seed) await boards.describe(scope);\n const row = await this.existing(scope, key);\n const input = this.validate({ key, ...definition });\n if (row.revision === expectedRevision && sameBoardDefinition(row, input)) {\n return { row, written: false };\n }\n await this.#checkPhasesFree(scope, row, input.phases);\n const { key: _key, ...replacement } = input;\n const replaced = await stored(() =>\n storage.replace(scope, key, replacement, { expectedRevision, actor: writer.id }),\n );\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'updated', input);\n return { row: replaced, written: true };\n }\n\n /** Deletes a stored board that no card sits on. */\n async remove(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<void> {\n this.refuseCodeBoard(key, 'delete');\n // The project's first load stores Factory's boards.\n if (this.deps.boards.seedFor(key)) await this.deps.boards.describe(scope);\n const row = await this.existing(scope, key);\n const { cards } = await this.#occupancy(scope, key);\n if (cards > 0) {\n throw new BoardWriteError(409, {\n error: 'board_in_use',\n message: `Board \"${key}\" still has cards; move or delete them first.`,\n cards,\n });\n }\n await stored(() => this.deps.storage.delete(scope, key, { expectedRevision }));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'deleted', row);\n }\n\n /** Rewrites a board Factory stores to Factory's current definition of it, at the next revision. */\n async reset(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<StoredBoardRecord> {\n const { storage, boards } = this.deps;\n const seed = boards.seedFor(key);\n if (!seed) {\n this.refuseCodeBoard(key, 'edit');\n await this.existing(scope, key);\n throw new BoardWriteError(409, {\n error: 'not_code_board',\n message: `Board \"${key}\" was created in this project and has no default to reset to.`,\n });\n }\n await boards.describe(scope);\n const row = await this.existing(scope, key);\n // A board the app upserts for every project resets to the app's. Factory's Work resets to the\n // Work the project was stored with: today's for a project Factory created with it, Work with\n // Triage for every other.\n const definition = boards.seedFor(key, row) ?? seed;\n await this.#checkPhasesFree(scope, row, definition.phases);\n const reset = await stored(() => storage.resetTo(scope, key, definition, { expectedRevision, actor: writer.id }));\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'reset', row);\n return reset;\n }\n\n /** The cards on a board, and how many sit in each phase. */\n async #occupancy(scope: StoredBoardScope, key: string): Promise<{ cards: number; phases: Map<string, number> }> {\n const phases = new Map<string, number>();\n let cards = 0;\n for (const item of await this.deps.workItems.list(scope)) {\n if (boardForWorkItem(item) !== key) continue;\n cards++;\n for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);\n }\n return { cards, phases };\n }\n\n /** Refuses a change that removes, or changes the kind of, a phase cards sit in. */\n async #checkPhasesFree(\n scope: StoredBoardScope,\n row: StoredBoardRecord,\n next: readonly StoredPhaseInput[],\n ): Promise<void> {\n const kinds = new Map(next.map(phase => [phase.key, phase.kind]));\n const changed = row.phases.filter(phase => kinds.get(phase.key) !== phase.kind).map(phase => phase.key);\n if (changed.length === 0) return;\n const occupancy = (await this.#occupancy(scope, row.key)).phases;\n const inUse = Object.fromEntries(changed.flatMap(key => (occupancy.get(key) ? [[key, occupancy.get(key)!]] : [])));\n if (Object.keys(inUse).length === 0) return;\n throw new BoardWriteError(409, {\n error: 'phase_in_use',\n message: `Cards sit in ${Object.entries(inUse)\n .map(([key, count]) => `\"${key}\" (${count})`)\n .join(', ')}; move them before removing those phases or changing their kind.`,\n phases: inUse,\n });\n }\n\n async #audit(\n scope: StoredBoardScope,\n writer: BoardWriter,\n action: 'created' | 'updated' | 'deleted' | 'reset',\n board: { key: string; name: string },\n ): Promise<void> {\n await writer.audit({\n action: `factory.board.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'board', id: board.key, name: board.name }],\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAiDA,IAAa,kBAAb,cAAqC,MAAM;CAG9B;CACA;CAHX,OAAgB;CAChB,YACE,QACA,MACA;EACA,MAAM,KAAK,WAAW,KAAK,KAAK;EAHvB,KAAA,SAAA;EACA,KAAA,OAAA;CAGX;CAEA,IAAI,OAAe;EACjB,OAAO,KAAK,KAAK;CACnB;AACF;AAEA,SAAgB,aAAa,QAA6C;CACxE,OAAO,OACJ,KAAI,UAAU,MAAM,KAAK,SAAS,IAAI,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,IAAI,MAAM,YAAY,MAAM,OAAQ,CAAC,CACnG,KAAK,IAAI;AACd;AAEA,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;AAGxB,eAAe,OAAU,OAAqC;CAC5D,IAAI;EACF,OAAO,MAAM,MAAM;CACrB,SAAS,OAAO;EACd,IAAI,iBAAiB,kBACnB,MAAM,IAAI,gBAAgB,MAAM,SAAS,oBAAoB,MAAM,KAAK;GACtE,OAAO,MAAM;GACb,SAAS,MAAM;EACjB,CAAC;EAEH,MAAM;CACR;AACF;;;;;AAMA,SAAS,oBAAoB,KAAmB;CAC9C,IAAI,QAAA,UAA6B;CACjC,MAAM,IAAI,gBAAgB,KAAK;EAC7B,OAAO;EACP,SAAS,UAAU,IAAI;CACzB,CAAC;AACH;AAEA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,MAAwC;EAAvB,KAAA,OAAA;CAAwB;;;;;CAMrD,gBAAgB,KAAa,QAA4C;EACvE,oBAAoB,GAAG;EACvB,MAAM,EAAE,WAAW,KAAK;EACxB,MAAM,OAAO,OAAO,aAAa,IAAI,GAAG;EACxC,IA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K,KAAI,UAAS,CAAC,MAAM,KAAK,MAAM,IAAI,CAAC,CAAC;EAChE,MAAM,UAAU,IAAI,OAAO,QAAO,UAAS,MAAM,IAAI,MAAM,GAAG,MAAM,MAAM,IAAI,CAAC,CAAC,KAAI,UAAS,MAAM,GAAG;EACtG,IAAI,QAAQ,WAAW,GAAG;EAC1B,MAAM,aAAa,MAAM,KAAK,WAAW,OAAO,IAAI,GAAG,EAAA,CAAG;EAC1D,MAAM,QAAQ,OAAO,YAAY,QAAQ,SAAQ,QAAQ,UAAU,IAAI,GAAG,IAAI,CAAC,CAAC,KAAK,UAAU,IAAI,GAAG,CAAE,CAAC,IAAI,CAAC,CAAE,CAAC;EACjH,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG;EACrC,MAAM,IAAI,gBAAgB,KAAK;GAC7B,OAAO;GACP,SAAS,gBAAgB,OAAO,QAAQ,KAAK,CAAC,CAC3C,KAAK,CAAC,KAAK,WAAW,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC,CAC5C,KAAK,IAAI,EAAE;GACd,QAAQ;EACV,CAAC;CACH;CAEA,MAAM,OACJ,OACA,QACA,QACA,OACe;EACf,MAAM,OAAO,MAAM;GACjB,QAAQ,iBAAiB;GACzB,kBAAkB,MAAM;GACxB,SAAS,CAAC;IAAE,MAAM;IAAS,IAAI,MAAM;IAAK,MAAM,MAAM;GAAK,CAAC;EAC9D,CAAC;CACH;AACF"}
|
package/dist/boards/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export type { BoardDefinition, BoardEventIntegration, BoardEventRules, BoardPhas
|
|
|
5
5
|
export { boardEventHandlers, awaitsAcceptance, boardFlow, boardPhaseOutcomes, boardForWorkItem, cardBoardFlow, boundChangeRequestNumber, eventBoardId, cardOwnsBranch, hasPullRequest, isPullRequestCard, isPullRequestReviewPhase, isTerminalWorkItem, newestOpenPullRequestNumber, newestOwnedOpenPullRequestNumber, pullRequestSourceNumber, pullRequestSources, resolveBoardClosure, reviewedChangeRequest, reviewedPullRequest, sourceExternalId, reviewsPullRequest, resolveBoardToolRule, rulePhaseContext, rulePhaseField, resolvePhaseSemantics, withBoardClosure, withBoardFlow, intakeTarget, withIntakeTarget, workItemPhaseSemantics, } from './semantics.js';
|
|
6
6
|
export type { PhaseSemantics, ReviewedChangeRequest } from './semantics.js';
|
|
7
7
|
export type { BoardTransitionPolicy, BoardTransitionPolicyContext, BoardTransitionPolicyResult, } from './transition-policy.js';
|
|
8
|
-
export { createBoardRegistry, defaultBoards } from './registry.js';
|
|
8
|
+
export { boardRegistryOf, createBoardRegistry, defaultBoards } from './registry.js';
|
|
9
9
|
export type { BoardRegistry, InstalledBoard } from './registry.js';
|
|
10
10
|
export { workBoard } from './work.js';
|
|
11
11
|
export type { WorkBoardPhase } from './work.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/boards/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,WAAW,EACX,gBAAgB,EAChB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EACV,eAAe,EACf,qBAAqB,EACrB,eAAe,EACf,UAAU,EACV,oBAAoB,EACpB,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,0BAA0B,EAC1B,aAAa,EACb,cAAc,EACd,eAAe,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,SAAS,EACT,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,EACb,wBAAwB,EACxB,YAAY,EACZ,cAAc,EACd,cAAc,EACd,iBAAiB,EACjB,wBAAwB,EACxB,kBAAkB,EAClB,2BAA2B,EAC3B,gCAAgC,EAChC,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,EACd,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC5E,YAAY,EACV,qBAAqB,EACrB,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/boards/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,WAAW,EACX,gBAAgB,EAChB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EACV,eAAe,EACf,qBAAqB,EACrB,eAAe,EACf,UAAU,EACV,oBAAoB,EACpB,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,0BAA0B,EAC1B,aAAa,EACb,cAAc,EACd,eAAe,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,SAAS,EACT,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,EACb,wBAAwB,EACxB,YAAY,EACZ,cAAc,EACd,cAAc,EACd,iBAAiB,EACjB,wBAAwB,EACxB,kBAAkB,EAClB,2BAA2B,EAC3B,gCAAgC,EAChC,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,EACd,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC5E,YAAY,EACV,qBAAqB,EACrB,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACpF,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC"}
|
package/dist/boards/index.js
CHANGED
|
@@ -2,6 +2,6 @@ import { BoardDefinitionError, DEFAULT_PHASE_CONTEXT, FACTORY_AGENT_ID, REVIEW_C
|
|
|
2
2
|
import { DEFAULT_BOARD_ID } from "./default-board.js";
|
|
3
3
|
import { cardRuleFacts } from "./card-facts.js";
|
|
4
4
|
import { awaitsAcceptance, boardEventHandlers, boardFlow, boardForWorkItem, boardPhaseOutcomes, boundChangeRequestNumber, cardBoardFlow, cardOwnsBranch, eventBoardId, hasPullRequest, intakeTarget, isPullRequestCard, isPullRequestReviewPhase, isTerminalWorkItem, newestOpenPullRequestNumber, newestOwnedOpenPullRequestNumber, pullRequestSourceNumber, pullRequestSources, resolveBoardClosure, resolveBoardToolRule, resolvePhaseSemantics, reviewedChangeRequest, reviewedPullRequest, reviewsPullRequest, rulePhaseContext, rulePhaseField, sourceExternalId, withBoardClosure, withBoardFlow, withIntakeTarget, workItemPhaseSemantics } from "./semantics.js";
|
|
5
|
-
import { createBoardRegistry, defaultBoards } from "./registry.js";
|
|
5
|
+
import { boardRegistryOf, createBoardRegistry, defaultBoards } from "./registry.js";
|
|
6
6
|
import { workBoard } from "./work.js";
|
|
7
|
-
export { BoardDefinitionError, DEFAULT_BOARD_ID, DEFAULT_PHASE_CONTEXT, FACTORY_AGENT_ID, REVIEW_CONTEXT, awaitsAcceptance, boardEventHandlers, boardFlow, boardForWorkItem, boardPhaseOutcomes, boundChangeRequestNumber, cardBoardFlow, cardOwnsBranch, cardRuleFacts, createBoardRegistry, defaultBoards, defineBoard, eventBoardId, hasPullRequest, intakeTarget, isPullRequestCard, isPullRequestReviewPhase, isTerminalWorkItem, newestOpenPullRequestNumber, newestOwnedOpenPullRequestNumber, pullRequestSourceNumber, pullRequestSources, resolveBoardClosure, resolveBoardToolRule, resolvePhaseSemantics, reviewedChangeRequest, reviewedPullRequest, reviewsPullRequest, rulePhaseContext, rulePhaseField, sourceExternalId, withBoardClosure, withBoardFlow, withIntakeTarget, workBoard, workItemPhaseSemantics };
|
|
7
|
+
export { BoardDefinitionError, DEFAULT_BOARD_ID, DEFAULT_PHASE_CONTEXT, FACTORY_AGENT_ID, REVIEW_CONTEXT, awaitsAcceptance, boardEventHandlers, boardFlow, boardForWorkItem, boardPhaseOutcomes, boardRegistryOf, boundChangeRequestNumber, cardBoardFlow, cardOwnsBranch, cardRuleFacts, createBoardRegistry, defaultBoards, defineBoard, eventBoardId, hasPullRequest, intakeTarget, isPullRequestCard, isPullRequestReviewPhase, isTerminalWorkItem, newestOpenPullRequestNumber, newestOwnedOpenPullRequestNumber, pullRequestSourceNumber, pullRequestSources, resolveBoardClosure, resolveBoardToolRule, resolvePhaseSemantics, reviewedChangeRequest, reviewedPullRequest, reviewsPullRequest, rulePhaseContext, rulePhaseField, sourceExternalId, withBoardClosure, withBoardFlow, withIntakeTarget, workBoard, workItemPhaseSemantics };
|
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import type { InlineSkill } from '@mastra/core/skills';
|
|
2
2
|
import type { FactoryStorageOps } from '@mastra/core/storage';
|
|
3
|
-
import type { StoredBoardInput, StoredBoardScope, StoredBoardsStorage } from '../storage/domains/boards/base.js';
|
|
3
|
+
import type { StoredBoardInput, StoredBoardRecord, StoredBoardScope, StoredBoardsStorage } from '../storage/domains/boards/base.js';
|
|
4
4
|
import type { RetiredAutomationSettings } from '../storage/domains/projects/base.js';
|
|
5
5
|
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
6
6
|
import type { BoardRegistry } from './registry.js';
|
|
7
|
+
/**
|
|
8
|
+
* The creator Factory records on the Work board it stores in a project as the project is
|
|
9
|
+
* created: that board is today's Work, and reset gives it back. Any other Work row Factory stored
|
|
10
|
+
* is the one with Triage. Only Factory writes this id; a person's writes carry their user id.
|
|
11
|
+
*/
|
|
12
|
+
export declare const NEW_PROJECT_SEED_ACTOR = "factory:new-project";
|
|
7
13
|
/** Where a board in a project's catalog came from. */
|
|
8
14
|
export type BoardSourceKind = 'builtin' | 'app' | 'stored';
|
|
9
15
|
export interface StoredBoardDetails {
|
|
@@ -85,10 +91,30 @@ export declare class ProjectBoardCache implements ProjectBoardSource {
|
|
|
85
91
|
readonly [PROJECT_BOARD_SOURCE] = true;
|
|
86
92
|
readonly codeRegistry: BoardRegistry;
|
|
87
93
|
constructor(options: ProjectBoardCacheOptions);
|
|
88
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* The boards Factory stores once in a project it didn't create: Work as it was with Triage, so a
|
|
96
|
+
* project from an older release keeps the phases its cards know, then the app boards, in order.
|
|
97
|
+
*/
|
|
89
98
|
seeds(): StoredBoardInput[];
|
|
90
|
-
/**
|
|
91
|
-
|
|
99
|
+
/**
|
|
100
|
+
* The definition reset restores for `key`; undefined when there is none. A board the app upserted
|
|
101
|
+
* for every project comes first, so reset never swaps an app's Work for Factory's. Factory's Work
|
|
102
|
+
* is today's Work for a project Factory created with it (`row` created by
|
|
103
|
+
* {@link NEW_PROJECT_SEED_ACTOR}), and Work with Triage for every other project.
|
|
104
|
+
*/
|
|
105
|
+
seedFor(key: string, row?: Pick<StoredBoardRecord, 'createdBy'>): StoredBoardInput | undefined;
|
|
106
|
+
/**
|
|
107
|
+
* Stores Factory's boards in a project that was just created, with today's Work (no Triage).
|
|
108
|
+
* Only the project-creation route calls this; every other load stores {@link seeds}.
|
|
109
|
+
*/
|
|
110
|
+
seedNewProject(scope: StoredBoardScope): Promise<ProjectBoards>;
|
|
111
|
+
/**
|
|
112
|
+
* Remembers a board the app upserted for every project, so a project that has no boards yet (one
|
|
113
|
+
* created later, or one that never loaded) gets it on its first load before Factory's own boards;
|
|
114
|
+
* having it, the project then gets no Work from Factory. Kept for this process: an app upserts
|
|
115
|
+
* its boards at every startup.
|
|
116
|
+
*/
|
|
117
|
+
rememberBoardForAllProjects(board: StoredBoardInput): void;
|
|
92
118
|
load(scope: StoredBoardScope): Promise<BoardRegistry>;
|
|
93
119
|
/** The project's boards with their source, whether they can be edited, and problems, brought up to date. */
|
|
94
120
|
describe(scope: StoredBoardScope): Promise<ProjectBoards>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-boards.d.ts","sourceRoot":"","sources":["../../src/boards/project-boards.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,KAAK,EAEV,gBAAgB,
|
|
1
|
+
{"version":3,"file":"project-boards.d.ts","sourceRoot":"","sources":["../../src/boards/project-boards.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,KAAK,EAEV,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACpB,MAAM,mCAAmC,CAAC;AAE3C,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,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;IACvC,QAAQ,CAAC,YAAY,EAAE,aAAa,CAAC;IAmBrC,YAAY,OAAO,EAAE,wBAAwB,EAqB5C;IAED;;;OAGG;IACH,KAAK,IAAI,gBAAgB,EAAE,CAE1B;IAED;;;;;OAKG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,WAAW,CAAC,GAAG,gBAAgB,GAAG,SAAS,CAM7F;IAED;;;OAGG;IACG,cAAc,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,aAAa,CAAC,CASpE;IAED;;;;;OAKG;IACH,2BAA2B,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI,CAEzD;IAYK,IAAI,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,aAAa,CAAC,CAE1D;IAED,4GAA4G;IACtG,QAAQ,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,aAAa,CAAC,CAY9D;IAED;;;;OAIG;IACH,UAAU,CAAC,KAAK,EAAE,gBAAgB,GAAG,aAAa,CAcjD;IAED,+CAA+C;IAC/C,IAAI,UAAU,IAAI,SAAS,WAAW,EAAE,CAEvC;IAED,oGAAoG;IACpG,UAAU,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI,CAMxC;IAED,yGAAyG;IACnG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAe7B;CA0LF"}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { findBoardSkillProblems } from "../skills/app-skills.js";
|
|
2
2
|
import "../storage/domains/boards/base.js";
|
|
3
3
|
import { LEGACY_REVIEW_BOARD } from "../storage/domains/work-items/legacy-review.js";
|
|
4
|
-
import { createBoardRegistry, defaultBoards } from "./registry.js";
|
|
4
|
+
import { boardRegistryOf, createBoardRegistry, defaultBoards } from "./registry.js";
|
|
5
5
|
import { reviewBoard } from "./review.js";
|
|
6
6
|
import { boardForWorkItem } from "./semantics.js";
|
|
7
7
|
import { boardDefinitionOf, compileStoredBoard, mergeCodeBehaviour } from "./stored-board.js";
|
|
8
8
|
import { BOARD_MIGRATIONS } from "./work-migrations.js";
|
|
9
|
+
import { workSeedWithTriage } from "./work-seeds.js";
|
|
10
|
+
import { workBoard } from "./work.js";
|
|
9
11
|
// src/boards/project-boards.ts
|
|
10
12
|
const DEFAULT_RECHECK_MS = 1e3;
|
|
11
13
|
/** A row under the retired Review board's key is never served: the key is the Review board's alone. */
|
|
@@ -28,6 +30,12 @@ function isUntouchedReviewSeed(row) {
|
|
|
28
30
|
return phases.length === REVIEW_SEED_PHASES.length && phases.every((phase, index) => phase.key === REVIEW_SEED_PHASES[index].key && phase.name === REVIEW_SEED_PHASES[index].name && phase.kind === REVIEW_SEED_PHASES[index].kind);
|
|
29
31
|
}
|
|
30
32
|
const SNAPSHOT_ATTEMPTS = 3;
|
|
33
|
+
/**
|
|
34
|
+
* The creator Factory records on the Work board it stores in a project as the project is
|
|
35
|
+
* created: that board is today's Work, and reset gives it back. Any other Work row Factory stored
|
|
36
|
+
* is the one with Triage. Only Factory writes this id; a person's writes carry their user id.
|
|
37
|
+
*/
|
|
38
|
+
const NEW_PROJECT_SEED_ACTOR = "factory:new-project";
|
|
31
39
|
const PROJECT_BOARD_SOURCE = Symbol("ProjectBoardSource");
|
|
32
40
|
/** Accepts either a fixed registry (tests, standalone services) or a per-project source. */
|
|
33
41
|
function toBoardSource(boards) {
|
|
@@ -90,6 +98,8 @@ var ProjectBoardCache = class {
|
|
|
90
98
|
#seeded = /* @__PURE__ */ new Set();
|
|
91
99
|
#codeSkills;
|
|
92
100
|
#seeds;
|
|
101
|
+
/** Boards the app upserted for every project, which a project with no boards gets before Factory's. */
|
|
102
|
+
#appBoards = /* @__PURE__ */ new Map();
|
|
93
103
|
#reviewBoardInUse;
|
|
94
104
|
#occupiedPhases;
|
|
95
105
|
constructor(options) {
|
|
@@ -109,13 +119,54 @@ var ProjectBoardCache = class {
|
|
|
109
119
|
}]));
|
|
110
120
|
this.#seeds = new Map([...this.codeRegistry.values()].map((board) => [board.id, boardDefinitionOf(board)]));
|
|
111
121
|
}
|
|
112
|
-
/**
|
|
122
|
+
/**
|
|
123
|
+
* The boards Factory stores once in a project it didn't create: Work as it was with Triage, so a
|
|
124
|
+
* project from an older release keeps the phases its cards know, then the app boards, in order.
|
|
125
|
+
*/
|
|
113
126
|
seeds() {
|
|
114
|
-
return [...this.#seeds.values()];
|
|
127
|
+
return [...this.#seeds.values()].map((seed) => this.#isFactoryWork(seed.key) ? workSeedWithTriage() : seed);
|
|
115
128
|
}
|
|
116
|
-
/**
|
|
117
|
-
|
|
118
|
-
|
|
129
|
+
/**
|
|
130
|
+
* The definition reset restores for `key`; undefined when there is none. A board the app upserted
|
|
131
|
+
* for every project comes first, so reset never swaps an app's Work for Factory's. Factory's Work
|
|
132
|
+
* is today's Work for a project Factory created with it (`row` created by
|
|
133
|
+
* {@link NEW_PROJECT_SEED_ACTOR}), and Work with Triage for every other project.
|
|
134
|
+
*/
|
|
135
|
+
seedFor(key, row) {
|
|
136
|
+
const app = this.#appBoards.get(key);
|
|
137
|
+
if (app) return app;
|
|
138
|
+
const seed = this.#seeds.get(key);
|
|
139
|
+
if (!seed || !this.#isFactoryWork(key) || row?.createdBy === "factory:new-project") return seed;
|
|
140
|
+
return workSeedWithTriage();
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Stores Factory's boards in a project that was just created, with today's Work (no Triage).
|
|
144
|
+
* Only the project-creation route calls this; every other load stores {@link seeds}.
|
|
145
|
+
*/
|
|
146
|
+
async seedNewProject(scope) {
|
|
147
|
+
if (this.#seeds.size > 0 || this.#appBoards.size > 0) await this.#storage.seedBoards(scope, [...this.#seeds.values()], {
|
|
148
|
+
actor: NEW_PROJECT_SEED_ACTOR,
|
|
149
|
+
onlyIntoEmpty: this.#onlyIntoEmpty(),
|
|
150
|
+
intoEmpty: [...this.#appBoards.values()]
|
|
151
|
+
});
|
|
152
|
+
return this.describe(scope);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Remembers a board the app upserted for every project, so a project that has no boards yet (one
|
|
156
|
+
* created later, or one that never loaded) gets it on its first load before Factory's own boards;
|
|
157
|
+
* having it, the project then gets no Work from Factory. Kept for this process: an app upserts
|
|
158
|
+
* its boards at every startup.
|
|
159
|
+
*/
|
|
160
|
+
rememberBoardForAllProjects(board) {
|
|
161
|
+
this.#appBoards.set(board.key, board);
|
|
162
|
+
}
|
|
163
|
+
/** Whether `key` is Factory's own Work board, rather than none or an app board under its key. */
|
|
164
|
+
#isFactoryWork(key) {
|
|
165
|
+
return key === workBoard.id && this.codeRegistry.get(key) === workBoard;
|
|
166
|
+
}
|
|
167
|
+
/** Work is stored only into a project with no boards: one that has any keeps what it has. */
|
|
168
|
+
#onlyIntoEmpty() {
|
|
169
|
+
return this.#isFactoryWork(workBoard.id) ? [workBoard.id] : [];
|
|
119
170
|
}
|
|
120
171
|
async load(scope) {
|
|
121
172
|
return (await this.describe(scope)).registry;
|
|
@@ -209,20 +260,27 @@ var ProjectBoardCache = class {
|
|
|
209
260
|
async #seed(scope, key) {
|
|
210
261
|
if (this.#seeded.has(key)) return;
|
|
211
262
|
try {
|
|
212
|
-
|
|
213
|
-
await this.#
|
|
263
|
+
const seeded = await this.#storage.seededBoardKeys(scope);
|
|
264
|
+
if (this.#seeds.size > 0 || this.#appBoards.size > 0) await this.#storage.seedBoards(scope, this.seeds(), {
|
|
265
|
+
onlyIntoEmpty: this.#onlyIntoEmpty(),
|
|
266
|
+
intoEmpty: [...this.#appBoards.values()]
|
|
267
|
+
});
|
|
268
|
+
await this.#migrate(scope, seeded);
|
|
214
269
|
this.#seeded.add(key);
|
|
215
270
|
} catch (error) {
|
|
216
271
|
this.#warnOnce(`seed:${key}`, `Boards for project ${scope.factoryProjectId} could not be stored; Factory stores them on the next load: ${error instanceof Error ? error.message : String(error)}`);
|
|
217
272
|
}
|
|
218
273
|
}
|
|
219
274
|
/** Runs the board migrations of the boards Factory stores here that the project hasn't had yet. */
|
|
220
|
-
async #migrate(scope) {
|
|
275
|
+
async #migrate(scope, seededBefore) {
|
|
221
276
|
const migrations = BOARD_MIGRATIONS.filter((migration) => {
|
|
222
277
|
if (migration.boardKey === null) return true;
|
|
223
278
|
const code = this.codeRegistry.get(migration.boardKey);
|
|
224
279
|
return code !== void 0 && defaultBoards.includes(code);
|
|
225
|
-
})
|
|
280
|
+
}).map((migration) => migration.boardKey !== null && (this.#appBoards.has(migration.boardKey) || seededBefore !== null && !seededBefore.includes(migration.boardKey)) ? {
|
|
281
|
+
...migration,
|
|
282
|
+
migrate: () => void 0
|
|
283
|
+
} : migration);
|
|
226
284
|
const changed = await this.#storage.applyBoardMigrations(scope, migrations, (ops) => this.#migrationContext(scope, ops));
|
|
227
285
|
if (changed.length === 0) return;
|
|
228
286
|
const filled = changed.map(({ boardKey, filled }) => `${boardKey}: ${filled.join(", ")}`).join("; ");
|
|
@@ -304,19 +362,13 @@ var ProjectBoardCache = class {
|
|
|
304
362
|
});
|
|
305
363
|
}
|
|
306
364
|
return {
|
|
307
|
-
registry:
|
|
308
|
-
boards,
|
|
309
|
-
includeDefaultBoards: false
|
|
310
|
-
}),
|
|
365
|
+
registry: boardRegistryOf(boards),
|
|
311
366
|
details,
|
|
312
367
|
problems
|
|
313
368
|
};
|
|
314
369
|
}
|
|
315
370
|
#skillProblems(board) {
|
|
316
|
-
return findBoardSkillProblems(
|
|
317
|
-
boards: [board],
|
|
318
|
-
includeDefaultBoards: false
|
|
319
|
-
}), this.#codeSkills);
|
|
371
|
+
return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills);
|
|
320
372
|
}
|
|
321
373
|
#warnOnce(key, message, debug = false) {
|
|
322
374
|
if (this.#warned.has(key)) return;
|
|
@@ -328,6 +380,6 @@ var ProjectBoardCache = class {
|
|
|
328
380
|
this.#warn(message);
|
|
329
381
|
}
|
|
330
382
|
};
|
|
331
|
-
export { ProjectBoardCache, occupiedPhasesOf, toBoardSource };
|
|
383
|
+
export { NEW_PROJECT_SEED_ACTOR, ProjectBoardCache, occupiedPhasesOf, toBoardSource };
|
|
332
384
|
|
|
333
385
|
//# sourceMappingURL=project-boards.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-boards.js","names":[],"sources":["../../src/boards/project-boards.ts"],"sourcesContent":["import type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type {\n BoardMigrationContext,\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n} from '../storage/domains/boards/base.js';\nimport { DEFAULT_INTAKE_ROUTE_ACTOR } from '../storage/domains/boards/base.js';\nimport type { RetiredAutomationSettings } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport { createBoardRegistry, defaultBoards } from './registry.js';\nimport type { BoardRegistry, InstalledBoard } from './registry.js';\nimport { reviewBoard } from './review.js';\nimport { boardForWorkItem } from './semantics.js';\nimport { boardDefinitionOf, compileStoredBoard, mergeCodeBehaviour } from './stored-board.js';\nimport { BOARD_MIGRATIONS } from './work-migrations.js';\n\nconst DEFAULT_RECHECK_MS = 1000;\n/** A row under the retired Review board's key is never served: the key is the Review board's alone. */\nconst RESERVED_REVIEW_ROW = `Stored board \"${LEGACY_REVIEW_BOARD}\" isn't served: the key is reserved for the retired Review board.`;\nconst PRELOAD_CONCURRENCY = 8;\n/** The phases every release seeded the Review board with; only runners and tools changed between them. */\nconst REVIEW_SEED_PHASES = boardDefinitionOf(reviewBoard).phases.map(({ key, name, kind }) => ({ key, name, kind }));\n\n/**\n * Whether `row` is the Review board as Factory seeded it: written once by Factory, never\n * revised, and shaped like the seed. The actor alone is not proof, as any caller can pass it.\n */\nfunction isUntouchedReviewSeed(row: StoredBoardRecord): boolean {\n if (row.revision !== 1 || row.createdBy !== DEFAULT_INTAKE_ROUTE_ACTOR) return false;\n if (row.updatedBy !== DEFAULT_INTAKE_ROUTE_ACTOR || row.name !== reviewBoard.name) return false;\n const phases = [...row.phases].sort((a, b) => a.position - b.position);\n return (\n phases.length === REVIEW_SEED_PHASES.length &&\n phases.every(\n (phase, index) =>\n phase.key === REVIEW_SEED_PHASES[index]!.key &&\n phase.name === REVIEW_SEED_PHASES[index]!.name &&\n phase.kind === REVIEW_SEED_PHASES[index]!.kind,\n )\n );\n}\nconst SNAPSHOT_ATTEMPTS = 3;\n\n/** Where a board in a project's catalog came from. */\nexport type BoardSourceKind = 'builtin' | 'app' | 'stored';\n\nexport interface StoredBoardDetails {\n source: BoardSourceKind;\n /** Stored boards, the built-in Work board and app boards can all be edited; the retired Review board can't. */\n editable: boolean;\n problems: string[];\n}\n\n/** A project's boards: the code boards plus its stored boards, and what to report about each board. */\nexport interface ProjectBoards {\n readonly registry: BoardRegistry;\n readonly details: ReadonlyMap<string, StoredBoardDetails>;\n /** Problems with stored boards that are left out of the registry. */\n readonly problems: readonly string[];\n}\n\nconst PROJECT_BOARD_SOURCE = Symbol('ProjectBoardSource');\n\n/**\n * Serves each project its boards. `load` is the async entry point that brings a project's\n * boards up to date; `forProject` is the sync read for code that already loaded the project.\n */\nexport interface ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE]: true;\n /** The code boards: built-in and app boards, served to every project as code built them. */\n readonly codeRegistry: BoardRegistry;\n load(scope: StoredBoardScope): Promise<BoardRegistry>;\n forProject(scope: StoredBoardScope): BoardRegistry;\n describe?(scope: StoredBoardScope): Promise<ProjectBoards>;\n}\n\n/** Accepts either a fixed registry (tests, standalone services) or a per-project source. */\nexport function toBoardSource(boards: BoardRegistry | ProjectBoardSource | undefined): ProjectBoardSource {\n const source = boards ?? createBoardRegistry();\n if (isBoardSource(source)) return source;\n return {\n [PROJECT_BOARD_SOURCE]: true,\n codeRegistry: source,\n load: async () => source,\n forProject: () => source,\n };\n}\n\nfunction isBoardSource(boards: BoardRegistry | ProjectBoardSource): boards is ProjectBoardSource {\n return PROJECT_BOARD_SOURCE in boards;\n}\n\ninterface CacheEntry {\n boards: ProjectBoards;\n version: string | null;\n reviewInUse: boolean;\n checkedAt: number;\n}\n\nexport interface ProjectBoardCacheOptions {\n /** The code boards, built-ins included when enabled. */\n codeRegistry: BoardRegistry;\n storage: StoredBoardsStorage;\n /**\n * Lists every project, to warm them at boot, and reads the retired switches the board\n * migrations carry into each project's boards.\n */\n projects?: {\n listAll(): Promise<readonly { orgId: string; id: string }[]>;\n retiredAutomationSettings?(\n project: { orgId: string; id: string },\n ops: FactoryStorageOps,\n ): Promise<RetiredAutomationSettings | null>;\n };\n /** The phases cards sit in on each of the project's boards, which a board migration must not remove. */\n occupiedPhases?: (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ) => Promise<ReadonlyMap<string, ReadonlySet<string>> | null>;\n codeSkills?: readonly InlineSkill[];\n /**\n * Whether the project still uses the retired Review board (an open card is stored on it). Such\n * a project is served Review alongside its boards; without this, no project is.\n */\n reviewBoardInUse?: (scope: StoredBoardScope) => Promise<boolean>;\n recheckMs?: number;\n now?: () => number;\n warn?: (message: string) => void;\n}\n\nfunction scopeKey(scope: StoredBoardScope): string {\n return `${scope.orgId}\\0${scope.factoryProjectId}`;\n}\n\n/**\n * Reads the phases cards sit in on each of a project's boards, for `occupiedPhases`. Null while\n * cards from before the work-item split are still being copied: `listWith` can't see those yet.\n */\nexport function occupiedPhasesOf(workItems: Pick<WorkItemsStorage, 'listWith' | 'legacyBackfillPending'>) {\n return async (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ): Promise<ReadonlyMap<string, ReadonlySet<string>> | null> => {\n if (workItems.legacyBackfillPending) return null;\n const occupied = new Map<string, Set<string>>();\n for (const item of await workItems.listWith(ops, scope)) {\n const board = boardForWorkItem(item);\n const phases = occupied.get(board) ?? new Set<string>();\n for (const stage of item.stages) phases.add(stage);\n occupied.set(board, phases);\n }\n return occupied;\n };\n}\n\n/**\n * The per-project board cache. A project's boards are its rows: the Work and app boards Factory\n * stored in it, in code order, then the others. A Work or app board's row runs with the code\n * behaviour of its board and phase keys that still fits it ({@link mergeCodeBehaviour}). A project\n * that still uses the retired Review board is served it from code, never stored, until its last\n * open card there finishes. The first load of each project in a process stores the\n * boards Factory hasn't stored in it yet, each once ({@link StoredBoardsStorage.seedBoards}); a\n * release never rewrites them. Loads recheck the project's board version at most every\n * `recheckMs` and recompile when it changed, so stored edits on other replicas arrive within that\n * delay.\n */\nexport class ProjectBoardCache implements ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE] = true;\n readonly codeRegistry: BoardRegistry;\n readonly #codeDetails: ReadonlyMap<string, StoredBoardDetails>;\n readonly #storage: StoredBoardsStorage;\n readonly #projects: ProjectBoardCacheOptions['projects'];\n readonly #recheckMs: number;\n readonly #now: () => number;\n readonly #warn: (message: string) => void;\n readonly #entries = new Map<string, CacheEntry>();\n readonly #loading = new Map<string, Promise<ProjectBoards>>();\n readonly #generations = new Map<string, number>();\n readonly #warned = new Set<string>();\n readonly #seeded = new Set<string>();\n readonly #codeSkills: readonly InlineSkill[];\n readonly #seeds: ReadonlyMap<string, StoredBoardInput>;\n readonly #reviewBoardInUse: ProjectBoardCacheOptions['reviewBoardInUse'];\n readonly #occupiedPhases: ProjectBoardCacheOptions['occupiedPhases'];\n\n constructor(options: ProjectBoardCacheOptions) {\n this.codeRegistry = options.codeRegistry;\n this.#storage = options.storage;\n this.#reviewBoardInUse = options.reviewBoardInUse;\n this.#occupiedPhases = options.occupiedPhases;\n this.#projects = options.projects;\n this.#codeSkills = options.codeSkills ?? [];\n this.#recheckMs = options.recheckMs ?? DEFAULT_RECHECK_MS;\n this.#now = options.now ?? Date.now;\n this.#warn = options.warn ?? (message => console.warn(`[factory] ${message}`));\n this.#codeDetails = new Map(\n [...this.codeRegistry.values()].map(board => [\n board.id,\n {\n source: defaultBoards.includes(board) ? 'builtin' : 'app',\n editable: true,\n problems: this.#skillProblems(board),\n },\n ]),\n );\n this.#seeds = new Map([...this.codeRegistry.values()].map(board => [board.id, boardDefinitionOf(board)]));\n }\n\n /** The boards Factory stores in each project once, in order. */\n seeds(): StoredBoardInput[] {\n return [...this.#seeds.values()];\n }\n\n /** Factory's current definition for `key`, which reset restores; undefined when Factory has none. */\n seedFor(key: string): StoredBoardInput | undefined {\n return this.#seeds.get(key);\n }\n\n async load(scope: StoredBoardScope): Promise<BoardRegistry> {\n return (await this.describe(scope)).registry;\n }\n\n /** The project's boards with their source, whether they can be edited, and problems, brought up to date. */\n async describe(scope: StoredBoardScope): Promise<ProjectBoards> {\n const key = scopeKey(scope);\n const entry = this.#entries.get(key);\n if (entry && this.#now() - entry.checkedAt < this.#recheckMs) return entry.boards;\n const inFlight = this.#loading.get(key);\n if (inFlight) return inFlight;\n const generation = this.#generations.get(key) ?? 0;\n const loading = this.#refresh(scope, key, generation).finally(() => {\n if (this.#loading.get(key) === loading) this.#loading.delete(key);\n });\n this.#loading.set(key, loading);\n return loading;\n }\n\n /**\n * The project's loaded boards. Before the project's first load (boot preload not finished, or a\n * project created on another replica) this is the code boards alone, without the project's\n * stored boards.\n */\n forProject(scope: StoredBoardScope): BoardRegistry {\n // Storage asks about a row it is about to insert by its board and stages alone, with no\n // project to look up; the code boards answer for it.\n if (!scope.orgId || !scope.factoryProjectId) return this.codeRegistry;\n const entry = this.#entries.get(scopeKey(scope));\n if (entry) return entry.boards.registry;\n // Warm the project so the next sync read sees its stored boards.\n void this.load(scope).catch(() => {});\n this.#warnOnce(\n `cold:${scopeKey(scope)}`,\n `Boards for project ${scope.factoryProjectId} were read before they were loaded; using the code boards.`,\n true,\n );\n return this.codeRegistry;\n }\n\n /** The code skills stored runners may name. */\n get codeSkills(): readonly InlineSkill[] {\n return this.#codeSkills;\n }\n\n /** Makes the next load reread the project. The loaded boards keep serving sync reads until then. */\n invalidate(scope: StoredBoardScope): void {\n const key = scopeKey(scope);\n this.#generations.set(key, (this.#generations.get(key) ?? 0) + 1);\n this.#loading.delete(key);\n const entry = this.#entries.get(key);\n if (entry) entry.checkedAt = Number.NEGATIVE_INFINITY;\n }\n\n /** Loads every project, a few at a time, so sync reads find them warm and each has its boards stored. */\n async preload(): Promise<void> {\n const projects = (await this.#projects?.listAll()) ?? [];\n let next = 0;\n const worker = async () => {\n while (next < projects.length) {\n const project = projects[next++]!;\n // A project that fails to load here loads on first use; the others still load now.\n await this.load({ orgId: project.orgId, factoryProjectId: project.id }).catch(error =>\n this.#warn(\n `Boards for project ${project.id} did not load at startup; they load on first use: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(PRELOAD_CONCURRENCY, projects.length) }, worker));\n }\n\n async #refresh(scope: StoredBoardScope, key: string, generation: number): Promise<ProjectBoards> {\n await this.#seed(scope, key);\n const current = this.#entries.get(key);\n const version = await this.#storage.readVersion(scope);\n const reviewInUse = (await this.#reviewBoardInUse?.(scope)) ?? false;\n if (current && current.version === version && current.reviewInUse === reviewInUse) {\n if ((this.#generations.get(key) ?? 0) === generation) current.checkedAt = this.#now();\n return current.boards;\n }\n const snapshot = await this.#consistentSnapshot(scope);\n const boards = this.#compile(scope, snapshot.boards, reviewInUse);\n if ((this.#generations.get(key) ?? 0) === generation) {\n this.#entries.set(key, { boards, version: snapshot.version, reviewInUse, checkedAt: this.#now() });\n }\n return boards;\n }\n\n /** Boards and phases are read in two statements; reread when a write landed between them. */\n async #consistentSnapshot(scope: StoredBoardScope) {\n let snapshot = await this.#storage.snapshot(scope);\n for (let attempt = 1; attempt < SNAPSHOT_ATTEMPTS; attempt++) {\n if ((await this.#storage.readVersion(scope)) === snapshot.version) break;\n snapshot = await this.#storage.snapshot(scope);\n }\n return snapshot;\n }\n\n /**\n * Stores the boards Factory hasn't stored in the project yet, once per process. A failure is\n * logged and retried on the next load; the boards it didn't store aren't served meanwhile.\n */\n async #seed(scope: StoredBoardScope, key: string): Promise<void> {\n if (this.#seeded.has(key)) return;\n try {\n if (this.#seeds.size > 0) await this.#storage.seedBoards(scope, this.seeds());\n await this.#migrate(scope);\n this.#seeded.add(key);\n } catch (error) {\n this.#warnOnce(\n `seed:${key}`,\n `Boards for project ${scope.factoryProjectId} could not be stored; Factory stores them on the next load: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Runs the board migrations of the boards Factory stores here that the project hasn't had yet. */\n async #migrate(scope: StoredBoardScope): Promise<void> {\n // A migration of one board rewrites Factory's own board; an app board under the same key keeps\n // its settings. One that carries a project setting into every board rewrites them all.\n const migrations = BOARD_MIGRATIONS.filter(migration => {\n if (migration.boardKey === null) return true;\n const code = this.codeRegistry.get(migration.boardKey);\n return code !== undefined && defaultBoards.includes(code);\n });\n const changed = await this.#storage.applyBoardMigrations(scope, migrations, ops =>\n this.#migrationContext(scope, ops),\n );\n if (changed.length === 0) return;\n const filled = changed.map(({ boardKey, filled }) => `${boardKey}: ${filled.join(', ')}`).join('; ');\n console.info(`[factory] Migrated the boards of project ${scope.factoryProjectId} (${filled}).`);\n }\n\n /** Read through the migration transaction's `ops`, so card moves can't slip in unseen on LibSQL. */\n async #migrationContext(scope: StoredBoardScope, ops: FactoryStorageOps): Promise<BoardMigrationContext> {\n const retiredSettings =\n (await this.#projects?.retiredAutomationSettings?.({ orgId: scope.orgId, id: scope.factoryProjectId }, ops)) ??\n null;\n return {\n retiredSettings,\n occupiedPhases: retiredSettings && this.#occupiedPhases ? await this.#occupiedPhases(scope, ops) : null,\n codePhases: boardKey => {\n const code = this.codeRegistry.get(boardKey);\n return code ? new Set(Object.keys(code.phases)) : undefined;\n },\n warn: message =>\n this.#warnOnce(`migration:${scopeKey(scope)}:${message}`, `${message} (project ${scope.factoryProjectId})`),\n };\n }\n\n #compile(scope: StoredBoardScope, rows: readonly StoredBoardRecord[], reviewInUse: boolean): ProjectBoards {\n const byKey = new Map(rows.map(row => [row.key, row]));\n const details = new Map(this.#codeDetails);\n const problems: string[] = [];\n const report = (row: StoredBoardRecord, messages: readonly string[]) => {\n problems.push(...messages);\n for (const message of messages) {\n this.#warnOnce(\n `row:${scopeKey(scope)}:${row.key}:${row.revision}:${message}`,\n `${message} (project ${scope.factoryProjectId})`,\n );\n }\n };\n const boards: InstalledBoard[] = [];\n // Work and app boards keep their code order, each served from its row.\n for (const code of this.codeRegistry.values()) {\n const row = byKey.get(code.id);\n if (!row) {\n details.delete(code.id);\n // Stored once and deleted since, or not stored because storing failed.\n if (!this.#seeded.has(scopeKey(scope))) {\n problems.push(`Board \"${code.id}\" isn't stored in this project yet; Factory stores it on the next load.`);\n }\n continue;\n }\n let merged: ReturnType<typeof mergeCodeBehaviour>;\n try {\n merged = mergeCodeBehaviour(row, code);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n report(row, merged.problems);\n details.set(code.id, {\n ...details.get(code.id)!,\n problems: [...merged.problems, ...this.#skillProblems(merged.board)],\n });\n boards.push(merged.board);\n }\n // Served from code and never stored, so nobody edits a board on its way out.\n if (reviewInUse) {\n boards.push(reviewBoard);\n details.set(reviewBoard.id, { source: 'builtin', editable: false, problems: [] });\n }\n for (const row of rows) {\n if (this.codeRegistry.has(row.key)) continue;\n if (row.key === LEGACY_REVIEW_BOARD) {\n // Factory seeded this row while Review was a built-in board and nobody edited it since:\n // there is nothing in it to lose, so it is no problem. A person's edits are reported.\n if (isUntouchedReviewSeed(row)) continue;\n report(row, [\n reviewInUse\n ? `Stored board \"${row.key}\" is hidden by the code board with the same key.`\n : RESERVED_REVIEW_ROW,\n ]);\n continue;\n }\n let board: InstalledBoard;\n try {\n board = compileStoredBoard(row);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n boards.push(board);\n details.set(row.key, { source: 'stored', editable: true, problems: this.#skillProblems(board) });\n }\n return {\n registry: createBoardRegistry({ boards, includeDefaultBoards: false }),\n details,\n problems,\n };\n }\n\n #skillProblems(board: InstalledBoard): string[] {\n return findBoardSkillProblems(\n createBoardRegistry({ boards: [board], includeDefaultBoards: false }),\n this.#codeSkills,\n );\n }\n\n #warnOnce(key: string, message: string, debug = false): void {\n if (this.#warned.has(key)) return;\n this.#warned.add(key);\n if (debug) {\n console.debug(`[factory] ${message}`);\n return;\n }\n this.#warn(message);\n }\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,qBAAqB;;AAE3B,MAAM,sBAAsB,iBAAiB,oBAAoB;AACjE,MAAM,sBAAsB;;AAE5B,MAAM,qBAAqB,kBAAkB,WAAW,CAAC,CAAC,OAAO,KAAK,EAAE,KAAK,MAAM,YAAY;CAAE;CAAK;CAAM;AAAK,EAAE;;;;;AAMnH,SAAS,sBAAsB,KAAiC;CAC9D,IAAI,IAAI,aAAa,KAAK,IAAI,cAAA,WAA0C,OAAO;CAC/E,IAAI,IAAI,cAAA,aAA4C,IAAI,SAAS,YAAY,MAAM,OAAO;CAC1F,MAAM,SAAS,CAAC,GAAG,IAAI,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;CACrE,OACE,OAAO,WAAW,mBAAmB,UACrC,OAAO,OACJ,OAAO,UACN,MAAM,QAAQ,mBAAmB,MAAM,CAAE,OACzC,MAAM,SAAS,mBAAmB,MAAM,CAAE,QAC1C,MAAM,SAAS,mBAAmB,MAAM,CAAE,IAC9C;AAEJ;AACA,MAAM,oBAAoB;AAoB1B,MAAM,uBAAuB,OAAO,oBAAoB;;AAgBxD,SAAgB,cAAc,QAA4E;CACxG,MAAM,SAAS,UAAU,oBAAoB;CAC7C,IAAI,cAAc,MAAM,GAAG,OAAO;CAClC,OAAO;GACJ,uBAAuB;EACxB,cAAc;EACd,MAAM,YAAY;EAClB,kBAAkB;CACpB;AACF;AAEA,SAAS,cAAc,QAA0E;CAC/F,OAAO,wBAAwB;AACjC;AAwCA,SAAS,SAAS,OAAiC;C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AAK;GAAG,sBAAsB;EAAM,CAAC,GACpE,KAAK,WACP;CACF;CAEA,UAAU,KAAa,SAAiB,QAAQ,OAAa;EAC3D,IAAI,KAAK,QAAQ,IAAI,GAAG,GAAG;EAC3B,KAAK,QAAQ,IAAI,GAAG;EACpB,IAAI,OAAO;GACT,QAAQ,MAAM,aAAa,SAAS;GACpC;EACF;EACA,KAAK,MAAM,OAAO;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"project-boards.js","names":[],"sources":["../../src/boards/project-boards.ts"],"sourcesContent":["import type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type {\n BoardMigrationContext,\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n} from '../storage/domains/boards/base.js';\nimport { DEFAULT_INTAKE_ROUTE_ACTOR } from '../storage/domains/boards/base.js';\nimport type { RetiredAutomationSettings } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport { boardRegistryOf, createBoardRegistry, defaultBoards } from './registry.js';\nimport type { BoardRegistry, InstalledBoard } from './registry.js';\nimport { reviewBoard } from './review.js';\nimport { boardForWorkItem } from './semantics.js';\nimport { boardDefinitionOf, compileStoredBoard, mergeCodeBehaviour } from './stored-board.js';\nimport { BOARD_MIGRATIONS } from './work-migrations.js';\nimport { workSeedWithTriage } from './work-seeds.js';\nimport { workBoard } from './work.js';\n\nconst DEFAULT_RECHECK_MS = 1000;\n/** A row under the retired Review board's key is never served: the key is the Review board's alone. */\nconst RESERVED_REVIEW_ROW = `Stored board \"${LEGACY_REVIEW_BOARD}\" isn't served: the key is reserved for the retired Review board.`;\nconst PRELOAD_CONCURRENCY = 8;\n/** The phases every release seeded the Review board with; only runners and tools changed between them. */\nconst REVIEW_SEED_PHASES = boardDefinitionOf(reviewBoard).phases.map(({ key, name, kind }) => ({ key, name, kind }));\n\n/**\n * Whether `row` is the Review board as Factory seeded it: written once by Factory, never\n * revised, and shaped like the seed. The actor alone is not proof, as any caller can pass it.\n */\nfunction isUntouchedReviewSeed(row: StoredBoardRecord): boolean {\n if (row.revision !== 1 || row.createdBy !== DEFAULT_INTAKE_ROUTE_ACTOR) return false;\n if (row.updatedBy !== DEFAULT_INTAKE_ROUTE_ACTOR || row.name !== reviewBoard.name) return false;\n const phases = [...row.phases].sort((a, b) => a.position - b.position);\n return (\n phases.length === REVIEW_SEED_PHASES.length &&\n phases.every(\n (phase, index) =>\n phase.key === REVIEW_SEED_PHASES[index]!.key &&\n phase.name === REVIEW_SEED_PHASES[index]!.name &&\n phase.kind === REVIEW_SEED_PHASES[index]!.kind,\n )\n );\n}\nconst SNAPSHOT_ATTEMPTS = 3;\n\n/**\n * The creator Factory records on the Work board it stores in a project as the project is\n * created: that board is today's Work, and reset gives it back. Any other Work row Factory stored\n * is the one with Triage. Only Factory writes this id; a person's writes carry their user id.\n */\nexport const NEW_PROJECT_SEED_ACTOR = 'factory:new-project';\n\n/** Where a board in a project's catalog came from. */\nexport type BoardSourceKind = 'builtin' | 'app' | 'stored';\n\nexport interface StoredBoardDetails {\n source: BoardSourceKind;\n /** Stored boards, the built-in Work board and app boards can all be edited; the retired Review board can't. */\n editable: boolean;\n problems: string[];\n}\n\n/** A project's boards: the code boards plus its stored boards, and what to report about each board. */\nexport interface ProjectBoards {\n readonly registry: BoardRegistry;\n readonly details: ReadonlyMap<string, StoredBoardDetails>;\n /** Problems with stored boards that are left out of the registry. */\n readonly problems: readonly string[];\n}\n\nconst PROJECT_BOARD_SOURCE = Symbol('ProjectBoardSource');\n\n/**\n * Serves each project its boards. `load` is the async entry point that brings a project's\n * boards up to date; `forProject` is the sync read for code that already loaded the project.\n */\nexport interface ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE]: true;\n /** The code boards: built-in and app boards, served to every project as code built them. */\n readonly codeRegistry: BoardRegistry;\n load(scope: StoredBoardScope): Promise<BoardRegistry>;\n forProject(scope: StoredBoardScope): BoardRegistry;\n describe?(scope: StoredBoardScope): Promise<ProjectBoards>;\n}\n\n/** Accepts either a fixed registry (tests, standalone services) or a per-project source. */\nexport function toBoardSource(boards: BoardRegistry | ProjectBoardSource | undefined): ProjectBoardSource {\n const source = boards ?? createBoardRegistry();\n if (isBoardSource(source)) return source;\n return {\n [PROJECT_BOARD_SOURCE]: true,\n codeRegistry: source,\n load: async () => source,\n forProject: () => source,\n };\n}\n\nfunction isBoardSource(boards: BoardRegistry | ProjectBoardSource): boards is ProjectBoardSource {\n return PROJECT_BOARD_SOURCE in boards;\n}\n\ninterface CacheEntry {\n boards: ProjectBoards;\n version: string | null;\n reviewInUse: boolean;\n checkedAt: number;\n}\n\nexport interface ProjectBoardCacheOptions {\n /** The code boards, built-ins included when enabled. */\n codeRegistry: BoardRegistry;\n storage: StoredBoardsStorage;\n /**\n * Lists every project, to warm them at boot, and reads the retired switches the board\n * migrations carry into each project's boards.\n */\n projects?: {\n listAll(): Promise<readonly { orgId: string; id: string }[]>;\n retiredAutomationSettings?(\n project: { orgId: string; id: string },\n ops: FactoryStorageOps,\n ): Promise<RetiredAutomationSettings | null>;\n };\n /** The phases cards sit in on each of the project's boards, which a board migration must not remove. */\n occupiedPhases?: (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ) => Promise<ReadonlyMap<string, ReadonlySet<string>> | null>;\n codeSkills?: readonly InlineSkill[];\n /**\n * Whether the project still uses the retired Review board (an open card is stored on it). Such\n * a project is served Review alongside its boards; without this, no project is.\n */\n reviewBoardInUse?: (scope: StoredBoardScope) => Promise<boolean>;\n recheckMs?: number;\n now?: () => number;\n warn?: (message: string) => void;\n}\n\nfunction scopeKey(scope: StoredBoardScope): string {\n return `${scope.orgId}\\0${scope.factoryProjectId}`;\n}\n\n/**\n * Reads the phases cards sit in on each of a project's boards, for `occupiedPhases`. Null while\n * cards from before the work-item split are still being copied: `listWith` can't see those yet.\n */\nexport function occupiedPhasesOf(workItems: Pick<WorkItemsStorage, 'listWith' | 'legacyBackfillPending'>) {\n return async (\n scope: StoredBoardScope,\n ops: FactoryStorageOps,\n ): Promise<ReadonlyMap<string, ReadonlySet<string>> | null> => {\n if (workItems.legacyBackfillPending) return null;\n const occupied = new Map<string, Set<string>>();\n for (const item of await workItems.listWith(ops, scope)) {\n const board = boardForWorkItem(item);\n const phases = occupied.get(board) ?? new Set<string>();\n for (const stage of item.stages) phases.add(stage);\n occupied.set(board, phases);\n }\n return occupied;\n };\n}\n\n/**\n * The per-project board cache. A project's boards are its rows: the Work and app boards Factory\n * stored in it, in code order, then the others. A Work or app board's row runs with the code\n * behaviour of its board and phase keys that still fits it ({@link mergeCodeBehaviour}). A project\n * that still uses the retired Review board is served it from code, never stored, until its last\n * open card there finishes. The first load of each project in a process stores the\n * boards Factory hasn't stored in it yet, each once ({@link StoredBoardsStorage.seedBoards}); a\n * release never rewrites them. Loads recheck the project's board version at most every\n * `recheckMs` and recompile when it changed, so stored edits on other replicas arrive within that\n * delay.\n */\nexport class ProjectBoardCache implements ProjectBoardSource {\n readonly [PROJECT_BOARD_SOURCE] = true;\n readonly codeRegistry: BoardRegistry;\n readonly #codeDetails: ReadonlyMap<string, StoredBoardDetails>;\n readonly #storage: StoredBoardsStorage;\n readonly #projects: ProjectBoardCacheOptions['projects'];\n readonly #recheckMs: number;\n readonly #now: () => number;\n readonly #warn: (message: string) => void;\n readonly #entries = new Map<string, CacheEntry>();\n readonly #loading = new Map<string, Promise<ProjectBoards>>();\n readonly #generations = new Map<string, number>();\n readonly #warned = new Set<string>();\n readonly #seeded = new Set<string>();\n readonly #codeSkills: readonly InlineSkill[];\n readonly #seeds: ReadonlyMap<string, StoredBoardInput>;\n /** Boards the app upserted for every project, which a project with no boards gets before Factory's. */\n readonly #appBoards = new Map<string, StoredBoardInput>();\n readonly #reviewBoardInUse: ProjectBoardCacheOptions['reviewBoardInUse'];\n readonly #occupiedPhases: ProjectBoardCacheOptions['occupiedPhases'];\n\n constructor(options: ProjectBoardCacheOptions) {\n this.codeRegistry = options.codeRegistry;\n this.#storage = options.storage;\n this.#reviewBoardInUse = options.reviewBoardInUse;\n this.#occupiedPhases = options.occupiedPhases;\n this.#projects = options.projects;\n this.#codeSkills = options.codeSkills ?? [];\n this.#recheckMs = options.recheckMs ?? DEFAULT_RECHECK_MS;\n this.#now = options.now ?? Date.now;\n this.#warn = options.warn ?? (message => console.warn(`[factory] ${message}`));\n this.#codeDetails = new Map(\n [...this.codeRegistry.values()].map(board => [\n board.id,\n {\n source: defaultBoards.includes(board) ? 'builtin' : 'app',\n editable: true,\n problems: this.#skillProblems(board),\n },\n ]),\n );\n this.#seeds = new Map([...this.codeRegistry.values()].map(board => [board.id, boardDefinitionOf(board)]));\n }\n\n /**\n * The boards Factory stores once in a project it didn't create: Work as it was with Triage, so a\n * project from an older release keeps the phases its cards know, then the app boards, in order.\n */\n seeds(): StoredBoardInput[] {\n return [...this.#seeds.values()].map(seed => (this.#isFactoryWork(seed.key) ? workSeedWithTriage() : seed));\n }\n\n /**\n * The definition reset restores for `key`; undefined when there is none. A board the app upserted\n * for every project comes first, so reset never swaps an app's Work for Factory's. Factory's Work\n * is today's Work for a project Factory created with it (`row` created by\n * {@link NEW_PROJECT_SEED_ACTOR}), and Work with Triage for every other project.\n */\n seedFor(key: string, row?: Pick<StoredBoardRecord, 'createdBy'>): StoredBoardInput | undefined {\n const app = this.#appBoards.get(key);\n if (app) return app;\n const seed = this.#seeds.get(key);\n if (!seed || !this.#isFactoryWork(key) || row?.createdBy === NEW_PROJECT_SEED_ACTOR) return seed;\n return workSeedWithTriage();\n }\n\n /**\n * Stores Factory's boards in a project that was just created, with today's Work (no Triage).\n * Only the project-creation route calls this; every other load stores {@link seeds}.\n */\n async seedNewProject(scope: StoredBoardScope): Promise<ProjectBoards> {\n if (this.#seeds.size > 0 || this.#appBoards.size > 0) {\n await this.#storage.seedBoards(scope, [...this.#seeds.values()], {\n actor: NEW_PROJECT_SEED_ACTOR,\n onlyIntoEmpty: this.#onlyIntoEmpty(),\n intoEmpty: [...this.#appBoards.values()],\n });\n }\n return this.describe(scope);\n }\n\n /**\n * Remembers a board the app upserted for every project, so a project that has no boards yet (one\n * created later, or one that never loaded) gets it on its first load before Factory's own boards;\n * having it, the project then gets no Work from Factory. Kept for this process: an app upserts\n * its boards at every startup.\n */\n rememberBoardForAllProjects(board: StoredBoardInput): void {\n this.#appBoards.set(board.key, board);\n }\n\n /** Whether `key` is Factory's own Work board, rather than none or an app board under its key. */\n #isFactoryWork(key: string): boolean {\n return key === workBoard.id && this.codeRegistry.get(key) === workBoard;\n }\n\n /** Work is stored only into a project with no boards: one that has any keeps what it has. */\n #onlyIntoEmpty(): string[] {\n return this.#isFactoryWork(workBoard.id) ? [workBoard.id] : [];\n }\n\n async load(scope: StoredBoardScope): Promise<BoardRegistry> {\n return (await this.describe(scope)).registry;\n }\n\n /** The project's boards with their source, whether they can be edited, and problems, brought up to date. */\n async describe(scope: StoredBoardScope): Promise<ProjectBoards> {\n const key = scopeKey(scope);\n const entry = this.#entries.get(key);\n if (entry && this.#now() - entry.checkedAt < this.#recheckMs) return entry.boards;\n const inFlight = this.#loading.get(key);\n if (inFlight) return inFlight;\n const generation = this.#generations.get(key) ?? 0;\n const loading = this.#refresh(scope, key, generation).finally(() => {\n if (this.#loading.get(key) === loading) this.#loading.delete(key);\n });\n this.#loading.set(key, loading);\n return loading;\n }\n\n /**\n * The project's loaded boards. Before the project's first load (boot preload not finished, or a\n * project created on another replica) this is the code boards alone, without the project's\n * stored boards.\n */\n forProject(scope: StoredBoardScope): BoardRegistry {\n // Storage asks about a row it is about to insert by its board and stages alone, with no\n // project to look up; the code boards answer for it.\n if (!scope.orgId || !scope.factoryProjectId) return this.codeRegistry;\n const entry = this.#entries.get(scopeKey(scope));\n if (entry) return entry.boards.registry;\n // Warm the project so the next sync read sees its stored boards.\n void this.load(scope).catch(() => {});\n this.#warnOnce(\n `cold:${scopeKey(scope)}`,\n `Boards for project ${scope.factoryProjectId} were read before they were loaded; using the code boards.`,\n true,\n );\n return this.codeRegistry;\n }\n\n /** The code skills stored runners may name. */\n get codeSkills(): readonly InlineSkill[] {\n return this.#codeSkills;\n }\n\n /** Makes the next load reread the project. The loaded boards keep serving sync reads until then. */\n invalidate(scope: StoredBoardScope): void {\n const key = scopeKey(scope);\n this.#generations.set(key, (this.#generations.get(key) ?? 0) + 1);\n this.#loading.delete(key);\n const entry = this.#entries.get(key);\n if (entry) entry.checkedAt = Number.NEGATIVE_INFINITY;\n }\n\n /** Loads every project, a few at a time, so sync reads find them warm and each has its boards stored. */\n async preload(): Promise<void> {\n const projects = (await this.#projects?.listAll()) ?? [];\n let next = 0;\n const worker = async () => {\n while (next < projects.length) {\n const project = projects[next++]!;\n // A project that fails to load here loads on first use; the others still load now.\n await this.load({ orgId: project.orgId, factoryProjectId: project.id }).catch(error =>\n this.#warn(\n `Boards for project ${project.id} did not load at startup; they load on first use: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(PRELOAD_CONCURRENCY, projects.length) }, worker));\n }\n\n async #refresh(scope: StoredBoardScope, key: string, generation: number): Promise<ProjectBoards> {\n await this.#seed(scope, key);\n const current = this.#entries.get(key);\n const version = await this.#storage.readVersion(scope);\n const reviewInUse = (await this.#reviewBoardInUse?.(scope)) ?? false;\n if (current && current.version === version && current.reviewInUse === reviewInUse) {\n if ((this.#generations.get(key) ?? 0) === generation) current.checkedAt = this.#now();\n return current.boards;\n }\n const snapshot = await this.#consistentSnapshot(scope);\n const boards = this.#compile(scope, snapshot.boards, reviewInUse);\n if ((this.#generations.get(key) ?? 0) === generation) {\n this.#entries.set(key, { boards, version: snapshot.version, reviewInUse, checkedAt: this.#now() });\n }\n return boards;\n }\n\n /** Boards and phases are read in two statements; reread when a write landed between them. */\n async #consistentSnapshot(scope: StoredBoardScope) {\n let snapshot = await this.#storage.snapshot(scope);\n for (let attempt = 1; attempt < SNAPSHOT_ATTEMPTS; attempt++) {\n if ((await this.#storage.readVersion(scope)) === snapshot.version) break;\n snapshot = await this.#storage.snapshot(scope);\n }\n return snapshot;\n }\n\n /**\n * Stores the boards Factory hasn't stored in the project yet, once per process. A failure is\n * logged and retried on the next load; the boards it didn't store aren't served meanwhile.\n */\n async #seed(scope: StoredBoardScope, key: string): Promise<void> {\n if (this.#seeded.has(key)) return;\n try {\n // Read before seeding records Work's key: a project whose list lacked it has no Work of Factory's.\n const seeded = await this.#storage.seededBoardKeys(scope);\n if (this.#seeds.size > 0 || this.#appBoards.size > 0) {\n await this.#storage.seedBoards(scope, this.seeds(), {\n onlyIntoEmpty: this.#onlyIntoEmpty(),\n intoEmpty: [...this.#appBoards.values()],\n });\n }\n await this.#migrate(scope, seeded);\n this.#seeded.add(key);\n } catch (error) {\n this.#warnOnce(\n `seed:${key}`,\n `Boards for project ${scope.factoryProjectId} could not be stored; Factory stores them on the next load: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Runs the board migrations of the boards Factory stores here that the project hasn't had yet. */\n async #migrate(scope: StoredBoardScope, seededBefore: readonly string[] | null): Promise<void> {\n // A migration of one board rewrites Factory's own board; an app board under the same key keeps\n // its settings. One that carries a project setting into every board rewrites them all. A board\n // Factory never stored in the project (an app wrote the row first), or one the app upserts for\n // every project, is an app's: its one-board migrations are recorded as applied without running.\n const migrations = BOARD_MIGRATIONS.filter(migration => {\n if (migration.boardKey === null) return true;\n const code = this.codeRegistry.get(migration.boardKey);\n return code !== undefined && defaultBoards.includes(code);\n }).map(migration =>\n migration.boardKey !== null &&\n (this.#appBoards.has(migration.boardKey) || (seededBefore !== null && !seededBefore.includes(migration.boardKey)))\n ? { ...migration, migrate: () => undefined }\n : migration,\n );\n const changed = await this.#storage.applyBoardMigrations(scope, migrations, ops =>\n this.#migrationContext(scope, ops),\n );\n if (changed.length === 0) return;\n const filled = changed.map(({ boardKey, filled }) => `${boardKey}: ${filled.join(', ')}`).join('; ');\n console.info(`[factory] Migrated the boards of project ${scope.factoryProjectId} (${filled}).`);\n }\n\n /** Read through the migration transaction's `ops`, so card moves can't slip in unseen on LibSQL. */\n async #migrationContext(scope: StoredBoardScope, ops: FactoryStorageOps): Promise<BoardMigrationContext> {\n const retiredSettings =\n (await this.#projects?.retiredAutomationSettings?.({ orgId: scope.orgId, id: scope.factoryProjectId }, ops)) ??\n null;\n return {\n retiredSettings,\n occupiedPhases: retiredSettings && this.#occupiedPhases ? await this.#occupiedPhases(scope, ops) : null,\n codePhases: boardKey => {\n const code = this.codeRegistry.get(boardKey);\n return code ? new Set(Object.keys(code.phases)) : undefined;\n },\n warn: message =>\n this.#warnOnce(`migration:${scopeKey(scope)}:${message}`, `${message} (project ${scope.factoryProjectId})`),\n };\n }\n\n #compile(scope: StoredBoardScope, rows: readonly StoredBoardRecord[], reviewInUse: boolean): ProjectBoards {\n const byKey = new Map(rows.map(row => [row.key, row]));\n const details = new Map(this.#codeDetails);\n const problems: string[] = [];\n const report = (row: StoredBoardRecord, messages: readonly string[]) => {\n problems.push(...messages);\n for (const message of messages) {\n this.#warnOnce(\n `row:${scopeKey(scope)}:${row.key}:${row.revision}:${message}`,\n `${message} (project ${scope.factoryProjectId})`,\n );\n }\n };\n const boards: InstalledBoard[] = [];\n // Work and app boards keep their code order, each served from its row.\n for (const code of this.codeRegistry.values()) {\n const row = byKey.get(code.id);\n if (!row) {\n details.delete(code.id);\n // Stored once and deleted since, or not stored because storing failed.\n if (!this.#seeded.has(scopeKey(scope))) {\n problems.push(`Board \"${code.id}\" isn't stored in this project yet; Factory stores it on the next load.`);\n }\n continue;\n }\n let merged: ReturnType<typeof mergeCodeBehaviour>;\n try {\n merged = mergeCodeBehaviour(row, code);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n report(row, merged.problems);\n details.set(code.id, {\n ...details.get(code.id)!,\n problems: [...merged.problems, ...this.#skillProblems(merged.board)],\n });\n boards.push(merged.board);\n }\n // Served from code and never stored, so nobody edits a board on its way out.\n if (reviewInUse) {\n boards.push(reviewBoard);\n details.set(reviewBoard.id, { source: 'builtin', editable: false, problems: [] });\n }\n for (const row of rows) {\n if (this.codeRegistry.has(row.key)) continue;\n if (row.key === LEGACY_REVIEW_BOARD) {\n // Factory seeded this row while Review was a built-in board and nobody edited it since:\n // there is nothing in it to lose, so it is no problem. A person's edits are reported.\n if (isUntouchedReviewSeed(row)) continue;\n report(row, [\n reviewInUse\n ? `Stored board \"${row.key}\" is hidden by the code board with the same key.`\n : RESERVED_REVIEW_ROW,\n ]);\n continue;\n }\n let board: InstalledBoard;\n try {\n board = compileStoredBoard(row);\n } catch (error) {\n report(row, [\n `Board '${row.key}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`,\n ]);\n continue;\n }\n boards.push(board);\n details.set(row.key, { source: 'stored', editable: true, problems: this.#skillProblems(board) });\n }\n return {\n registry: boardRegistryOf(boards),\n details,\n problems,\n };\n }\n\n #skillProblems(board: InstalledBoard): string[] {\n return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills);\n }\n\n #warnOnce(key: string, message: string, debug = false): void {\n if (this.#warned.has(key)) return;\n this.#warned.add(key);\n if (debug) {\n console.debug(`[factory] ${message}`);\n return;\n }\n this.#warn(message);\n }\n}\n"],"mappings":";;;;;;;;;;;AAwBA,MAAM,qBAAqB;;AAE3B,MAAM,sBAAsB,iBAAiB,oBAAoB;AACjE,MAAM,sBAAsB;;AAE5B,MAAM,qBAAqB,kBAAkB,WAAW,CAAC,CAAC,OAAO,KAAK,EAAE,KAAK,MAAM,YAAY;CAAE;CAAK;CAAM;AAAK,EAAE;;;;;AAMnH,SAAS,sBAAsB,KAAiC;CAC9D,IAAI,IAAI,aAAa,KAAK,IAAI,cAAA,WAA0C,OAAO;CAC/E,IAAI,IAAI,cAAA,aAA4C,IAAI,SAAS,YAAY,MAAM,OAAO;CAC1F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GACpC,IAAI,IAAI,QAAA,UAA6B;IAGnC,IAAI,sBAAsB,GAAG,GAAG;IAChC,OAAO,KAAK,CACV,cACI,iBAAiB,IAAI,IAAI,oDACzB,mBACN,CAAC;IACD;GACF;GACA,IAAI;GACJ,IAAI;IACF,QAAQ,mBAAmB,GAAG;GAChC,SAAS,OAAO;IACd,OAAO,KAAK,CACV,UAAU,IAAI,IAAI,yBAAyB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAClG,CAAC;IACD;GACF;GACA,OAAO,KAAK,KAAK;GACjB,QAAQ,IAAI,IAAI,KAAK;IAAE,QAAQ;IAAU,UAAU;IAAM,UAAU,KAAK,eAAe,KAAK;GAAE,CAAC;EACjG;EACA,OAAO;GACL,UAAU,gBAAgB,MAAM;GAChC;GACA;EACF;CACF;CAEA,eAAe,OAAiC;EAC9C,OAAO,uBAAuB,gBAAgB,CAAC,KAAK,CAAC,GAAG,KAAK,WAAW;CAC1E;CAEA,UAAU,KAAa,SAAiB,QAAQ,OAAa;EAC3D,IAAI,KAAK,QAAQ,IAAI,GAAG,GAAG;EAC3B,KAAK,QAAQ,IAAI,GAAG;EACpB,IAAI,OAAO;GACT,QAAQ,MAAM,aAAa,SAAS;GACpC;EACF;EACA,KAAK,MAAM,OAAO;CACpB;AACF"}
|
|
@@ -9,8 +9,14 @@ export interface BoardRegistry extends Iterable<[string, InstalledBoard]> {
|
|
|
9
9
|
entries(): MapIterator<[string, InstalledBoard]>;
|
|
10
10
|
}
|
|
11
11
|
export declare const defaultBoards: readonly InstalledBoard[];
|
|
12
|
+
/**
|
|
13
|
+
* Factory's boards: its Work board, then `boards`. Work is always installed; to run another Work,
|
|
14
|
+
* store it under the `work` key with `factory.upsertBoard()`. The exported `workBoard` itself is
|
|
15
|
+
* accepted in `boards` and installed once.
|
|
16
|
+
*/
|
|
12
17
|
export declare function createBoardRegistry(options?: {
|
|
13
18
|
boards?: readonly InstalledBoard[];
|
|
14
|
-
includeDefaultBoards?: boolean;
|
|
15
19
|
}): BoardRegistry;
|
|
20
|
+
/** A registry of exactly `boards`, in order, such as the boards a project stored. */
|
|
21
|
+
export declare function boardRegistryOf(boards: readonly InstalledBoard[]): BoardRegistry;
|
|
16
22
|
//# sourceMappingURL=registry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/boards/registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIzD,MAAM,MAAM,cAAc,GAAG,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7D,MAAM,WAAW,aAAc,SAAQ,QAAQ,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAAC;IAC5C,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,IAAI,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5B,MAAM,IAAI,WAAW,CAAC,cAAc,CAAC,CAAC;IACtC,OAAO,IAAI,WAAW,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;CAClD;AAED,eAAO,MAAM,aAAa,EAAiC,SAAS,cAAc,EAAE,CAAC;AAErF,wBAAgB,mBAAmB,
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/boards/registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIzD,MAAM,MAAM,cAAc,GAAG,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7D,MAAM,WAAW,aAAc,SAAQ,QAAQ,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAAC;IAC5C,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,IAAI,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5B,MAAM,IAAI,WAAW,CAAC,cAAc,CAAC,CAAC;IACtC,OAAO,IAAI,WAAW,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;CAClD;AAED,eAAO,MAAM,aAAa,EAAiC,SAAS,cAAc,EAAE,CAAC;AAErF;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,SAAS,cAAc,EAAE,CAAA;CAAO,GAAG,aAAa,CAYvG;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,GAAG,aAAa,CAwBhF"}
|
package/dist/boards/registry.js
CHANGED
|
@@ -3,10 +3,23 @@ import { reviewBoard } from "./review.js";
|
|
|
3
3
|
import { workBoard } from "./work.js";
|
|
4
4
|
// src/boards/registry.ts
|
|
5
5
|
const defaultBoards = Object.freeze([workBoard]);
|
|
6
|
+
/**
|
|
7
|
+
* Factory's boards: its Work board, then `boards`. Work is always installed; to run another Work,
|
|
8
|
+
* store it under the `work` key with `factory.upsertBoard()`. The exported `workBoard` itself is
|
|
9
|
+
* accepted in `boards` and installed once.
|
|
10
|
+
*/
|
|
6
11
|
function createBoardRegistry(options = {}) {
|
|
7
|
-
const
|
|
12
|
+
const boards = (options.boards ?? []).filter((board) => !defaultBoards.includes(board));
|
|
13
|
+
for (const board of boards) {
|
|
14
|
+
const builtIn = defaultBoards.find((candidate) => candidate.id === board.id);
|
|
15
|
+
if (builtIn) throw new Error(`MastraFactory: board id '${board.id}' is Factory's ${builtIn.name} board, which every project has. To run your own, store it under '${board.id}' with factory.upsertBoard(board, { projects: 'all' }).`);
|
|
16
|
+
}
|
|
17
|
+
return boardRegistryOf([...defaultBoards, ...boards]);
|
|
18
|
+
}
|
|
19
|
+
/** A registry of exactly `boards`, in order, such as the boards a project stored. */
|
|
20
|
+
function boardRegistryOf(boards) {
|
|
8
21
|
const registry = /* @__PURE__ */ new Map();
|
|
9
|
-
for (const board of
|
|
22
|
+
for (const board of boards) {
|
|
10
23
|
if (board.id === "review" && board !== reviewBoard) throw new Error(`MastraFactory: board id '${LEGACY_REVIEW_BOARD}' is reserved for the retired Review board.`);
|
|
11
24
|
if (registry.has(board.id)) throw new Error(`MastraFactory: duplicate board id '${board.id}' in 'boards'.`);
|
|
12
25
|
registry.set(board.id, board);
|
|
@@ -21,6 +34,6 @@ function createBoardRegistry(options = {}) {
|
|
|
21
34
|
[Symbol.iterator]: registry[Symbol.iterator].bind(registry)
|
|
22
35
|
});
|
|
23
36
|
}
|
|
24
|
-
export { createBoardRegistry, defaultBoards };
|
|
37
|
+
export { boardRegistryOf, createBoardRegistry, defaultBoards };
|
|
25
38
|
|
|
26
39
|
//# sourceMappingURL=registry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","names":[],"sources":["../../src/boards/registry.ts"],"sourcesContent":["import { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport type { BoardDefinition } from './define-board.js';\nimport { reviewBoard } from './review.js';\nimport { workBoard } from './work.js';\n\nexport type InstalledBoard = BoardDefinition<string, string>;\nexport interface BoardRegistry extends Iterable<[string, InstalledBoard]> {\n readonly size: number;\n get(id: string): InstalledBoard | undefined;\n has(id: string): boolean;\n keys(): MapIterator<string>;\n values(): MapIterator<InstalledBoard>;\n entries(): MapIterator<[string, InstalledBoard]>;\n}\n\nexport const defaultBoards = Object.freeze([workBoard]) as readonly InstalledBoard[];\n\nexport function createBoardRegistry(
|
|
1
|
+
{"version":3,"file":"registry.js","names":[],"sources":["../../src/boards/registry.ts"],"sourcesContent":["import { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport type { BoardDefinition } from './define-board.js';\nimport { reviewBoard } from './review.js';\nimport { workBoard } from './work.js';\n\nexport type InstalledBoard = BoardDefinition<string, string>;\nexport interface BoardRegistry extends Iterable<[string, InstalledBoard]> {\n readonly size: number;\n get(id: string): InstalledBoard | undefined;\n has(id: string): boolean;\n keys(): MapIterator<string>;\n values(): MapIterator<InstalledBoard>;\n entries(): MapIterator<[string, InstalledBoard]>;\n}\n\nexport const defaultBoards = Object.freeze([workBoard]) as readonly InstalledBoard[];\n\n/**\n * Factory's boards: its Work board, then `boards`. Work is always installed; to run another Work,\n * store it under the `work` key with `factory.upsertBoard()`. The exported `workBoard` itself is\n * accepted in `boards` and installed once.\n */\nexport function createBoardRegistry(options: { boards?: readonly InstalledBoard[] } = {}): BoardRegistry {\n const boards = (options.boards ?? []).filter(board => !defaultBoards.includes(board));\n for (const board of boards) {\n const builtIn = defaultBoards.find(candidate => candidate.id === board.id);\n if (builtIn) {\n throw new Error(\n `MastraFactory: board id '${board.id}' is Factory's ${builtIn.name} board, which every project has. ` +\n `To run your own, store it under '${board.id}' with factory.upsertBoard(board, { projects: 'all' }).`,\n );\n }\n }\n return boardRegistryOf([...defaultBoards, ...boards]);\n}\n\n/** A registry of exactly `boards`, in order, such as the boards a project stored. */\nexport function boardRegistryOf(boards: readonly InstalledBoard[]): BoardRegistry {\n const registry = new Map<string, InstalledBoard>();\n\n for (const board of boards) {\n // The retired Review board is served only as itself, to projects still using it; a new board\n // under its id would take over the cards stored there.\n if (board.id === LEGACY_REVIEW_BOARD && board !== reviewBoard) {\n throw new Error(`MastraFactory: board id '${LEGACY_REVIEW_BOARD}' is reserved for the retired Review board.`);\n }\n if (registry.has(board.id)) {\n throw new Error(`MastraFactory: duplicate board id '${board.id}' in 'boards'.`);\n }\n registry.set(board.id, board);\n }\n\n return Object.freeze({\n size: registry.size,\n get: registry.get.bind(registry),\n has: registry.has.bind(registry),\n keys: registry.keys.bind(registry),\n values: registry.values.bind(registry),\n entries: registry.entries.bind(registry),\n [Symbol.iterator]: registry[Symbol.iterator].bind(registry),\n });\n}\n"],"mappings":";;;;AAeA,MAAa,gBAAgB,OAAO,OAAO,CAAC,SAAS,CAAC;;;;;;AAOtD,SAAgB,oBAAoB,UAAkD,CAAC,GAAkB;CACvG,MAAM,UAAU,QAAQ,UAAU,CAAC,EAAA,CAAG,QAAO,UAAS,CAAC,cAAc,SAAS,KAAK,CAAC;CACpF,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,UAAU,cAAc,MAAK,cAAa,UAAU,OAAO,MAAM,EAAE;EACzE,IAAI,SACF,MAAM,IAAI,MACR,4BAA4B,MAAM,GAAG,iBAAiB,QAAQ,KAAK,oEAC7B,MAAM,GAAG,wDACjD;CAEJ;CACA,OAAO,gBAAgB,CAAC,GAAG,eAAe,GAAG,MAAM,CAAC;AACtD;;AAGA,SAAgB,gBAAgB,QAAkD;CAChF,MAAM,2BAAW,IAAI,IAA4B;CAEjD,KAAK,MAAM,SAAS,QAAQ;EAG1B,IAAI,MAAM,OAAA,YAA8B,UAAU,aAChD,MAAM,IAAI,MAAM,4BAA4B,oBAAoB,4CAA4C;EAE9G,IAAI,SAAS,IAAI,MAAM,EAAE,GACvB,MAAM,IAAI,MAAM,sCAAsC,MAAM,GAAG,eAAe;EAEhF,SAAS,IAAI,MAAM,IAAI,KAAK;CAC9B;CAEA,OAAO,OAAO,OAAO;EACnB,MAAM,SAAS;EACf,KAAK,SAAS,IAAI,KAAK,QAAQ;EAC/B,KAAK,SAAS,IAAI,KAAK,QAAQ;EAC/B,MAAM,SAAS,KAAK,KAAK,QAAQ;EACjC,QAAQ,SAAS,OAAO,KAAK,QAAQ;EACrC,SAAS,SAAS,QAAQ,KAAK,QAAQ;GACtC,OAAO,WAAW,SAAS,OAAO,SAAS,CAAC,KAAK,QAAQ;CAC5D,CAAC;AACH"}
|
|
@@ -39,12 +39,13 @@ export declare function boardForWorkItem(item: Pick<Card, 'board'>): string;
|
|
|
39
39
|
*/
|
|
40
40
|
export declare function boardFlow(board: InstalledBoard | undefined): FactoryRuleBoardFlow;
|
|
41
41
|
/**
|
|
42
|
-
* Where integrations file new items
|
|
43
|
-
*
|
|
42
|
+
* Where integrations file new items, and where one lands when no intake route takes it: the
|
|
43
|
+
* project's Work board's initial phase, else (a project an app gave only its own boards) the
|
|
44
|
+
* initial phase of its first board in catalog order. Undefined only for a project with no boards.
|
|
44
45
|
*/
|
|
45
|
-
export declare function intakeTarget(boards: Pick<BoardRegistry, 'get'>): FactoryRuleIntakeTarget | undefined;
|
|
46
|
+
export declare function intakeTarget(boards: Pick<BoardRegistry, 'get' | 'values'>): FactoryRuleIntakeTarget | undefined;
|
|
46
47
|
/** {@link intakeTarget} as a rule context field. */
|
|
47
|
-
export declare function withIntakeTarget(boards: Pick<BoardRegistry, 'get'>): {
|
|
48
|
+
export declare function withIntakeTarget(boards: Pick<BoardRegistry, 'get' | 'values'>): {
|
|
48
49
|
intake?: FactoryRuleIntakeTarget;
|
|
49
50
|
};
|
|
50
51
|
/** {@link boardFlow} of the board a card sits on. */
|