@mastra/factory 0.27.0-alpha.2 → 0.27.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -47
- package/dist/boards/card-facts.d.ts +4 -2
- package/dist/boards/card-facts.d.ts.map +1 -1
- package/dist/boards/card-facts.js +7 -4
- package/dist/boards/card-facts.js.map +1 -1
- package/dist/boards/define-board.d.ts +2 -0
- package/dist/boards/define-board.d.ts.map +1 -1
- package/dist/boards/define-board.js +1 -0
- package/dist/boards/define-board.js.map +1 -1
- package/dist/boards/intake-routing.d.ts +2 -2
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/phase-automation.d.ts +4 -4
- package/dist/boards/phase-automation.d.ts.map +1 -1
- package/dist/boards/phase-automation.js.map +1 -1
- package/dist/boards/pull-request-review.d.ts +0 -7
- package/dist/boards/pull-request-review.d.ts.map +1 -1
- package/dist/boards/pull-request-review.js +15 -14
- package/dist/boards/pull-request-review.js.map +1 -1
- package/dist/boards/relocate.d.ts +4 -4
- package/dist/boards/relocate.d.ts.map +1 -1
- package/dist/boards/relocate.js +1 -1
- package/dist/boards/relocate.js.map +1 -1
- package/dist/boards/review.d.ts.map +1 -1
- package/dist/boards/review.js +1 -2
- package/dist/boards/review.js.map +1 -1
- package/dist/boards/semantics.d.ts +8 -8
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/transition-policy.d.ts +7 -0
- package/dist/boards/transition-policy.d.ts.map +1 -1
- package/dist/boards/transition-policy.js.map +1 -1
- package/dist/boards/work.d.ts +6 -0
- package/dist/boards/work.d.ts.map +1 -1
- package/dist/boards/work.js +71 -25
- package/dist/boards/work.js.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +6 -15
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/integrations/github/acceptance-labels.d.ts +2 -2
- package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
- package/dist/integrations/github/acceptance-labels.js +2 -2
- package/dist/integrations/github/acceptance-labels.js.map +1 -1
- package/dist/integrations/github/default-rules.d.ts +5 -11
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +6 -22
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +6 -4
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/provenance.d.ts +2 -2
- package/dist/integrations/github/provenance.d.ts.map +1 -1
- package/dist/integrations/github/provenance.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +46 -1
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +3 -3
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +43 -39
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/gitlab/default-rules.d.ts +2 -9
- package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +2 -19
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.js +2 -2
- package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js +11 -11
- package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +2 -1
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +1 -0
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/issue-reconciler.d.ts +7 -7
- package/dist/integrations/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/issue-reconciler.js +11 -14
- package/dist/integrations/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +1 -0
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/issue-reconciler.js +2 -2
- package/dist/integrations/linear/issue-reconciler.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +1 -1
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +2 -1
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/slack/feed-publisher.d.ts +2 -2
- package/dist/integrations/slack/feed-publisher.d.ts.map +1 -1
- package/dist/integrations/slack/feed-publisher.js.map +1 -1
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/packages/_internals/workspace/dist/index.js +1 -1
- package/dist/routes/attention-activity.js +1 -1
- package/dist/routes/attention-activity.js.map +1 -1
- package/dist/routes/attention-parked.js.map +1 -1
- package/dist/routes/attention-providers.d.ts +4 -4
- package/dist/routes/attention-providers.d.ts.map +1 -1
- package/dist/routes/attention-providers.js +2 -2
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/contracts.d.ts +33 -5
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +13 -4
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +1 -1
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/projects.js +3 -2
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/surface.js +4 -4
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +9 -3
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.js +1 -1
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/decision-applicability.d.ts +2 -2
- package/dist/rules/decision-applicability.d.ts.map +1 -1
- package/dist/rules/decision-applicability.js +1 -1
- package/dist/rules/decision-applicability.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +2 -7
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +13 -17
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +2 -2
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +4 -2
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/review-source-tool.d.ts.map +1 -1
- package/dist/rules/review-source-tool.js +2 -4
- package/dist/rules/review-source-tool.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +5 -2
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.d.ts.map +1 -1
- package/dist/rules/tools.js +7 -10
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +8 -16
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +19 -21
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +9 -3
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +2 -2
- package/dist/rules/types.js.map +1 -1
- package/dist/session/resource-migration.d.ts +3 -3
- package/dist/session/resource-migration.d.ts.map +1 -1
- package/dist/session/resource-migration.js.map +1 -1
- package/dist/session/work-item-repository.d.ts +4 -2
- package/dist/session/work-item-repository.d.ts.map +1 -1
- package/dist/session/work-item-repository.js +2 -2
- package/dist/session/work-item-repository.js.map +1 -1
- package/dist/skills/catalog.js +1 -1
- package/dist/storage/domains/comments/base.d.ts.map +1 -1
- package/dist/storage/domains/comments/base.js +15 -8
- package/dist/storage/domains/comments/base.js.map +1 -1
- package/dist/storage/domains/comments/domain.d.ts +2 -2
- package/dist/storage/domains/comments/domain.d.ts.map +1 -1
- package/dist/storage/domains/comments/domain.js +1 -1
- package/dist/storage/domains/comments/domain.js.map +1 -1
- package/dist/storage/domains/comments/feed-sync.d.ts +2 -2
- package/dist/storage/domains/comments/feed-sync.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +0 -3
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +0 -3
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +94 -34
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +311 -160
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/board-version.d.ts +2 -2
- package/dist/storage/domains/work-items/board-version.d.ts.map +1 -1
- package/dist/storage/domains/work-items/board-version.js +16 -5
- package/dist/storage/domains/work-items/board-version.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +50 -0
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -0
- package/dist/storage/domains/work-items/cards.js +284 -0
- package/dist/storage/domains/work-items/cards.js.map +1 -0
- package/dist/storage/domains/work-items/metrics.d.ts +2 -2
- package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +117 -0
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -0
- package/dist/storage/domains/work-items/work-item-schema.js +300 -0
- package/dist/storage/domains/work-items/work-item-schema.js.map +1 -0
- package/dist/tools/read-tools.d.ts +4 -4
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +19 -9
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/side-sessions.d.ts +2 -2
- package/dist/tools/side-sessions.d.ts.map +1 -1
- package/dist/tools/side-sessions.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +12 -17
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts +3 -3
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/providers/base.d.ts +22 -0
- package/dist/work-items/providers/base.d.ts.map +1 -0
- package/dist/work-items/providers/base.js +44 -0
- package/dist/work-items/providers/base.js.map +1 -0
- package/dist/work-items/providers/factory.d.ts +4 -0
- package/dist/work-items/providers/factory.d.ts.map +1 -0
- package/dist/work-items/providers/factory.js +13 -0
- package/dist/work-items/providers/factory.js.map +1 -0
- package/dist/work-items/providers/github.d.ts +3 -0
- package/dist/work-items/providers/github.d.ts.map +1 -0
- package/dist/work-items/providers/github.js +30 -0
- package/dist/work-items/providers/github.js.map +1 -0
- package/dist/work-items/providers/gitlab.d.ts +3 -0
- package/dist/work-items/providers/gitlab.d.ts.map +1 -0
- package/dist/work-items/providers/gitlab.js +35 -0
- package/dist/work-items/providers/gitlab.js.map +1 -0
- package/dist/work-items/providers/incidentio.d.ts +3 -0
- package/dist/work-items/providers/incidentio.d.ts.map +1 -0
- package/dist/work-items/providers/incidentio.js +23 -0
- package/dist/work-items/providers/incidentio.js.map +1 -0
- package/dist/work-items/providers/index.d.ts +8 -0
- package/dist/work-items/providers/index.d.ts.map +1 -0
- package/dist/work-items/providers/index.js +34 -0
- package/dist/work-items/providers/index.js.map +1 -0
- package/dist/work-items/providers/jira.d.ts +3 -0
- package/dist/work-items/providers/jira.d.ts.map +1 -0
- package/dist/work-items/providers/jira.js +16 -0
- package/dist/work-items/providers/jira.js.map +1 -0
- package/dist/work-items/providers/linear.d.ts +3 -0
- package/dist/work-items/providers/linear.d.ts.map +1 -0
- package/dist/work-items/providers/linear.js +24 -0
- package/dist/work-items/providers/linear.js.map +1 -0
- package/dist/work-items/providers/metadata-keys.d.ts +24 -0
- package/dist/work-items/providers/metadata-keys.d.ts.map +1 -0
- package/dist/work-items/providers/metadata-keys.js +84 -0
- package/dist/work-items/providers/metadata-keys.js.map +1 -0
- package/dist/work-items/providers/slack.d.ts +6 -0
- package/dist/work-items/providers/slack.d.ts.map +1 -0
- package/dist/work-items/providers/slack.js +15 -0
- package/dist/work-items/providers/slack.js.map +1 -0
- package/dist/work-items/providers/types.d.ts +23 -0
- package/dist/work-items/providers/types.d.ts.map +1 -0
- package/dist/work-items/providers/types.js +1 -0
- package/dist/work-items/split-migration.d.ts +51 -0
- package/dist/work-items/split-migration.d.ts.map +1 -0
- package/dist/work-items/split-migration.js +293 -0
- package/dist/work-items/split-migration.js.map +1 -0
- package/factory-skills/configure-factory-rules/SKILL.md +12 -16
- package/factory-skills/factory-self-review/SKILL.md +1 -1
- package/factory-skills/factory-triage/SKILL.md +3 -3
- package/package.json +11 -11
- package/dist/boards/work-transition-policy.d.ts +0 -3
- package/dist/boards/work-transition-policy.d.ts.map +0 -1
- package/dist/boards/work-transition-policy.js +0 -78
- package/dist/boards/work-transition-policy.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';
|
|
2
2
|
/**
|
|
3
3
|
* One row per project whose `version` is replaced after every committed write to that project's
|
|
4
|
-
*
|
|
4
|
+
* cards (board items and work items). Readers of the full card list compare it against the version their snapshot was
|
|
5
5
|
* taken at, so an unchanged board costs one indexed row read instead of every card.
|
|
6
6
|
*/
|
|
7
7
|
export declare const FACTORY_BOARD_VERSIONS_SCHEMA: CollectionSchema;
|
|
@@ -11,7 +11,7 @@ export interface BoardScope {
|
|
|
11
11
|
factoryProjectId?: string;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* Wrap `ops` so every write to
|
|
14
|
+
* Wrap `ops` so every write to a card table reports the board it changed, once the write has
|
|
15
15
|
* resolved. Writes outside any tenant (`dangerouslyClearAll`) report nothing.
|
|
16
16
|
*/
|
|
17
17
|
export declare function trackBoardWrites(ops: FactoryStorageOps, changed: (scope: BoardScope) => void | Promise<void>): FactoryStorageOps;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"board-version.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/board-version.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAmB,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"board-version.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/board-version.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAmB,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAQjG;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,EAAE,gBAU3C,CAAC;AAEF,sFAAsF;AACtF,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AA6BD;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,iBAAiB,EACtB,OAAO,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACnD,iBAAiB,CA6CnB;AAED,6FAA6F;AAC7F,qBAAa,WAAW;;IAGtB,GAAG,UAAW,UAAU,KAAG,IAAI,CAE7B;IAEF,MAAM,IAAI,UAAU,EAAE,CAErB;CACF;AAED,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,iBAAiB,EAAE,MAAM,EAAE,SAAS,UAAU,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAgB5G;AAED,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,iBAAiB,EACtB,KAAK,EAAE,MAAM,EACb,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAM7B"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { FACTORY_BOARD_ITEMS_SCHEMA, FACTORY_WORK_ITEMS_SCHEMA, FACTORY_WORK_ITEM_SOURCES_SCHEMA } from "./work-item-schema.js";
|
|
1
2
|
import { randomUUID } from "crypto";
|
|
2
3
|
// src/storage/domains/work-items/board-version.ts
|
|
3
4
|
/**
|
|
4
5
|
* One row per project whose `version` is replaced after every committed write to that project's
|
|
5
|
-
*
|
|
6
|
+
* cards (board items and work items). Readers of the full card list compare it against the version their snapshot was
|
|
6
7
|
* taken at, so an unchanged board costs one indexed row read instead of every card.
|
|
7
8
|
*/
|
|
8
9
|
const FACTORY_BOARD_VERSIONS_SCHEMA = {
|
|
@@ -19,6 +20,16 @@ const FACTORY_BOARD_VERSIONS_SCHEMA = {
|
|
|
19
20
|
columns: ["org_id", "factory_project_id"]
|
|
20
21
|
}]
|
|
21
22
|
};
|
|
23
|
+
/** The tables a card is stored in. */
|
|
24
|
+
const CARD_TABLES = /* @__PURE__ */ new Set([
|
|
25
|
+
FACTORY_BOARD_ITEMS_SCHEMA.name,
|
|
26
|
+
FACTORY_WORK_ITEMS_SCHEMA.name,
|
|
27
|
+
FACTORY_WORK_ITEM_SOURCES_SCHEMA.name,
|
|
28
|
+
"work_items"
|
|
29
|
+
]);
|
|
30
|
+
function isCardTable(collection) {
|
|
31
|
+
return CARD_TABLES.has(collection);
|
|
32
|
+
}
|
|
22
33
|
const scopeKey = (scope) => `${scope.orgId}\u0000${scope.factoryProjectId ?? ""}`;
|
|
23
34
|
function scopeOfRow(row) {
|
|
24
35
|
if (!row || typeof row.org_id !== "string") return void 0;
|
|
@@ -35,7 +46,7 @@ function scopeOfWhere(where) {
|
|
|
35
46
|
} : { orgId: where.org_id };
|
|
36
47
|
}
|
|
37
48
|
/**
|
|
38
|
-
* Wrap `ops` so every write to
|
|
49
|
+
* Wrap `ops` so every write to a card table reports the board it changed, once the write has
|
|
39
50
|
* resolved. Writes outside any tenant (`dangerouslyClearAll`) report nothing.
|
|
40
51
|
*/
|
|
41
52
|
function trackBoardWrites(ops, changed) {
|
|
@@ -53,19 +64,19 @@ function trackBoardWrites(ops, changed) {
|
|
|
53
64
|
patched = patch != null;
|
|
54
65
|
return patch;
|
|
55
66
|
}, ...args);
|
|
56
|
-
if (collection
|
|
67
|
+
if (isCardTable(collection) && patched) await report(scopeOfRow(row));
|
|
57
68
|
return row;
|
|
58
69
|
};
|
|
59
70
|
case "insertOne":
|
|
60
71
|
case "upsertOne": return async (collection, ...args) => {
|
|
61
72
|
const row = await value.call(target, collection, ...args);
|
|
62
|
-
if (collection
|
|
73
|
+
if (isCardTable(collection)) await report(scopeOfRow(row));
|
|
63
74
|
return row;
|
|
64
75
|
};
|
|
65
76
|
case "updateMany":
|
|
66
77
|
case "deleteMany": return async (collection, where, ...args) => {
|
|
67
78
|
const count = await value.call(target, collection, where, ...args);
|
|
68
|
-
if (collection
|
|
79
|
+
if (isCardTable(collection) && count > 0) await report(scopeOfWhere(where));
|
|
69
80
|
return count;
|
|
70
81
|
};
|
|
71
82
|
default: return value.bind(target);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"board-version.js","names":[],"sources":["../../../../src/storage/domains/work-items/board-version.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { CollectionSchema, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\n\n/**\n * One row per project whose `version` is replaced after every committed write to that project's\n *
|
|
1
|
+
{"version":3,"file":"board-version.js","names":[],"sources":["../../../../src/storage/domains/work-items/board-version.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { CollectionSchema, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\n\nimport {\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n} from './work-item-schema.js';\n\n/**\n * One row per project whose `version` is replaced after every committed write to that project's\n * cards (board items and work items). Readers of the full card list compare it against the version their snapshot was\n * taken at, so an unchanged board costs one indexed row read instead of every card.\n */\nexport const FACTORY_BOARD_VERSIONS_SCHEMA: CollectionSchema = {\n name: 'factory_board_versions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n version: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_board_versions_scope_unique', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A project, or every project in an org when a write's filter only names the org. */\nexport interface BoardScope {\n orgId: string;\n factoryProjectId?: string;\n}\n\n/** The tables a card is stored in. */\nconst CARD_TABLES = new Set([\n FACTORY_BOARD_ITEMS_SCHEMA.name,\n FACTORY_WORK_ITEMS_SCHEMA.name,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA.name,\n 'work_items',\n]);\nfunction isCardTable(collection: string): boolean {\n return CARD_TABLES.has(collection);\n}\n\nconst scopeKey = (scope: BoardScope) => `${scope.orgId}\\u0000${scope.factoryProjectId ?? ''}`;\n\nfunction scopeOfRow(row: Record<string, unknown> | null): BoardScope | undefined {\n if (!row || typeof row.org_id !== 'string') return undefined;\n return typeof row.factory_project_id === 'string'\n ? { orgId: row.org_id, factoryProjectId: row.factory_project_id }\n : { orgId: row.org_id };\n}\n\nfunction scopeOfWhere(where: CollectionWhere): BoardScope | undefined {\n if (typeof where.org_id !== 'string') return undefined;\n return typeof where.factory_project_id === 'string'\n ? { orgId: where.org_id, factoryProjectId: where.factory_project_id }\n : { orgId: where.org_id };\n}\n\n/**\n * Wrap `ops` so every write to a card table reports the board it changed, once the write has\n * resolved. Writes outside any tenant (`dangerouslyClearAll`) report nothing.\n */\nexport function trackBoardWrites(\n ops: FactoryStorageOps,\n changed: (scope: BoardScope) => void | Promise<void>,\n): FactoryStorageOps {\n const report = async (scope: BoardScope | undefined) => {\n if (scope) await changed(scope);\n };\n return new Proxy(ops, {\n get(target, property, receiver) {\n const value = Reflect.get(target, property, receiver);\n if (typeof value !== 'function') return value;\n switch (property) {\n case 'updateAtomic':\n return async (collection: string, where: unknown, updater: (row: unknown) => unknown, ...args: unknown[]) => {\n let patched = false;\n const row = await value.call(\n target,\n collection,\n where,\n async (current: unknown) => {\n const patch = await updater(current);\n patched = patch != null;\n return patch;\n },\n ...args,\n );\n if (isCardTable(collection) && patched) await report(scopeOfRow(row));\n return row;\n };\n case 'insertOne':\n case 'upsertOne':\n return async (collection: string, ...args: unknown[]) => {\n const row = await value.call(target, collection, ...args);\n if (isCardTable(collection)) await report(scopeOfRow(row));\n return row;\n };\n case 'updateMany':\n case 'deleteMany':\n return async (collection: string, where: CollectionWhere, ...args: unknown[]) => {\n const count: number = await value.call(target, collection, where, ...args);\n if (isCardTable(collection) && count > 0) await report(scopeOfWhere(where));\n return count;\n };\n default:\n return value.bind(target);\n }\n },\n });\n}\n\n/** Collects the boards a transaction changed so they can be bumped once it has committed. */\nexport class BoardScopes {\n readonly #scopes = new Map<string, BoardScope>();\n\n add = (scope: BoardScope): void => {\n this.#scopes.set(scopeKey(scope), scope);\n };\n\n values(): BoardScope[] {\n return [...this.#scopes.values()];\n }\n}\n\nexport async function bumpBoardVersions(ops: FactoryStorageOps, scopes: readonly BoardScope[]): Promise<void> {\n for (const scope of scopes) {\n const version = randomUUID();\n const updated_at = new Date();\n if (scope.factoryProjectId) {\n await ops.upsertOne(FACTORY_BOARD_VERSIONS_SCHEMA.name, ['org_id', 'factory_project_id'], {\n org_id: scope.orgId,\n factory_project_id: scope.factoryProjectId,\n version,\n updated_at,\n });\n } else {\n // Projects without a row yet have no version, which never matches a snapshot.\n await ops.updateMany(FACTORY_BOARD_VERSIONS_SCHEMA.name, { org_id: scope.orgId }, { version, updated_at });\n }\n }\n}\n\nexport async function readBoardVersion(\n ops: FactoryStorageOps,\n orgId: string,\n factoryProjectId: string,\n): Promise<string | undefined> {\n const row = await ops.findOne<{ version: string }>(FACTORY_BOARD_VERSIONS_SCHEMA.name, {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n });\n return row?.version;\n}\n"],"mappings":";;;;;;;;AAcA,MAAa,gCAAkD;CAC7D,MAAM;CACN,S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,MAAM,EAAE,QAAQ,MAAM,MAAM,GAAG;GAAE;GAAS;EAAW,CAAC;CAE7G;AACF;AAEA,eAAsB,iBACpB,KACA,OACA,kBAC6B;CAK7B,QAAO,MAJW,IAAI,QAA6B,8BAA8B,MAAM;EACrF,QAAQ;EACR,oBAAoB;CACtB,CAAC,EAAA,EACW;AACd"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { CollectionListOptions, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';
|
|
2
|
+
import type { WorkItemDbRow } from './base.js';
|
|
3
|
+
import type { WorkItemDbRecord, WorkItemSourceDbRecord } from './work-item-schema.js';
|
|
4
|
+
export type CardInsert = Pick<WorkItemDbRow, 'org_id' | 'factory_project_id' | 'board' | 'external_source' | 'source_key' | 'parent_work_item_id' | 'title' | 'stages' | 'stage_history' | 'sessions' | 'metadata' | 'revision' | 'created_by' | 'created_at' | 'updated_at'>;
|
|
5
|
+
export declare function splitCardRows(card: WorkItemDbRow, options: {
|
|
6
|
+
workItemId: string;
|
|
7
|
+
revision?: number;
|
|
8
|
+
}): {
|
|
9
|
+
previousHash?: string | null;
|
|
10
|
+
workItem: WorkItemDbRecord;
|
|
11
|
+
source: WorkItemSourceDbRecord | null;
|
|
12
|
+
boardItem: {
|
|
13
|
+
id: string;
|
|
14
|
+
org_id: string;
|
|
15
|
+
factory_project_id: string;
|
|
16
|
+
work_item_id: string;
|
|
17
|
+
triage_type: import("../../../rules/types.js").FactoryTriageType | null;
|
|
18
|
+
accepted_at: Date | null;
|
|
19
|
+
autonomy_armed_at: Date | null;
|
|
20
|
+
plans_preapproved_at: Date | null;
|
|
21
|
+
board: string | null;
|
|
22
|
+
parent_board_item_id: string | null;
|
|
23
|
+
stages: string[];
|
|
24
|
+
stage_history: unknown[];
|
|
25
|
+
sessions: Record<string, unknown>;
|
|
26
|
+
metadata: Record<string, unknown> | null;
|
|
27
|
+
comment_count: number;
|
|
28
|
+
feed_activity_at: Date | null;
|
|
29
|
+
revision: number;
|
|
30
|
+
created_by: string;
|
|
31
|
+
created_at: Date;
|
|
32
|
+
updated_at: Date;
|
|
33
|
+
migrated_from_updated_at: null;
|
|
34
|
+
migrated_from_hash: null;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
/** Compatibility row operations over work, source and placement tables. Writes require transaction ops. */
|
|
38
|
+
export declare class Cards {
|
|
39
|
+
#private;
|
|
40
|
+
private readonly ops;
|
|
41
|
+
private readonly legacyMode;
|
|
42
|
+
constructor(ops: FactoryStorageOps, legacyMode?: boolean);
|
|
43
|
+
findOne(where: CollectionWhere): Promise<WorkItemDbRow | null>;
|
|
44
|
+
findMany(where: CollectionWhere, options?: CollectionListOptions): Promise<WorkItemDbRow[]>;
|
|
45
|
+
insertOne(card: CardInsert): Promise<WorkItemDbRow>;
|
|
46
|
+
updateAtomic(where: CollectionWhere, updater: (card: WorkItemDbRow) => Partial<WorkItemDbRow> | null | Promise<Partial<WorkItemDbRow> | null>): Promise<WorkItemDbRow | null>;
|
|
47
|
+
updateMany(where: CollectionWhere, patch: Partial<WorkItemDbRow>): Promise<number>;
|
|
48
|
+
deleteMany(where: CollectionWhere): Promise<number>;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=cards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cards.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/cards.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAGtG,OAAO,KAAK,EAA0B,aAAa,EAAE,MAAM,WAAW,CAAC;AASvE,OAAO,KAAK,EAAqB,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAiBzG,MAAM,MAAM,UAAU,GAAG,IAAI,CAC3B,aAAa,EACX,QAAQ,GACR,oBAAoB,GACpB,OAAO,GACP,iBAAiB,GACjB,YAAY,GACZ,qB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HEMA, FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA, FACTORY_WORK_ITEMS_SCHEMA, FACTORY_WORK_ITEM_SOURCES_SCHEMA, FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA, WORK_ITEMS_SCHEMA } from "./work-item-schema.js";
|
|
2
|
+
import { splitLegacyWorkItem } from "../../../work-items/split-migration.js";
|
|
3
|
+
import { randomUUID } from "crypto";
|
|
4
|
+
// src/storage/domains/work-items/cards.ts
|
|
5
|
+
const BOARD_ITEMS = FACTORY_BOARD_ITEMS_SCHEMA.name;
|
|
6
|
+
const WORK_ITEMS = FACTORY_WORK_ITEMS_SCHEMA.name;
|
|
7
|
+
const SOURCES = FACTORY_WORK_ITEM_SOURCES_SCHEMA.name;
|
|
8
|
+
const BOARD_COLUMNS = new Set(Object.keys(FACTORY_BOARD_ITEMS_SCHEMA.columns));
|
|
9
|
+
const PROJECTED_COLUMNS = /* @__PURE__ */ new Set([
|
|
10
|
+
"work_item",
|
|
11
|
+
"work_item_sources",
|
|
12
|
+
"external_source",
|
|
13
|
+
"source_key",
|
|
14
|
+
"title",
|
|
15
|
+
"comment_count",
|
|
16
|
+
"feed_activity_at"
|
|
17
|
+
]);
|
|
18
|
+
const ID_BATCH = 500;
|
|
19
|
+
function splitCardRows(card, options) {
|
|
20
|
+
const rows = splitLegacyWorkItem(card, options);
|
|
21
|
+
return {
|
|
22
|
+
...rows,
|
|
23
|
+
boardItem: {
|
|
24
|
+
...rows.boardItem,
|
|
25
|
+
migrated_from_updated_at: null,
|
|
26
|
+
migrated_from_hash: null
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function externalSourceOf(source) {
|
|
31
|
+
if (!source) return null;
|
|
32
|
+
const prefix = `${source.source_type}:${source.workspace_id ? `${source.workspace_id}:` : ""}`;
|
|
33
|
+
return {
|
|
34
|
+
integrationId: source.integration_id,
|
|
35
|
+
type: source.source_type,
|
|
36
|
+
...source.workspace_id ? { workspaceId: source.workspace_id } : {},
|
|
37
|
+
externalId: source.external_id.startsWith(prefix) ? source.external_id.slice(prefix.length) : source.external_id,
|
|
38
|
+
...source.url ? { url: source.url } : {}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function joinCard(board, work, sources) {
|
|
42
|
+
if (!work) throw new Error(`Board item ${board.id} has no work item ${board.work_item_id}.`);
|
|
43
|
+
const source = sources[0];
|
|
44
|
+
return {
|
|
45
|
+
work_item: work,
|
|
46
|
+
work_item_sources: sources,
|
|
47
|
+
id: board.id,
|
|
48
|
+
org_id: board.org_id,
|
|
49
|
+
factory_project_id: board.factory_project_id,
|
|
50
|
+
board: board.board,
|
|
51
|
+
external_source: externalSourceOf(source),
|
|
52
|
+
source_key: source?.source_key ?? null,
|
|
53
|
+
claim_key: null,
|
|
54
|
+
parent_work_item_id: board.parent_board_item_id,
|
|
55
|
+
title: work.title,
|
|
56
|
+
stages: board.stages,
|
|
57
|
+
stage_history: board.stage_history,
|
|
58
|
+
sessions: board.sessions,
|
|
59
|
+
metadata: board.metadata || source?.metadata ? {
|
|
60
|
+
...board.metadata,
|
|
61
|
+
...source?.metadata
|
|
62
|
+
} : null,
|
|
63
|
+
triage_type: board.triage_type ?? null,
|
|
64
|
+
autonomy_armed_at: board.autonomy_armed_at ?? null,
|
|
65
|
+
plans_preapproved_at: board.plans_preapproved_at ?? null,
|
|
66
|
+
accepted_at: board.accepted_at ?? null,
|
|
67
|
+
comment_count: board.comment_count ?? 0,
|
|
68
|
+
feed_activity_at: board.feed_activity_at ?? null,
|
|
69
|
+
revision: board.revision,
|
|
70
|
+
created_by: board.created_by,
|
|
71
|
+
created_at: board.created_at,
|
|
72
|
+
updated_at: board.updated_at
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function boardColumns(patch, { filter = false } = {}) {
|
|
76
|
+
const columns = {};
|
|
77
|
+
for (const [column, value] of Object.entries(patch)) {
|
|
78
|
+
if (column === "id" && !filter || column === "claim_key" || PROJECTED_COLUMNS.has(column)) continue;
|
|
79
|
+
if (column === "parent_work_item_id") columns.parent_board_item_id = value;
|
|
80
|
+
else if (BOARD_COLUMNS.has(column)) columns[column] = value;
|
|
81
|
+
else throw new Error(`[cards] unknown card column '${column}'.`);
|
|
82
|
+
}
|
|
83
|
+
return columns;
|
|
84
|
+
}
|
|
85
|
+
/** Compatibility row operations over work, source and placement tables. Writes require transaction ops. */
|
|
86
|
+
var Cards = class {
|
|
87
|
+
ops;
|
|
88
|
+
legacyMode;
|
|
89
|
+
constructor(ops, legacyMode = false) {
|
|
90
|
+
this.ops = ops;
|
|
91
|
+
this.legacyMode = legacyMode;
|
|
92
|
+
}
|
|
93
|
+
async #where(where) {
|
|
94
|
+
const { source_key: sourceKey, ...rest } = where;
|
|
95
|
+
const boardWhere = boardColumns(rest, { filter: true });
|
|
96
|
+
if (sourceKey === void 0) return boardWhere;
|
|
97
|
+
const scope = {};
|
|
98
|
+
if (rest.org_id !== void 0) scope.org_id = rest.org_id;
|
|
99
|
+
if (rest.factory_project_id !== void 0) scope.factory_project_id = rest.factory_project_id;
|
|
100
|
+
const sources = await this.ops.findMany(SOURCES, {
|
|
101
|
+
...scope,
|
|
102
|
+
source_key: sourceKey
|
|
103
|
+
});
|
|
104
|
+
return sources.length ? {
|
|
105
|
+
...boardWhere,
|
|
106
|
+
work_item_id: { in: sources.map((source) => source.work_item_id) }
|
|
107
|
+
} : null;
|
|
108
|
+
}
|
|
109
|
+
async #join(boards) {
|
|
110
|
+
const ids = [...new Set(boards.map((board) => board.work_item_id))];
|
|
111
|
+
const items = /* @__PURE__ */ new Map();
|
|
112
|
+
const sources = /* @__PURE__ */ new Map();
|
|
113
|
+
for (let index = 0; index < ids.length; index += ID_BATCH) {
|
|
114
|
+
const pageIds = ids.slice(index, index + ID_BATCH);
|
|
115
|
+
const page = await this.ops.findMany(WORK_ITEMS, { id: { in: pageIds } });
|
|
116
|
+
for (const item of page) items.set(item.id, item);
|
|
117
|
+
const sourcePage = await this.ops.findMany(SOURCES, { work_item_id: { in: pageIds } }, { orderBy: [["created_at", "asc"], ["id", "asc"]] });
|
|
118
|
+
for (const source of sourcePage) {
|
|
119
|
+
const group = sources.get(source.work_item_id) ?? [];
|
|
120
|
+
group.push(source);
|
|
121
|
+
sources.set(source.work_item_id, group);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return boards.map((board) => joinCard(board, items.get(board.work_item_id) ?? null, sources.get(board.work_item_id) ?? []));
|
|
125
|
+
}
|
|
126
|
+
async findOne(where) {
|
|
127
|
+
if (this.legacyMode) return this.ops.findOne(WORK_ITEMS_SCHEMA.name, where);
|
|
128
|
+
const boardWhere = await this.#where(where);
|
|
129
|
+
if (!boardWhere) return null;
|
|
130
|
+
const board = await this.ops.findOne(BOARD_ITEMS, boardWhere);
|
|
131
|
+
return board ? (await this.#join([board]))[0] : null;
|
|
132
|
+
}
|
|
133
|
+
async findMany(where, options) {
|
|
134
|
+
if (this.legacyMode) return this.ops.findMany(WORK_ITEMS_SCHEMA.name, where, options);
|
|
135
|
+
const boardWhere = await this.#where(where);
|
|
136
|
+
return boardWhere ? this.#join(await this.ops.findMany(BOARD_ITEMS, boardWhere, options)) : [];
|
|
137
|
+
}
|
|
138
|
+
async insertOne(card) {
|
|
139
|
+
if (this.legacyMode) return this.ops.insertOne(WORK_ITEMS_SCHEMA.name, card);
|
|
140
|
+
const rows = splitCardRows({
|
|
141
|
+
claim_key: null,
|
|
142
|
+
triage_type: null,
|
|
143
|
+
autonomy_armed_at: null,
|
|
144
|
+
plans_preapproved_at: null,
|
|
145
|
+
accepted_at: null,
|
|
146
|
+
comment_count: 0,
|
|
147
|
+
feed_activity_at: null,
|
|
148
|
+
...card,
|
|
149
|
+
id: randomUUID()
|
|
150
|
+
}, { workItemId: randomUUID() });
|
|
151
|
+
const work = await this.ops.insertOne(WORK_ITEMS, rows.workItem);
|
|
152
|
+
if (rows.source) await this.ops.insertOne(SOURCES, rows.source);
|
|
153
|
+
return joinCard(await this.ops.insertOne(BOARD_ITEMS, rows.boardItem), work, rows.source ? [rows.source] : []);
|
|
154
|
+
}
|
|
155
|
+
async updateAtomic(where, updater) {
|
|
156
|
+
if (this.legacyMode) return this.ops.updateAtomic(WORK_ITEMS_SCHEMA.name, where, updater);
|
|
157
|
+
const boardWhere = await this.#where(where);
|
|
158
|
+
if (!boardWhere) return null;
|
|
159
|
+
const board = await this.ops.updateAtomic(BOARD_ITEMS, boardWhere, async (row) => {
|
|
160
|
+
const joined = (await this.#join([row]))[0];
|
|
161
|
+
const matchedSource = joined.work_item_sources?.find((source) => source.source_key === where.source_key);
|
|
162
|
+
const current = matchedSource ? {
|
|
163
|
+
...joined,
|
|
164
|
+
external_source: externalSourceOf(matchedSource),
|
|
165
|
+
source_key: matchedSource.source_key,
|
|
166
|
+
metadata: row.metadata || matchedSource.metadata ? {
|
|
167
|
+
...row.metadata,
|
|
168
|
+
...matchedSource.metadata
|
|
169
|
+
} : null,
|
|
170
|
+
work_item_sources: [matchedSource, ...joined.work_item_sources.filter((source) => source.id !== matchedSource.id)]
|
|
171
|
+
} : joined;
|
|
172
|
+
const patch = await updater(current);
|
|
173
|
+
if (!patch) return null;
|
|
174
|
+
const columns = boardColumns(patch);
|
|
175
|
+
if (patch.metadata !== void 0) columns.metadata = splitCardRows({
|
|
176
|
+
...current,
|
|
177
|
+
...patch
|
|
178
|
+
}, { workItemId: row.work_item_id }).boardItem.metadata;
|
|
179
|
+
if (patch.title !== void 0 && patch.title !== current.title) await this.ops.updateAtomic(WORK_ITEMS, { id: row.work_item_id }, (work) => ({
|
|
180
|
+
title: patch.title,
|
|
181
|
+
revision: work.revision + 1,
|
|
182
|
+
updated_at: /* @__PURE__ */ new Date()
|
|
183
|
+
}));
|
|
184
|
+
if (patch.metadata !== void 0 || patch.external_source !== void 0) {
|
|
185
|
+
const next = splitCardRows({
|
|
186
|
+
...current,
|
|
187
|
+
...patch
|
|
188
|
+
}, { workItemId: row.work_item_id }).source;
|
|
189
|
+
const previous = current.work_item_sources?.[0];
|
|
190
|
+
if (next && previous) {
|
|
191
|
+
const before = splitCardRows(current, { workItemId: row.work_item_id }).source;
|
|
192
|
+
const changed = Object.fromEntries(Object.entries(next).filter(([key, value]) => ![
|
|
193
|
+
"id",
|
|
194
|
+
"revision",
|
|
195
|
+
"created_at",
|
|
196
|
+
"updated_at",
|
|
197
|
+
"synced_at"
|
|
198
|
+
].includes(key) && JSON.stringify(before?.[key]) !== JSON.stringify(value)));
|
|
199
|
+
if (Object.keys(changed).length) await this.ops.updateAtomic(SOURCES, { id: previous.id }, (source) => {
|
|
200
|
+
const metadata = { ...source.metadata };
|
|
201
|
+
if ("metadata" in changed && next.metadata !== null) for (const key of /* @__PURE__ */ new Set([...Object.keys(before?.metadata ?? {}), ...Object.keys(next.metadata)])) {
|
|
202
|
+
if (JSON.stringify(before?.metadata?.[key]) === JSON.stringify(next.metadata[key])) continue;
|
|
203
|
+
if (Object.hasOwn(next.metadata, key)) metadata[key] = next.metadata[key];
|
|
204
|
+
else delete metadata[key];
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
...changed,
|
|
208
|
+
..."metadata" in changed ? { metadata: next.metadata === null ? null : metadata } : {},
|
|
209
|
+
revision: source.revision + 1,
|
|
210
|
+
updated_at: /* @__PURE__ */ new Date(),
|
|
211
|
+
synced_at: /* @__PURE__ */ new Date()
|
|
212
|
+
};
|
|
213
|
+
});
|
|
214
|
+
} else if (next) await this.ops.insertOne(SOURCES, next);
|
|
215
|
+
else if (previous) await this.ops.deleteMany(SOURCES, { id: previous.id });
|
|
216
|
+
}
|
|
217
|
+
const nativeTitleChanged = !current.external_source && patch.title !== void 0 && patch.title !== current.title;
|
|
218
|
+
if (!(nativeTitleChanged || Object.entries(columns).some(([key, value]) => !["revision", "updated_at"].includes(key) && JSON.stringify(row[key]) !== JSON.stringify(value)))) return null;
|
|
219
|
+
return {
|
|
220
|
+
...columns,
|
|
221
|
+
...nativeTitleChanged ? {
|
|
222
|
+
revision: patch.revision ?? row.revision + 1,
|
|
223
|
+
updated_at: patch.updated_at ?? /* @__PURE__ */ new Date()
|
|
224
|
+
} : {}
|
|
225
|
+
};
|
|
226
|
+
});
|
|
227
|
+
return board ? (await this.#join([board]))[0] : null;
|
|
228
|
+
}
|
|
229
|
+
async updateMany(where, patch) {
|
|
230
|
+
if (this.legacyMode) return this.ops.updateMany(WORK_ITEMS_SCHEMA.name, where, patch);
|
|
231
|
+
const boards = await this.findMany(where);
|
|
232
|
+
for (const board of boards) await this.updateAtomic({ id: board.id }, () => patch);
|
|
233
|
+
return boards.length;
|
|
234
|
+
}
|
|
235
|
+
async deleteMany(where) {
|
|
236
|
+
if (this.legacyMode) return this.ops.deleteMany(WORK_ITEMS_SCHEMA.name, where);
|
|
237
|
+
const boardWhere = await this.#where(where);
|
|
238
|
+
if (!boardWhere) return 0;
|
|
239
|
+
const boards = await this.ops.findMany(BOARD_ITEMS, boardWhere, { orderBy: [["id", "asc"]] });
|
|
240
|
+
for (const board of boards) {
|
|
241
|
+
const scope = {
|
|
242
|
+
org_id: board.org_id,
|
|
243
|
+
factory_project_id: board.factory_project_id
|
|
244
|
+
};
|
|
245
|
+
if (!await this.ops.updateAtomic(FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name, { id: board.id }, () => null)) await this.ops.insertOne(FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name, {
|
|
246
|
+
...scope,
|
|
247
|
+
id: board.id
|
|
248
|
+
});
|
|
249
|
+
if (!await this.ops.updateAtomic(BOARD_ITEMS, {
|
|
250
|
+
...scope,
|
|
251
|
+
id: board.id
|
|
252
|
+
}, () => null)) continue;
|
|
253
|
+
await this.ops.updateAtomic(WORK_ITEMS, {
|
|
254
|
+
...scope,
|
|
255
|
+
id: board.work_item_id
|
|
256
|
+
}, () => null);
|
|
257
|
+
const sources = await this.ops.findMany(SOURCES, {
|
|
258
|
+
...scope,
|
|
259
|
+
work_item_id: board.work_item_id
|
|
260
|
+
}, { orderBy: [["id", "asc"]] });
|
|
261
|
+
for (const source of sources) await this.ops.updateAtomic(SOURCES, { id: source.id }, () => null);
|
|
262
|
+
await this.ops.deleteMany(SOURCES, {
|
|
263
|
+
...scope,
|
|
264
|
+
work_item_id: board.work_item_id
|
|
265
|
+
});
|
|
266
|
+
await this.ops.deleteMany(BOARD_ITEMS, {
|
|
267
|
+
...scope,
|
|
268
|
+
id: board.id
|
|
269
|
+
});
|
|
270
|
+
await this.ops.deleteMany(WORK_ITEMS, {
|
|
271
|
+
...scope,
|
|
272
|
+
id: board.work_item_id
|
|
273
|
+
});
|
|
274
|
+
await this.ops.upsertOne(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, ["id"], {
|
|
275
|
+
...scope,
|
|
276
|
+
id: board.id
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return boards.length;
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
export { Cards, splitCardRows };
|
|
283
|
+
|
|
284
|
+
//# sourceMappingURL=cards.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cards.js","names":[],"sources":["../../../../src/storage/domains/work-items/cards.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { CollectionListOptions, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { splitLegacyWorkItem } from '../../../work-items/split-migration.js';\nimport type { ExternalWorkItemSource, WorkItemDbRow } from './base.js';\nimport {\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n WORK_ITEMS_SCHEMA,\n} from './work-item-schema.js';\nimport type { BoardItemDbRecord, WorkItemDbRecord, WorkItemSourceDbRecord } from './work-item-schema.js';\n\nconst BOARD_ITEMS = FACTORY_BOARD_ITEMS_SCHEMA.name;\nconst WORK_ITEMS = FACTORY_WORK_ITEMS_SCHEMA.name;\nconst SOURCES = FACTORY_WORK_ITEM_SOURCES_SCHEMA.name;\nconst BOARD_COLUMNS = new Set(Object.keys(FACTORY_BOARD_ITEMS_SCHEMA.columns));\nconst PROJECTED_COLUMNS = new Set([\n 'work_item',\n 'work_item_sources',\n 'external_source',\n 'source_key',\n 'title',\n 'comment_count',\n 'feed_activity_at',\n]);\nconst ID_BATCH = 500;\n\nexport type CardInsert = Pick<\n WorkItemDbRow,\n | 'org_id'\n | 'factory_project_id'\n | 'board'\n | 'external_source'\n | 'source_key'\n | 'parent_work_item_id'\n | 'title'\n | 'stages'\n | 'stage_history'\n | 'sessions'\n | 'metadata'\n | 'revision'\n | 'created_by'\n | 'created_at'\n | 'updated_at'\n>;\n\nexport function splitCardRows(card: WorkItemDbRow, options: { workItemId: string; revision?: number }) {\n const rows = splitLegacyWorkItem(card, options);\n return { ...rows, boardItem: { ...rows.boardItem, migrated_from_updated_at: null, migrated_from_hash: null } };\n}\n\nfunction externalSourceOf(source: WorkItemSourceDbRecord | undefined): ExternalWorkItemSource | null {\n if (!source) return null;\n const prefix = `${source.source_type}:${source.workspace_id ? `${source.workspace_id}:` : ''}`;\n return {\n integrationId: source.integration_id,\n type: source.source_type,\n ...(source.workspace_id ? { workspaceId: source.workspace_id } : {}),\n externalId: source.external_id.startsWith(prefix) ? source.external_id.slice(prefix.length) : source.external_id,\n ...(source.url ? { url: source.url } : {}),\n };\n}\n\nfunction joinCard(\n board: BoardItemDbRecord,\n work: WorkItemDbRecord | null,\n sources: WorkItemSourceDbRecord[],\n): WorkItemDbRow {\n if (!work) throw new Error(`Board item ${board.id} has no work item ${board.work_item_id}.`);\n const source = sources[0];\n return {\n work_item: work,\n work_item_sources: sources,\n id: board.id,\n org_id: board.org_id,\n factory_project_id: board.factory_project_id,\n board: board.board,\n external_source: externalSourceOf(source),\n source_key: source?.source_key ?? null,\n claim_key: null,\n parent_work_item_id: board.parent_board_item_id,\n title: work.title,\n stages: board.stages,\n stage_history: board.stage_history as WorkItemDbRow['stage_history'],\n sessions: board.sessions as WorkItemDbRow['sessions'],\n metadata: board.metadata || source?.metadata ? { ...board.metadata, ...source?.metadata } : null,\n triage_type: board.triage_type ?? null,\n autonomy_armed_at: board.autonomy_armed_at ?? null,\n plans_preapproved_at: board.plans_preapproved_at ?? null,\n accepted_at: board.accepted_at ?? null,\n comment_count: board.comment_count ?? 0,\n feed_activity_at: board.feed_activity_at ?? null,\n revision: board.revision,\n created_by: board.created_by,\n created_at: board.created_at,\n updated_at: board.updated_at,\n };\n}\n\nfunction boardColumns(patch: Partial<WorkItemDbRow>, { filter = false } = {}): Partial<BoardItemDbRecord> {\n const columns: Record<string, unknown> = {};\n for (const [column, value] of Object.entries(patch)) {\n if ((column === 'id' && !filter) || column === 'claim_key' || PROJECTED_COLUMNS.has(column)) continue;\n if (column === 'parent_work_item_id') columns.parent_board_item_id = value;\n else if (BOARD_COLUMNS.has(column)) columns[column] = value;\n else throw new Error(`[cards] unknown card column '${column}'.`);\n }\n return columns as Partial<BoardItemDbRecord>;\n}\n\n/** Compatibility row operations over work, source and placement tables. Writes require transaction ops. */\nexport class Cards {\n constructor(\n private readonly ops: FactoryStorageOps,\n private readonly legacyMode = false,\n ) {}\n\n async #where(where: CollectionWhere): Promise<CollectionWhere | null> {\n const { source_key: sourceKey, ...rest } = where;\n const boardWhere = boardColumns(rest as Partial<WorkItemDbRow>, { filter: true }) as CollectionWhere;\n if (sourceKey === undefined) return boardWhere;\n const scope: CollectionWhere = {};\n if (rest.org_id !== undefined) scope.org_id = rest.org_id;\n if (rest.factory_project_id !== undefined) scope.factory_project_id = rest.factory_project_id;\n const sources = await this.ops.findMany<WorkItemSourceDbRecord>(SOURCES, { ...scope, source_key: sourceKey });\n return sources.length ? { ...boardWhere, work_item_id: { in: sources.map(source => source.work_item_id) } } : null;\n }\n\n async #join(boards: readonly BoardItemDbRecord[]): Promise<WorkItemDbRow[]> {\n const ids = [...new Set(boards.map(board => board.work_item_id))];\n const items = new Map<string, WorkItemDbRecord>();\n const sources = new Map<string, WorkItemSourceDbRecord[]>();\n for (let index = 0; index < ids.length; index += ID_BATCH) {\n const pageIds = ids.slice(index, index + ID_BATCH);\n const page = await this.ops.findMany<WorkItemDbRecord>(WORK_ITEMS, { id: { in: pageIds } });\n for (const item of page) items.set(item.id, item);\n const sourcePage = await this.ops.findMany<WorkItemSourceDbRecord>(\n SOURCES,\n { work_item_id: { in: pageIds } },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n },\n );\n for (const source of sourcePage) {\n const group = sources.get(source.work_item_id) ?? [];\n group.push(source);\n sources.set(source.work_item_id, group);\n }\n }\n return boards.map(board =>\n joinCard(board, items.get(board.work_item_id) ?? null, sources.get(board.work_item_id) ?? []),\n );\n }\n\n async findOne(where: CollectionWhere): Promise<WorkItemDbRow | null> {\n if (this.legacyMode) return this.ops.findOne(WORK_ITEMS_SCHEMA.name, where);\n const boardWhere = await this.#where(where);\n if (!boardWhere) return null;\n const board = await this.ops.findOne<BoardItemDbRecord>(BOARD_ITEMS, boardWhere);\n return board ? (await this.#join([board]))[0]! : null;\n }\n\n async findMany(where: CollectionWhere, options?: CollectionListOptions): Promise<WorkItemDbRow[]> {\n if (this.legacyMode) return this.ops.findMany(WORK_ITEMS_SCHEMA.name, where, options);\n const boardWhere = await this.#where(where);\n return boardWhere ? this.#join(await this.ops.findMany<BoardItemDbRecord>(BOARD_ITEMS, boardWhere, options)) : [];\n }\n\n async insertOne(card: CardInsert): Promise<WorkItemDbRow> {\n if (this.legacyMode) return this.ops.insertOne<WorkItemDbRow>(WORK_ITEMS_SCHEMA.name, card);\n const rows = splitCardRows(\n {\n claim_key: null,\n triage_type: null,\n autonomy_armed_at: null,\n plans_preapproved_at: null,\n accepted_at: null,\n comment_count: 0,\n feed_activity_at: null,\n ...card,\n id: randomUUID(),\n },\n { workItemId: randomUUID() },\n );\n const work = await this.ops.insertOne<WorkItemDbRecord>(WORK_ITEMS, rows.workItem);\n if (rows.source) await this.ops.insertOne(SOURCES, rows.source);\n const board = await this.ops.insertOne<BoardItemDbRecord>(BOARD_ITEMS, rows.boardItem);\n return joinCard(board, work, rows.source ? [rows.source] : []);\n }\n\n async updateAtomic(\n where: CollectionWhere,\n updater: (card: WorkItemDbRow) => Partial<WorkItemDbRow> | null | Promise<Partial<WorkItemDbRow> | null>,\n ): Promise<WorkItemDbRow | null> {\n if (this.legacyMode) return this.ops.updateAtomic(WORK_ITEMS_SCHEMA.name, where, updater);\n const boardWhere = await this.#where(where);\n if (!boardWhere) return null;\n const board = await this.ops.updateAtomic<BoardItemDbRecord>(BOARD_ITEMS, boardWhere, async row => {\n const joined = (await this.#join([row]))[0]!;\n const matchedSource = joined.work_item_sources?.find(source => source.source_key === where.source_key);\n const current = matchedSource\n ? {\n ...joined,\n external_source: externalSourceOf(matchedSource),\n source_key: matchedSource.source_key,\n metadata: row.metadata || matchedSource.metadata ? { ...row.metadata, ...matchedSource.metadata } : null,\n work_item_sources: [\n matchedSource,\n ...joined.work_item_sources!.filter(source => source.id !== matchedSource.id),\n ],\n }\n : joined;\n const patch = await updater(current);\n if (!patch) return null;\n const columns = boardColumns(patch);\n if (patch.metadata !== undefined) {\n const next = { ...current, ...patch };\n const split = splitCardRows(next, { workItemId: row.work_item_id });\n columns.metadata = split.boardItem.metadata;\n }\n if (patch.title !== undefined && patch.title !== current.title) {\n await this.ops.updateAtomic<WorkItemDbRecord>(WORK_ITEMS, { id: row.work_item_id }, work => ({\n title: patch.title,\n revision: work.revision + 1,\n updated_at: new Date(),\n }));\n }\n if (patch.metadata !== undefined || patch.external_source !== undefined) {\n const next = splitCardRows({ ...current, ...patch }, { workItemId: row.work_item_id }).source;\n const previous = current.work_item_sources?.[0];\n if (next && previous) {\n const before = splitCardRows(current, { workItemId: row.work_item_id }).source;\n const changed = Object.fromEntries(\n Object.entries(next).filter(\n ([key, value]) =>\n !['id', 'revision', 'created_at', 'updated_at', 'synced_at'].includes(key) &&\n JSON.stringify(before?.[key]) !== JSON.stringify(value),\n ),\n );\n if (Object.keys(changed).length)\n await this.ops.updateAtomic<WorkItemSourceDbRecord>(SOURCES, { id: previous.id }, source => {\n const metadata = { ...source.metadata };\n if ('metadata' in changed && next.metadata !== null) {\n for (const key of new Set([...Object.keys(before?.metadata ?? {}), ...Object.keys(next.metadata)])) {\n if (JSON.stringify(before?.metadata?.[key]) === JSON.stringify(next.metadata[key])) continue;\n if (Object.hasOwn(next.metadata, key)) metadata[key] = next.metadata[key];\n else delete metadata[key];\n }\n }\n return {\n ...changed,\n ...('metadata' in changed ? { metadata: next.metadata === null ? null : metadata } : {}),\n revision: source.revision + 1,\n updated_at: new Date(),\n synced_at: new Date(),\n };\n });\n } else if (next) await this.ops.insertOne(SOURCES, next);\n else if (previous) await this.ops.deleteMany(SOURCES, { id: previous.id });\n }\n const nativeTitleChanged = !current.external_source && patch.title !== undefined && patch.title !== current.title;\n const boardChanged =\n nativeTitleChanged ||\n Object.entries(columns).some(\n ([key, value]) =>\n !['revision', 'updated_at'].includes(key) && JSON.stringify(row[key]) !== JSON.stringify(value),\n );\n if (!boardChanged) return null;\n return {\n ...columns,\n ...(nativeTitleChanged\n ? { revision: patch.revision ?? row.revision + 1, updated_at: patch.updated_at ?? new Date() }\n : {}),\n };\n });\n return board ? (await this.#join([board]))[0]! : null;\n }\n\n async updateMany(where: CollectionWhere, patch: Partial<WorkItemDbRow>): Promise<number> {\n if (this.legacyMode) return this.ops.updateMany(WORK_ITEMS_SCHEMA.name, where, patch);\n const boards = await this.findMany(where);\n for (const board of boards) await this.updateAtomic({ id: board.id }, () => patch);\n return boards.length;\n }\n\n async deleteMany(where: CollectionWhere): Promise<number> {\n if (this.legacyMode) return this.ops.deleteMany(WORK_ITEMS_SCHEMA.name, where);\n const boardWhere = await this.#where(where);\n if (!boardWhere) return 0;\n const boards = await this.ops.findMany<BoardItemDbRecord>(BOARD_ITEMS, boardWhere, { orderBy: [['id', 'asc']] });\n for (const board of boards) {\n const scope = { org_id: board.org_id, factory_project_id: board.factory_project_id };\n const guard = await this.ops.updateAtomic(\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name,\n { id: board.id },\n () => null,\n );\n if (!guard) await this.ops.insertOne(FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name, { ...scope, id: board.id });\n const locked = await this.ops.updateAtomic(BOARD_ITEMS, { ...scope, id: board.id }, () => null);\n if (!locked) continue;\n await this.ops.updateAtomic(WORK_ITEMS, { ...scope, id: board.work_item_id }, () => null);\n const sources = await this.ops.findMany<WorkItemSourceDbRecord>(\n SOURCES,\n { ...scope, work_item_id: board.work_item_id },\n { orderBy: [['id', 'asc']] },\n );\n for (const source of sources) await this.ops.updateAtomic(SOURCES, { id: source.id }, () => null);\n await this.ops.deleteMany(SOURCES, { ...scope, work_item_id: board.work_item_id });\n await this.ops.deleteMany(BOARD_ITEMS, { ...scope, id: board.id });\n await this.ops.deleteMany(WORK_ITEMS, { ...scope, id: board.work_item_id });\n await this.ops.upsertOne(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, ['id'], { ...scope, id: board.id });\n }\n return boards.length;\n }\n}\n"],"mappings":";;;;AAgBA,MAAM,cAAc,2BAA2B;AAC/C,MAAM,aAAa,0BAA0B;AAC7C,MAAM,UAAU,iCAAiC;AACjD,MAAM,gBAAgB,IAAI,IAAI,OAAO,KAAK,2BAA2B,OAAO,CAAC;AAC7E,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,WAAW;AAqBjB,SAAgB,cAAc,MAAqB,SAAoD;CACrG,MAAM,OAAO,oBAAoB,MAAM,OAAO;CAC9C,OAAO;EAAE,GAAG;EAAM,WAAW;GAAE,GAAG,KAAK;GAAW,0BAA0B;GAAM,oBAAoB;EAAK;CAAE;AAC/G;AAEA,SAAS,iBAAiB,QAA2E;CACnG,IAAI,CAAC,QAAQ,O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M;GAAG,CAAC;EACxG;EACA,OAAO,OAAO;CAChB;AACF"}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* never as "the state the board happens to be in now", so re-querying a past
|
|
11
11
|
* window always returns the same numbers.
|
|
12
12
|
*/
|
|
13
|
-
import type {
|
|
13
|
+
import type { Card } from './base.js';
|
|
14
14
|
/** Default window span (days) when the request omits or malforms the range. */
|
|
15
15
|
export declare const DEFAULT_METRICS_WINDOW = 30;
|
|
16
16
|
/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */
|
|
@@ -92,6 +92,6 @@ type Window = {
|
|
|
92
92
|
windowStart: number;
|
|
93
93
|
windowEnd: number;
|
|
94
94
|
};
|
|
95
|
-
export declare function computeFactoryMetrics(boardItems:
|
|
95
|
+
export declare function computeFactoryMetrics(boardItems: Card[], window: Window): FactoryMetrics;
|
|
96
96
|
export {};
|
|
97
97
|
//# sourceMappingURL=metrics.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/metrics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/metrics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEtC,+EAA+E;AAC/E,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,kFAAkF;AAClF,eAAO,MAAM,kBAAkB,MAAM,CAAC;AAqCtC;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,6EAA6E;IAC7E,QAAQ,EAAE;QAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7E,0EAA0E;IAC1E,QAAQ,EAAE,MAAM,CAAC;IACjB,8CAA8C;IAC9C,SAAS,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC/C,2EAA2E;IAC3E,aAAa,EAAE;QACb,KAAK,EAAE,MAAM,CAAC;QACd;;;;;WAKG;QACH,MAAM,EAAE,MAAM,CAAC;QACf;;;;;;WAMG;QACH,OAAO,EAAE,MAAM,CAAC;QAChB;;;;;;WAMG;QACH,QAAQ,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAA;SAAE,CAAC;KAClF,EAAE,CAAC;CACL;AAqBD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,OAAO,EAClB,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,IAAI,GACR;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAY5C;AA2CD,KAAK,MAAM,GAAG;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AA8FzD,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,CAoBxF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.js","names":[],"sources":["../../../../src/storage/domains/work-items/metrics.ts"],"sourcesContent":["/**\n * Aggregation math for the Factory Overview page.\n *\n * Pure functions over `work_items` rows — throughput, lead time, in-flight\n * count, demand mix and per-stage agent coverage, all read from the\n * server-appended `stageHistory` log. Keeping this DB-free makes the math unit\n * testable and lets the route stay a thin shell.\n *\n * Everything windowed is counted as an event that happened inside the window,\n * never as \"the state the board happens to be in now\", so re-querying a past\n * window always returns the same numbers.\n */\n\nimport { isAgentActor } from './base.js';\nimport type { WorkItemRow } from './base.js';\n\n/** Default window span (days) when the request omits or malforms the range. */\nexport const DEFAULT_METRICS_WINDOW = 30;\n/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */\nexport const MAX_METRICS_WINDOW = 366;\n\nconst DAY_MS = 86_400_000;\n\n/** Terminal stage — items here count as completed, not in-flight. */\nconst DONE_STAGE = 'done';\n\n/** Terminal stage for tracked non-completions — never a completion. */\nconst CANCELED_STAGE = 'canceled';\n\n/**\n * Terminal stages — items holding only these are not in-flight. `done` is a\n * completion (feeds throughput/lead time); `canceled` is a tracked\n * non-completion outcome and feeds neither.\n */\nconst TERMINAL_STAGES = new Set([DONE_STAGE, CANCELED_STAGE]);\n\nconst INTAKE_STAGE = 'intake';\n\n/**\n * Pipeline work excludes the inbox as well as the terminal stages: an intake\n * card is queued, not in flight, and its pass through is the poller filing it.\n */\nfunction isPipelineStage(stage: string): boolean {\n return !TERMINAL_STAGES.has(stage) && stage !== INTAKE_STAGE;\n}\n\n/**\n * Cards the Factory ran: starting a run records its session on the row. The\n * integrations sync every issue and PR of a connected repo into the board and\n * those outnumber the Factory's own work by an order of magnitude, so counting\n * them reports the upstream repo's flow as the Factory's.\n */\nfunction hasFactoryRun(item: WorkItemRow): boolean {\n return Object.keys(item.sessions).length > 0;\n}\n\n/**\n * Flow metrics over the cards the Factory ran ({@link hasFactoryRun}) — synced\n * upstream issues and PRs nobody started a run on are not the Factory's work\n * and are excluded from every field below.\n */\nexport interface FactoryMetrics {\n /**\n * Days the series covers: the requested window clipped to the board's life.\n * Days before the first card could hold no completion, so counting them would\n * drag the per-day rate toward zero on a young board.\n */\n daysCovered: number;\n /** Entries into `done` per UTC day, gap-filled across the covered days. */\n throughput: { date: string; count: number }[];\n /** Card creation → `done` for every completion that landed in the window. */\n leadTime: { medianMs: number | null; p90Ms: number | null; samples: number };\n /** Distinct cards in a pipeline stage — past intake, not yet terminal. */\n wipTotal: number;\n /** Cards created in the window, by source. */\n sourceMix: { source: string; count: number }[];\n /** Per-stage agent coverage over first visits that ended in the window. */\n agentCoverage: {\n stage: string;\n /**\n * First visits to this stage that ended in the window. Repeat visits are\n * excluded from both sides: they are rework, already reported as such, and\n * counting them in the denominator alone caps a fully agent-run stage below\n * 100%.\n */\n passes: number;\n /**\n * Of those: passes an agent finished (`exitedBy` is an agent actor). The\n * entry actor is not required — the rules engine is what queues a card into\n * a stage, so demanding both ends would report 0% for stages agents run\n * end to end. Missing `exitedBy` (entries written before exit stamping)\n * does not count.\n */\n byAgent: number;\n /**\n * Outcomes of the agent-finished passes' items as of the window's end,\n * mutually exclusive, first match wins: `reworked` (a later visit to the\n * same stage — deliberately outranks `done`: a pass that needed a redo is a\n * failed pass even if the item eventually merged), then `done`, then\n * `canceled`, then `inFlight`.\n */\n outcomes: { done: number; canceled: number; reworked: number; inFlight: number };\n }[];\n}\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Datetime carrying an explicit `Z` or `±HH:MM` offset. */\nconst ZONED_DATETIME_RE = /(?:[Zz]|[+-]\\d{2}:?\\d{2})$/;\n\nfunction parseRangeParam(value: unknown, boundary: 'from' | 'to'): number | undefined {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n const dateOnly = DATE_ONLY_RE.test(value);\n // Timezone-less datetimes are parsed as server-local by Date.parse, so the\n // window would shift by deployment region — reject them as invalid.\n if (!dateOnly && !ZONED_DATETIME_RE.test(value)) return undefined;\n const time = Date.parse(value);\n if (Number.isNaN(time)) return undefined;\n return boundary === 'to' && dateOnly ? time + DAY_MS : time;\n}\n\nfunction utcDayStart(time: number): number {\n return Date.parse(`${utcDay(time)}T00:00:00Z`);\n}\n\n/**\n * Resolve untrusted `from`/`to` into a bounded half-open UTC window. A date-only\n * `to` covers the whole day; an open/future end resolves to the end of the\n * current UTC day (not `now`) so an event at this instant stays inside the\n * window instead of on its excluded edge.\n */\nexport function parseMetricsRange(\n fromParam: unknown,\n toParam: unknown,\n now: Date,\n): { windowStart: number; windowEnd: number } {\n const nowMs = now.getTime();\n const endOfToday = utcDayStart(nowMs) + DAY_MS;\n const requestedEnd = parseRangeParam(toParam, 'to') ?? endOfToday;\n const windowEnd = Math.min(requestedEnd, endOfToday);\n const lastIncludedDay = utcDayStart(windowEnd - 1);\n const defaultStart = lastIncludedDay - (DEFAULT_METRICS_WINDOW - 1) * DAY_MS;\n const parsedFrom = parseRangeParam(fromParam, 'from');\n let windowStart = parsedFrom !== undefined && parsedFrom < windowEnd ? parsedFrom : defaultStart;\n const earliestStart = lastIncludedDay - (MAX_METRICS_WINDOW - 1) * DAY_MS;\n if (windowStart < earliestStart) windowStart = earliestStart;\n return { windowStart, windowEnd };\n}\n\n/** Stage history is server-appended, so an unparsable stamp is a corrupt row. */\nfunction parseTime(iso: string): number {\n const time = Date.parse(iso);\n if (Number.isNaN(time)) throw new Error(`Unparsable stage-history timestamp: ${iso}`);\n return time;\n}\n\n/** Asserted up front so a corrupt row fails every window, not just the ones that read it. */\nfunction assertParsableHistory(items: WorkItemRow[]): void {\n for (const item of items) {\n for (const entry of item.stageHistory) {\n parseTime(entry.enteredAt);\n if (entry.exitedAt !== undefined) parseTime(entry.exitedAt);\n }\n }\n}\n\n/** Nearest-rank percentile over an unsorted sample list. */\nfunction percentile(samples: number[], fraction: number): number | null {\n if (samples.length === 0) return null;\n const sorted = [...samples].sort((a, b) => a - b);\n const rank = Math.max(1, Math.ceil(fraction * sorted.length));\n return sorted[rank - 1]!;\n}\n\n/** UTC `YYYY-MM-DD` for a timestamp. */\nfunction utcDay(time: number): string {\n return new Date(time).toISOString().slice(0, 10);\n}\n\n/** Stages the item was holding at `time`, replayed from its history. */\nfunction stagesHeldAt(item: WorkItemRow, time: number): Set<string> {\n const held = new Set<string>();\n for (const entry of item.stageHistory) {\n if (parseTime(entry.enteredAt) >= time) continue;\n if (entry.exitedAt !== undefined && parseTime(entry.exitedAt) <= time) continue;\n held.add(entry.stage);\n }\n return held;\n}\n\ntype Window = { windowStart: number; windowEnd: number };\n\n/**\n * Completions per UTC day, plus one lead-time sample each. A completion is an\n * entry *into* `done`, not the state of the card now: a card reopened today\n * must not erase the day it shipped, and a card that shipped twice shipped\n * twice. Days before the oldest card are left out rather than gap-filled with\n * zeroes that would drag the daily average down.\n */\nfunction completions(items: WorkItemRow[], { windowStart, windowEnd }: Window) {\n let earliestItem = Infinity;\n for (const item of items) earliestItem = Math.min(earliestItem, item.createdAt.getTime());\n const boardStart = Number.isFinite(earliestItem) ? utcDayStart(earliestItem) : -Infinity;\n\n const byDay = new Map<string, number>();\n for (let day = Math.max(utcDayStart(windowStart), boardStart); day < windowEnd; day += DAY_MS) {\n byDay.set(utcDay(day), 0);\n }\n\n const leadSamples: number[] = [];\n for (const item of items) {\n for (const entry of item.stageHistory) {\n if (entry.stage !== DONE_STAGE) continue;\n const doneAt = parseTime(entry.enteredAt);\n if (doneAt < windowStart || doneAt >= windowEnd) continue;\n byDay.set(utcDay(doneAt), (byDay.get(utcDay(doneAt)) ?? 0) + 1);\n leadSamples.push(Math.max(0, doneAt - item.createdAt.getTime()));\n }\n }\n return { byDay, leadSamples };\n}\n\n/** Cards holding at least one pipeline stage right now — window-independent. */\nfunction countInFlight(items: WorkItemRow[]): number {\n return items.filter(item => item.stages.some(isPipelineStage)).length;\n}\n\n/** Where the window's cards came from, most common first. */\nfunction demandMix(items: WorkItemRow[], { windowStart, windowEnd }: Window): FactoryMetrics['sourceMix'] {\n const counts = new Map<string, number>();\n for (const item of items) {\n const created = item.createdAt.getTime();\n if (created < windowStart || created >= windowEnd) continue;\n const source = item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual';\n counts.set(source, (counts.get(source) ?? 0) + 1);\n }\n return [...counts.entries()].map(([source, count]) => ({ source, count })).sort((a, b) => b.count - a.count);\n}\n\n/**\n * How much of each stage's work an agent finished, counting a card's first\n * visit to a stage once. Rows appear in insertion order of each stage's first\n * counted exit; only pipeline stages get rows, since intake and terminal\n * stages have no pass to hand over.\n */\nfunction agentCoverage(items: WorkItemRow[], { windowStart, windowEnd }: Window): FactoryMetrics['agentCoverage'] {\n const byStage = new Map<string, FactoryMetrics['agentCoverage'][number]>();\n for (const item of items) {\n const heldAtWindowEnd = stagesHeldAt(item, windowEnd);\n const visited = new Set<string>();\n for (let i = 0; i < item.stageHistory.length; i++) {\n const entry = item.stageHistory[i]!;\n if (!isPipelineStage(entry.stage) || visited.has(entry.stage)) continue;\n visited.add(entry.stage);\n if (entry.exitedAt === undefined) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n\n let row = byStage.get(entry.stage);\n if (!row) {\n row = {\n stage: entry.stage,\n passes: 0,\n byAgent: 0,\n outcomes: { done: 0, canceled: 0, reworked: 0, inFlight: 0 },\n };\n byStage.set(entry.stage, row);\n }\n row.passes += 1;\n if (!isAgentActor(entry.exitedBy)) continue;\n row.byAgent += 1;\n\n const reworked = item.stageHistory.some(\n (later, j) => j > i && later.stage === entry.stage && parseTime(later.enteredAt) < windowEnd,\n );\n if (reworked) row.outcomes.reworked += 1;\n else if (heldAtWindowEnd.has(DONE_STAGE)) row.outcomes.done += 1;\n else if (heldAtWindowEnd.has(CANCELED_STAGE)) row.outcomes.canceled += 1;\n else row.outcomes.inFlight += 1;\n }\n }\n return [...byStage.values()];\n}\n\nexport function computeFactoryMetrics(boardItems: WorkItemRow[], window: Window): FactoryMetrics {\n const items = boardItems.filter(hasFactoryRun);\n assertParsableHistory(items);\n\n const { byDay, leadSamples } = completions(items, window);\n\n return {\n daysCovered: byDay.size,\n throughput: [...byDay.entries()]\n .map(([date, count]) => ({ date, count }))\n .sort((a, b) => a.date.localeCompare(b.date)),\n leadTime: {\n medianMs: percentile(leadSamples, 0.5),\n p90Ms: percentile(leadSamples, 0.9),\n samples: leadSamples.length,\n },\n wipTotal: countInFlight(items),\n sourceMix: demandMix(items, window),\n agentCoverage: agentCoverage(items, window),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,yBAAyB;;AAEtC,MAAa,qBAAqB;AAElC,MAAM,SAAS;;AAGf,MAAM,aAAa;;AAGnB,MAAM,iBAAiB;;;;;;AAOvB,MAAM,kCAAkB,IAAI,IAAI,CAAC,YAAY,cAAc,CAAC;AAE5D,MAAM,eAAe;;;;;AAMrB,SAAS,gBAAgB,OAAwB;CAC/C,OAAO,CAAC,gBAAgB,IAAI,KAAK,KAAK,UAAU;AAClD;;;;;;;AAQA,SAAS,cAAc,MAA4B;CACjD,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,SAAS;AAC7C;AAmDA,MAAM,eAAe;;AAErB,MAAM,oBAAoB;AAE1B,SAAS,gBAAgB,OAAgB,UAA6C;CACpF,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,OAAO,KAAA;CAC5D,MAAM,WAAW,aAAa,KAAK,KAAK;CAGxC,IAAI,CAAC,YAAY,CAAC,kBAAkB,KAAK,KAAK,GAAG,OAAO,KAAA;CACxD,MAAM,OAAO,KAAK,MAAM,KAAK;CAC7B,IAAI,OAAO,MAAM,IAAI,GAAG,OAAO,KAAA;CAC/B,OAAO,aAAa,QAAQ,WAAW,OAAO,SAAS;AACzD;AAEA,SAAS,YAAY,MAAsB;CACzC,OAAO,KAAK,MAAM,GAAG,OAAO,IAAI,EAAE,WAAW;AAC/C;;;;;;;AAQA,SAAgB,kBACd,WACA,SACA,KAC4C;CAE5C,MAAM,aAAa,YADL,IAAI,QACiB,CAAC,IAAI;CACxC,MAAM,eAAe,gBAAgB,SAAS,IAAI,KAAK;CACvD,MAAM,YAAY,KAAK,IAAI,cAAc,UAAU;CACnD,MAAM,kBAAkB,YAAY,YAAY,CAAC;CACjD,MAAM,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YAA2B,QAAgC;CAC/F,MAAM,QAAQ,WAAW,OAAO,aAAa;CAC7C,sBAAsB,KAAK;CAE3B,MAAM,EAAE,OAAO,gBAAgB,YAAY,OAAO,MAAM;CAExD,OAAO;EACL,aAAa,MAAM;EACnB,YAAY,CAAC,GAAG,MAAM,QAAQ,CAAC,CAAC,CAC7B,KAAK,CAAC,MAAM,YAAY;GAAE;GAAM;EAAM,EAAE,CAAC,CACzC,MAAM,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;EAC9C,UAAU;GACR,UAAU,WAAW,aAAa,EAAG;GACrC,OAAO,WAAW,aAAa,EAAG;GAClC,SAAS,YAAY;EACvB;EACA,UAAU,cAAc,KAAK;EAC7B,WAAW,UAAU,OAAO,MAAM;EAClC,eAAe,cAAc,OAAO,MAAM;CAC5C;AACF"}
|
|
1
|
+
{"version":3,"file":"metrics.js","names":[],"sources":["../../../../src/storage/domains/work-items/metrics.ts"],"sourcesContent":["/**\n * Aggregation math for the Factory Overview page.\n *\n * Pure functions over `work_items` rows — throughput, lead time, in-flight\n * count, demand mix and per-stage agent coverage, all read from the\n * server-appended `stageHistory` log. Keeping this DB-free makes the math unit\n * testable and lets the route stay a thin shell.\n *\n * Everything windowed is counted as an event that happened inside the window,\n * never as \"the state the board happens to be in now\", so re-querying a past\n * window always returns the same numbers.\n */\n\nimport { isAgentActor } from './base.js';\nimport type { Card } from './base.js';\n\n/** Default window span (days) when the request omits or malforms the range. */\nexport const DEFAULT_METRICS_WINDOW = 30;\n/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */\nexport const MAX_METRICS_WINDOW = 366;\n\nconst DAY_MS = 86_400_000;\n\n/** Terminal stage — items here count as completed, not in-flight. */\nconst DONE_STAGE = 'done';\n\n/** Terminal stage for tracked non-completions — never a completion. */\nconst CANCELED_STAGE = 'canceled';\n\n/**\n * Terminal stages — items holding only these are not in-flight. `done` is a\n * completion (feeds throughput/lead time); `canceled` is a tracked\n * non-completion outcome and feeds neither.\n */\nconst TERMINAL_STAGES = new Set([DONE_STAGE, CANCELED_STAGE]);\n\nconst INTAKE_STAGE = 'intake';\n\n/**\n * Pipeline work excludes the inbox as well as the terminal stages: an intake\n * card is queued, not in flight, and its pass through is the poller filing it.\n */\nfunction isPipelineStage(stage: string): boolean {\n return !TERMINAL_STAGES.has(stage) && stage !== INTAKE_STAGE;\n}\n\n/**\n * Cards the Factory ran: starting a run records its session on the row. The\n * integrations sync every issue and PR of a connected repo into the board and\n * those outnumber the Factory's own work by an order of magnitude, so counting\n * them reports the upstream repo's flow as the Factory's.\n */\nfunction hasFactoryRun(item: Card): boolean {\n return Object.keys(item.sessions).length > 0;\n}\n\n/**\n * Flow metrics over the cards the Factory ran ({@link hasFactoryRun}) — synced\n * upstream issues and PRs nobody started a run on are not the Factory's work\n * and are excluded from every field below.\n */\nexport interface FactoryMetrics {\n /**\n * Days the series covers: the requested window clipped to the board's life.\n * Days before the first card could hold no completion, so counting them would\n * drag the per-day rate toward zero on a young board.\n */\n daysCovered: number;\n /** Entries into `done` per UTC day, gap-filled across the covered days. */\n throughput: { date: string; count: number }[];\n /** Card creation → `done` for every completion that landed in the window. */\n leadTime: { medianMs: number | null; p90Ms: number | null; samples: number };\n /** Distinct cards in a pipeline stage — past intake, not yet terminal. */\n wipTotal: number;\n /** Cards created in the window, by source. */\n sourceMix: { source: string; count: number }[];\n /** Per-stage agent coverage over first visits that ended in the window. */\n agentCoverage: {\n stage: string;\n /**\n * First visits to this stage that ended in the window. Repeat visits are\n * excluded from both sides: they are rework, already reported as such, and\n * counting them in the denominator alone caps a fully agent-run stage below\n * 100%.\n */\n passes: number;\n /**\n * Of those: passes an agent finished (`exitedBy` is an agent actor). The\n * entry actor is not required — the rules engine is what queues a card into\n * a stage, so demanding both ends would report 0% for stages agents run\n * end to end. Missing `exitedBy` (entries written before exit stamping)\n * does not count.\n */\n byAgent: number;\n /**\n * Outcomes of the agent-finished passes' items as of the window's end,\n * mutually exclusive, first match wins: `reworked` (a later visit to the\n * same stage — deliberately outranks `done`: a pass that needed a redo is a\n * failed pass even if the item eventually merged), then `done`, then\n * `canceled`, then `inFlight`.\n */\n outcomes: { done: number; canceled: number; reworked: number; inFlight: number };\n }[];\n}\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Datetime carrying an explicit `Z` or `±HH:MM` offset. */\nconst ZONED_DATETIME_RE = /(?:[Zz]|[+-]\\d{2}:?\\d{2})$/;\n\nfunction parseRangeParam(value: unknown, boundary: 'from' | 'to'): number | undefined {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n const dateOnly = DATE_ONLY_RE.test(value);\n // Timezone-less datetimes are parsed as server-local by Date.parse, so the\n // window would shift by deployment region — reject them as invalid.\n if (!dateOnly && !ZONED_DATETIME_RE.test(value)) return undefined;\n const time = Date.parse(value);\n if (Number.isNaN(time)) return undefined;\n return boundary === 'to' && dateOnly ? time + DAY_MS : time;\n}\n\nfunction utcDayStart(time: number): number {\n return Date.parse(`${utcDay(time)}T00:00:00Z`);\n}\n\n/**\n * Resolve untrusted `from`/`to` into a bounded half-open UTC window. A date-only\n * `to` covers the whole day; an open/future end resolves to the end of the\n * current UTC day (not `now`) so an event at this instant stays inside the\n * window instead of on its excluded edge.\n */\nexport function parseMetricsRange(\n fromParam: unknown,\n toParam: unknown,\n now: Date,\n): { windowStart: number; windowEnd: number } {\n const nowMs = now.getTime();\n const endOfToday = utcDayStart(nowMs) + DAY_MS;\n const requestedEnd = parseRangeParam(toParam, 'to') ?? endOfToday;\n const windowEnd = Math.min(requestedEnd, endOfToday);\n const lastIncludedDay = utcDayStart(windowEnd - 1);\n const defaultStart = lastIncludedDay - (DEFAULT_METRICS_WINDOW - 1) * DAY_MS;\n const parsedFrom = parseRangeParam(fromParam, 'from');\n let windowStart = parsedFrom !== undefined && parsedFrom < windowEnd ? parsedFrom : defaultStart;\n const earliestStart = lastIncludedDay - (MAX_METRICS_WINDOW - 1) * DAY_MS;\n if (windowStart < earliestStart) windowStart = earliestStart;\n return { windowStart, windowEnd };\n}\n\n/** Stage history is server-appended, so an unparsable stamp is a corrupt row. */\nfunction parseTime(iso: string): number {\n const time = Date.parse(iso);\n if (Number.isNaN(time)) throw new Error(`Unparsable stage-history timestamp: ${iso}`);\n return time;\n}\n\n/** Asserted up front so a corrupt row fails every window, not just the ones that read it. */\nfunction assertParsableHistory(items: Card[]): void {\n for (const item of items) {\n for (const entry of item.stageHistory) {\n parseTime(entry.enteredAt);\n if (entry.exitedAt !== undefined) parseTime(entry.exitedAt);\n }\n }\n}\n\n/** Nearest-rank percentile over an unsorted sample list. */\nfunction percentile(samples: number[], fraction: number): number | null {\n if (samples.length === 0) return null;\n const sorted = [...samples].sort((a, b) => a - b);\n const rank = Math.max(1, Math.ceil(fraction * sorted.length));\n return sorted[rank - 1]!;\n}\n\n/** UTC `YYYY-MM-DD` for a timestamp. */\nfunction utcDay(time: number): string {\n return new Date(time).toISOString().slice(0, 10);\n}\n\n/** Stages the item was holding at `time`, replayed from its history. */\nfunction stagesHeldAt(item: Card, time: number): Set<string> {\n const held = new Set<string>();\n for (const entry of item.stageHistory) {\n if (parseTime(entry.enteredAt) >= time) continue;\n if (entry.exitedAt !== undefined && parseTime(entry.exitedAt) <= time) continue;\n held.add(entry.stage);\n }\n return held;\n}\n\ntype Window = { windowStart: number; windowEnd: number };\n\n/**\n * Completions per UTC day, plus one lead-time sample each. A completion is an\n * entry *into* `done`, not the state of the card now: a card reopened today\n * must not erase the day it shipped, and a card that shipped twice shipped\n * twice. Days before the oldest card are left out rather than gap-filled with\n * zeroes that would drag the daily average down.\n */\nfunction completions(items: Card[], { windowStart, windowEnd }: Window) {\n let earliestItem = Infinity;\n for (const item of items) earliestItem = Math.min(earliestItem, item.createdAt.getTime());\n const boardStart = Number.isFinite(earliestItem) ? utcDayStart(earliestItem) : -Infinity;\n\n const byDay = new Map<string, number>();\n for (let day = Math.max(utcDayStart(windowStart), boardStart); day < windowEnd; day += DAY_MS) {\n byDay.set(utcDay(day), 0);\n }\n\n const leadSamples: number[] = [];\n for (const item of items) {\n for (const entry of item.stageHistory) {\n if (entry.stage !== DONE_STAGE) continue;\n const doneAt = parseTime(entry.enteredAt);\n if (doneAt < windowStart || doneAt >= windowEnd) continue;\n byDay.set(utcDay(doneAt), (byDay.get(utcDay(doneAt)) ?? 0) + 1);\n leadSamples.push(Math.max(0, doneAt - item.createdAt.getTime()));\n }\n }\n return { byDay, leadSamples };\n}\n\n/** Cards holding at least one pipeline stage right now — window-independent. */\nfunction countInFlight(items: Card[]): number {\n return items.filter(item => item.stages.some(isPipelineStage)).length;\n}\n\n/** Where the window's cards came from, most common first. */\nfunction demandMix(items: Card[], { windowStart, windowEnd }: Window): FactoryMetrics['sourceMix'] {\n const counts = new Map<string, number>();\n for (const item of items) {\n const created = item.createdAt.getTime();\n if (created < windowStart || created >= windowEnd) continue;\n const source = item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual';\n counts.set(source, (counts.get(source) ?? 0) + 1);\n }\n return [...counts.entries()].map(([source, count]) => ({ source, count })).sort((a, b) => b.count - a.count);\n}\n\n/**\n * How much of each stage's work an agent finished, counting a card's first\n * visit to a stage once. Rows appear in insertion order of each stage's first\n * counted exit; only pipeline stages get rows, since intake and terminal\n * stages have no pass to hand over.\n */\nfunction agentCoverage(items: Card[], { windowStart, windowEnd }: Window): FactoryMetrics['agentCoverage'] {\n const byStage = new Map<string, FactoryMetrics['agentCoverage'][number]>();\n for (const item of items) {\n const heldAtWindowEnd = stagesHeldAt(item, windowEnd);\n const visited = new Set<string>();\n for (let i = 0; i < item.stageHistory.length; i++) {\n const entry = item.stageHistory[i]!;\n if (!isPipelineStage(entry.stage) || visited.has(entry.stage)) continue;\n visited.add(entry.stage);\n if (entry.exitedAt === undefined) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n\n let row = byStage.get(entry.stage);\n if (!row) {\n row = {\n stage: entry.stage,\n passes: 0,\n byAgent: 0,\n outcomes: { done: 0, canceled: 0, reworked: 0, inFlight: 0 },\n };\n byStage.set(entry.stage, row);\n }\n row.passes += 1;\n if (!isAgentActor(entry.exitedBy)) continue;\n row.byAgent += 1;\n\n const reworked = item.stageHistory.some(\n (later, j) => j > i && later.stage === entry.stage && parseTime(later.enteredAt) < windowEnd,\n );\n if (reworked) row.outcomes.reworked += 1;\n else if (heldAtWindowEnd.has(DONE_STAGE)) row.outcomes.done += 1;\n else if (heldAtWindowEnd.has(CANCELED_STAGE)) row.outcomes.canceled += 1;\n else row.outcomes.inFlight += 1;\n }\n }\n return [...byStage.values()];\n}\n\nexport function computeFactoryMetrics(boardItems: Card[], window: Window): FactoryMetrics {\n const items = boardItems.filter(hasFactoryRun);\n assertParsableHistory(items);\n\n const { byDay, leadSamples } = completions(items, window);\n\n return {\n daysCovered: byDay.size,\n throughput: [...byDay.entries()]\n .map(([date, count]) => ({ date, count }))\n .sort((a, b) => a.date.localeCompare(b.date)),\n leadTime: {\n medianMs: percentile(leadSamples, 0.5),\n p90Ms: percentile(leadSamples, 0.9),\n samples: leadSamples.length,\n },\n wipTotal: countInFlight(items),\n sourceMix: demandMix(items, window),\n agentCoverage: agentCoverage(items, window),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,yBAAyB;;AAEtC,MAAa,qBAAqB;AAElC,MAAM,SAAS;;AAGf,MAAM,aAAa;;AAGnB,MAAM,iBAAiB;;;;;;AAOvB,MAAM,kCAAkB,IAAI,IAAI,CAAC,YAAY,cAAc,CAAC;AAE5D,MAAM,eAAe;;;;;AAMrB,SAAS,gBAAgB,OAAwB;CAC/C,OAAO,CAAC,gBAAgB,IAAI,KAAK,KAAK,UAAU;AAClD;;;;;;;AAQA,SAAS,cAAc,MAAqB;CAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,SAAS;AAC7C;AAmDA,MAAM,eAAe;;AAErB,MAAM,oBAAoB;AAE1B,SAAS,gBAAgB,OAAgB,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