@mastra/factory 0.29.0-alpha.6 → 0.29.0-alpha.8

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.
Files changed (149) hide show
  1. package/README.md +50 -20
  2. package/dist/boards/board-events.d.ts +23 -0
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +37 -3
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts +6 -4
  7. package/dist/boards/board-writes.d.ts.map +1 -1
  8. package/dist/boards/board-writes.js +9 -6
  9. package/dist/boards/board-writes.js.map +1 -1
  10. package/dist/boards/intake-routing.d.ts +30 -16
  11. package/dist/boards/intake-routing.d.ts.map +1 -1
  12. package/dist/boards/intake-routing.js +41 -28
  13. package/dist/boards/intake-routing.js.map +1 -1
  14. package/dist/boards/project-boards.d.ts +15 -0
  15. package/dist/boards/project-boards.d.ts.map +1 -1
  16. package/dist/boards/project-boards.js +43 -7
  17. package/dist/boards/project-boards.js.map +1 -1
  18. package/dist/factory.d.ts +4 -14
  19. package/dist/factory.d.ts.map +1 -1
  20. package/dist/factory.js +22 -15
  21. package/dist/factory.js.map +1 -1
  22. package/dist/integrations/github/integration.d.ts.map +1 -1
  23. package/dist/integrations/github/integration.js +101 -0
  24. package/dist/integrations/github/integration.js.map +1 -1
  25. package/dist/integrations/github/rules.d.ts.map +1 -1
  26. package/dist/integrations/github/rules.js +7 -3
  27. package/dist/integrations/github/rules.js.map +1 -1
  28. package/dist/integrations/github/sandbox.d.ts +7 -1
  29. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  30. package/dist/integrations/github/sandbox.js +15 -1
  31. package/dist/integrations/github/sandbox.js.map +1 -1
  32. package/dist/integrations/github/session-subscriptions.js +1 -1
  33. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  34. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  35. package/dist/integrations/gitlab/rules.js +2 -1
  36. package/dist/integrations/gitlab/rules.js.map +1 -1
  37. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  38. package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
  39. package/dist/integrations/slack/channel-reply-processor.d.ts +1 -0
  40. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  41. package/dist/integrations/slack/channel-reply-processor.js +4 -1
  42. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  43. package/dist/integrations/slack/run-error-card.js +6 -1
  44. package/dist/integrations/slack/run-error-card.js.map +1 -1
  45. package/dist/links.d.ts +4 -2
  46. package/dist/links.d.ts.map +1 -1
  47. package/dist/links.js +5 -3
  48. package/dist/links.js.map +1 -1
  49. package/dist/routes/boards.d.ts +1 -1
  50. package/dist/routes/boards.d.ts.map +1 -1
  51. package/dist/routes/boards.js.map +1 -1
  52. package/dist/routes/contracts.d.ts +32 -5
  53. package/dist/routes/contracts.d.ts.map +1 -1
  54. package/dist/routes/contracts.js +36 -9
  55. package/dist/routes/contracts.js.map +1 -1
  56. package/dist/routes/intake-check.d.ts.map +1 -1
  57. package/dist/routes/intake-check.js +3 -1
  58. package/dist/routes/intake-check.js.map +1 -1
  59. package/dist/routes/intake-routes.d.ts +0 -3
  60. package/dist/routes/intake-routes.d.ts.map +1 -1
  61. package/dist/routes/intake-routes.js +1 -1
  62. package/dist/routes/intake-routes.js.map +1 -1
  63. package/dist/routes/skills.d.ts +1 -1
  64. package/dist/routes/skills.d.ts.map +1 -1
  65. package/dist/routes/skills.js +92 -28
  66. package/dist/routes/skills.js.map +1 -1
  67. package/dist/routes/surface.d.ts +0 -3
  68. package/dist/routes/surface.d.ts.map +1 -1
  69. package/dist/routes/surface.js +0 -1
  70. package/dist/routes/surface.js.map +1 -1
  71. package/dist/rules/dispatch-errors.d.ts +6 -0
  72. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  73. package/dist/rules/dispatch-errors.js +10 -1
  74. package/dist/rules/dispatch-errors.js.map +1 -1
  75. package/dist/rules/dispatcher.d.ts.map +1 -1
  76. package/dist/rules/dispatcher.js +74 -32
  77. package/dist/rules/dispatcher.js.map +1 -1
  78. package/dist/rules/event-rules.d.ts +3 -2
  79. package/dist/rules/event-rules.d.ts.map +1 -1
  80. package/dist/rules/event-rules.js +5 -3
  81. package/dist/rules/event-rules.js.map +1 -1
  82. package/dist/rules/public-failure-reason.d.ts +11 -0
  83. package/dist/rules/public-failure-reason.d.ts.map +1 -0
  84. package/dist/rules/public-failure-reason.js +136 -0
  85. package/dist/rules/public-failure-reason.js.map +1 -0
  86. package/dist/rules/transition-service.d.ts +13 -0
  87. package/dist/rules/transition-service.d.ts.map +1 -1
  88. package/dist/rules/transition-service.js +5 -1
  89. package/dist/rules/transition-service.js.map +1 -1
  90. package/dist/rules/types.d.ts +12 -0
  91. package/dist/rules/types.d.ts.map +1 -1
  92. package/dist/rules/types.js.map +1 -1
  93. package/dist/rules/validation.d.ts.map +1 -1
  94. package/dist/rules/validation.js +11 -2
  95. package/dist/rules/validation.js.map +1 -1
  96. package/dist/run-error.d.ts +1 -1
  97. package/dist/run-error.d.ts.map +1 -1
  98. package/dist/run-error.js +21 -12
  99. package/dist/run-error.js.map +1 -1
  100. package/dist/session/environment-state-processor.d.ts.map +1 -1
  101. package/dist/session/environment-state-processor.js +6 -2
  102. package/dist/session/environment-state-processor.js.map +1 -1
  103. package/dist/session/session-row-view.js +1 -1
  104. package/dist/session/session-row-view.js.map +1 -1
  105. package/dist/session/source-control-tools.d.ts.map +1 -1
  106. package/dist/session/source-control-tools.js +5 -3
  107. package/dist/session/source-control-tools.js.map +1 -1
  108. package/dist/skills/app-skills.d.ts +3 -2
  109. package/dist/skills/app-skills.d.ts.map +1 -1
  110. package/dist/skills/app-skills.js +5 -3
  111. package/dist/skills/app-skills.js.map +1 -1
  112. package/dist/skills/catalog.d.ts +23 -4
  113. package/dist/skills/catalog.d.ts.map +1 -1
  114. package/dist/skills/catalog.js +61 -28
  115. package/dist/skills/catalog.js.map +1 -1
  116. package/dist/storage/domains/audit/actions.d.ts +1 -1
  117. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  118. package/dist/storage/domains/audit/actions.js +6 -1
  119. package/dist/storage/domains/audit/actions.js.map +1 -1
  120. package/dist/storage/domains/boards/base.d.ts +12 -0
  121. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  122. package/dist/storage/domains/boards/base.js +3 -0
  123. package/dist/storage/domains/boards/base.js.map +1 -1
  124. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  125. package/dist/storage/domains/boards/schemas.js +4 -0
  126. package/dist/storage/domains/boards/schemas.js.map +1 -1
  127. package/dist/storage/domains/skill-overrides/base.d.ts +28 -4
  128. package/dist/storage/domains/skill-overrides/base.d.ts.map +1 -1
  129. package/dist/storage/domains/skill-overrides/base.js +54 -1
  130. package/dist/storage/domains/skill-overrides/base.js.map +1 -1
  131. package/dist/storage/domains/work-items/base.d.ts +2 -0
  132. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  133. package/dist/storage/domains/work-items/base.js +13 -5
  134. package/dist/storage/domains/work-items/base.js.map +1 -1
  135. package/dist/tools/audit-events-tool.d.ts +1 -1
  136. package/dist/tools/read-tools.d.ts.map +1 -1
  137. package/dist/tools/read-tools.js +0 -1
  138. package/dist/tools/read-tools.js.map +1 -1
  139. package/dist/tools/work-item-tools.d.ts.map +1 -1
  140. package/dist/tools/work-item-tools.js +0 -3
  141. package/dist/tools/work-item-tools.js.map +1 -1
  142. package/dist/work-items/create-work-item.d.ts.map +1 -1
  143. package/dist/work-items/create-work-item.js +2 -1
  144. package/dist/work-items/create-work-item.js.map +1 -1
  145. package/dist/workspace.d.ts +5 -1
  146. package/dist/workspace.d.ts.map +1 -1
  147. package/dist/workspace.js +69 -9
  148. package/dist/workspace.js.map +1 -1
  149. package/package.json +8 -8
