@mastra/factory 0.28.0-alpha.13 → 0.28.0-alpha.15

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 (123) hide show
  1. package/README.md +43 -28
  2. package/dist/boards/board-writes.d.ts +3 -3
  3. package/dist/boards/board-writes.d.ts.map +1 -1
  4. package/dist/boards/board-writes.js +24 -20
  5. package/dist/boards/board-writes.js.map +1 -1
  6. package/dist/boards/project-boards.d.ts +20 -0
  7. package/dist/boards/project-boards.d.ts.map +1 -1
  8. package/dist/boards/project-boards.js +35 -11
  9. package/dist/boards/project-boards.js.map +1 -1
  10. package/dist/boards/registry.d.ts.map +1 -1
  11. package/dist/boards/registry.js +0 -3
  12. package/dist/boards/registry.js.map +1 -1
  13. package/dist/environment/build-runner.d.ts +13 -2
  14. package/dist/environment/build-runner.d.ts.map +1 -1
  15. package/dist/environment/build-runner.js +42 -0
  16. package/dist/environment/build-runner.js.map +1 -1
  17. package/dist/environment/build-workflow.d.ts +6 -4
  18. package/dist/environment/build-workflow.d.ts.map +1 -1
  19. package/dist/environment/build-workflow.js +70 -66
  20. package/dist/environment/build-workflow.js.map +1 -1
  21. package/dist/environment/build.d.ts +19 -4
  22. package/dist/environment/build.d.ts.map +1 -1
  23. package/dist/environment/build.js +70 -14
  24. package/dist/environment/build.js.map +1 -1
  25. package/dist/factory.d.ts +5 -2
  26. package/dist/factory.d.ts.map +1 -1
  27. package/dist/factory.js +29 -24
  28. package/dist/factory.js.map +1 -1
  29. package/dist/integrations/github/sandbox-release.d.ts +12 -0
  30. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  31. package/dist/integrations/github/sandbox-release.js +16 -1
  32. package/dist/integrations/github/sandbox-release.js.map +1 -1
  33. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  34. package/dist/integrations/platform/github/integration.js +24 -12
  35. package/dist/integrations/platform/github/integration.js.map +1 -1
  36. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  37. package/dist/integrations/platform/jira/integration.js +5 -1
  38. package/dist/integrations/platform/jira/integration.js.map +1 -1
  39. package/dist/routes/board-snapshot.d.ts +5 -0
  40. package/dist/routes/board-snapshot.d.ts.map +1 -1
  41. package/dist/routes/board-snapshot.js +12 -1
  42. package/dist/routes/board-snapshot.js.map +1 -1
  43. package/dist/routes/boards.d.ts +2 -3
  44. package/dist/routes/boards.d.ts.map +1 -1
  45. package/dist/routes/boards.js.map +1 -1
  46. package/dist/routes/contracts.d.ts +66 -0
  47. package/dist/routes/contracts.d.ts.map +1 -1
  48. package/dist/routes/contracts.js +41 -1
  49. package/dist/routes/contracts.js.map +1 -1
  50. package/dist/routes/projects.d.ts.map +1 -1
  51. package/dist/routes/projects.js +5 -0
  52. package/dist/routes/projects.js.map +1 -1
  53. package/dist/routes/sandbox-envs.d.ts +2 -0
  54. package/dist/routes/sandbox-envs.d.ts.map +1 -1
  55. package/dist/routes/sandbox-envs.js +3 -0
  56. package/dist/routes/sandbox-envs.js.map +1 -1
  57. package/dist/routes/source-control-settings.d.ts +2 -0
  58. package/dist/routes/source-control-settings.d.ts.map +1 -1
  59. package/dist/routes/source-control-settings.js +5 -0
  60. package/dist/routes/source-control-settings.js.map +1 -1
  61. package/dist/routes/surface.d.ts +2 -0
  62. package/dist/routes/surface.d.ts.map +1 -1
  63. package/dist/routes/surface.js +2 -1
  64. package/dist/routes/surface.js.map +1 -1
  65. package/dist/routes/work-item-activity.d.ts +11 -0
  66. package/dist/routes/work-item-activity.d.ts.map +1 -0
  67. package/dist/routes/work-item-activity.js +25 -0
  68. package/dist/routes/work-item-activity.js.map +1 -0
  69. package/dist/routes/work-item-starters.d.ts +29 -0
  70. package/dist/routes/work-item-starters.d.ts.map +1 -0
  71. package/dist/routes/work-item-starters.js +169 -0
  72. package/dist/routes/work-item-starters.js.map +1 -0
  73. package/dist/routes/work-items.d.ts.map +1 -1
  74. package/dist/routes/work-items.js +59 -1
  75. package/dist/routes/work-items.js.map +1 -1
  76. package/dist/rules/dispatcher.d.ts.map +1 -1
  77. package/dist/rules/dispatcher.js +49 -14
  78. package/dist/rules/dispatcher.js.map +1 -1
  79. package/dist/rules/transition-service.d.ts +20 -2
  80. package/dist/rules/transition-service.d.ts.map +1 -1
  81. package/dist/rules/transition-service.js +40 -18
  82. package/dist/rules/transition-service.js.map +1 -1
  83. package/dist/sandbox/context-sandboxes.d.ts +70 -0
  84. package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
  85. package/dist/sandbox/context-sandboxes.js +120 -0
  86. package/dist/sandbox/context-sandboxes.js.map +1 -0
  87. package/dist/sandbox/session-retirement.d.ts +11 -4
  88. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  89. package/dist/sandbox/session-retirement.js +39 -13
  90. package/dist/sandbox/session-retirement.js.map +1 -1
  91. package/dist/storage/domains/boards/base.d.ts +25 -5
  92. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  93. package/dist/storage/domains/boards/base.js +57 -20
  94. package/dist/storage/domains/boards/base.js.map +1 -1
  95. package/dist/storage/domains/projects/base.d.ts +8 -2
  96. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  97. package/dist/storage/domains/projects/base.js +21 -4
  98. package/dist/storage/domains/projects/base.js.map +1 -1
  99. package/dist/storage/domains/work-items/base.d.ts +17 -4
  100. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  101. package/dist/storage/domains/work-items/base.js +24 -4
  102. package/dist/storage/domains/work-items/base.js.map +1 -1
  103. package/dist/storage/domains/work-items/legacy-review.d.ts +19 -1
  104. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -1
  105. package/dist/storage/domains/work-items/legacy-review.js +47 -2
  106. package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
  107. package/dist/tools/annotations.d.ts.map +1 -1
  108. package/dist/tools/annotations.js +4 -0
  109. package/dist/tools/annotations.js.map +1 -1
  110. package/dist/tools/audit-events-tool.d.ts +29 -0
  111. package/dist/tools/audit-events-tool.d.ts.map +1 -0
  112. package/dist/tools/audit-events-tool.js +180 -0
  113. package/dist/tools/audit-events-tool.js.map +1 -0
  114. package/dist/tools/index.d.ts +2 -1
  115. package/dist/tools/index.d.ts.map +1 -1
  116. package/dist/tools/index.js +2 -0
  117. package/dist/tools/index.js.map +1 -1
  118. package/dist/tools/permissions.d.ts.map +1 -1
  119. package/dist/tools/permissions.js +1 -0
  120. package/dist/tools/permissions.js.map +1 -1
  121. package/dist/tools/sessions-state-processor.js +1 -1
  122. package/dist/tools/sessions-state-processor.js.map +1 -1
  123. package/package.json +9 -9
@@ -5,13 +5,20 @@ import type { WorkItemDbRow, WorkItemStageEntry } from './base.js';
5
5
  * still holds a card stored on it that isn't Done or Canceled ({@link readReviewBoardInUse});
6
6
  * there its cards stay on Review. In every other project it is redundant: reads present its
7
7
  * rows as Work cards, with the old `review` phase shown as Work's `pr-review`, and the next
8
- * ordinary write stores the Work placement. Rows are never rewritten in bulk.
8
+ * ordinary write stores the Work placement. The rows are rewritten together only when the project
9
+ * gets a board of its own under the key ({@link releaseLegacyReviewCards}).
9
10
  */
10
11
  export declare const LEGACY_REVIEW_BOARD = "review";
11
12
  export interface ReviewBoardScope {
12
13
  orgId: string;
13
14
  factoryProjectId: string;
14
15
  }
16
+ /** A board can't take the key `review` yet: the retired Review board still holds open cards. */
17
+ export declare class ReviewBoardInUseError extends Error {
18
+ readonly cards: number;
19
+ name: string;
20
+ constructor(cards: number);
21
+ }
15
22
  /** Answers whether a project still uses the Review board, reading through the caller's `ops`. */
16
23
  export type ReviewBoardInUse = (ops: FactoryStorageOps, scope: ReviewBoardScope) => Promise<boolean>;
17
24
  /**
@@ -23,6 +30,17 @@ export declare function readReviewBoardInUse(ops: FactoryStorageOps, scope: Revi
23
30
  split: boolean;
24
31
  legacy: boolean;
25
32
  }): Promise<boolean>;
33
+ /**
34
+ * Stores the Work placement of every card stored on `review`, the way an ordinary write to such a
35
+ * card does, so a board about to take the key starts with none of the retired Review board's
36
+ * cards. `open` says what happens to cards that aren't Done or Canceled: `refuse` throws
37
+ * {@link ReviewBoardInUseError} and writes nothing, `move` takes them to Work too. Returns how
38
+ * many rows it rewrote.
39
+ */
40
+ export declare function releaseLegacyReviewCards(ops: FactoryStorageOps, scope: ReviewBoardScope, tables: {
41
+ split: boolean;
42
+ legacy: boolean;
43
+ }, open: 'refuse' | 'move'): Promise<number>;
26
44
  /**
27
45
  * Work's keys, for rows written when Work was the only board: they carry no board, or Work's,
28
46
  * and their phases are Work's by name. Only migrations and legacy writers read these.
@@ -1 +1 @@
1
- {"version":3,"file":"legacy-review.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/legacy-review.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAqC,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEjG,OAAO,KAAK,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAGnE;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,WAAW,CAAC;AAE5C,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,iGAAiG;AACjG,MAAM,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,iBAAiB,EAAE,KAAK,EAAE,gBAAgB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAQrG;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,GAAG,EAAE,iBAAiB,EACtB,KAAK,EAAE,gBAAgB,EACvB,MAAM,GAAE;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAmC,GAC3E,OAAO,CAAC,OAAO,CAAC,CA0BlB;AAID;;;GAGG;AACH,eAAO,MAAM,iBAAiB,SAAS,CAAC;AACxC,eAAO,MAAM,mBAAmB,WAAW,CAAC;AAC5C,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAE1C;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,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,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,OAAO,CAAA;CAAE,EAC1E,OAAO,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,GAC7E;IAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,kBAAkB,EAAE,CAAA;CAAE,CASjF;AAED,yEAAyE;AACzE,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAYrE"}
@@ -5,9 +5,19 @@ import { FACTORY_BOARD_ITEMS_SCHEMA, WORK_ITEMS_SCHEMA } from "./work-item-schem
5
5
  * still holds a card stored on it that isn't Done or Canceled ({@link readReviewBoardInUse});
6
6
  * there its cards stay on Review. In every other project it is redundant: reads present its
7
7
  * rows as Work cards, with the old `review` phase shown as Work's `pr-review`, and the next
8
- * ordinary write stores the Work placement. Rows are never rewritten in bulk.
8
+ * ordinary write stores the Work placement. The rows are rewritten together only when the project
9
+ * gets a board of its own under the key ({@link releaseLegacyReviewCards}).
9
10
  */