@@ -62,6 +62,9 @@ function toBoardSource(boards) {
62
62
  function isBoardSource(boards) {
63
63
  return PROJECT_BOARD_SOURCE in boards;
64
64
  }
65
+ const NO_PROJECT_SKILLS = /* @__PURE__ */ new Set();
66
+ /** Recorded when the project's skills couldn't be read; never a stored revision, so the next load rereads them. */
67
+ const UNREAD_SKILLS_REVISION = -1;
65
68
  function scopeKey(scope) {
66
69
  return `${scope.orgId}\0${scope.factoryProjectId}`;
67
70
  }
@@ -108,6 +111,7 @@ var ProjectBoardCache = class {
108
111
  #warned = /* @__PURE__ */ new Set();
109
112
  #seeded = /* @__PURE__ */ new Set();
110
113
  #codeSkills;
114
+ #projectSkills;
111
115
  #seeds;
112
116
  /** Boards the app upserted for every project, which a project with no boards gets before Factory's. */
113
117
  #appBoards = /* @__PURE__ */ new Map();
@@ -122,6 +126,7 @@ var ProjectBoardCache = class {
122
126
  this.#occupiedPhases = options.occupiedPhases;
123
127
  this.#projects = options.projects;
124
128
  this.#codeSkills = options.codeSkills ?? [];
129
+ this.#projectSkills = options.projectSkills;
125
130
  this.#recheckMs = options.recheckMs ?? DEFAULT_RECHECK_MS;
126
131
  this.#now = options.now ?? Date.now;
127
132
  this.#warn = options.warn ?? ((message) => console.warn(`[factory] ${message}`));
@@ -215,6 +220,33 @@ var ProjectBoardCache = class {
215
220
  get codeSkills() {
216
221
  return this.#codeSkills;
217
222
  }
223
+ /**
224
+ * The skills the project created, which its runners may name besides the app's. Throws when they can't be
225
+ * read, so a board write fails with the storage error instead of refusing a skill the project has.
226
+ */
227
+ async projectSkillNames(scope) {
228
+ return this.#projectSkills ? this.#projectSkills.names(scope) : NO_PROJECT_SKILLS;
229
+ }
230
+ /**
231
+ * The names for a load, or undefined when they can't be read: the load still serves the boards, flags their
232
+ * created skills as missing, and doesn't cache what it compiled without them.
233
+ */
234
+ async #readProjectSkillNames(scope) {
235
+ try {
236
+ return await this.projectSkillNames(scope);
237
+ } catch (error) {
238
+ this.#warnOnce(`project-skills:${scopeKey(scope)}`, `Could not read the skills project ${scope.factoryProjectId} created; boards that run them show them as missing: ${error instanceof Error ? error.message : String(error)}`);
239
+ return;
240
+ }
241
+ }
242
+ async #projectSkillsRevision(scope) {
243
+ if (!this.#projectSkills) return 0;
244
+ try {
245
+ return await this.#projectSkills.revision(scope);
246
+ } catch {
247
+ return UNREAD_SKILLS_REVISION;
248
+ }
249
+ }
218
250
  /** Makes the next load reread the project. The loaded boards keep serving sync reads until then. */
219
251
  invalidate(scope) {
220
252
  const key = scopeKey(scope);
@@ -243,16 +275,20 @@ var ProjectBoardCache = class {
243
275
  const current = this.#entries.get(key);
244
276
  const version = await this.#storage.readVersion(scope);
245
277
  const reviewInUse = await this.#reviewBoardInUse?.(scope) ?? false;
246
- if (current && current.version === version && current.reviewInUse === reviewInUse) {
278
+ let skillsRevision = await this.#projectSkillsRevision(scope);
279
+ if (current && current.version === version && current.reviewInUse === reviewInUse && current.skillsRevision === skillsRevision && skillsRevision !== UNREAD_SKILLS_REVISION) {
247
280
  if ((this.#generations.get(key) ?? 0) === generation) current.checkedAt = this.#now();
248
281
  return current.boards;
249
282
  }
250
283
  const snapshot = await this.#consistentSnapshot(scope);
251
- const boards = this.#compile(scope, snapshot.boards, reviewInUse);
284
+ const projectSkills = await this.#readProjectSkillNames(scope);
285
+ if (projectSkills === void 0) skillsRevision = UNREAD_SKILLS_REVISION;
286
+ const boards = this.#compile(scope, snapshot.boards, reviewInUse, projectSkills ?? NO_PROJECT_SKILLS);
252
287
  if ((this.#generations.get(key) ?? 0) === generation) this.#entries.set(key, {
253
288
  boards,
254
289
  version: snapshot.version,
255
290
  reviewInUse,
291
+ skillsRevision,
256
292
  checkedAt: this.#now()
257
293
  });
258
294
  return boards;
@@ -324,7 +360,7 @@ var ProjectBoardCache = class {
324
360
  warn: (message) => this.#warnOnce(`migration:${scopeKey(scope)}:${message}`, `${message} (project ${scope.factoryProjectId})`)
325
361
  };
326
362
  }
327
- #compile(scope, rows, reviewInUse) {
363
+ #compile(scope, rows, reviewInUse, projectSkills) {
328
364
  const byKey = new Map(rows.map((row) => [row.key, row]));
329
365
  const details = new Map(this.#codeDetails);
330
366
  const problems = [];
@@ -354,7 +390,7 @@ var ProjectBoardCache = class {
354
390
  report(row, merged.problems);
355
391
  details.set(code.id, {
356
392
  ...details.get(code.id),
357
- problems: [...merged.problems, ...this.#skillProblems(merged.board)]
393
+ problems: [...merged.problems, ...this.#skillProblems(merged.board, projectSkills)]
358
394
  });
359
395
  boards.push(merged.board);
360
396
  }
@@ -382,7 +418,7 @@ var ProjectBoardCache = class {
382
418
  details.set(row.key, {
383
419
  source: "stored",
384
420
  editable: true,
385
- problems: this.#skillProblems(board)
421
+ problems: this.#skillProblems(board, projectSkills)
386
422
  });
387
423
  }
388
424
  return {
@@ -391,8 +427,8 @@ var ProjectBoardCache = class {
391
427
  problems
392
428
  };
393
429
  }
394
- #skillProblems(board) {
395
- return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills);
430
+ #skillProblems(board, projectSkills) {
431
+ return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills, void 0, projectSkills);
396
432
  }
397
433
  #warnOnce(key, message, debug = false) {
398
434
  if (this.#warned.has(key)) return;
@@ -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, readStoredBoard } 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 type { ReviewBoardInUse } 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;\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 */\nexport function 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}\n\n/**\n * Whether a project has a board of its own under `review`: a stored row other than the seed an\n * earlier release left behind. Cards stored on it are its own; anywhere else they are the retired\n * Review board's. An app that defines the board owns it in a project from when its row is stored\n * there. Without stored boards (`stored: false`) the app's boards are served as they are.\n */\nexport function ownReviewBoard(codeRegistry: BoardRegistry, { stored = true } = {}): ReviewBoardInUse {\n if (!stored) return async () => codeRegistry.has(LEGACY_REVIEW_BOARD);\n return async (ops, scope) => {\n const row = await readStoredBoard(ops, scope, LEGACY_REVIEW_BOARD);\n return row !== null && !isUntouchedReviewSeed(row);\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 /**\n * Stores the Work placement of every card the retired Review board left on `review`, through\n * `ops`. Run in the transaction that stores an app's board under that key in a project.\n */\n releaseReviewCards?: (ops: FactoryStorageOps, scope: StoredBoardScope) => Promise<void>;\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 #releaseReviewCards: ProjectBoardCacheOptions['releaseReviewCards'];\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.#releaseReviewCards = options.releaseReviewCards;\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 const release = this.#releaseReviewCards;\n const review = this.#seeds.get(LEGACY_REVIEW_BOARD);\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 // An app's board under `review` starts without the cards the retired Review board left there.\n before: async (ops, board) => {\n if (board === LEGACY_REVIEW_BOARD) await release?.(ops, scope);\n },\n });\n }\n // The row an earlier release seeded for the retired board becomes the app's board.\n if (review) {\n await this.#storage.adoptSeed(scope, review, {\n when: isUntouchedReviewSeed,\n before: ops => release?.(ops, scope) ?? Promise.resolve(),\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 // Still the retired board's seed: the app's board is served once its row replaces it.\n if (row && code.id === LEGACY_REVIEW_BOARD && isUntouchedReviewSeed(row)) {\n details.delete(code.id);\n continue;\n }\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 // A board of the project's own under the retired Review board's key is served like any other.\n const reviewRow = byKey.get(LEGACY_REVIEW_BOARD);\n const ownsReview = reviewRow !== undefined && !isUntouchedReviewSeed(reviewRow);\n // Served from code and never stored, so nobody edits a board on its way out.\n if (reviewInUse && !ownsReview) {\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 // Factory seeded this row while Review was a built-in board and nobody edited it since:\n // it is not a board the project made, so it is not served.\n if (row.key === LEGACY_REVIEW_BOARD && !ownsReview) continue;\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":";;;;;;;;;;;AAyBA,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;;AAE5B,MAAM,qBAAqB,kBAAkB,WAAW,CAAC,CAAC,OAAO,KAAK,EAAE,KAAK,MAAM,YAAY;CAAE;CAAK;CAAM;AAAK,EAAE;;;;;AAMnH,SAAgB,sBAAsB,KAAiC;CACrE,IAAI,IAAI,aAAa,KAAK,IAAI,cAAA,WAA0C,OAAO;CAC/E,IAAI,IAAI,cAAA,aAA4C,IAAI,SAAS,YAAY,MAAM,OAAO;CAC1F,MAAM,SAAS,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AAuB,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"}
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, readStoredBoard } 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 type { ReviewBoardInUse } 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;\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 */\nexport function 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}\n\n/**\n * Whether a project has a board of its own under `review`: a stored row other than the seed an\n * earlier release left behind. Cards stored on it are its own; anywhere else they are the retired\n * Review board's. An app that defines the board owns it in a project from when its row is stored\n * there. Without stored boards (`stored: false`) the app's boards are served as they are.\n */\nexport function ownReviewBoard(codeRegistry: BoardRegistry, { stored = true } = {}): ReviewBoardInUse {\n if (!stored) return async () => codeRegistry.has(LEGACY_REVIEW_BOARD);\n return async (ops, scope) => {\n const row = await readStoredBoard(ops, scope, LEGACY_REVIEW_BOARD);\n return row !== null && !isUntouchedReviewSeed(row);\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 /** The project's skill revision the boards' skill problems were checked at. */\n skillsRevision: number;\n checkedAt: number;\n}\n\n/**\n * The skills a project created (Settings › Skills), which its boards' runners may name besides the app's.\n * `revision` moves whenever the project's skills change, so loads recheck the names only then.\n */\nexport interface ProjectSkillNames {\n revision(scope: StoredBoardScope): Promise<number>;\n names(scope: StoredBoardScope): Promise<ReadonlySet<string>>;\n}\n\nconst NO_PROJECT_SKILLS: ReadonlySet<string> = new Set();\n/** Recorded when the project's skills couldn't be read; never a stored revision, so the next load rereads them. */\nconst UNREAD_SKILLS_REVISION = -1;\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 /** The skills each project created. Without it, runners may only name the app's skills. */\n projectSkills?: ProjectSkillNames;\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 /**\n * Stores the Work placement of every card the retired Review board left on `review`, through\n * `ops`. Run in the transaction that stores an app's board under that key in a project.\n */\n releaseReviewCards?: (ops: FactoryStorageOps, scope: StoredBoardScope) => Promise<void>;\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 #projectSkills: ProjectSkillNames | undefined;\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 #releaseReviewCards: ProjectBoardCacheOptions['releaseReviewCards'];\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.#releaseReviewCards = options.releaseReviewCards;\n this.#occupiedPhases = options.occupiedPhases;\n this.#projects = options.projects;\n this.#codeSkills = options.codeSkills ?? [];\n this.#projectSkills = options.projectSkills;\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 /**\n * The skills the project created, which its runners may name besides the app's. Throws when they can't be\n * read, so a board write fails with the storage error instead of refusing a skill the project has.\n */\n async projectSkillNames(scope: StoredBoardScope): Promise<ReadonlySet<string>> {\n return this.#projectSkills ? this.#projectSkills.names(scope) : NO_PROJECT_SKILLS;\n }\n\n /**\n * The names for a load, or undefined when they can't be read: the load still serves the boards, flags their\n * created skills as missing, and doesn't cache what it compiled without them.\n */\n async #readProjectSkillNames(scope: StoredBoardScope): Promise<ReadonlySet<string> | undefined> {\n try {\n return await this.projectSkillNames(scope);\n } catch (error) {\n this.#warnOnce(\n `project-skills:${scopeKey(scope)}`,\n `Could not read the skills project ${scope.factoryProjectId} created; boards that run them show them as missing: ${error instanceof Error ? error.message : String(error)}`,\n );\n return undefined;\n }\n }\n\n async #projectSkillsRevision(scope: StoredBoardScope): Promise<number> {\n if (!this.#projectSkills) return 0;\n try {\n return await this.#projectSkills.revision(scope);\n } catch {\n return UNREAD_SKILLS_REVISION;\n }\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 let skillsRevision = await this.#projectSkillsRevision(scope);\n if (\n current &&\n current.version === version &&\n current.reviewInUse === reviewInUse &&\n current.skillsRevision === skillsRevision &&\n skillsRevision !== UNREAD_SKILLS_REVISION\n ) {\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 projectSkills = await this.#readProjectSkillNames(scope);\n // Compiled without the names, the boards flag their skills as missing: the next load reads them again.\n if (projectSkills === undefined) skillsRevision = UNREAD_SKILLS_REVISION;\n const boards = this.#compile(scope, snapshot.boards, reviewInUse, projectSkills ?? NO_PROJECT_SKILLS);\n if ((this.#generations.get(key) ?? 0) === generation) {\n this.#entries.set(key, {\n boards,\n version: snapshot.version,\n reviewInUse,\n skillsRevision,\n checkedAt: this.#now(),\n });\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 const release = this.#releaseReviewCards;\n const review = this.#seeds.get(LEGACY_REVIEW_BOARD);\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 // An app's board under `review` starts without the cards the retired Review board left there.\n before: async (ops, board) => {\n if (board === LEGACY_REVIEW_BOARD) await release?.(ops, scope);\n },\n });\n }\n // The row an earlier release seeded for the retired board becomes the app's board.\n if (review) {\n await this.#storage.adoptSeed(scope, review, {\n when: isUntouchedReviewSeed,\n before: ops => release?.(ops, scope) ?? Promise.resolve(),\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(\n scope: StoredBoardScope,\n rows: readonly StoredBoardRecord[],\n reviewInUse: boolean,\n projectSkills: ReadonlySet<string>,\n ): 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 // Still the retired board's seed: the app's board is served once its row replaces it.\n if (row && code.id === LEGACY_REVIEW_BOARD && isUntouchedReviewSeed(row)) {\n details.delete(code.id);\n continue;\n }\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, projectSkills)],\n });\n boards.push(merged.board);\n }\n // A board of the project's own under the retired Review board's key is served like any other.\n const reviewRow = byKey.get(LEGACY_REVIEW_BOARD);\n const ownsReview = reviewRow !== undefined && !isUntouchedReviewSeed(reviewRow);\n // Served from code and never stored, so nobody edits a board on its way out.\n if (reviewInUse && !ownsReview) {\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 // Factory seeded this row while Review was a built-in board and nobody edited it since:\n // it is not a board the project made, so it is not served.\n if (row.key === LEGACY_REVIEW_BOARD && !ownsReview) continue;\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, projectSkills) });\n }\n return {\n registry: boardRegistryOf(boards),\n details,\n problems,\n };\n }\n\n #skillProblems(board: InstalledBoard, projectSkills?: ReadonlySet<string>): string[] {\n return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills, undefined, projectSkills);\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":";;;;;;;;;;;AAyBA,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;;AAE5B,MAAM,qBAAqB,kBAAkB,WAAW,CAAC,CAAC,OAAO,KAAK,EAAE,KAAK,MAAM,YAAY;CAAE;CAAK;CAAM;AAAK,EAAE;;;;;AAMnH,SAAgB,sBAAsB,KAAiC;CACrE,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,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AE,QAAQ;IAAW,UAAU;IAAO,UAAU,CAAC;GAAE,CAAC;EAClF;EACA,KAAK,MAAM,OAAO,MAAM;GACtB,IAAI,KAAK,aAAa,IAAI,IAAI,GAAG,GAAG;GAGpC,IAAI,IAAI,QAAA,YAA+B,CAAC,YAAY;GACpD,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,OAAO,aAAa;GAAE,CAAC;EAChH;EACA,OAAO;GACL,UAAU,gBAAgB,MAAM;GAChC;GACA;EACF;CACF;CAEA,eAAe,OAAuB,eAA+C;EACnF,OAAO,uBAAuB,gBAAgB,CAAC,KAAK,CAAC,GAAG,KAAK,aAAa,KAAA,GAAW,aAAa;CACpG;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"}
package/dist/factory.d.ts CHANGED
@@ -39,7 +39,7 @@ import type { MastraFactorySandboxOption } from './sandbox/session-sandbox.js';
39
39
  import type { FactorySecretEncryption } from './secret-encryption.js';
40
40
  import type { IdleSessionUnloadOptions } from './session/session-unloader.js';
41
41
  import type { ReviewedChangeRequest } from './session/source-control-tools.js';
42
- import type { IntakeEvaluator, StoredBoardInput, StoredBoardScope } from './storage/domains/boards/base.js';
42
+ import type { StoredBoardInput, StoredBoardScope } from './storage/domains/boards/base.js';
43
43
  import type { FactorySandboxStart } from './workspace.js';
44
44
  /** Constructor args for the `new Mastra(...)` literal in the deploy entry. */
45
45
  export type MastraArgs = NonNullable<ConstructorParameters<typeof Mastra>[0]>;
@@ -183,18 +183,6 @@ export interface MastraFactoryConfig {
183
183
  tools?: FactoryTools;
184
184
  /** Background Factory dispatcher configuration. */
185
185
  dispatcher?: MastraFactoryDispatcherConfig;
186
- /** How intake places a new item. */
187
- intake?: {
188
- /**
189
- * Forces one evaluator on every project. `route-list` runs the project's intake rules as one list
190
- * and files an item no rule takes on Work, else the first board. `intake-order` asks each board
191
- * in the project's intake order and records an item no board takes as Not routed instead.
192
- * Unset (and `FACTORY_INTAKE_EVALUATOR` unset too), each project uses its own setting:
193
- * `intake-order` for a project created since it shipped, `route-list` for an older one until an
194
- * admin switches it. Overrides `FACTORY_INTAKE_EVALUATOR`.
195
- */
196
- evaluator?: IntakeEvaluator;
197
- };
198
186
  /**
199
187
  * Deployment-stable secret for signing integration OAuth `state` values.
200
188
  * Omitted → a per-process random secret, which is fine for single-process
@@ -321,7 +309,9 @@ export declare class MastraFactory {
321
309
  * project gets none. This lasts for the process, so run it at every startup. A Work or app
322
310
  * board's key keeps that board's code behaviour,
323
311
  * so the definition is checked as an edit is; a new key gets none (no tool, source-closed or
324
- * event rules). The board is validated once, as the boards API does, and each write is audited
312
+ * event rules). The board is validated as the boards API validates it; a runner may name a skill a
313
+ * project created in Settings › Skills only when `projects` lists the projects, and each listed
314
+ * project must have it, while a board for `'all'` projects may only run the app's skills. Each write is audited
325
315
  * as `factory.board.created` or `factory.board.updated` by `system:factory`. Refusals throw a
326
316
  * `BoardWriteError` (`invalid_board`, `unknown_skill`, `code_behaviour`, `phase_in_use` when cards
327
317
  * sit in a phase it removes, `board_in_use` when the key is `review` and the retired Review board
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAMH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,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AM,WAAW,6BAA6B;IAC5C,iHAAiH;IACjH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAqID,qBAAa,aAAa;;IA2CxB,YAAY,MAAM,EAAE,mBAAmB,EAgCtC;IAED;;;;OAIG;IACH,IAAI,kBAAkB,IAAI,yBAAyB,GAAG,SAAS,CAI9D;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACG,WAAW,CACf,KAAK,EAAE,gBAAgB,EACvB,OAAO,EAAE;QAAE,QAAQ,EAAE,KAAK,GAAG,SAAS,gBAAgB,EAAE,CAAA;KAAE,GACzD,OAAO,CAAC;QAAE,QAAQ,EAAE,gBAAgB,EAAE,CAAC;QAAC,OAAO,EAAE,gBAAgB,EAAE,CAAC;QAAC,SAAS,EAAE,gBAAgB,EAAE,CAAA;KAAE,CAAC,CA+CvG;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,qBAAqB,CAAC,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAKtG;IAED;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,CAw0DnC;IAED;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA0B9B;IAiBD,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAqD9B;CACF"}
package/dist/factory.js CHANGED
@@ -82,6 +82,7 @@ import { observeSessionThreadTitle } from "./session/thread-title-mirror.js";
82
82
  import { FactoryWorkItemStateProcessor } from "./session/work-item-state-processor.js";
83
83
  import { shareSessionListChanges } from "./session-list-changes.js";
84
84
  import { assertFactorySkills, findBoardSkillProblems } from "./skills/app-skills.js";
85
+ import { projectSkillNamesOf } from "./skills/catalog.js";
85
86
  import { createSpaStaticMiddleware, resolveUiDistDir } from "./spa-static.js";
86
87
  import { createStateSigner } from "./state-signing.js";
87
88
  import { observeAgentGitAction } from "./storage/domains/audit/agent-audit.js";
@@ -254,7 +255,7 @@ var MastraFactory = class {
254
255
  #boards;
255
256
  /** Each project's boards: the code boards plus the boards it stored. Undefined until `prepare()` or when the boards domain is down. */
256
257
  #projectBoards;
257
- /** The evaluator forced on every project, if any; see `MastraFactoryConfig.intake`. */
258
+ /** The evaluator forced on every project by `FACTORY_INTAKE_EVALUATOR`, if set. */
258
259
  #forcedIntake;
259
260
  /** Writes to stored boards for `upsertBoard()`; undefined until `prepare()` or when the boards domain is down. */
260
261
  #boardStore;
@@ -291,8 +292,9 @@ var MastraFactory = class {
291
292
  this.#boards = createBoardRegistry({ boards: config.boards });
292
293
  warnDefinedBoards(this.#boards);
293
294
  if ("rules" in config) throw new Error("MastraFactory: 'rules' was removed. Set 'configVersion' for the audit label and declare tool-result rules on the owning board (`tools`).");
295
+ if ("intake" in config) throw new Error("MastraFactory: 'intake' was removed. New projects use the intake order; to force an evaluator on every project set FACTORY_INTAKE_EVALUATOR (`intake-order` or `route-list`) on every replica.");
294
296
  this.#skills = assertFactorySkills(config.skills);
295
- this.#forcedIntake = intakeEvaluatorFrom(config.intake?.evaluator, process.env);
297
+ this.#forcedIntake = intakeEvaluatorFrom(process.env);
296
298
  for (const problem of findBoardSkillProblems(this.#boards, this.#skills)) console.warn(`[factory] ${problem}`);
297
299
  this.#configVersion = assertFactoryConfigVersion(config.configVersion ?? "factory-config-v1");
298
300
  this.#config = config;
@@ -318,7 +320,9 @@ var MastraFactory = class {
318
320
  * project gets none. This lasts for the process, so run it at every startup. A Work or app
319
321
  * board's key keeps that board's code behaviour,
320
322
  * so the definition is checked as an edit is; a new key gets none (no tool, source-closed or
321
- * event rules). The board is validated once, as the boards API does, and each write is audited
323
+ * event rules). The board is validated as the boards API validates it; a runner may name a skill a
324
+ * project created in Settings › Skills only when `projects` lists the projects, and each listed
325
+ * project must have it, while a board for `'all'` projects may only run the app's skills. Each write is audited
322
326
  * as `factory.board.created` or `factory.board.updated` by `system:factory`. Refusals throw a
323
327
  * `BoardWriteError` (`invalid_board`, `unknown_skill`, `code_behaviour`, `phase_in_use` when cards
324
328
  * sit in a phase it removes, `board_in_use` when the key is `review` and the retired Review board
@@ -347,7 +351,7 @@ var MastraFactory = class {
347
351
  const store = this.#boardStore;
348
352
  if (!store) throw new Error(this.#preparing ? "MastraFactory.upsertBoard(): the boards storage isn't available, so boards can't be stored." : "MastraFactory.upsertBoard() needs prepare() first.");
349
353
  const { writes, boards, projects, audit } = store;
350
- const input = writes.validate(board);
354
+ const input = writes.validate(board, options.projects === "all" ? void 0 : null);
351
355
  writes.refuseCodeBoard(input.key, "edit");
352
356
  await projects.ensureReady();
353
357
  let scopes;
@@ -359,13 +363,16 @@ var MastraFactory = class {
359
363
  }));
360
364
  } else {
361
365
  scopes = [...options.projects];
362
- for (const scope of scopes) if (!await projects.get({
363
- orgId: scope.orgId,
364
- id: scope.factoryProjectId
365
- })) throw new BoardWriteError(404, {
366
- error: "project_not_found",
367
- message: `Project "${scope.factoryProjectId}" does not exist.`
368
- });
366
+ for (const scope of scopes) {
367
+ if (!await projects.get({
368
+ orgId: scope.orgId,
369
+ id: scope.factoryProjectId
370
+ })) throw new BoardWriteError(404, {
371
+ error: "project_not_found",
372
+ message: `Project "${scope.factoryProjectId}" does not exist.`
373
+ });
374
+ writes.validate(input, await boards.projectSkillNames(scope));
375
+ }
369
376
  }
370
377
  const result = {
371
378
  inserted: [],
@@ -590,6 +597,7 @@ var MastraFactory = class {
590
597
  storage: storedBoardsStorage,
591
598
  projects: factoryProjectsStorage,
592
599
  codeSkills: this.#skills,
600
+ ...storage.isDomainReady("skill-overrides") ? { projectSkills: projectSkillNamesOf(skillOverridesStorage) } : {},
593
601
  ...storage.isDomainReady("work-items") ? {
594
602
  reviewBoardInUse: (scope) => workItemsStorage.reviewBoardInUse(scope),
595
603
  releaseReviewCards: (ops, scope) => workItemsStorage.releaseReviewCards(ops, scope, { open: "move" }),
@@ -855,7 +863,7 @@ var MastraFactory = class {
855
863
  workItems: workItemsStorage,
856
864
  audit: auditStorage,
857
865
  boards,
858
- intakeEvaluator: this.#forcedIntake?.evaluator,
866
+ intakeEvaluator: this.#forcedIntake,
859
867
  ...this.#projectBoards ? { intakeRoutes: storedBoardsStorage } : {},
860
868
  transitionService,
861
869
  auditRecorder: auditDomain,
@@ -1431,8 +1439,7 @@ var MastraFactory = class {
1431
1439
  knowledgeKey: this.#config.knowledge?.key,
1432
1440
  configVersion,
1433
1441
  boardRegistry: boards,
1434
- intakeEvaluator: this.#forcedIntake?.evaluator,
1435
- intakeEvaluatorSource: this.#forcedIntake?.source,
1442
+ intakeEvaluator: this.#forcedIntake,
1436
1443
  ...this.#projectBoards ? { storedBoards: {
1437
1444
  storage: storedBoardsStorage,
1438
1445
  cache: this.#projectBoards
@@ -1446,7 +1453,7 @@ var MastraFactory = class {
1446
1453
  storage: storage.getDomain("work-items"),
1447
1454
  audit: auditDomain,
1448
1455
  boards,
1449
- intakeEvaluator: this.#forcedIntake?.evaluator,
1456
+ intakeEvaluator: this.#forcedIntake,
1450
1457
  ...this.#projectBoards ? { intakeRoutes: storedBoardsStorage } : {},
1451
1458
  maxInFlight: this.#config.dispatcher?.maxInFlight,
1452
1459
  maxInteractiveInFlight: this.#config.dispatcher?.maxInteractiveInFlight,