10
11
  const LEGACY_REVIEW_BOARD = "review";
12
+ /** A board can't take the key `review` yet: the retired Review board still holds open cards. */
13
+ var ReviewBoardInUseError = class extends Error {
14
+ cards;
15
+ name = "ReviewBoardInUseError";
16
+ constructor(cards) {
17
+ super(`The retired Review board still has ${cards} open ${cards === 1 ? "card" : "cards"}; move or finish ${cards === 1 ? "it" : "them"} before a board takes the key "review".`);
18
+ this.cards = cards;
19
+ }
20
+ };
11
21
  function openOnReview(row) {
12
22
  return row.board === "review" && (row.stages ?? []).some((stage) => stage !== "done" && stage !== "canceled");
13
23
  }
@@ -44,6 +54,41 @@ async function readReviewBoardInUse(ops, scope, tables = {
44
54
  }
45
55
  const REVIEW_IN_USE_PAGE = 100;
46
56
  /**
57
+ * Stores the Work placement of every card stored on `review`, the way an ordinary write to such a
58
+ * card does, so a board about to take the key starts with none of the retired Review board's
59
+ * cards. `open` says what happens to cards that aren't Done or Canceled: `refuse` throws
60
+ * {@link ReviewBoardInUseError} and writes nothing, `move` takes them to Work too. Returns how
61
+ * many rows it rewrote.
62
+ */
63
+ async function releaseLegacyReviewCards(ops, scope, tables, open) {
64
+ const where = {
65
+ org_id: scope.orgId,
66
+ factory_project_id: scope.factoryProjectId,
67
+ board: LEGACY_REVIEW_BOARD
68
+ };
69
+ const found = [];
70
+ for (const collection of [...tables.split ? [FACTORY_BOARD_ITEMS_SCHEMA.name] : [], ...tables.legacy ? [WORK_ITEMS_SCHEMA.name] : []]) found.push({
71
+ collection,
72
+ rows: await ops.findMany(collection, where)
73
+ });
74
+ if (open === "refuse") {
75
+ const stillOpen = new Set(found.flatMap(({ rows }) => rows.filter(openOnReview).map((row) => row.id)));
76
+ if (stillOpen.size > 0) throw new ReviewBoardInUseError(stillOpen.size);
77
+ }
78
+ let rewritten = 0;
79
+ for (const { collection, rows } of found) for (const { id } of rows) if (await ops.updateAtomic(collection, {
80
+ id,
81
+ board: "review"
82
+ }, (current) => {
83
+ if (open === "refuse" && openOnReview(current)) throw new ReviewBoardInUseError(1);
84
+ return normalizeLegacyReviewColumns({
85
+ ...current,
86
+ stages: current.stages ?? []
87
+ }, {});
88
+ })) rewritten += 1;
89
+ return rewritten;
90
+ }
91
+ /**
47
92
  * Work's keys, for rows written when Work was the only board: they carry no board, or Work's,
48
93
  * and their phases are Work's by name. Only migrations and legacy writers read these.
49
94
  */
@@ -104,6 +149,6 @@ function widenLegacyReviewBoardFilter(filter) {
104
149
  };
105
150
  return filter;
106
151
  }
107
- export { LEGACY_REST_PHASE, LEGACY_REVIEW_BOARD, LEGACY_TRIAGE_PHASE, LEGACY_WORK_BOARD, isLegacyReviewPlacement, normalizeLegacyReviewColumns, readLegacyReviewRow, readReviewBoardInUse, widenLegacyReviewBoardFilter };
152
+ export { LEGACY_REST_PHASE, LEGACY_REVIEW_BOARD, LEGACY_TRIAGE_PHASE, LEGACY_WORK_BOARD, ReviewBoardInUseError, isLegacyReviewPlacement, normalizeLegacyReviewColumns, readLegacyReviewRow, readReviewBoardInUse, releaseLegacyReviewCards, widenLegacyReviewBoardFilter };
108
153
 
109
154
  //# sourceMappingURL=legacy-review.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"legacy-review.js","names":[],"sources":["../../../../src/storage/domains/work-items/legacy-review.ts"],"sourcesContent":["import type { CollectionCursor, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\n\nimport type { WorkItemDbRow, WorkItemStageEntry } from './base.js';\nimport { FACTORY_BOARD_ITEMS_SCHEMA, WORK_ITEMS_SCHEMA } from './work-item-schema.js';\n\n/**\n * The retired built-in Review board. New projects never get it. A project keeps it while it\n * still holds a card stored on it that isn't Done or Canceled ({@link readReviewBoardInUse});\n * there its cards stay on Review. In every other project it is redundant: reads present its\n * rows as Work cards, with the old `review` phase shown as Work's `pr-review`, and the next\n * ordinary write stores the Work placement. Rows are never rewritten in bulk.\n */\nexport const LEGACY_REVIEW_BOARD = 'review';\n\nexport interface ReviewBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\n/** Answers whether a project still uses the Review board, reading through the caller's `ops`. */\nexport type ReviewBoardInUse = (ops: FactoryStorageOps, scope: ReviewBoardScope) => Promise<boolean>;\n\nfunction openOnReview(row: { board: string | null; stages: readonly string[] | null }): boolean {\n return (\n row.board === LEGACY_REVIEW_BOARD && (row.stages ?? []).some(stage => stage !== 'done' && stage !== 'canceled')\n );\n}\n\n/**\n * Whether the project still uses the Review board: a card stored on it is in a phase other than\n * Done or Canceled. `tables` names where cards live: the split board items, the legacy table, or\n * both while legacy cards are still being copied.\n */\nexport async function readReviewBoardInUse(\n ops: FactoryStorageOps,\n scope: ReviewBoardScope,\n tables: { split: boolean; legacy: boolean } = { split: true, legacy: false },\n): Promise<boolean> {\n const where: CollectionWhere = {\n org_id: scope.orgId,\n factory_project_id: scope.factoryProjectId,\n board: LEGACY_REVIEW_BOARD,\n };\n const collections = [\n ...(tables.split ? [FACTORY_BOARD_ITEMS_SCHEMA.name] : []),\n ...(tables.legacy ? [WORK_ITEMS_SCHEMA.name] : []),\n ];\n // Paged so a project with an open card answers from the first page instead of reading every Review row.\n const orderBy: [string, 'asc'][] = [['id', 'asc']];\n for (const collection of collections) {\n let cursor: CollectionCursor | undefined;\n for (;;) {\n const rows = await ops.findMany<{ id: string; board: string | null; stages: string[] | null }>(\n collection,\n where,\n { orderBy, limit: REVIEW_IN_USE_PAGE, ...(cursor ? { cursor } : {}) },\n );\n if (rows.some(openOnReview)) return true;\n if (rows.length < REVIEW_IN_USE_PAGE) break;\n cursor = { values: [rows[rows.length - 1]!.id] };\n }\n }\n return false;\n}\n\nconst REVIEW_IN_USE_PAGE = 100;\n\n/**\n * Work's keys, for rows written when Work was the only board: they carry no board, or Work's,\n * and their phases are Work's by name. Only migrations and legacy writers read these.\n */\nexport const LEGACY_WORK_BOARD = 'work';\nexport const LEGACY_TRIAGE_PHASE = 'triage';\nexport const LEGACY_REST_PHASE = 'intake';\n\n/**\n * Whether a stored placement belongs to the retired Review board: stored on it, or a\n * pull request's own card from before boards were persisted, which sat on Review.\n */\nexport function isLegacyReviewPlacement(board: string | null, primarySourceType: string | undefined): boolean {\n return board === LEGACY_REVIEW_BOARD || (board === null && primarySourceType === 'pull-request');\n}\n\nfunction workStage(stage: string): string {\n return stage === 'review' ? 'pr-review' : stage;\n}\n\nfunction workStages(stages: readonly string[]): string[] {\n return stages.map(workStage);\n}\n\nfunction workStageHistory(history: readonly WorkItemStageEntry[] | null | undefined): WorkItemStageEntry[] {\n return (history ?? []).map(entry => (entry.stage === 'review' ? { ...entry, stage: 'pr-review' } : entry));\n}\n\n/**\n * A row as its project sees it. In a project that keeps Review (`reviewInUse`), a row stored on\n * it stays there; otherwise a Review placement reads as Work, `review` as `pr-review`.\n */\nexport function readLegacyReviewRow<\n Row extends Pick<WorkItemDbRow, 'board' | 'stages' | 'stage_history' | 'work_item_sources'>,\n>(row: Row, reviewInUse = false): Row {\n if (!isLegacyReviewPlacement(row.board, row.work_item_sources?.[0]?.source_type)) return row;\n if (reviewInUse && row.board === LEGACY_REVIEW_BOARD) return row;\n return { ...row, board: 'work', stages: workStages(row.stages), stage_history: workStageHistory(row.stage_history) };\n}\n\n/**\n * Columns that store a legacy Review row's placement as Work, merged over the\n * columns a write already sets. Values a write passes are already in Work's\n * vocabulary (the caller read the aliased row); only stored ones are translated.\n */\nexport function normalizeLegacyReviewColumns(\n stored: { board: string | null; stages: string[]; stage_history: unknown },\n columns: { board?: string | null; stages?: string[]; stage_history?: unknown },\n): { board: string | null; stages: string[]; stage_history: WorkItemStageEntry[] } {\n const board = columns.board === undefined || columns.board === LEGACY_REVIEW_BOARD ? 'work' : columns.board;\n return {\n board,\n stages: columns.stages ?? workStages(stored.stages),\n stage_history:\n (columns.stage_history as WorkItemStageEntry[] | undefined) ??\n workStageHistory(stored.stage_history as WorkItemStageEntry[] | null | undefined),\n };\n}\n\n/** Widen a board filter so stored legacy Review rows answer for Work. */\nexport function widenLegacyReviewBoardFilter(filter: unknown): unknown {\n if (filter === 'work') return { in: ['work', LEGACY_REVIEW_BOARD] };\n if (\n filter &&\n typeof filter === 'object' &&\n 'in' in filter &&\n Array.isArray(filter.in) &&\n filter.in.includes('work')\n ) {\n return { ...filter, in: [...new Set([...filter.in, LEGACY_REVIEW_BOARD])] };\n }\n return filter;\n}\n"],"mappings":";;;;;;;;;AAYA,MAAa,sBAAsB;AAUnC,SAAS,aAAa,KAA0E;CAC9F,OACE,IAAI,UAAA,aAAkC,IAAI,UAAU,CAAC,EAAA,CAAG,MAAK,UAAS,UAAU,UAAU,UAAU,UAAU;AAElH;;;;;;AAOA,eAAsB,qBACpB,KACA,OACA,SAA8C;CAAE,OAAO;CAAM,QAAQ;AAAM,GACzD;CAClB,MA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OAAO;EAAE,GAAG;EAAK,OAAO;EAAQ,QAAQ,WAAW,IAAI,MAAM;EAAG,eAAe,iBAAiB,IAAI,aAAa;CAAE;AACrH;;;;;;AAOA,SAAgB,6BACd,QACA,SACiF;CAEjF,OAAO;EACL,OAFY,QAAQ,UAAU,KAAA,KAAa,QAAQ,UAAA,WAAgC,SAAS,QAAQ;EAGpG,QAAQ,QAAQ,UAAU,WAAW,OAAO,MAAM;EAClD,eACG,QAAQ,iBACT,iBAAiB,OAAO,aAAwD;CACpF;AACF;;AAGA,SAAgB,6BAA6B,QAA0B;CACrE,IAAI,WAAW,QAAQ,OAAO,EAAE,IAAI,CAAC,QAAQ,mBAAmB,EAAE;CAClE,IACE,UACA,OAAO,WAAW,YAClB,QAAQ,UACR,MAAM,QAAQ,OAAO,EAAE,KACvB,OAAO,GAAG,SAAS,MAAM,GAEzB,OAAO;EAAE,GAAG;EAAQ,IAAI,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,OAAO,IAAI,mBAAmB,CAAC,CAAC;CAAE;CAE5E,OAAO;AACT"}
1
+ {"version":3,"file":"legacy-review.js","names":[],"sources":["../../../../src/storage/domains/work-items/legacy-review.ts"],"sourcesContent":["import type { CollectionCursor, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\n\nimport type { WorkItemDbRow, WorkItemStageEntry } from './base.js';\nimport { FACTORY_BOARD_ITEMS_SCHEMA, WORK_ITEMS_SCHEMA } from './work-item-schema.js';\n\n/**\n * The retired built-in Review board. New projects never get it. A project keeps it while it\n * still holds a card stored on it that isn't Done or Canceled ({@link readReviewBoardInUse});\n * there its cards stay on Review. In every other project it is redundant: reads present its\n * rows as Work cards, with the old `review` phase shown as Work's `pr-review`, and the next\n * ordinary write stores the Work placement. The rows are rewritten together only when the project\n * gets a board of its own under the key ({@link releaseLegacyReviewCards}).\n */\nexport const LEGACY_REVIEW_BOARD = 'review';\n\nexport interface ReviewBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\n/** A board can't take the key `review` yet: the retired Review board still holds open cards. */\nexport class ReviewBoardInUseError extends Error {\n override name = 'ReviewBoardInUseError';\n constructor(readonly cards: number) {\n super(\n `The retired Review board still has ${cards} open ${cards === 1 ? 'card' : 'cards'}; move or finish ${\n cards === 1 ? 'it' : 'them'\n } before a board takes the key \"review\".`,\n );\n }\n}\n\n/** Answers whether a project still uses the Review board, reading through the caller's `ops`. */\nexport type ReviewBoardInUse = (ops: FactoryStorageOps, scope: ReviewBoardScope) => Promise<boolean>;\n\nfunction openOnReview(row: { board: string | null; stages: readonly string[] | null }): boolean {\n return (\n row.board === LEGACY_REVIEW_BOARD && (row.stages ?? []).some(stage => stage !== 'done' && stage !== 'canceled')\n );\n}\n\n/**\n * Whether the project still uses the Review board: a card stored on it is in a phase other than\n * Done or Canceled. `tables` names where cards live: the split board items, the legacy table, or\n * both while legacy cards are still being copied.\n */\nexport async function readReviewBoardInUse(\n ops: FactoryStorageOps,\n scope: ReviewBoardScope,\n tables: { split: boolean; legacy: boolean } = { split: true, legacy: false },\n): Promise<boolean> {\n const where: CollectionWhere = {\n org_id: scope.orgId,\n factory_project_id: scope.factoryProjectId,\n board: LEGACY_REVIEW_BOARD,\n };\n const collections = [\n ...(tables.split ? [FACTORY_BOARD_ITEMS_SCHEMA.name] : []),\n ...(tables.legacy ? [WORK_ITEMS_SCHEMA.name] : []),\n ];\n // Paged so a project with an open card answers from the first page instead of reading every Review row.\n const orderBy: [string, 'asc'][] = [['id', 'asc']];\n for (const collection of collections) {\n let cursor: CollectionCursor | undefined;\n for (;;) {\n const rows = await ops.findMany<{ id: string; board: string | null; stages: string[] | null }>(\n collection,\n where,\n { orderBy, limit: REVIEW_IN_USE_PAGE, ...(cursor ? { cursor } : {}) },\n );\n if (rows.some(openOnReview)) return true;\n if (rows.length < REVIEW_IN_USE_PAGE) break;\n cursor = { values: [rows[rows.length - 1]!.id] };\n }\n }\n return false;\n}\n\nconst REVIEW_IN_USE_PAGE = 100;\n\ntype ReviewRow = { id: string; board: string | null; stages: string[] | null; stage_history: unknown };\n\n/**\n * Stores the Work placement of every card stored on `review`, the way an ordinary write to such a\n * card does, so a board about to take the key starts with none of the retired Review board's\n * cards. `open` says what happens to cards that aren't Done or Canceled: `refuse` throws\n * {@link ReviewBoardInUseError} and writes nothing, `move` takes them to Work too. Returns how\n * many rows it rewrote.\n */\nexport async function releaseLegacyReviewCards(\n ops: FactoryStorageOps,\n scope: ReviewBoardScope,\n tables: { split: boolean; legacy: boolean },\n open: 'refuse' | 'move',\n): Promise<number> {\n const where: CollectionWhere = {\n org_id: scope.orgId,\n factory_project_id: scope.factoryProjectId,\n board: LEGACY_REVIEW_BOARD,\n };\n const found: Array<{ collection: string; rows: ReviewRow[] }> = [];\n for (const collection of [\n ...(tables.split ? [FACTORY_BOARD_ITEMS_SCHEMA.name] : []),\n ...(tables.legacy ? [WORK_ITEMS_SCHEMA.name] : []),\n ]) {\n found.push({ collection, rows: await ops.findMany<ReviewRow>(collection, where) });\n }\n if (open === 'refuse') {\n // A card not copied to the split tables yet is in both; count it once.\n const stillOpen = new Set(found.flatMap(({ rows }) => rows.filter(openOnReview).map(row => row.id)));\n if (stillOpen.size > 0) throw new ReviewBoardInUseError(stillOpen.size);\n }\n let rewritten = 0;\n for (const { collection, rows } of found) {\n for (const { id } of rows) {\n // The card can have moved since it was read, so its placement comes from the row as it is now.\n const released = await ops.updateAtomic<ReviewRow>(collection, { id, board: LEGACY_REVIEW_BOARD }, current => {\n if (open === 'refuse' && openOnReview(current)) throw new ReviewBoardInUseError(1);\n return normalizeLegacyReviewColumns({ ...current, stages: current.stages ?? [] }, {});\n });\n if (released) rewritten += 1;\n }\n }\n return rewritten;\n}\n\n/**\n * Work's keys, for rows written when Work was the only board: they carry no board, or Work's,\n * and their phases are Work's by name. Only migrations and legacy writers read these.\n */\nexport const LEGACY_WORK_BOARD = 'work';\nexport const LEGACY_TRIAGE_PHASE = 'triage';\nexport const LEGACY_REST_PHASE = 'intake';\n\n/**\n * Whether a stored placement belongs to the retired Review board: stored on it, or a\n * pull request's own card from before boards were persisted, which sat on Review.\n */\nexport function isLegacyReviewPlacement(board: string | null, primarySourceType: string | undefined): boolean {\n return board === LEGACY_REVIEW_BOARD || (board === null && primarySourceType === 'pull-request');\n}\n\nfunction workStage(stage: string): string {\n return stage === 'review' ? 'pr-review' : stage;\n}\n\nfunction workStages(stages: readonly string[]): string[] {\n return stages.map(workStage);\n}\n\nfunction workStageHistory(history: readonly WorkItemStageEntry[] | null | undefined): WorkItemStageEntry[] {\n return (history ?? []).map(entry => (entry.stage === 'review' ? { ...entry, stage: 'pr-review' } : entry));\n}\n\n/**\n * A row as its project sees it. In a project that keeps Review (`reviewInUse`), a row stored on\n * it stays there; otherwise a Review placement reads as Work, `review` as `pr-review`.\n */\nexport function readLegacyReviewRow<\n Row extends Pick<WorkItemDbRow, 'board' | 'stages' | 'stage_history' | 'work_item_sources'>,\n>(row: Row, reviewInUse = false): Row {\n if (!isLegacyReviewPlacement(row.board, row.work_item_sources?.[0]?.source_type)) return row;\n if (reviewInUse && row.board === LEGACY_REVIEW_BOARD) return row;\n return { ...row, board: 'work', stages: workStages(row.stages), stage_history: workStageHistory(row.stage_history) };\n}\n\n/**\n * Columns that store a legacy Review row's placement as Work, merged over the\n * columns a write already sets. Values a write passes are already in Work's\n * vocabulary (the caller read the aliased row); only stored ones are translated.\n */\nexport function normalizeLegacyReviewColumns(\n stored: { board: string | null; stages: string[]; stage_history: unknown },\n columns: { board?: string | null; stages?: string[]; stage_history?: unknown },\n): { board: string | null; stages: string[]; stage_history: WorkItemStageEntry[] } {\n const board = columns.board === undefined || columns.board === LEGACY_REVIEW_BOARD ? 'work' : columns.board;\n return {\n board,\n stages: columns.stages ?? workStages(stored.stages),\n stage_history:\n (columns.stage_history as WorkItemStageEntry[] | undefined) ??\n workStageHistory(stored.stage_history as WorkItemStageEntry[] | null | undefined),\n };\n}\n\n/** Widen a board filter so stored legacy Review rows answer for Work. */\nexport function widenLegacyReviewBoardFilter(filter: unknown): unknown {\n if (filter === 'work') return { in: ['work', LEGACY_REVIEW_BOARD] };\n if (\n filter &&\n typeof filter === 'object' &&\n 'in' in filter &&\n Array.isArray(filter.in) &&\n filter.in.includes('work')\n ) {\n return { ...filter, in: [...new Set([...filter.in, LEGACY_REVIEW_BOARD])] };\n }\n return filter;\n}\n"],"mappings":";;;;;;;;;;AAaA,MAAa,sBAAsB;;AAQnC,IAAa,wBAAb,cAA2C,MAAM;CAE1B;CADrB,OAAgB;CAChB,YAAY,OAAwB;EAClC,MACE,sCAAsC,MAAM,QAAQ,UAAU,IAAI,SAAS,QAAQ,mBACjF,UAAU,IAAI,OAAO,OACtB,wCACH;EALmB,KAAA,QAAA;CAMrB;AACF;AAKA,SAAS,aAAa,KAA0E;CAC9F,OACE,IAAI,UAAA,aAAkC,IAAI,UAAU,CAAC,EAAA,CAAG,MAAK,UAAS,UAAU,UAAU,UAAU,UAAU;AAElH;;;;;;AAOA,eAAsB,qBACpB,KACA,OACA,SAA8C;CAAE,OAAO;CAAM,QAAQ;AAAM,GACzD;CAClB,MAAM,QAAyB;EAC7B,QAAQ,MAAM;EACd,oBAAoB,MAAM;EAC1B,OAAO;CACT;CACA,MAAM,cAAc,CAClB,GAAI,OAAO,QAAQ,CAAC,2BAA2B,IAAI,IAAI,CAAC,GACxD,GAAI,OAAO,SAAS,CAAC,kBAAkB,IAAI,IAAI,CAAC,CAClD;CAEA,MAAM,UAA6B,CAAC,CAAC,MAAM,KAAK,CAAC;CACjD,KAAK,MAAM,cAAc,aAAa;EACpC,IAAI;EACJ,SAAS;GACP,MAAM,OAAO,MAAM,IAAI,SACrB,YACA,OACA;IAAE;IAAS,OAAO;IAAoB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAAG,CACtE;GACA,IAAI,KAAK,KAAK,YAAY,GAAG,OAAO;GACpC,IAAI,KAAK,SAAS,oBAAoB;GACtC,SAAS,EAAE,QAAQ,CAAC,KAAK,KAAK,SAAS,EAAE,CAAE,EAA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,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAkBpE,CAAC"}
1
+ {"version":3,"file":"annotations.d.ts","sourceRoot":"","sources":["../../src/tools/annotations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAY1D;;;GAGG;AACH,eAAO,MAAM,wBAAwB,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAmBpE,CAAC"}
@@ -36,6 +36,10 @@ const FACTORY_TOOL_ANNOTATIONS = {
36
36
  ...read,
37
37
  title: "List items that need attention"
38
38
  },
39
+ factory_list_audit_events: {
40
+ ...read,
41
+ title: "List audit events"
42
+ },
39
43
  factory_create_work_item: {
40
44
  ...additive,
41
45
  title: "Create a work item"
@@ -1 +1 @@
1
- {"version":3,"file":"annotations.js","names":[],"sources":["../../src/tools/annotations.ts"],"sourcesContent":["import type { ToolAnnotations } from '@mastra/core/tools';\n\nconst read: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst additive: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\nconst toggle: ToolAnnotations = { ...additive, idempotentHint: true };\nconst changes: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };\n\n/**\n * MCP hints for each Factory tool, so clients like ChatGPT can tell lookups\n * from writes and ask before a tool changes or discards state.\n */\nexport const FACTORY_TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {\n factory_list_work_items: { ...read, title: 'List work items' },\n factory_inspect_work_item: { ...read, title: 'Inspect a work item' },\n factory_list_attention: { ...read, title: 'List items that need attention' },\n factory_create_work_item: { ...additive, title: 'Create a work item' },\n factory_update_work_item: { ...changes, title: 'Update a work item' },\n factory_transition_work_item: { ...changes, title: 'Move a work item to another stage' },\n factory_retry_decision: { ...additive, title: 'Retry a failed decision' },\n factory_dismiss_decision: { ...changes, title: 'Dismiss a decision' },\n factory_resolve_proposal: { ...changes, title: 'Approve or reject a proposal' },\n factory_subscribe_work_item: { ...toggle, title: 'Follow a work item' },\n factory_unsubscribe_work_item: { ...toggle, title: 'Stop following a work item' },\n factory_start_session: { ...additive, openWorldHint: true, title: 'Start an agent session' },\n factory_signal_session: { ...additive, openWorldHint: true, title: 'Message a running session' },\n factory_message_origin: { ...additive, title: 'Reply to the session that started this one' },\n factory_answer_approval: { ...changes, openWorldHint: true, title: 'Answer a session approval request' },\n search: { ...read, title: 'Search work items' },\n fetch: { ...read, title: 'Fetch a work item' },\n};\n"],"mappings":";AAEA,MAAM,OAAwB;CAC5B,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,eAAe;AACjB;AACA,MAAM,WAA4B;CAAE,cAAc;CAAO,iBAAiB;CAAO,eAAe;AAAM;AACtG,MAAM,SAA0B;CAAE,GAAG;CAAU,gBAAgB;AAAK;AACpE,MAAM,UAA2B;CAAE,cAAc;CAAO,iBAAiB;CAAM,eAAe;AAAM;;;;;AAMpG,MAAa,2BAA4D;CACvE,yBAAyB;EAAE,GAAG;EAAM,OAAO;CAAkB;CAC7D,2BAA2B;EAAE,GAAG;EAAM,OAAO;CAAsB;CACnE,wBAAwB;EAAE,GAAG;EAAM,OAAO;CAAiC;CAC3E,0BAA0B;EAAE,GAAG;EAAU,OAAO;CAAqB;CACrE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,8BAA8B;EAAE,GAAG;EAAS,OAAO;CAAoC;CACvF,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA0B;CACxE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAA+B;CAC9E,6BAA6B;EAAE,GAAG;EAAQ,OAAO;CAAqB;CACtE,+BAA+B;EAAE,GAAG;EAAQ,OAAO;CAA6B;CAChF,uBAAuB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAAyB;CAC3F,wBAAwB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAA4B;CAC/F,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA6C;CAC3F,yBAAyB;EAAE,GAAG;EAAS,eAAe;EAAM,OAAO;CAAoC;CACvG,QAAQ;EAAE,GAAG;EAAM,OAAO;CAAoB;CAC9C,OAAO;EAAE,GAAG;EAAM,OAAO;CAAoB;AAC/C"}
1
+ {"version":3,"file":"annotations.js","names":[],"sources":["../../src/tools/annotations.ts"],"sourcesContent":["import type { ToolAnnotations } from '@mastra/core/tools';\n\nconst read: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst additive: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\nconst toggle: ToolAnnotations = { ...additive, idempotentHint: true };\nconst changes: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };\n\n/**\n * MCP hints for each Factory tool, so clients like ChatGPT can tell lookups\n * from writes and ask before a tool changes or discards state.\n */\nexport const FACTORY_TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {\n factory_list_work_items: { ...read, title: 'List work items' },\n factory_inspect_work_item: { ...read, title: 'Inspect a work item' },\n factory_list_attention: { ...read, title: 'List items that need attention' },\n factory_list_audit_events: { ...read, title: 'List audit events' },\n factory_create_work_item: { ...additive, title: 'Create a work item' },\n factory_update_work_item: { ...changes, title: 'Update a work item' },\n factory_transition_work_item: { ...changes, title: 'Move a work item to another stage' },\n factory_retry_decision: { ...additive, title: 'Retry a failed decision' },\n factory_dismiss_decision: { ...changes, title: 'Dismiss a decision' },\n factory_resolve_proposal: { ...changes, title: 'Approve or reject a proposal' },\n factory_subscribe_work_item: { ...toggle, title: 'Follow a work item' },\n factory_unsubscribe_work_item: { ...toggle, title: 'Stop following a work item' },\n factory_start_session: { ...additive, openWorldHint: true, title: 'Start an agent session' },\n factory_signal_session: { ...additive, openWorldHint: true, title: 'Message a running session' },\n factory_message_origin: { ...additive, title: 'Reply to the session that started this one' },\n factory_answer_approval: { ...changes, openWorldHint: true, title: 'Answer a session approval request' },\n search: { ...read, title: 'Search work items' },\n fetch: { ...read, title: 'Fetch a work item' },\n};\n"],"mappings":";AAEA,MAAM,OAAwB;CAC5B,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,eAAe;AACjB;AACA,MAAM,WAA4B;CAAE,cAAc;CAAO,iBAAiB;CAAO,eAAe;AAAM;AACtG,MAAM,SAA0B;CAAE,GAAG;CAAU,gBAAgB;AAAK;AACpE,MAAM,UAA2B;CAAE,cAAc;CAAO,iBAAiB;CAAM,eAAe;AAAM;;;;;AAMpG,MAAa,2BAA4D;CACvE,yBAAyB;EAAE,GAAG;EAAM,OAAO;CAAkB;CAC7D,2BAA2B;EAAE,GAAG;EAAM,OAAO;CAAsB;CACnE,wBAAwB;EAAE,GAAG;EAAM,OAAO;CAAiC;CAC3E,2BAA2B;EAAE,GAAG;EAAM,OAAO;CAAoB;CACjE,0BAA0B;EAAE,GAAG;EAAU,OAAO;CAAqB;CACrE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,8BAA8B;EAAE,GAAG;EAAS,OAAO;CAAoC;CACvF,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA0B;CACxE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAA+B;CAC9E,6BAA6B;EAAE,GAAG;EAAQ,OAAO;CAAqB;CACtE,+BAA+B;EAAE,GAAG;EAAQ,OAAO;CAA6B;CAChF,uBAAuB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAAyB;CAC3F,wBAAwB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAA4B;CAC/F,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA6C;CAC3F,yBAAyB;EAAE,GAAG;EAAS,eAAe;EAAM,OAAO;CAAoC;CACvG,QAAQ;EAAE,GAAG;EAAM,OAAO;CAAoB;CAC9C,OAAO;EAAE,GAAG;EAAM,OAAO;CAAoB;AAC/C"}
@@ -0,0 +1,29 @@
1
+ import type { SourceControlSessionLookup } from '../session/factory-session.js';
2
+ import type { FactoryReadToolDependencies } from './read-tools.js';
3
+ import type { FactoryToolScope } from './scope.js';
4
+ export interface FactoryAuditToolDependencies {
5
+ workItems: FactoryReadToolDependencies['workItems'];
6
+ audit: FactoryReadToolDependencies['audit'];
7
+ messaging?: FactoryReadToolDependencies['messaging'];
8
+ /** Finds the sessions an event names or an agent ran in, to leave out other people's private sessions. */
9
+ sessions?: Pick<SourceControlSessionLookup, 'getBySessionId'>;
10
+ }
11
+ /**
12
+ * Who did what in this Factory, from its audit trail. The trail is org-wide and
13
+ * its reads are unscoped by design, so this tool narrows what it hands back:
14
+ * only this Factory's events, never request context (IP, user agent), names but
15
+ * never emails, no metadata beyond what was acted on, and no events from or
16
+ * about another person's private session.
17
+ */
18
+ export declare function createAuditEventsTool(scope: FactoryToolScope, deps: FactoryAuditToolDependencies): import("@mastra/core/tools").Tool<{
19
+ actor?: string | undefined;
20
+ includeAgentRuns?: boolean | undefined;
21
+ namespace?: "agent" | "board" | "git" | "intake" | "intake_route" | "run" | "sandbox_env" | "session" | "skill" | "work_item" | undefined;
22
+ actions?: ("factory.agent.commit" | "factory.agent.pr_opened" | "factory.agent.push" | "factory.agent.signaled" | "factory.board.created" | "factory.board.deleted" | "factory.board.reset" | "factory.board.updated" | "factory.git.commit" | "factory.git.pr_opened" | "factory.git.push" | "factory.intake.binding_updated" | "factory.intake.config_updated" | "factory.intake.label_route_updated" | "factory.intake_route.created" | "factory.intake_route.deleted" | "factory.intake_route.reordered" | "factory.intake_route.updated" | "factory.run.approved" | "factory.run.dismissed" | "factory.run.ended" | "factory.run.queued" | "factory.run.rejected" | "factory.run.retry" | "factory.run.started" | "factory.sandbox_env.deleted" | "factory.sandbox_env.set" | "factory.sandbox_env.updated" | "factory.session.owner_transferred" | "factory.skill.reverted" | "factory.skill.updated" | "factory.work_item.created" | "factory.work_item.deleted" | "factory.work_item.labels_reconciled" | "factory.work_item.stage_moved" | "factory.work_item.transition_rejected" | "factory.work_item.updated")[] | undefined;
23
+ workItem?: string | undefined;
24
+ since?: string | undefined;
25
+ until?: string | undefined;
26
+ cursor?: string | undefined;
27
+ limit?: number | undefined;
28
+ }, unknown, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, "factory_list_audit_events", unknown>;
29
+ //# sourceMappingURL=audit-events-tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-events-tool.d.ts","sourceRoot":"","sources":["../../src/tools/audit-events-tool.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAUhF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AASnD,MAAM,WAAW,4BAA4B;IAC3C,SAAS,EAAE,2BAA2B,CAAC,WAAW,CAAC,CAAC;IACpD,KAAK,EAAE,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAC5C,SAAS,CAAC,EAAE,2BAA2B,CAAC,WAAW,CAAC,CAAC;IACrD,0GAA0G;IAC1G,QAAQ,CAAC,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;CAC/D;AA4CD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,gBAAgB,EAAE,IAAI,EAAE,4BAA4B;;;;;;;;;;kJAmEhG"}
@@ -0,0 +1,180 @@
1
+ import { auditActionsInNamespaces, auditNamespaces, isAuditAction } from "../storage/domains/audit/actions.js";
2
+ import { ACTOR_PROFILE_METADATA_KEY, auditCursorAt, decodeAuditAfterCursor, encodeAuditCursor } from "../storage/domains/audit/base.js";
3
+ import { findWorkItem, truncate, workItemNotFound, workItemRefSchema } from "./read-tools.js";
4
+ import { createTool } from "@mastra/core/tools";
5
+ import { z } from "zod";
6
+ // src/tools/audit-events-tool.ts
7
+ const DEFAULT_LIMIT = 25;
8
+ const PAGE_SIZE = 200;
9
+ /** Pages read per call before handing back a cursor, so a narrow filter can't scan the whole trail at once. */
10
+ const MAX_PAGES = 5;
11
+ const AGENT_ACTOR_PREFIX = "agent:";
12
+ const SESSION_ACTOR_PREFIX = "session:";
13
+ const namespaces = auditNamespaces();
14
+ const inputSchema = z.object({
15
+ actor: z.string().trim().min(1).max(200).optional().describe("\"me\", a user id, or an agent actor id like \"agent:<threadId>\". Only events this actor performed."),
16
+ includeAgentRuns: z.boolean().optional().describe("With a person as `actor`: also include what agents did in runs that person started."),
17
+ namespace: z.enum(namespaces).optional().describe("Only actions in this namespace, e.g. \"work_item\" or \"run\"."),
18
+ actions: z.array(z.string().refine(isAuditAction, { message: "Not a Factory audit action." })).min(1).max(50).optional().describe("Only these exact actions, e.g. [\"factory.work_item.stage_moved\"]."),
19
+ workItem: workItemRefSchema.optional().describe("Only events that acted on this work item (id or \"#123\")."),
20
+ since: z.iso.datetime({ offset: true }).optional().describe("Only events at or after this ISO time."),
21
+ until: z.iso.datetime({ offset: true }).optional().describe("Only events before this ISO time."),
22
+ cursor: z.string().min(1).max(200).optional().describe("`nextCursor` from a previous call, to read older events."),
23
+ limit: z.number().int().min(1).max(50).optional().describe(`Default ${DEFAULT_LIMIT}, max 50.`)
24
+ }).strict();
25
+ /** A display name stamped at record time, or nothing when it is an email (the fallback when a person has no name). */
26
+ function actorName(event) {
27
+ const profile = event.metadata?.[ACTOR_PROFILE_METADATA_KEY];
28
+ const name = typeof profile?.name === "string" ? profile.name.trim() : "";
29
+ return name && !name.includes("@") ? truncate(name, 600) : void 0;
30
+ }
31
+ function startedBy(event) {
32
+ const value = event.metadata?.startedBy;
33
+ return event.actorType === "agent" && typeof value === "string" ? value : void 0;
34
+ }
35
+ /**
36
+ * Who did what in this Factory, from its audit trail. The trail is org-wide and
37
+ * its reads are unscoped by design, so this tool narrows what it hands back:
38
+ * only this Factory's events, never request context (IP, user agent), names but
39
+ * never emails, no metadata beyond what was acted on, and no events from or
40
+ * about another person's private session.
41
+ */
42
+ function createAuditEventsTool(scope, deps) {
43
+ const project = {
44
+ orgId: scope.orgId,
45
+ factoryProjectId: scope.factoryProjectId
46
+ };
47
+ return createTool({
48
+ id: "factory_list_audit_events",
49
+ description: "List this Factory's audit events, newest first: who did what to which work item, run, branch or setting, and when. Filter by actor (\"me\" or a user id, optionally with the agent runs they started), action namespace or exact actions, work item, and time range. Pass `nextCursor` back as `cursor` for older events. Events from other people's private sessions are left out.",
50
+ inputSchema,
51
+ execute: async (input) => {
52
+ if (input.cursor && !decodeAuditAfterCursor(input.cursor)) throw new Error("That cursor is not one this tool returned.");
53
+ const since = input.since ? new Date(input.since) : void 0;
54
+ const until = input.until ? new Date(input.until) : void 0;
55
+ if (since && until && since >= until) throw new Error("`since` must be before `until`.");
56
+ if (input.includeAgentRuns && (!input.actor || input.actor.startsWith(AGENT_ACTOR_PREFIX))) throw new Error("`includeAgentRuns` needs a person as `actor`.");
57
+ let workItemId;
58
+ if (input.workItem) {
59
+ const item = await findWorkItem(deps.workItems, scope, input.workItem);
60
+ if (!item) throw workItemNotFound(input.workItem);
61
+ workItemId = item.id;
62
+ }
63
+ const namespaceActions = input.namespace ? auditActionsInNamespaces([input.namespace]) : void 0;
64
+ const actions = input.actions && namespaceActions ? input.actions.filter((action) => namespaceActions.includes(action)) : input.actions ?? namespaceActions;
65
+ if (actions && actions.length === 0) return { events: [] };
66
+ const actorId = input.actor === "me" ? scope.userId : input.actor;
67
+ const limit = input.limit ?? DEFAULT_LIMIT;
68
+ const visible = eventVisibility(scope, deps);
69
+ const events = [];
70
+ let before = input.cursor ?? (until ? auditCursorAt(until) : void 0);
71
+ const beforeUntil = (event) => !until || event.occurredAt < until;
72
+ for (let page = 0; page < MAX_PAGES; page++) {
73
+ const result = await deps.audit.list({
74
+ ...project,
75
+ ...actions ? { actions } : {},
76
+ ...actorId && !input.includeAgentRuns ? { actorId } : {},
77
+ ...before ? { before } : {},
78
+ limit: PAGE_SIZE
79
+ });
80
+ for (const event of result.events) {
81
+ if (since && event.occurredAt < since) return { events };
82
+ if (!beforeUntil(event)) continue;
83
+ if (actorId && event.actorId !== actorId && startedBy(event) !== actorId) continue;
84
+ if (workItemId && !event.targets.some((target) => target.type === "work_item" && target.id === workItemId)) continue;
85
+ if (!await visible(event)) continue;
86
+ events.push(summarize(event));
87
+ if (events.length === limit) return {
88
+ events,
89
+ nextCursor: encodeAuditCursor(event)
90
+ };
91
+ }
92
+ if (!result.nextCursor) return { events };
93
+ before = result.nextCursor;
94
+ }
95
+ return {
96
+ events,
97
+ nextCursor: before
98
+ };
99
+ }
100
+ });
101
+ }
102
+ function summarize(event) {
103
+ const name = actorName(event);
104
+ const runStartedBy = startedBy(event);
105
+ return {
106
+ action: event.action,
107
+ occurredAt: event.occurredAt.toISOString(),
108
+ actor: {
109
+ type: event.actorType,
110
+ id: event.actorId,
111
+ ...name ? { name } : {}
112
+ },
113
+ ...runStartedBy ? { startedBy: runStartedBy } : {},
114
+ targets: event.targets.slice(0, 10).map((target) => ({
115
+ type: target.type,
116
+ id: truncate(target.id, 600),
117
+ ...target.name ? { name: truncate(target.name, 600) } : {}
118
+ }))
119
+ };
120
+ }
121
+ /** Sessions an event names: its session targets and the session it records it acted in. */
122
+ function sessionRefs(event) {
123
+ const ids = event.targets.filter((target) => target.type === "session").map((target) => target.id);
124
+ const recorded = event.metadata?.sessionId;
125
+ if (typeof recorded === "string") ids.push(recorded);
126
+ return [...new Set(ids)];
127
+ }
128
+ /**
129
+ * Whether the caller may see an event. An event that names a session, or an
130
+ * agent's act (which belongs to the session it ran in), is only visible when
131
+ * every such session is shared or the caller's own. Fails closed when a
132
+ * session can't be found.
133
+ */
134
+ function eventVisibility(scope, deps) {
135
+ const sessions = /* @__PURE__ */ new Map();
136
+ const threads = /* @__PURE__ */ new Map();
137
+ let runAgents;
138
+ const sessionVisible = (sessionId) => {
139
+ let result = sessions.get(sessionId);
140
+ if (!result) {
141
+ result = (async () => {
142
+ const row = await deps.sessions?.getBySessionId(sessionId);
143
+ if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) return false;
144
+ return row.visibility !== "private" || row.userId === scope.userId;
145
+ })().catch(() => false);
146
+ sessions.set(sessionId, result);
147
+ }
148
+ return result;
149
+ };
150
+ const threadVisible = async (threadId) => {
151
+ runAgents ??= deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId).then((bindings) => new Set(bindings.flatMap((binding) => [binding.threadId, binding.id])));
152
+ if ((await runAgents).has(threadId)) return true;
153
+ const controller = (await deps.messaging?.())?.controller;
154
+ if (!controller) return false;
155
+ const thread = await controller.queryThreadById({ threadId });
156
+ if (!thread) return false;
157
+ const stamped = thread.metadata?.factorySessionId;
158
+ return sessionVisible(typeof stamped === "string" ? stamped : thread.id);
159
+ };
160
+ const agentVisible = (event) => {
161
+ if (startedBy(event) === scope.userId) return true;
162
+ if (!event.actorId.startsWith(AGENT_ACTOR_PREFIX)) return false;
163
+ const threadId = event.actorId.slice(6);
164
+ let result = threads.get(threadId);
165
+ if (!result) {
166
+ const sessionId = threadId.startsWith(SESSION_ACTOR_PREFIX) ? threadId.slice(8) : void 0;
167
+ result = (sessionId ? sessionVisible(sessionId) : threadVisible(threadId)).catch(() => false);
168
+ threads.set(threadId, result);
169
+ }
170
+ return result;
171
+ };
172
+ return async (event) => {
173
+ if (event.actorType === "agent" && !await agentVisible(event)) return false;
174
+ for (const sessionId of sessionRefs(event)) if (!await sessionVisible(sessionId)) return false;
175
+ return true;
176
+ };
177
+ }
178
+ export { createAuditEventsTool };
179
+
180
+ //# sourceMappingURL=audit-events-tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-events-tool.js","names":[],"sources":["../../src/tools/audit-events-tool.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport { auditActionsInNamespaces, auditNamespaces, isAuditAction } from '../storage/domains/audit/actions.js';\nimport type { AuditNamespace } from '../storage/domains/audit/actions.js';\nimport {\n ACTOR_PROFILE_METADATA_KEY,\n auditCursorAt,\n decodeAuditAfterCursor,\n encodeAuditCursor,\n} from '../storage/domains/audit/base.js';\nimport type { AuditEventRow } from '../storage/domains/audit/base.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport { MAX_LIST, MAX_TEXT, findWorkItem, truncate, workItemNotFound, workItemRefSchema } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\n\nconst DEFAULT_LIMIT = 25;\nconst PAGE_SIZE = 200;\n/** Pages read per call before handing back a cursor, so a narrow filter can't scan the whole trail at once. */\nconst MAX_PAGES = 5;\nconst AGENT_ACTOR_PREFIX = 'agent:';\nconst SESSION_ACTOR_PREFIX = 'session:';\n\nexport interface FactoryAuditToolDependencies {\n workItems: FactoryReadToolDependencies['workItems'];\n audit: FactoryReadToolDependencies['audit'];\n messaging?: FactoryReadToolDependencies['messaging'];\n /** Finds the sessions an event names or an agent ran in, to leave out other people's private sessions. */\n sessions?: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n}\n\nconst namespaces = auditNamespaces() as [AuditNamespace, ...AuditNamespace[]];\n\nconst inputSchema = z\n .object({\n actor: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe('\"me\", a user id, or an agent actor id like \"agent:<threadId>\". Only events this actor performed.'),\n includeAgentRuns: z\n .boolean()\n .optional()\n .describe('With a person as `actor`: also include what agents did in runs that person started.'),\n namespace: z.enum(namespaces).optional().describe('Only actions in this namespace, e.g. \"work_item\" or \"run\".'),\n actions: z\n .array(z.string().refine(isAuditAction, { message: 'Not a Factory audit action.' }))\n .min(1)\n .max(50)\n .optional()\n .describe('Only these exact actions, e.g. [\"factory.work_item.stage_moved\"].'),\n workItem: workItemRefSchema.optional().describe('Only events that acted on this work item (id or \"#123\").'),\n since: z.iso.datetime({ offset: true }).optional().describe('Only events at or after this ISO time.'),\n until: z.iso.datetime({ offset: true }).optional().describe('Only events before this ISO time.'),\n cursor: z.string().min(1).max(200).optional().describe('`nextCursor` from a previous call, to read older events.'),\n limit: z.number().int().min(1).max(MAX_LIST).optional().describe(`Default ${DEFAULT_LIMIT}, max ${MAX_LIST}.`),\n })\n .strict();\n\n/** A display name stamped at record time, or nothing when it is an email (the fallback when a person has no name). */\nfunction actorName(event: AuditEventRow): string | undefined {\n const profile = event.metadata?.[ACTOR_PROFILE_METADATA_KEY] as { name?: unknown } | undefined;\n const name = typeof profile?.name === 'string' ? profile.name.trim() : '';\n return name && !name.includes('@') ? truncate(name, MAX_TEXT) : undefined;\n}\n\nfunction startedBy(event: AuditEventRow): string | undefined {\n const value = event.metadata?.startedBy;\n return event.actorType === 'agent' && typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Who did what in this Factory, from its audit trail. The trail is org-wide and\n * its reads are unscoped by design, so this tool narrows what it hands back:\n * only this Factory's events, never request context (IP, user agent), names but\n * never emails, no metadata beyond what was acted on, and no events from or\n * about another person's private session.\n */\nexport function createAuditEventsTool(scope: FactoryToolScope, deps: FactoryAuditToolDependencies) {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n\n return createTool({\n id: 'factory_list_audit_events',\n description:\n 'List this Factory\\'s audit events, newest first: who did what to which work item, run, branch or setting, and when. Filter by actor (\"me\" or a user id, optionally with the agent runs they started), action namespace or exact actions, work item, and time range. Pass `nextCursor` back as `cursor` for older events. Events from other people\\'s private sessions are left out.',\n inputSchema,\n execute: async input => {\n if (input.cursor && !decodeAuditAfterCursor(input.cursor)) {\n throw new Error('That cursor is not one this tool returned.');\n }\n const since = input.since ? new Date(input.since) : undefined;\n const until = input.until ? new Date(input.until) : undefined;\n if (since && until && since >= until) throw new Error('`since` must be before `until`.');\n if (input.includeAgentRuns && (!input.actor || input.actor.startsWith(AGENT_ACTOR_PREFIX))) {\n throw new Error('`includeAgentRuns` needs a person as `actor`.');\n }\n\n let workItemId: string | undefined;\n if (input.workItem) {\n const item = await findWorkItem(deps.workItems, scope, input.workItem);\n if (!item) throw workItemNotFound(input.workItem);\n workItemId = item.id;\n }\n\n const namespaceActions = input.namespace ? auditActionsInNamespaces([input.namespace]) : undefined;\n const actions =\n input.actions && namespaceActions\n ? input.actions.filter(action => namespaceActions.includes(action))\n : (input.actions ?? namespaceActions);\n if (actions && actions.length === 0) return { events: [] };\n\n const actorId = input.actor === 'me' ? scope.userId : input.actor;\n const limit = input.limit ?? DEFAULT_LIMIT;\n const visible = eventVisibility(scope, deps);\n\n const events: ReturnType<typeof summarize>[] = [];\n let before = input.cursor ?? (until ? auditCursorAt(until) : undefined);\n // `auditCursorAt` sits after every row at that instant; `until` excludes them.\n const beforeUntil = (event: AuditEventRow) => !until || event.occurredAt < until;\n for (let page = 0; page < MAX_PAGES; page++) {\n const result = await deps.audit.list({\n ...project,\n ...(actions ? { actions } : {}),\n ...(actorId && !input.includeAgentRuns ? { actorId } : {}),\n ...(before ? { before } : {}),\n limit: PAGE_SIZE,\n });\n for (const event of result.events) {\n if (since && event.occurredAt < since) return { events };\n if (!beforeUntil(event)) continue;\n if (actorId && event.actorId !== actorId && startedBy(event) !== actorId) continue;\n if (workItemId && !event.targets.some(target => target.type === 'work_item' && target.id === workItemId)) {\n continue;\n }\n if (!(await visible(event))) continue;\n events.push(summarize(event));\n if (events.length === limit) return { events, nextCursor: encodeAuditCursor(event) };\n }\n if (!result.nextCursor) return { events };\n before = result.nextCursor;\n }\n // Scan budget spent: hand back where to pick up, even with fewer events than asked for.\n return { events, nextCursor: before };\n },\n });\n}\n\nfunction summarize(event: AuditEventRow) {\n const name = actorName(event);\n const runStartedBy = startedBy(event);\n return {\n action: event.action,\n occurredAt: event.occurredAt.toISOString(),\n actor: { type: event.actorType, id: event.actorId, ...(name ? { name } : {}) },\n ...(runStartedBy ? { startedBy: runStartedBy } : {}),\n targets: event.targets.slice(0, 10).map(target => ({\n type: target.type,\n id: truncate(target.id, MAX_TEXT),\n ...(target.name ? { name: truncate(target.name, MAX_TEXT) } : {}),\n })),\n };\n}\n\n/** Sessions an event names: its session targets and the session it records it acted in. */\nfunction sessionRefs(event: AuditEventRow): string[] {\n const ids = event.targets.filter(target => target.type === 'session').map(target => target.id);\n const recorded = event.metadata?.sessionId;\n if (typeof recorded === 'string') ids.push(recorded);\n return [...new Set(ids)];\n}\n\n/**\n * Whether the caller may see an event. An event that names a session, or an\n * agent's act (which belongs to the session it ran in), is only visible when\n * every such session is shared or the caller's own. Fails closed when a\n * session can't be found.\n */\nfunction eventVisibility(scope: FactoryToolScope, deps: FactoryAuditToolDependencies) {\n const sessions = new Map<string, Promise<boolean>>();\n const threads = new Map<string, Promise<boolean>>();\n let runAgents: Promise<Set<string>> | undefined;\n\n const sessionVisible = (sessionId: string): Promise<boolean> => {\n let result = sessions.get(sessionId);\n if (!result) {\n result = (async () => {\n const row = await deps.sessions?.getBySessionId(sessionId);\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) return false;\n return row.visibility !== 'private' || row.userId === scope.userId;\n })().catch(() => false);\n sessions.set(sessionId, result);\n }\n return result;\n };\n\n const threadVisible = async (threadId: string): Promise<boolean> => {\n // Work item runs are on the board for everyone in the Factory. A run's agent is recorded\n // under its thread (commits, pushes, signals) or under its binding (stage moves).\n runAgents ??= deps.workItems\n .listRunBindings(scope.orgId, scope.factoryProjectId)\n .then(bindings => new Set(bindings.flatMap(binding => [binding.threadId, binding.id])));\n if ((await runAgents).has(threadId)) return true;\n\n const controller = (await deps.messaging?.())?.controller;\n if (!controller) return false;\n const thread = await controller.queryThreadById({ threadId });\n if (!thread) return false;\n const stamped = thread.metadata?.factorySessionId;\n return sessionVisible(typeof stamped === 'string' ? stamped : thread.id);\n };\n\n const agentVisible = (event: AuditEventRow): Promise<boolean> | boolean => {\n if (startedBy(event) === scope.userId) return true;\n if (!event.actorId.startsWith(AGENT_ACTOR_PREFIX)) return false;\n const threadId = event.actorId.slice(AGENT_ACTOR_PREFIX.length);\n let result = threads.get(threadId);\n if (!result) {\n // Turns nobody signed in started are recorded as their session's agent: `agent:session:<sessionId>`.\n // Work item runs are created shared, so the session's own visibility decides.\n const sessionId = threadId.startsWith(SESSION_ACTOR_PREFIX)\n ? threadId.slice(SESSION_ACTOR_PREFIX.length)\n : undefined;\n result = (sessionId ? sessionVisible(sessionId) : threadVisible(threadId)).catch(() => false);\n threads.set(threadId, result);\n }\n return result;\n };\n\n return async (event: AuditEventRow): Promise<boolean> => {\n if (event.actorType === 'agent' && !(await agentVisible(event))) return false;\n for (const sessionId of sessionRefs(event)) {\n if (!(await sessionVisible(sessionId))) return false;\n }\n return true;\n };\n}\n"],"mappings":";;;;;;AAiBA,MAAM,gBAAgB;AACtB,MAAM,YAAY;;AAElB,MAAM,YAAY;AAClB,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAU7B,MAAM,aAAa,gBAAgB;AAEnC,MAAM,cAAc,EACjB,OAAO;CACN,OAAO,EACJ,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,IAAI,GAAG,CAAC,CACR,SAAS,CAAC,CACV,SAAS,sGAAkG;CAC9G,kBAAkB,EACf,QAAQ,CAAC,CACT,SAAS,CAAC,CACV,SAAS,qFAAqF;CACjG,WAAW,EAAE,KAAK,UAAU,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,gEAA4D;CAC9G,SAAS,EACN,MAAM,EAAE,OAAO,CAAC,CAAC,OAAO,eAAe,EAAE,SAAS,8BAA8B,CAAC,CAAC,CAAC,CACnF,IAAI,CAAC,CAAC,CACN,IAAI,EAAE,CAAC,CACP,SAAS,CAAC,CACV,SAAS,qEAAmE;CAC/E,UAAU,kBAAkB,SAAS,CAAC,CAAC,SAAS,4DAA0D;CAC1G,OAAO,EAAE,IAAI,SAAS,EAAE,QAAQ,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,wCAAwC;CACpG,O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A2B,IAC1C,KAAA;GACJ,UAAU,YAAY,eAAe,SAAS,IAAI,cAAc,QAAQ,EAAA,CAAG,YAAY,KAAK;GAC5F,QAAQ,IAAI,UAAU,MAAM;EAC9B;EACA,OAAO;CACT;CAEA,OAAO,OAAO,UAA2C;EACvD,IAAI,MAAM,cAAc,WAAW,CAAE,MAAM,aAAa,KAAK,GAAI,OAAO;EACxE,KAAK,MAAM,aAAa,YAAY,KAAK,GACvC,IAAI,CAAE,MAAM,eAAe,SAAS,GAAI,OAAO;EAEjD,OAAO;CACT;AACF"}
@@ -1,5 +1,6 @@
1
1
  import type { IntegrationTools } from '../integrations/base.js';
2
2
  import type { FactoryApprovalToolDependencies } from './approval-tools.js';
3
+ import type { FactoryAuditToolDependencies } from './audit-events-tool.js';
3
4
  import type { FactoryMessagingToolDependencies } from './messaging-tools.js';
4
5
  import type { FactoryReadToolDependencies } from './read-tools.js';
5
6
  import type { FactoryToolScope } from './scope.js';
@@ -9,7 +10,7 @@ export { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './p
9
10
  export { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';
10
11
  export type { FactoryToolScope } from './scope.js';
11
12
  /** Storage and services the Factory tools act through. */
12
- export type FactoryToolDependencies = FactoryReadToolDependencies & FactoryWorkItemToolDependencies & FactoryMessagingToolDependencies & FactorySessionToolDependencies & FactoryApprovalToolDependencies;
13
+ export type FactoryToolDependencies = FactoryReadToolDependencies & FactoryAuditToolDependencies & FactoryWorkItemToolDependencies & FactoryMessagingToolDependencies & FactorySessionToolDependencies & FactoryApprovalToolDependencies;
13
14
  export interface CreateFactoryToolsOptions {
14
15
  scope: FactoryToolScope;
15
16
  deps: FactoryToolDependencies;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAEhE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AM,iBAAiB,CAAC;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AAEzE,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AAE5E,OAAO,EAAE,8BAA8B,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC/F,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAC9E,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,0DAA0D;AAC1D,MAAM,MAAM,uBAAuB,GAAG,2BAA2B,GAC/D,4BAA4B,GAC5B,+BAA+B,GAC/B,gCAAgC,GAChC,8BAA8B,GAC9B,+BAA+B,CAAC;AAElC,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,gBAAgB,CAAC;IACxB,IAAI,EAAE,uBAAuB,CAAC;CAC/B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,yBAAyB,GAAG,gBAAgB,CAW/F"}
@@ -1,5 +1,6 @@
1
1
  import { FACTORY_INTERACTIVE_KEY } from "../auth.js";
2
2
  import { createFactoryApprovalTools } from "./approval-tools.js";
3
+ import { createAuditEventsTool } from "./audit-events-tool.js";
3
4
  import { createFactoryMessagingTools } from "./messaging-tools.js";
4
5
  import { createFactoryReadTools } from "./read-tools.js";
5
6
  import { createFactorySessionTools } from "./session-tools.js";
@@ -24,6 +25,7 @@ function createFactoryTools({ scope, deps }) {
24
25
  if (scope.kind !== "user") return messagingTools;
25
26
  return {
26
27
  ...createFactoryReadTools(scope, deps),
28
+ factory_list_audit_events: createAuditEventsTool(scope, deps),
27
29
  ...messagingTools,
28
30
  ...createFactoryWorkItemTools(scope, deps),
29
31
  ...createFactorySessionTools(scope, deps),
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/tools/index.ts"],"sourcesContent":["import type { IntegrationTools } from '../integrations/base.js';\nimport { createFactoryApprovalTools } from './approval-tools.js';\nimport type { FactoryApprovalToolDependencies } from './approval-tools.js';\nimport { createFactoryMessagingTools } from './messaging-tools.js';\nimport type { FactoryMessagingToolDependencies } from './messaging-tools.js';\nimport { createFactoryReadTools } from './read-tools.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { createFactorySessionTools } from './session-tools.js';\nimport type { FactorySessionToolDependencies } from './session-tools.js';\nimport { createFactoryWorkItemTools } from './work-item-tools.js';\nimport type { FactoryWorkItemToolDependencies } from './work-item-tools.js';\n\nexport { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './permissions.js';\nexport { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';\nexport type { FactoryToolScope } from './scope.js';\n\n/** Storage and services the Factory tools act through. */\nexport type FactoryToolDependencies = FactoryReadToolDependencies &\n FactoryWorkItemToolDependencies &\n FactoryMessagingToolDependencies &\n FactorySessionToolDependencies &\n FactoryApprovalToolDependencies;\n\nexport interface CreateFactoryToolsOptions {\n scope: FactoryToolScope;\n deps: FactoryToolDependencies;\n}\n\n/**\n * The Factory toolset for a resolved scope. Tools take scope and storage by\n * closure and never read the request context, so a non-session transport\n * (an MCP server) can mount the same set with a scope it resolved itself.\n *\n * Worker and side sessions only answer messages. User sessions get every tool\n * on every turn. Turns nobody signed in started (notification wakes, webhooks,\n * dispatcher notices) carry text other people wrote, so each tool limits what\n * it does on them itself: approvals, proposals and muting\n * side sessions need a person, moves run as an agent, model switches reach\n * only this session and its side sessions, and starts are side sessions only.\n */\nexport function createFactoryTools({ scope, deps }: CreateFactoryToolsOptions): IntegrationTools {\n const messagingTools = createFactoryMessagingTools(scope, deps);\n if (scope.kind !== 'user') return messagingTools;\n return {\n ...createFactoryReadTools(scope, deps),\n ...messagingTools,\n ...createFactoryWorkItemTools(scope, deps),\n ...createFactorySessionTools(scope, deps),\n ...createFactoryApprovalTools(scope, deps),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,mBAAmB,EAAE,OAAO,QAAqD;CAC/F,MAAM,iBAAiB,4BAA4B,OAAO,IAAI;CAC9D,IAAI,MAAM,SAAS,QAAQ,OAAO;CAClC,OAAO;EACL,GAAG,uBAAuB,OAAO,IAAI;EACrC,GAAG;EACH,GAAG,2BAA2B,OAAO,IAAI;EACzC,GAAG,0BAA0B,OAAO,IAAI;EACxC,GAAG,2BAA2B,OAAO,IAAI;CAC3C;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/tools/index.ts"],"sourcesContent":["import type { IntegrationTools } from '../integrations/base.js';\nimport { createFactoryApprovalTools } from './approval-tools.js';\nimport type { FactoryApprovalToolDependencies } from './approval-tools.js';\nimport { createAuditEventsTool } from './audit-events-tool.js';\nimport type { FactoryAuditToolDependencies } from './audit-events-tool.js';\nimport { createFactoryMessagingTools } from './messaging-tools.js';\nimport type { FactoryMessagingToolDependencies } from './messaging-tools.js';\nimport { createFactoryReadTools } from './read-tools.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { createFactorySessionTools } from './session-tools.js';\nimport type { FactorySessionToolDependencies } from './session-tools.js';\nimport { createFactoryWorkItemTools } from './work-item-tools.js';\nimport type { FactoryWorkItemToolDependencies } from './work-item-tools.js';\n\nexport { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './permissions.js';\nexport { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';\nexport type { FactoryToolScope } from './scope.js';\n\n/** Storage and services the Factory tools act through. */\nexport type FactoryToolDependencies = FactoryReadToolDependencies &\n FactoryAuditToolDependencies &\n FactoryWorkItemToolDependencies &\n FactoryMessagingToolDependencies &\n FactorySessionToolDependencies &\n FactoryApprovalToolDependencies;\n\nexport interface CreateFactoryToolsOptions {\n scope: FactoryToolScope;\n deps: FactoryToolDependencies;\n}\n\n/**\n * The Factory toolset for a resolved scope. Tools take scope and storage by\n * closure and never read the request context, so a non-session transport\n * (an MCP server) can mount the same set with a scope it resolved itself.\n *\n * Worker and side sessions only answer messages. User sessions get every tool\n * on every turn. Turns nobody signed in started (notification wakes, webhooks,\n * dispatcher notices) carry text other people wrote, so each tool limits what\n * it does on them itself: approvals, proposals and muting\n * side sessions need a person, moves run as an agent, model switches reach\n * only this session and its side sessions, and starts are side sessions only.\n */\nexport function createFactoryTools({ scope, deps }: CreateFactoryToolsOptions): IntegrationTools {\n const messagingTools = createFactoryMessagingTools(scope, deps);\n if (scope.kind !== 'user') return messagingTools;\n return {\n ...createFactoryReadTools(scope, deps),\n factory_list_audit_events: createAuditEventsTool(scope, deps),\n ...messagingTools,\n ...createFactoryWorkItemTools(scope, deps),\n ...createFactorySessionTools(scope, deps),\n ...createFactoryApprovalTools(scope, deps),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,mBAAmB,EAAE,OAAO,QAAqD;CAC/F,MAAM,iBAAiB,4BAA4B,OAAO,IAAI;CAC9D,IAAI,MAAM,SAAS,QAAQ,OAAO;CAClC,OAAO;EACL,GAAG,uBAAuB,OAAO,IAAI;EACrC,2BAA2B,sBAAsB,OAAO,IAAI;EAC5D,GAAG;EACH,GAAG,2BAA2B,OAAO,IAAI;EACzC,GAAG,0BAA0B,OAAO,IAAI;EACxC,GAAG,2BAA2B,OAAO,IAAI;CAC3C;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"permissions.d.ts","sourceRoot":"","sources":["../../src/tools/permissions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEvF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAEhF;;;;GAIG;AACH,eAAO,MAA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AC;CACH;AAED,MAAM,WAAW,kCAAkC;IACjD,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;CAC9D;AAED;;;;;GAKG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,6BAA6B,EACtC,EAAE,QAAQ,EAAE,EAAE,kCAAkC,EAChD,SAAS,GAAE,SAAS,MAAM,EAAmC,GAC5D,OAAO,CAAC,IAAI,CAAC,CASf"}
@@ -8,6 +8,7 @@ const FACTORY_TOOLS_WITHOUT_APPROVAL = [
8
8
  "factory_list_work_items",
9
9
  "factory_inspect_work_item",
10
10
  "factory_list_attention",
11
+ "factory_list_audit_events",
11
12
  "factory_create_work_item",
12
13
  "factory_update_work_item",
13
14
  "factory_transition_work_item",
@@ -1 +1 @@
1
- {"version":3,"file":"permissions.js","names":[],"sources":["../../src/tools/permissions.ts"],"sourcesContent":["import type { PermissionPolicy, PermissionRules } from '@mastra/core/agent-controller';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\n\n/**\n * Factory tools that run without asking. Factory tools fall into the SDK's\n * `mcp` category, whose default policy is `ask`, so each of these needs an\n * explicit per-session `allow`.\n */\nexport const FACTORY_TOOLS_WITHOUT_APPROVAL: readonly string[] = [\n 'factory_list_work_items',\n 'factory_inspect_work_item',\n 'factory_list_attention',\n 'factory_create_work_item',\n 'factory_update_work_item',\n 'factory_transition_work_item',\n 'factory_retry_decision',\n 'factory_dismiss_decision',\n 'factory_resolve_proposal',\n 'factory_subscribe_work_item',\n 'factory_unsubscribe_work_item',\n 'factory_signal_session',\n 'factory_message_origin',\n 'factory_list_side_sessions',\n 'factory_subscribe_session',\n 'factory_unsubscribe_session',\n 'factory_start_session',\n 'factory_answer_approval',\n 'factory_switch_session_model',\n 'factory_recreate_sandbox',\n 'factory_sandbox_port_url',\n];\n\nexport interface FactoryToolPermissionsSession {\n readonly identity: { getId(): string };\n readonly permissions: {\n getRules(): PermissionRules;\n setForTool(args: { toolName: string; policy: PermissionPolicy }): Promise<void>;\n };\n}\n\nexport interface FactoryToolPermissionsDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n}\n\n/**\n * Allow the no-approval Factory tools on a newly created Factory session.\n * This only sets policy; which tools a turn actually gets is decided by the\n * tool scope. A person's own choices win: a per-tool policy is never\n * overwritten, and an explicit `mcp` category policy leaves everything alone.\n */\nexport async function applyFactoryToolPermissions(\n session: FactoryToolPermissionsSession,\n { sessions }: FactoryToolPermissionsDependencies,\n toolNames: readonly string[] = FACTORY_TOOLS_WITHOUT_APPROVAL,\n): Promise<void> {\n const row = await sessions.getBySessionId(session.identity.getId());\n if (!row?.factoryProjectId) return;\n const rules = session.permissions.getRules();\n if (rules.categories.mcp !== undefined) return;\n for (const toolName of toolNames) {\n if (session.permissions.getRules().tools[toolName] !== undefined) continue;\n await session.permissions.setForTool({ toolName, policy: 'allow' });\n }\n}\n"],"mappings":";;;;;;AASA,MAAa,iCAAoD;CAC/D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAoBA,eAAsB,4BACpB,SACA,EAAE,YACF,YAA+B,gCAChB;CAEf,IAAI,EAAC,MADa,SAAS,eAAe,QAAQ,SAAS,MAAM,CAAC,EAAA,EACxD,kBAAkB;CAE5B,IADc,QAAQ,YAAY,SAC1B,CAAC,CAAC,WAAW,QAAQ,KAAA,GAAW;CACxC,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,QAAQ,YAAY,SAAS,CAAC,CAAC,MAAM,cAAc,KAAA,GAAW;EAClE,MAAM,QAAQ,YAAY,WAAW;GAAE;GAAU,QAAQ;EAAQ,CAAC;CACpE;AACF"}
1
+ {"version":3,"file":"permissions.js","names":[],"sources":["../../src/tools/permissions.ts"],"sourcesContent":["import type { PermissionPolicy, PermissionRules } from '@mastra/core/agent-controller';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\n\n/**\n * Factory tools that run without asking. Factory tools fall into the SDK's\n * `mcp` category, whose default policy is `ask`, so each of these needs an\n * explicit per-session `allow`.\n */\nexport const FACTORY_TOOLS_WITHOUT_APPROVAL: readonly string[] = [\n 'factory_list_work_items',\n 'factory_inspect_work_item',\n 'factory_list_attention',\n 'factory_list_audit_events',\n 'factory_create_work_item',\n 'factory_update_work_item',\n 'factory_transition_work_item',\n 'factory_retry_decision',\n 'factory_dismiss_decision',\n 'factory_resolve_proposal',\n 'factory_subscribe_work_item',\n 'factory_unsubscribe_work_item',\n 'factory_signal_session',\n 'factory_message_origin',\n 'factory_list_side_sessions',\n 'factory_subscribe_session',\n 'factory_unsubscribe_session',\n 'factory_start_session',\n 'factory_answer_approval',\n 'factory_switch_session_model',\n 'factory_recreate_sandbox',\n 'factory_sandbox_port_url',\n];\n\nexport interface FactoryToolPermissionsSession {\n readonly identity: { getId(): string };\n readonly permissions: {\n getRules(): PermissionRules;\n setForTool(args: { toolName: string; policy: PermissionPolicy }): Promise<void>;\n };\n}\n\nexport interface FactoryToolPermissionsDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n}\n\n/**\n * Allow the no-approval Factory tools on a newly created Factory session.\n * This only sets policy; which tools a turn actually gets is decided by the\n * tool scope. A person's own choices win: a per-tool policy is never\n * overwritten, and an explicit `mcp` category policy leaves everything alone.\n */\nexport async function applyFactoryToolPermissions(\n session: FactoryToolPermissionsSession,\n { sessions }: FactoryToolPermissionsDependencies,\n toolNames: readonly string[] = FACTORY_TOOLS_WITHOUT_APPROVAL,\n): Promise<void> {\n const row = await sessions.getBySessionId(session.identity.getId());\n if (!row?.factoryProjectId) return;\n const rules = session.permissions.getRules();\n if (rules.categories.mcp !== undefined) return;\n for (const toolName of toolNames) {\n if (session.permissions.getRules().tools[toolName] !== undefined) continue;\n await session.permissions.setForTool({ toolName, policy: 'allow' });\n }\n}\n"],"mappings":";;;;;;AASA,MAAa,iCAAoD;CAC/D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAoBA,eAAsB,4BACpB,SACA,EAAE,YACF,YAA+B,gCAChB;CAEf,IAAI,EAAC,MADa,SAAS,eAAe,QAAQ,SAAS,MAAM,CAAC,EAAA,EACxD,kBAAkB;CAE5B,IADc,QAAQ,YAAY,SAC1B,CAAC,CAAC,WAAW,QAAQ,KAAA,GAAW;CACxC,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,QAAQ,YAAY,SAAS,CAAC,CAAC,MAAM,cAAc,KAAA,GAAW;EAClE,MAAM,QAAQ,YAAY,WAAW;GAAE;GAAU,QAAQ;EAAQ,CAAC;CACpE;AACF"}
@@ -87,12 +87,12 @@ var FactorySessionsStateProcessor = class {
87
87
  sessionId: scope.sessionId
88
88
  });
89
89
  if (!binding) return null;
90
- const item = await this.#deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, binding.workItemId);
91
90
  const following = (await this.#deps.workItems.listWorkItemSubscribers({
92
91
  orgId: scope.orgId,
93
92
  workItemId: binding.workItemId
94
93
  })).filter((subscriber) => subscriber.sessionId !== scope.sessionId).length;
95
94
  if (following === 0) return null;
95
+ const item = await this.#deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, binding.workItemId);
96
96
  return `Working on ${item ? itemLabel(item) : binding.workItemId} as ${binding.role}. Reports go to ${following} following session${following === 1 ? "" : "s"}. ${PROGRESS_ASK}`;
97
97
  }
98
98
  async #userState(scope) {