@mastra/factory 0.2.2-alpha.1 → 0.2.2-alpha.2

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 (155) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/auth.js +401 -334
  3. package/dist/auth.js.map +1 -1
  4. package/dist/capabilities/connection.js +1 -1
  5. package/dist/capabilities/intake.js +1 -1
  6. package/dist/capabilities/version-control.js +1 -1
  7. package/dist/factory.js +441 -39622
  8. package/dist/factory.js.map +1 -1
  9. package/dist/index.js +2 -39633
  10. package/dist/integrations/base.js +1 -1
  11. package/dist/integrations/github/config.js +36 -22
  12. package/dist/integrations/github/config.js.map +1 -1
  13. package/dist/integrations/github/factory-session.js +33 -37
  14. package/dist/integrations/github/factory-session.js.map +1 -1
  15. package/dist/integrations/github/integration.js +1037 -3672
  16. package/dist/integrations/github/integration.js.map +1 -1
  17. package/dist/integrations/github/issue-triage.js +71 -71
  18. package/dist/integrations/github/issue-triage.js.map +1 -1
  19. package/dist/integrations/github/pat.js +47 -36
  20. package/dist/integrations/github/pat.js.map +1 -1
  21. package/dist/integrations/github/provenance.js +72 -101
  22. package/dist/integrations/github/provenance.js.map +1 -1
  23. package/dist/integrations/github/routes.js +1272 -1881
  24. package/dist/integrations/github/routes.js.map +1 -1
  25. package/dist/integrations/github/rules.js +203 -471
  26. package/dist/integrations/github/rules.js.map +1 -1
  27. package/dist/integrations/github/sandbox.js +400 -345
  28. package/dist/integrations/github/sandbox.js.map +1 -1
  29. package/dist/integrations/github/session-subscriptions.js +165 -223
  30. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  31. package/dist/integrations/github/subscriptions.js +43 -51
  32. package/dist/integrations/github/subscriptions.js.map +1 -1
  33. package/dist/integrations/github/token-refresh.js +15 -18
  34. package/dist/integrations/github/token-refresh.js.map +1 -1
  35. package/dist/integrations/github/webhook.js +359 -343
  36. package/dist/integrations/github/webhook.js.map +1 -1
  37. package/dist/integrations/linear/agent-tools.js +77 -100
  38. package/dist/integrations/linear/agent-tools.js.map +1 -1
  39. package/dist/integrations/linear/integration.js +611 -1309
  40. package/dist/integrations/linear/integration.js.map +1 -1
  41. package/dist/integrations/linear/routes.js +227 -230
  42. package/dist/integrations/linear/routes.js.map +1 -1
  43. package/dist/integrations/linear/rules.js +126 -346
  44. package/dist/integrations/linear/rules.js.map +1 -1
  45. package/dist/integrations/linear/storage.js +1 -1
  46. package/dist/integrations/platform/api-client.js +131 -135
  47. package/dist/integrations/platform/api-client.js.map +1 -1
  48. package/dist/integrations/platform/github/event-worker.js +275 -573
  49. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  50. package/dist/integrations/platform/github/integration.js +845 -4022
  51. package/dist/integrations/platform/github/integration.js.map +1 -1
  52. package/dist/integrations/platform/linear/integration.js +457 -1309
  53. package/dist/integrations/platform/linear/integration.js.map +1 -1
  54. package/dist/integrations/workos/integration.js +80 -85
  55. package/dist/integrations/workos/integration.js.map +1 -1
  56. package/dist/routes/config.d.ts.map +1 -1
  57. package/dist/routes/config.js +933 -912
  58. package/dist/routes/config.js.map +1 -1
  59. package/dist/routes/custom-provider-source.js +110 -93
  60. package/dist/routes/custom-provider-source.js.map +1 -1
  61. package/dist/routes/fs.js +401 -349
  62. package/dist/routes/fs.js.map +1 -1
  63. package/dist/routes/intake.js +165 -165
  64. package/dist/routes/intake.js.map +1 -1
  65. package/dist/routes/oauth.js +447 -25166
  66. package/dist/routes/oauth.js.map +1 -1
  67. package/dist/routes/projects.js +437 -376
  68. package/dist/routes/projects.js.map +1 -1
  69. package/dist/routes/provider-credentials.js +76 -58
  70. package/dist/routes/provider-credentials.js.map +1 -1
  71. package/dist/routes/route.js +12 -8
  72. package/dist/routes/route.js.map +1 -1
  73. package/dist/routes/skills.js +160 -173
  74. package/dist/routes/skills.js.map +1 -1
  75. package/dist/routes/surface.js +250 -28615
  76. package/dist/routes/surface.js.map +1 -1
  77. package/dist/routes/tenant-credentials.js +141 -166
  78. package/dist/routes/tenant-credentials.js.map +1 -1
  79. package/dist/routes/work-items.js +654 -862
  80. package/dist/routes/work-items.js.map +1 -1
  81. package/dist/rules/binding-context.js +23 -35
  82. package/dist/rules/binding-context.js.map +1 -1
  83. package/dist/rules/defaults.js +200 -309
  84. package/dist/rules/defaults.js.map +1 -1
  85. package/dist/rules/dispatcher.js +438 -683
  86. package/dist/rules/dispatcher.js.map +1 -1
  87. package/dist/rules/index.js +5 -599
  88. package/dist/rules/processor.js +344 -596
  89. package/dist/rules/processor.js.map +1 -1
  90. package/dist/rules/resolve.js +21 -18
  91. package/dist/rules/resolve.js.map +1 -1
  92. package/dist/rules/start-coordinator.js +168 -157
  93. package/dist/rules/start-coordinator.js.map +1 -1
  94. package/dist/rules/tools.js +50 -85
  95. package/dist/rules/tools.js.map +1 -1
  96. package/dist/rules/transition-service.js +183 -454
  97. package/dist/rules/transition-service.js.map +1 -1
  98. package/dist/rules/types.js +33 -29
  99. package/dist/rules/types.js.map +1 -1
  100. package/dist/rules/validation.js +266 -281
  101. package/dist/rules/validation.js.map +1 -1
  102. package/dist/sandbox/fleet.js +272 -250
  103. package/dist/sandbox/fleet.js.map +1 -1
  104. package/dist/sandbox/reattach.js +13 -6
  105. package/dist/sandbox/reattach.js.map +1 -1
  106. package/dist/server-error.js +12 -16
  107. package/dist/server-error.js.map +1 -1
  108. package/dist/skills/service.js +30 -35
  109. package/dist/skills/service.js.map +1 -1
  110. package/dist/spa-static.js +91 -65
  111. package/dist/spa-static.js.map +1 -1
  112. package/dist/state-signing.js +73 -44
  113. package/dist/state-signing.js.map +1 -1
  114. package/dist/storage/domains/audit/agent-audit.js +60 -59
  115. package/dist/storage/domains/audit/agent-audit.js.map +1 -1
  116. package/dist/storage/domains/audit/base.js +169 -112
  117. package/dist/storage/domains/audit/base.js.map +1 -1
  118. package/dist/storage/domains/audit/domain.js +155 -153
  119. package/dist/storage/domains/audit/domain.js.map +1 -1
  120. package/dist/storage/domains/credentials/base.js +259 -243
  121. package/dist/storage/domains/credentials/base.js.map +1 -1
  122. package/dist/storage/domains/custom-providers/base.js +138 -143
  123. package/dist/storage/domains/custom-providers/base.js.map +1 -1
  124. package/dist/storage/domains/intake/base.js +75 -57
  125. package/dist/storage/domains/intake/base.js.map +1 -1
  126. package/dist/storage/domains/integrations/base.js +310 -245
  127. package/dist/storage/domains/integrations/base.js.map +1 -1
  128. package/dist/storage/domains/memory-settings/base.js +117 -102
  129. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  130. package/dist/storage/domains/model-packs/base.js +89 -88
  131. package/dist/storage/domains/model-packs/base.js.map +1 -1
  132. package/dist/storage/domains/projects/base.js +97 -92
  133. package/dist/storage/domains/projects/base.js.map +1 -1
  134. package/dist/storage/domains/queue-health/base.js +111 -76
  135. package/dist/storage/domains/queue-health/base.js.map +1 -1
  136. package/dist/storage/domains/source-control/base.js +777 -706
  137. package/dist/storage/domains/source-control/base.js.map +1 -1
  138. package/dist/storage/domains/source-control/inmemory.js +322 -348
  139. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  140. package/dist/storage/domains/work-items/base.js +1266 -1148
  141. package/dist/storage/domains/work-items/base.js.map +1 -1
  142. package/dist/storage/domains/work-items/metrics.js +202 -184
  143. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  144. package/dist/timing.js +29 -22
  145. package/dist/timing.js.map +1 -1
  146. package/dist/workspace.js +236 -477
  147. package/dist/workspace.js.map +1 -1
  148. package/package.json +8 -8
  149. package/dist/capabilities/connection.js.map +0 -1
  150. package/dist/capabilities/intake.js.map +0 -1
  151. package/dist/capabilities/version-control.js.map +0 -1
  152. package/dist/index.js.map +0 -1
  153. package/dist/integrations/base.js.map +0 -1
  154. package/dist/integrations/linear/storage.js.map +0 -1
  155. package/dist/rules/index.js.map +0 -1
@@ -1,1189 +1,1307 @@
1
- // src/storage/domains/work-items/base.ts
2
1
  import { createHash } from "crypto";
3
2
  import { FactoryStorageDomain, UniqueViolationError } from "@mastra/core/storage";
3
+ //#region src/storage/domains/work-items/base.ts
4
+ /**
5
+ * Factory work-items storage domain.
6
+ *
7
+ * Work items belong to a first-class Factory project. External intake items use
8
+ * a provider-neutral source reference; manual work items have no source.
9
+ * Stage history is server-owned, while session and metadata patches merge
10
+ * atomically so concurrent actors do not overwrite each other. The authoritative
11
+ * Factory transition path keeps one exclusive current stage per item.
12
+ */
4
13
  function stableJson(value) {
5
- if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
6
- if (value && typeof value === "object") {
7
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(",")}}`;
8
- }
9
- return JSON.stringify(value) ?? "null";
14
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
15
+ if (value && typeof value === "object") return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(",")}}`;
16
+ return JSON.stringify(value) ?? "null";
10
17
  }
11
18
  function factoryDecisionHash(decision) {
12
- return createHash("sha256").update(stableJson(decision)).digest("hex");
19
+ return createHash("sha256").update(stableJson(decision)).digest("hex");
13
20
  }
14
- var AUTOMATION_ACTORS = /* @__PURE__ */ new Set([
15
- "factory",
16
- "system",
17
- "automation",
18
- "factory-rule-dispatcher",
19
- "factory-tool-result-rule"
21
+ /**
22
+ * Sentinel actor ids that mark a stage transition as automation-driven (vs a
23
+ * human's WorkOS user id): generic sentinels plus the system ids the Factory
24
+ * rules engine stamps (see `actorId` in factory/rules/transition-service.ts).
25
+ * Metrics treat any other actor — including a missing `exitedBy` on
26
+ * pre-existing entries — as human.
27
+ */
28
+ const AUTOMATION_ACTORS = /* @__PURE__ */ new Set([
29
+ "factory",
30
+ "system",
31
+ "automation",
32
+ "factory-rule-dispatcher",
33
+ "factory-tool-result-rule"
20
34
  ]);
35
+ /**
36
+ * Whether an actor id marks a transition no human performed on the Factory
37
+ * board: a sentinel automation id, an agent binding (`agent:*`), or an
38
+ * external-webhook actor (`github:*` — a human may have acted on GitHub, but
39
+ * the board move itself was automated).
40
+ */
21
41
  function isAutomationActor(by) {
22
- if (by === void 0) return false;
23
- return AUTOMATION_ACTORS.has(by) || by.startsWith("agent:") || by.startsWith("github:");
42
+ if (by === void 0) return false;
43
+ return AUTOMATION_ACTORS.has(by) || by.startsWith("agent:") || by.startsWith("github:");
24
44
  }
25
- var WORK_ITEMS_SCHEMA = {
26
- name: "work_items",
27
- columns: {
28
- id: { type: "uuid-pk" },
29
- org_id: { type: "text" },
30
- factory_project_id: { type: "text" },
31
- external_source: { type: "json", nullable: true },
32
- source_key: { type: "text", nullable: true },
33
- parent_work_item_id: { type: "text", nullable: true },
34
- title: { type: "text" },
35
- stages: { type: "json" },
36
- stage_history: { type: "json" },
37
- sessions: { type: "json" },
38
- metadata: { type: "json", nullable: true },
39
- revision: { type: "integer", default: 1 },
40
- created_by: { type: "text" },
41
- created_at: { type: "timestamp" },
42
- updated_at: { type: "timestamp" }
43
- },
44
- uniqueIndexes: [
45
- {
46
- name: "work_items_project_source_key_unique",
47
- columns: ["factory_project_id", "source_key"]
48
- }
49
- ],
50
- indexes: [
51
- {
52
- name: "work_items_org_project_updated_at_idx",
53
- columns: ["org_id", "factory_project_id", "updated_at"]
54
- },
55
- {
56
- name: "work_items_project_parent_idx",
57
- columns: ["org_id", "factory_project_id", "parent_work_item_id"]
58
- }
59
- ]
45
+ const WORK_ITEMS_SCHEMA = {
46
+ name: "work_items",
47
+ columns: {
48
+ id: { type: "uuid-pk" },
49
+ org_id: { type: "text" },
50
+ factory_project_id: { type: "text" },
51
+ external_source: {
52
+ type: "json",
53
+ nullable: true
54
+ },
55
+ source_key: {
56
+ type: "text",
57
+ nullable: true
58
+ },
59
+ parent_work_item_id: {
60
+ type: "text",
61
+ nullable: true
62
+ },
63
+ title: { type: "text" },
64
+ stages: { type: "json" },
65
+ stage_history: { type: "json" },
66
+ sessions: { type: "json" },
67
+ metadata: {
68
+ type: "json",
69
+ nullable: true
70
+ },
71
+ revision: {
72
+ type: "integer",
73
+ default: 1
74
+ },
75
+ created_by: { type: "text" },
76
+ created_at: { type: "timestamp" },
77
+ updated_at: { type: "timestamp" }
78
+ },
79
+ uniqueIndexes: [{
80
+ name: "work_items_project_source_key_unique",
81
+ columns: ["factory_project_id", "source_key"]
82
+ }],
83
+ indexes: [{
84
+ name: "work_items_org_project_updated_at_idx",
85
+ columns: [
86
+ "org_id",
87
+ "factory_project_id",
88
+ "updated_at"
89
+ ]
90
+ }, {
91
+ name: "work_items_project_parent_idx",
92
+ columns: [
93
+ "org_id",
94
+ "factory_project_id",
95
+ "parent_work_item_id"
96
+ ]
97
+ }]
60
98
  };
61
99
  function sourceKey(source) {
62
- return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;
100
+ return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;
63
101
  }
64
102
  function toWorkItem(row) {
65
- return {
66
- id: row.id,
67
- orgId: row.org_id,
68
- factoryProjectId: String(row.factory_project_id),
69
- externalSource: row.external_source,
70
- parentWorkItemId: row.parent_work_item_id,
71
- title: row.title,
72
- stages: row.stages,
73
- stageHistory: row.stage_history,
74
- sessions: row.sessions,
75
- metadata: row.metadata,
76
- revision: row.revision,
77
- createdBy: row.created_by,
78
- createdAt: row.created_at,
79
- updatedAt: row.updated_at
80
- };
103
+ return {
104
+ id: row.id,
105
+ orgId: row.org_id,
106
+ factoryProjectId: String(row.factory_project_id),
107
+ externalSource: row.external_source,
108
+ parentWorkItemId: row.parent_work_item_id,
109
+ title: row.title,
110
+ stages: row.stages,
111
+ stageHistory: row.stage_history,
112
+ sessions: row.sessions,
113
+ metadata: row.metadata,
114
+ revision: row.revision,
115
+ createdBy: row.created_by,
116
+ createdAt: row.created_at,
117
+ updatedAt: row.updated_at
118
+ };
81
119
  }
82
- var toRow = toWorkItem;
120
+ const toRow = toWorkItem;
83
121
  function patchColumns(changes) {
84
- return {
85
- ...changes.parentWorkItemId !== void 0 ? { parent_work_item_id: changes.parentWorkItemId } : {},
86
- ...changes.title !== void 0 ? { title: changes.title } : {},
87
- ...changes.stages !== void 0 ? { stages: changes.stages } : {},
88
- ...changes.stageHistory !== void 0 ? { stage_history: changes.stageHistory } : {},
89
- ...changes.sessions !== void 0 ? { sessions: changes.sessions } : {},
90
- ...changes.metadata !== void 0 ? { metadata: changes.metadata } : {},
91
- ...changes.revision !== void 0 ? { revision: changes.revision } : {},
92
- ...changes.updatedAt !== void 0 ? { updated_at: changes.updatedAt } : {}
93
- };
122
+ return {
123
+ ...changes.parentWorkItemId !== void 0 ? { parent_work_item_id: changes.parentWorkItemId } : {},
124
+ ...changes.title !== void 0 ? { title: changes.title } : {},
125
+ ...changes.stages !== void 0 ? { stages: changes.stages } : {},
126
+ ...changes.stageHistory !== void 0 ? { stage_history: changes.stageHistory } : {},
127
+ ...changes.sessions !== void 0 ? { sessions: changes.sessions } : {},
128
+ ...changes.metadata !== void 0 ? { metadata: changes.metadata } : {},
129
+ ...changes.revision !== void 0 ? { revision: changes.revision } : {},
130
+ ...changes.updatedAt !== void 0 ? { updated_at: changes.updatedAt } : {}
131
+ };
94
132
  }
95
133
  function emptyPrior() {
96
- return { stages: [], sessionRoles: [] };
134
+ return {
135
+ stages: [],
136
+ sessionRoles: []
137
+ };
97
138
  }
98
139
  function priorState(row) {
99
- return { stages: row.stages, sessionRoles: Object.keys(row.sessions) };
140
+ return {
141
+ stages: row.stages,
142
+ sessionRoles: Object.keys(row.sessions)
143
+ };
100
144
  }
101
145
  var WorkItemRelationError = class extends Error {
102
- code = "invalid_work_item_relation";
146
+ code = "invalid_work_item_relation";
103
147
  };
104
148
  function validateParentRelation(projectItems, itemId, parentWorkItemId) {
105
- if (parentWorkItemId === null) return;
106
- const byId = new Map(projectItems.map((item) => [item.id, item]));
107
- const parent = byId.get(parentWorkItemId);
108
- if (!parent) throw new WorkItemRelationError("Related work item not found in this project.");
109
- if (itemId === parentWorkItemId) throw new WorkItemRelationError("A work item cannot relate to itself.");
110
- const visited = /* @__PURE__ */ new Set();
111
- let cursor = parent;
112
- while (cursor?.parentWorkItemId) {
113
- if (cursor.parentWorkItemId === itemId) {
114
- throw new WorkItemRelationError("This relationship would create a cycle.");
115
- }
116
- if (visited.has(cursor.id)) throw new WorkItemRelationError("The related work item chain contains a cycle.");
117
- visited.add(cursor.id);
118
- cursor = byId.get(cursor.parentWorkItemId);
119
- }
149
+ if (parentWorkItemId === null) return;
150
+ const byId = new Map(projectItems.map((item) => [item.id, item]));
151
+ const parent = byId.get(parentWorkItemId);
152
+ if (!parent) throw new WorkItemRelationError("Related work item not found in this project.");
153
+ if (itemId === parentWorkItemId) throw new WorkItemRelationError("A work item cannot relate to itself.");
154
+ const visited = /* @__PURE__ */ new Set();
155
+ let cursor = parent;
156
+ while (cursor?.parentWorkItemId) {
157
+ if (cursor.parentWorkItemId === itemId) throw new WorkItemRelationError("This relationship would create a cycle.");
158
+ if (visited.has(cursor.id)) throw new WorkItemRelationError("The related work item chain contains a cycle.");
159
+ visited.add(cursor.id);
160
+ cursor = byId.get(cursor.parentWorkItemId);
161
+ }
120
162
  }
163
+ /**
164
+ * Diff `oldStages` → `newStages` and return the updated history: exited stages
165
+ * get `exitedAt` + `exitedBy` stamped on their open entry, entered stages get
166
+ * a new entry.
167
+ */
121
168
  function applyStageTransition(history, oldStages, newStages, by, now) {
122
- const timestamp = now.toISOString();
123
- const next = history.map((entry) => ({ ...entry }));
124
- for (const stage of oldStages) {
125
- if (newStages.includes(stage)) continue;
126
- for (let i = next.length - 1; i >= 0; i--) {
127
- const entry = next[i];
128
- if (entry.stage === stage && entry.exitedAt === void 0) {
129
- entry.exitedAt = timestamp;
130
- entry.exitedBy = by;
131
- break;
132
- }
133
- }
134
- }
135
- for (const stage of newStages) {
136
- if (!oldStages.includes(stage)) next.push({ stage, enteredAt: timestamp, by });
137
- }
138
- return next;
169
+ const timestamp = now.toISOString();
170
+ const next = history.map((entry) => ({ ...entry }));
171
+ for (const stage of oldStages) {
172
+ if (newStages.includes(stage)) continue;
173
+ for (let i = next.length - 1; i >= 0; i--) {
174
+ const entry = next[i];
175
+ if (entry.stage === stage && entry.exitedAt === void 0) {
176
+ entry.exitedAt = timestamp;
177
+ entry.exitedBy = by;
178
+ break;
179
+ }
180
+ }
181
+ }
182
+ for (const stage of newStages) if (!oldStages.includes(stage)) next.push({
183
+ stage,
184
+ enteredAt: timestamp,
185
+ by
186
+ });
187
+ return next;
139
188
  }
140
189
  function stampSessions(sessions, by) {
141
- return Object.fromEntries(Object.entries(sessions).map(([role, session]) => [role, { ...session, startedBy: by }]));
190
+ return Object.fromEntries(Object.entries(sessions).map(([role, session]) => [role, {
191
+ ...session,
192
+ startedBy: by
193
+ }]));
142
194
  }
143
- function applyUpdate({
144
- current,
145
- userId,
146
- input
147
- }) {
148
- const now = /* @__PURE__ */ new Date();
149
- return {
150
- ...input.parentWorkItemId !== void 0 ? { parent_work_item_id: input.parentWorkItemId } : {},
151
- ...input.title !== void 0 ? { title: input.title } : {},
152
- ...input.stages !== void 0 ? {
153
- stages: input.stages,
154
- stage_history: applyStageTransition(current.stage_history, current.stages, input.stages, userId, now)
155
- } : {},
156
- ...input.sessions !== void 0 ? { sessions: { ...current.sessions, ...stampSessions(input.sessions, userId) } } : {},
157
- ...input.metadata !== void 0 ? { metadata: input.metadata === null ? null : { ...current.metadata ?? {}, ...input.metadata } } : {},
158
- revision: current.revision + 1,
159
- updated_at: now
160
- };
195
+ function applyUpdate({ current, userId, input }) {
196
+ const now = /* @__PURE__ */ new Date();
197
+ return {
198
+ ...input.parentWorkItemId !== void 0 ? { parent_work_item_id: input.parentWorkItemId } : {},
199
+ ...input.title !== void 0 ? { title: input.title } : {},
200
+ ...input.stages !== void 0 ? {
201
+ stages: input.stages,
202
+ stage_history: applyStageTransition(current.stage_history, current.stages, input.stages, userId, now)
203
+ } : {},
204
+ ...input.sessions !== void 0 ? { sessions: {
205
+ ...current.sessions,
206
+ ...stampSessions(input.sessions, userId)
207
+ } } : {},
208
+ ...input.metadata !== void 0 ? { metadata: input.metadata === null ? null : {
209
+ ...current.metadata ?? {},
210
+ ...input.metadata
211
+ } } : {},
212
+ revision: current.revision + 1,
213
+ updated_at: now
214
+ };
161
215
  }
162
- var projectRelationLocks = /* @__PURE__ */ new Map();
216
+ const projectRelationLocks = /* @__PURE__ */ new Map();
163
217
  function withInProcessProjectLock(key, fn) {
164
- const previous = projectRelationLocks.get(key) ?? Promise.resolve();
165
- const result = previous.then(fn, fn);
166
- const tail = result.then(
167
- () => void 0,
168
- () => void 0
169
- );
170
- projectRelationLocks.set(key, tail);
171
- void tail.then(() => {
172
- if (projectRelationLocks.get(key) === tail) projectRelationLocks.delete(key);
173
- });
174
- return result;
218
+ const result = (projectRelationLocks.get(key) ?? Promise.resolve()).then(fn, fn);
219
+ const tail = result.then(() => void 0, () => void 0);
220
+ projectRelationLocks.set(key, tail);
221
+ tail.then(() => {
222
+ if (projectRelationLocks.get(key) === tail) projectRelationLocks.delete(key);
223
+ });
224
+ return result;
175
225
  }
176
- var FACTORY_GOVERNANCE_SCHEMAS = [
177
- {
178
- name: "factory_rule_ingress",
179
- columns: {
180
- id: { type: "uuid-pk" },
181
- org_id: { type: "text" },
182
- factory_project_id: { type: "text" },
183
- identity: { type: "text" },
184
- trigger_type: { type: "text" },
185
- transition_id: { type: "text" },
186
- result: { type: "json" },
187
- created_at: { type: "timestamp" }
188
- },
189
- uniqueIndexes: [
190
- { name: "factory_rule_ingress_tenant_identity_unique", columns: ["org_id", "factory_project_id", "identity"] }
191
- ]
192
- },
193
- {
194
- name: "factory_rule_evaluations",
195
- columns: {
196
- id: { type: "uuid-pk" },
197
- ingress_id: { type: "text" },
198
- work_item_id: { type: "text", nullable: true },
199
- rule_set_version: { type: "text" },
200
- expected_revision: { type: "integer", nullable: true },
201
- outcome: { type: "text" },
202
- code: { type: "text", nullable: true },
203
- reason: { type: "text", nullable: true },
204
- causal_chain: { type: "json" },
205
- created_at: { type: "timestamp" }
206
- }
207
- },
208
- {
209
- name: "factory_deferred_decisions",
210
- columns: {
211
- id: { type: "uuid-pk" },
212
- org_id: { type: "text" },
213
- factory_project_id: { type: "text" },
214
- evaluation_id: { type: "text" },
215
- work_item_id: { type: "text", nullable: true },
216
- idempotency_key: { type: "text" },
217
- effect_ordinal: { type: "integer" },
218
- effect_hash: { type: "text" },
219
- causal_chain: { type: "json" },
220
- actor: { type: "json", nullable: true },
221
- decision: { type: "json" },
222
- status: { type: "text" },
223
- attempts: { type: "integer" },
224
- available_at: { type: "timestamp" },
225
- lease_owner: { type: "text", nullable: true },
226
- lease_expires_at: { type: "timestamp", nullable: true },
227
- last_error: { type: "text", nullable: true },
228
- completed_at: { type: "timestamp", nullable: true },
229
- created_at: { type: "timestamp" },
230
- updated_at: { type: "timestamp" }
231
- },
232
- uniqueIndexes: [
233
- {
234
- name: "factory_deferred_decisions_tenant_key_unique",
235
- columns: ["org_id", "factory_project_id", "idempotency_key"]
236
- }
237
- ],
238
- indexes: [{ name: "factory_deferred_decisions_claim_idx", columns: ["status", "created_at"] }]
239
- },
240
- {
241
- name: "factory_run_bindings",
242
- columns: {
243
- id: { type: "uuid-pk" },
244
- org_id: { type: "text" },
245
- factory_project_id: { type: "text" },
246
- work_item_id: { type: "text" },
247
- role: { type: "text" },
248
- thread_id: { type: "text" },
249
- resource_id: { type: "text" },
250
- session_id: { type: "text" },
251
- branch: { type: "text" },
252
- status: { type: "text" },
253
- created_at: { type: "timestamp" },
254
- revoked_at: { type: "timestamp", nullable: true }
255
- },
256
- indexes: [
257
- // Exact-address lookups run on every processor message; status filter is
258
- // applied on top of the address columns.
259
- {
260
- name: "factory_run_bindings_session_idx",
261
- columns: ["factory_project_id", "thread_id", "resource_id", "session_id"]
262
- },
263
- // Restart reconciler enumerates active bindings across all tenants.
264
- { name: "factory_run_bindings_status_idx", columns: ["status"] }
265
- ]
266
- },
267
- {
268
- name: "factory_tool_result_cursors",
269
- columns: {
270
- binding_id: { type: "text", primaryKey: true },
271
- org_id: { type: "text" },
272
- factory_project_id: { type: "text" },
273
- last_message_id: { type: "text" },
274
- last_message_created_at: { type: "timestamp" },
275
- updated_at: { type: "timestamp" }
276
- }
277
- },
278
- {
279
- name: "factory_pending_starts",
280
- columns: {
281
- id: { type: "uuid-pk" },
282
- org_id: { type: "text" },
283
- factory_project_id: { type: "text" },
284
- binding_id: { type: "text" },
285
- kickoff_key: { type: "text" },
286
- message: { type: "text", nullable: true },
287
- status: { type: "text" },
288
- attempts: { type: "integer" },
289
- available_at: { type: "timestamp" },
290
- lease_owner: { type: "text", nullable: true },
291
- lease_expires_at: { type: "timestamp", nullable: true },
292
- last_error: { type: "text", nullable: true },
293
- completed_at: { type: "timestamp", nullable: true },
294
- created_at: { type: "timestamp" },
295
- updated_at: { type: "timestamp" }
296
- },
297
- uniqueIndexes: [
298
- {
299
- name: "factory_pending_starts_tenant_kickoff_unique",
300
- columns: ["org_id", "factory_project_id", "kickoff_key"]
301
- }
302
- ],
303
- indexes: [{ name: "factory_pending_starts_claim_idx", columns: ["status", "created_at"] }]
304
- }
226
+ const FACTORY_GOVERNANCE_SCHEMAS = [
227
+ {
228
+ name: "factory_rule_ingress",
229
+ columns: {
230
+ id: { type: "uuid-pk" },
231
+ org_id: { type: "text" },
232
+ factory_project_id: { type: "text" },
233
+ identity: { type: "text" },
234
+ trigger_type: { type: "text" },
235
+ transition_id: { type: "text" },
236
+ result: { type: "json" },
237
+ created_at: { type: "timestamp" }
238
+ },
239
+ uniqueIndexes: [{
240
+ name: "factory_rule_ingress_tenant_identity_unique",
241
+ columns: [
242
+ "org_id",
243
+ "factory_project_id",
244
+ "identity"
245
+ ]
246
+ }]
247
+ },
248
+ {
249
+ name: "factory_rule_evaluations",
250
+ columns: {
251
+ id: { type: "uuid-pk" },
252
+ ingress_id: { type: "text" },
253
+ work_item_id: {
254
+ type: "text",
255
+ nullable: true
256
+ },
257
+ rule_set_version: { type: "text" },
258
+ expected_revision: {
259
+ type: "integer",
260
+ nullable: true
261
+ },
262
+ outcome: { type: "text" },
263
+ code: {
264
+ type: "text",
265
+ nullable: true
266
+ },
267
+ reason: {
268
+ type: "text",
269
+ nullable: true
270
+ },
271
+ causal_chain: { type: "json" },
272
+ created_at: { type: "timestamp" }
273
+ }
274
+ },
275
+ {
276
+ name: "factory_deferred_decisions",
277
+ columns: {
278
+ id: { type: "uuid-pk" },
279
+ org_id: { type: "text" },
280
+ factory_project_id: { type: "text" },
281
+ evaluation_id: { type: "text" },
282
+ work_item_id: {
283
+ type: "text",
284
+ nullable: true
285
+ },
286
+ idempotency_key: { type: "text" },
287
+ effect_ordinal: { type: "integer" },
288
+ effect_hash: { type: "text" },
289
+ causal_chain: { type: "json" },
290
+ actor: {
291
+ type: "json",
292
+ nullable: true
293
+ },
294
+ decision: { type: "json" },
295
+ status: { type: "text" },
296
+ attempts: { type: "integer" },
297
+ available_at: { type: "timestamp" },
298
+ lease_owner: {
299
+ type: "text",
300
+ nullable: true
301
+ },
302
+ lease_expires_at: {
303
+ type: "timestamp",
304
+ nullable: true
305
+ },
306
+ last_error: {
307
+ type: "text",
308
+ nullable: true
309
+ },
310
+ completed_at: {
311
+ type: "timestamp",
312
+ nullable: true
313
+ },
314
+ created_at: { type: "timestamp" },
315
+ updated_at: { type: "timestamp" }
316
+ },
317
+ uniqueIndexes: [{
318
+ name: "factory_deferred_decisions_tenant_key_unique",
319
+ columns: [
320
+ "org_id",
321
+ "factory_project_id",
322
+ "idempotency_key"
323
+ ]
324
+ }],
325
+ indexes: [{
326
+ name: "factory_deferred_decisions_claim_idx",
327
+ columns: ["status", "created_at"]
328
+ }]
329
+ },
330
+ {
331
+ name: "factory_run_bindings",
332
+ columns: {
333
+ id: { type: "uuid-pk" },
334
+ org_id: { type: "text" },
335
+ factory_project_id: { type: "text" },
336
+ work_item_id: { type: "text" },
337
+ role: { type: "text" },
338
+ thread_id: { type: "text" },
339
+ resource_id: { type: "text" },
340
+ session_id: { type: "text" },
341
+ branch: { type: "text" },
342
+ status: { type: "text" },
343
+ created_at: { type: "timestamp" },
344
+ revoked_at: {
345
+ type: "timestamp",
346
+ nullable: true
347
+ }
348
+ },
349
+ indexes: [{
350
+ name: "factory_run_bindings_session_idx",
351
+ columns: [
352
+ "factory_project_id",
353
+ "thread_id",
354
+ "resource_id",
355
+ "session_id"
356
+ ]
357
+ }, {
358
+ name: "factory_run_bindings_status_idx",
359
+ columns: ["status"]
360
+ }]
361
+ },
362
+ {
363
+ name: "factory_tool_result_cursors",
364
+ columns: {
365
+ binding_id: {
366
+ type: "text",
367
+ primaryKey: true
368
+ },
369
+ org_id: { type: "text" },
370
+ factory_project_id: { type: "text" },
371
+ last_message_id: { type: "text" },
372
+ last_message_created_at: { type: "timestamp" },
373
+ updated_at: { type: "timestamp" }
374
+ }
375
+ },
376
+ {
377
+ name: "factory_pending_starts",
378
+ columns: {
379
+ id: { type: "uuid-pk" },
380
+ org_id: { type: "text" },
381
+ factory_project_id: { type: "text" },
382
+ binding_id: { type: "text" },
383
+ kickoff_key: { type: "text" },
384
+ message: {
385
+ type: "text",
386
+ nullable: true
387
+ },
388
+ status: { type: "text" },
389
+ attempts: { type: "integer" },
390
+ available_at: { type: "timestamp" },
391
+ lease_owner: {
392
+ type: "text",
393
+ nullable: true
394
+ },
395
+ lease_expires_at: {
396
+ type: "timestamp",
397
+ nullable: true
398
+ },
399
+ last_error: {
400
+ type: "text",
401
+ nullable: true
402
+ },
403
+ completed_at: {
404
+ type: "timestamp",
405
+ nullable: true
406
+ },
407
+ created_at: { type: "timestamp" },
408
+ updated_at: { type: "timestamp" }
409
+ },
410
+ uniqueIndexes: [{
411
+ name: "factory_pending_starts_tenant_kickoff_unique",
412
+ columns: [
413
+ "org_id",
414
+ "factory_project_id",
415
+ "kickoff_key"
416
+ ]
417
+ }],
418
+ indexes: [{
419
+ name: "factory_pending_starts_claim_idx",
420
+ columns: ["status", "created_at"]
421
+ }]
422
+ }
305
423
  ];
306
424
  function toBinding(row) {
307
- return {
308
- id: row.id,
309
- orgId: row.org_id,
310
- factoryProjectId: String(row.factory_project_id),
311
- workItemId: String(row.work_item_id),
312
- role: String(row.role),
313
- threadId: String(row.thread_id),
314
- resourceId: String(row.resource_id),
315
- sessionId: String(row.session_id),
316
- branch: String(row.branch),
317
- status: row.status,
318
- createdAt: row.created_at,
319
- revokedAt: row.revoked_at ?? null
320
- };
425
+ return {
426
+ id: row.id,
427
+ orgId: row.org_id,
428
+ factoryProjectId: String(row.factory_project_id),
429
+ workItemId: String(row.work_item_id),
430
+ role: String(row.role),
431
+ threadId: String(row.thread_id),
432
+ resourceId: String(row.resource_id),
433
+ sessionId: String(row.session_id),
434
+ branch: String(row.branch),
435
+ status: row.status,
436
+ createdAt: row.created_at,
437
+ revokedAt: row.revoked_at ?? null
438
+ };
321
439
  }
322
440
  function toDeferredDecision(row) {
323
- return {
324
- id: row.id,
325
- orgId: row.org_id,
326
- factoryProjectId: String(row.factory_project_id),
327
- evaluationId: String(row.evaluation_id),
328
- workItemId: row.work_item_id === null || row.work_item_id === void 0 ? null : String(row.work_item_id),
329
- idempotencyKey: String(row.idempotency_key),
330
- effectOrdinal: Number(row.effect_ordinal),
331
- effectHash: String(row.effect_hash),
332
- causalChain: row.causal_chain ?? [],
333
- actor: row.actor ?? null,
334
- decision: row.decision,
335
- status: row.status,
336
- attempts: Number(row.attempts),
337
- availableAt: row.available_at,
338
- leaseOwner: row.lease_owner ?? null,
339
- leaseExpiresAt: row.lease_expires_at ?? null,
340
- lastError: row.last_error ?? null,
341
- completedAt: row.completed_at ?? null,
342
- createdAt: row.created_at,
343
- updatedAt: row.updated_at
344
- };
441
+ return {
442
+ id: row.id,
443
+ orgId: row.org_id,
444
+ factoryProjectId: String(row.factory_project_id),
445
+ evaluationId: String(row.evaluation_id),
446
+ workItemId: row.work_item_id === null || row.work_item_id === void 0 ? null : String(row.work_item_id),
447
+ idempotencyKey: String(row.idempotency_key),
448
+ effectOrdinal: Number(row.effect_ordinal),
449
+ effectHash: String(row.effect_hash),
450
+ causalChain: row.causal_chain ?? [],
451
+ actor: row.actor ?? null,
452
+ decision: row.decision,
453
+ status: row.status,
454
+ attempts: Number(row.attempts),
455
+ availableAt: row.available_at,
456
+ leaseOwner: row.lease_owner ?? null,
457
+ leaseExpiresAt: row.lease_expires_at ?? null,
458
+ lastError: row.last_error ?? null,
459
+ completedAt: row.completed_at ?? null,
460
+ createdAt: row.created_at,
461
+ updatedAt: row.updated_at
462
+ };
345
463
  }
346
464
  function toPendingStart(row) {
347
- return {
348
- id: row.id,
349
- orgId: row.org_id,
350
- factoryProjectId: String(row.factory_project_id),
351
- bindingId: String(row.binding_id),
352
- kickoffKey: String(row.kickoff_key),
353
- message: row.message ?? null,
354
- status: row.status,
355
- attempts: Number(row.attempts),
356
- availableAt: row.available_at,
357
- leaseOwner: row.lease_owner ?? null,
358
- leaseExpiresAt: row.lease_expires_at ?? null,
359
- lastError: row.last_error ?? null,
360
- completedAt: row.completed_at ?? null,
361
- createdAt: row.created_at,
362
- updatedAt: row.updated_at
363
- };
465
+ return {
466
+ id: row.id,
467
+ orgId: row.org_id,
468
+ factoryProjectId: String(row.factory_project_id),
469
+ bindingId: String(row.binding_id),
470
+ kickoffKey: String(row.kickoff_key),
471
+ message: row.message ?? null,
472
+ status: row.status,
473
+ attempts: Number(row.attempts),
474
+ availableAt: row.available_at,
475
+ leaseOwner: row.lease_owner ?? null,
476
+ leaseExpiresAt: row.lease_expires_at ?? null,
477
+ lastError: row.last_error ?? null,
478
+ completedAt: row.completed_at ?? null,
479
+ createdAt: row.created_at,
480
+ updatedAt: row.updated_at
481
+ };
364
482
  }
365
483
  var WorkItemsStorage = class extends FactoryStorageDomain {
366
- constructor() {
367
- super("work-items");
368
- }
369
- async init() {
370
- await this.ensureCollections([WORK_ITEMS_SCHEMA, ...FACTORY_GOVERNANCE_SCHEMAS]);
371
- }
372
- async dangerouslyClearAll() {
373
- await this.ops.deleteMany("work_items", {});
374
- }
375
- get #db() {
376
- return this.ops;
377
- }
378
- async #withProjectRelationTransaction(orgId, factoryProjectId, fn) {
379
- const key = `work-items:${orgId}:${factoryProjectId}`;
380
- return withInProcessProjectLock(key, () => this.storage.withTransaction(fn, { isolationLevel: "serializable" }));
381
- }
382
- async #claimLeases(table, input, map) {
383
- const claim = () => this.storage.withTransaction(async (ops) => {
384
- const candidates = await ops.findMany(
385
- table,
386
- { status: { in: ["pending", "retry", "leased"] } },
387
- { orderBy: [["created_at", "asc"]], limit: Math.max(input.limit * 5, 50) }
388
- );
389
- const claimed = [];
390
- for (const candidate of candidates) {
391
- if (claimed.length >= input.limit) break;
392
- const availableAt = new Date(candidate.available_at).getTime();
393
- const leaseExpiresAt = candidate.lease_expires_at ? new Date(candidate.lease_expires_at).getTime() : 0;
394
- const claimable = (candidate.status === "pending" || candidate.status === "retry") && availableAt <= input.now.getTime();
395
- const expired = candidate.status === "leased" && leaseExpiresAt <= input.now.getTime();
396
- if (!claimable && !expired) continue;
397
- let didClaim = false;
398
- const row = await ops.updateAtomic(table, { id: candidate.id }, (current) => {
399
- const currentAvailable = new Date(current.available_at).getTime();
400
- const currentExpiry = current.lease_expires_at ? new Date(current.lease_expires_at).getTime() : 0;
401
- const currentClaimable = (current.status === "pending" || current.status === "retry") && currentAvailable <= input.now.getTime();
402
- const currentExpired = current.status === "leased" && currentExpiry <= input.now.getTime();
403
- if (!currentClaimable && !currentExpired) return null;
404
- didClaim = true;
405
- return {
406
- status: "leased",
407
- attempts: Number(current.attempts) + 1,
408
- lease_owner: input.ownerId,
409
- lease_expires_at: input.leaseExpiresAt,
410
- updated_at: input.now
411
- };
412
- });
413
- if (didClaim && row) claimed.push(map(row));
414
- }
415
- return claimed;
416
- });
417
- return claim();
418
- }
419
- async #renewLease(table, identity, leaseExpiresAt) {
420
- let renewed = false;
421
- await this.#db.updateAtomic(
422
- table,
423
- { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },
424
- (current) => {
425
- if (current.status !== "leased" || current.lease_owner !== identity.ownerId) return null;
426
- renewed = true;
427
- return { lease_expires_at: leaseExpiresAt, updated_at: /* @__PURE__ */ new Date() };
428
- }
429
- );
430
- return renewed;
431
- }
432
- async #completeLease(table, identity, now) {
433
- let completed = false;
434
- const row = await this.#db.updateAtomic(
435
- table,
436
- { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },
437
- (current) => {
438
- if (current.status !== "leased" || current.lease_owner !== identity.ownerId) return null;
439
- completed = true;
440
- return {
441
- status: table === "factory_pending_starts" ? "sent" : "succeeded",
442
- lease_owner: null,
443
- lease_expires_at: null,
444
- completed_at: now,
445
- updated_at: now
446
- };
447
- }
448
- );
449
- return completed ? row : null;
450
- }
451
- async #failLease(table, input) {
452
- let failed = false;
453
- const row = await this.#db.updateAtomic(
454
- table,
455
- { id: input.id, org_id: input.orgId, factory_project_id: input.factoryProjectId },
456
- (current) => {
457
- if (current.status !== "leased" || current.lease_owner !== input.ownerId) return null;
458
- failed = true;
459
- return {
460
- status: input.terminal ? "failed" : "retry",
461
- available_at: input.availableAt,
462
- lease_owner: null,
463
- lease_expires_at: null,
464
- last_error: input.lastError,
465
- completed_at: input.terminal ? input.now : null,
466
- updated_at: input.now
467
- };
468
- }
469
- );
470
- return failed ? row : null;
471
- }
472
- async #listWithOps(ops, orgId, factoryProjectId) {
473
- const rows = await ops.findMany(
474
- "work_items",
475
- { org_id: orgId, factory_project_id: factoryProjectId },
476
- { orderBy: [["updated_at", "desc"]] }
477
- );
478
- return rows.map(toWorkItem);
479
- }
480
- /** List the org's work items for a project, newest first. */
481
- async list({ orgId, factoryProjectId }) {
482
- return this.#listWithOps(this.#db, orgId, factoryProjectId);
483
- }
484
- async get({ orgId, id }) {
485
- const row = await this.#db.findOne("work_items", { org_id: orgId, id });
486
- return row ? toWorkItem(row) : null;
487
- }
488
- async getForProject(orgId, factoryProjectId, id) {
489
- const row = await this.#db.findOne("work_items", {
490
- id,
491
- org_id: orgId,
492
- factory_project_id: factoryProjectId
493
- });
494
- return row ? toRow(row) : null;
495
- }
496
- async getTransitionResultByIngress(orgId, factoryProjectId, identity) {
497
- const row = await this.#db.findOne("factory_rule_ingress", {
498
- org_id: orgId,
499
- factory_project_id: factoryProjectId,
500
- identity
501
- });
502
- return row?.result ?? null;
503
- }
504
- async commitTransition(input) {
505
- const commit = () => this.storage.withTransaction(async (ops) => {
506
- const prior = await ops.findOne("factory_rule_ingress", {
507
- org_id: input.orgId,
508
- factory_project_id: input.factoryProjectId,
509
- identity: input.ingress.identity
510
- });
511
- if (prior)
512
- return {
513
- status: "replayed",
514
- item: await this.getForProject(input.orgId, input.factoryProjectId, input.workItemId),
515
- result: prior.result
516
- };
517
- const now = /* @__PURE__ */ new Date();
518
- let item = null;
519
- let code = null;
520
- let reason = null;
521
- let result;
522
- const updated = await ops.updateAtomic(
523
- "work_items",
524
- {
525
- id: input.workItemId,
526
- org_id: input.orgId,
527
- factory_project_id: input.factoryProjectId
528
- },
529
- (row) => {
530
- const existing = toRow(row);
531
- item = existing;
532
- if (existing.revision !== input.expectedRevision) {
533
- code = "stale";
534
- reason = "The work item changed before this transition committed.";
535
- return null;
536
- }
537
- if (input.evaluation.outcome === "rejected") {
538
- code = input.evaluation.code;
539
- reason = input.evaluation.reason;
540
- return null;
541
- }
542
- if (existing.stages.length === 1 && existing.stages[0] === input.destinationStage) return null;
543
- return patchColumns({
544
- stages: [input.destinationStage],
545
- stageHistory: applyStageTransition(
546
- existing.stageHistory,
547
- existing.stages,
548
- [input.destinationStage],
549
- input.actorId,
550
- now
551
- ),
552
- revision: existing.revision + 1,
553
- updatedAt: now
554
- });
555
- }
556
- );
557
- if (updated) item = toRow(updated);
558
- if (!item) {
559
- code = input.evaluation.outcome === "rejected" ? input.evaluation.code : "invalid_transition";
560
- reason = input.evaluation.outcome === "rejected" ? input.evaluation.reason : "Work item not found.";
561
- }
562
- const outcome = item && code === null && input.evaluation.outcome === "accepted" ? "accepted" : "rejected";
563
- result = outcome === "accepted" ? {
564
- status: "accepted",
565
- transitionId: input.ingress.transitionId,
566
- itemId: item.id,
567
- revision: item.revision,
568
- stage: input.destinationStage,
569
- decisions: input.evaluation.outcome === "accepted" ? input.evaluation.decisions : []
570
- } : { status: "rejected", transitionId: input.ingress.transitionId, itemId: input.workItemId, code, reason };
571
- const ingress = await ops.insertOne("factory_rule_ingress", {
572
- org_id: input.orgId,
573
- factory_project_id: input.factoryProjectId,
574
- identity: input.ingress.identity,
575
- trigger_type: input.ingress.triggerType,
576
- transition_id: input.ingress.transitionId,
577
- result,
578
- created_at: now
579
- });
580
- if (item) {
581
- const evaluation = await ops.insertOne("factory_rule_evaluations", {
582
- ingress_id: ingress.id,
583
- work_item_id: item.id,
584
- rule_set_version: input.ruleSetVersion,
585
- expected_revision: input.expectedRevision,
586
- outcome,
587
- code,
588
- reason,
589
- causal_chain: input.causalChain,
590
- created_at: now
591
- });
592
- if (outcome === "accepted" && input.evaluation.outcome === "accepted") {
593
- for (const [index, decision] of input.evaluation.decisions.entries()) {
594
- await ops.insertOne("factory_deferred_decisions", {
595
- org_id: input.orgId,
596
- factory_project_id: input.factoryProjectId,
597
- evaluation_id: evaluation.id,
598
- work_item_id: item.id,
599
- idempotency_key: String(decision.idempotencyKey),
600
- effect_ordinal: index,
601
- effect_hash: factoryDecisionHash(decision),
602
- causal_chain: input.causalChain,
603
- actor: null,
604
- decision,
605
- status: "pending",
606
- attempts: 0,
607
- available_at: now,
608
- lease_owner: null,
609
- lease_expires_at: null,
610
- last_error: null,
611
- completed_at: null,
612
- created_at: new Date(now.getTime() + index),
613
- updated_at: now
614
- });
615
- }
616
- }
617
- }
618
- return { status: "committed", item, result };
619
- });
620
- try {
621
- return await commit();
622
- } catch (error) {
623
- if (!(error instanceof UniqueViolationError)) throw error;
624
- return commit();
625
- }
626
- }
627
- async commitRuleEvaluation(input) {
628
- const commit = () => this.storage.withTransaction(async (ops) => {
629
- const prior = await ops.findOne("factory_rule_ingress", {
630
- org_id: input.orgId,
631
- factory_project_id: input.factoryProjectId,
632
- identity: input.ingress.identity
633
- });
634
- if (prior) {
635
- const result2 = prior.result;
636
- const decisions2 = Array.isArray(result2.decisions) ? result2.decisions : [];
637
- const evaluation2 = await ops.findOne("factory_rule_evaluations", { ingress_id: prior.id });
638
- for (const decision of decisions2) {
639
- if (!evaluation2 || !decision || typeof decision !== "object" || decision.type !== "upsertLinkedWorkItem" || typeof decision.sourceKey !== "string" || typeof decision.idempotencyKey !== "string") {
640
- continue;
641
- }
642
- const materialization = decision;
643
- const item2 = await ops.findOne("work_items", {
644
- org_id: input.orgId,
645
- factory_project_id: input.factoryProjectId,
646
- source_key: materialization.sourceKey
647
- });
648
- if (item2) continue;
649
- await ops.updateAtomic(
650
- "factory_deferred_decisions",
651
- {
652
- org_id: input.orgId,
653
- factory_project_id: input.factoryProjectId,
654
- evaluation_id: evaluation2.id,
655
- idempotency_key: materialization.idempotencyKey
656
- },
657
- (current) => current.status === "succeeded" ? {
658
- status: "retry",
659
- attempts: 0,
660
- available_at: input.now,
661
- lease_owner: null,
662
- lease_expires_at: null,
663
- last_error: null,
664
- completed_at: null,
665
- updated_at: input.now
666
- } : null
667
- );
668
- }
669
- return { status: "replayed", result: result2 };
670
- }
671
- const itemRow = input.workItemId ? await ops.findOne("work_items", {
672
- id: input.workItemId,
673
- org_id: input.orgId,
674
- factory_project_id: input.factoryProjectId
675
- }) : null;
676
- if (input.workItemId !== null && !itemRow) return { status: "missing" };
677
- const item = itemRow ? toRow(itemRow) : null;
678
- const stale = item !== null && item.revision !== input.expectedRevision;
679
- const outcome = stale ? "rejected" : input.outcome.status;
680
- const code = stale ? "stale" : input.outcome.code ?? null;
681
- const reason = stale ? "The work item changed before this rule evaluation committed." : input.outcome.reason ?? null;
682
- const decisions = outcome === "accepted" ? input.decisions : [];
683
- const result = {
684
- status: outcome,
685
- itemId: item?.id ?? null,
686
- revision: item?.revision ?? null,
687
- code,
688
- reason,
689
- decisions
690
- };
691
- const ingress = await ops.insertOne("factory_rule_ingress", {
692
- org_id: input.orgId,
693
- factory_project_id: input.factoryProjectId,
694
- identity: input.ingress.identity,
695
- trigger_type: input.ingress.triggerType,
696
- transition_id: input.ingress.identity,
697
- result,
698
- created_at: input.now
699
- });
700
- const evaluation = await ops.insertOne("factory_rule_evaluations", {
701
- ingress_id: ingress.id,
702
- work_item_id: item?.id ?? null,
703
- rule_set_version: input.ruleSetVersion,
704
- expected_revision: input.expectedRevision,
705
- outcome,
706
- code,
707
- reason,
708
- causal_chain: input.causalChain,
709
- created_at: input.now
710
- });
711
- for (const [effectOrdinal, decision] of decisions.entries()) {
712
- await ops.insertOne("factory_deferred_decisions", {
713
- org_id: input.orgId,
714
- factory_project_id: input.factoryProjectId,
715
- evaluation_id: evaluation.id,
716
- work_item_id: item?.id ?? null,
717
- idempotency_key: String(decision.idempotencyKey),
718
- effect_ordinal: effectOrdinal,
719
- effect_hash: factoryDecisionHash(decision),
720
- causal_chain: input.causalChain,
721
- actor: input.actor,
722
- decision,
723
- status: "pending",
724
- attempts: 0,
725
- available_at: input.now,
726
- lease_owner: null,
727
- lease_expires_at: null,
728
- last_error: null,
729
- completed_at: null,
730
- created_at: new Date(input.now.getTime() + effectOrdinal),
731
- updated_at: input.now
732
- });
733
- }
734
- return { status: "committed", result };
735
- });
736
- try {
737
- return await commit();
738
- } catch (error) {
739
- if (!(error instanceof UniqueViolationError)) throw error;
740
- return commit();
741
- }
742
- }
743
- async getToolResultCursor(orgId, factoryProjectId, bindingId) {
744
- const row = await this.#db.findOne("factory_tool_result_cursors", {
745
- org_id: orgId,
746
- factory_project_id: factoryProjectId,
747
- binding_id: bindingId
748
- });
749
- return row ? {
750
- bindingId: String(row.binding_id),
751
- orgId: row.org_id,
752
- factoryProjectId: String(row.factory_project_id),
753
- lastMessageId: String(row.last_message_id),
754
- lastMessageCreatedAt: row.last_message_created_at,
755
- updatedAt: row.updated_at
756
- } : null;
757
- }
758
- async advanceToolResultCursor(cursor) {
759
- const current = await this.getToolResultCursor(cursor.orgId, cursor.factoryProjectId, cursor.bindingId);
760
- if (current && current.lastMessageCreatedAt > cursor.lastMessageCreatedAt) return;
761
- await this.#db.upsertOne("factory_tool_result_cursors", ["binding_id"], {
762
- binding_id: cursor.bindingId,
763
- org_id: cursor.orgId,
764
- factory_project_id: cursor.factoryProjectId,
765
- last_message_id: cursor.lastMessageId,
766
- last_message_created_at: cursor.lastMessageCreatedAt,
767
- updated_at: cursor.updatedAt
768
- });
769
- }
770
- async listDeferredDecisions(orgId, factoryProjectId) {
771
- return (await this.#db.findMany(
772
- "factory_deferred_decisions",
773
- { org_id: orgId, factory_project_id: factoryProjectId },
774
- { orderBy: [["created_at", "asc"]] }
775
- )).map(toDeferredDecision);
776
- }
777
- /** Read a bounded newest-first status page without exposing another tenant. */
778
- async listDeferredDecisionPage(input) {
779
- const rows = await this.#db.findMany(
780
- "factory_deferred_decisions",
781
- {
782
- org_id: input.orgId,
783
- factory_project_id: input.factoryProjectId,
784
- ...input.statuses ? { status: { in: input.statuses } } : {}
785
- },
786
- {
787
- orderBy: [
788
- ["created_at", "desc"],
789
- ["id", "desc"]
790
- ],
791
- limit: input.limit + 1,
792
- ...input.before ? { cursor: { values: [input.before.createdAt, input.before.id] } } : {}
793
- }
794
- );
795
- return { decisions: rows.slice(0, input.limit).map(toDeferredDecision), hasMore: rows.length > input.limit };
796
- }
797
- async claimDeferredDecisions(input) {
798
- return this.#claimLeases("factory_deferred_decisions", input, toDeferredDecision);
799
- }
800
- async renewDeferredDecisionLease(identity, leaseExpiresAt) {
801
- return this.#renewLease("factory_deferred_decisions", identity, leaseExpiresAt);
802
- }
803
- async completeDeferredDecision(identity, now) {
804
- const row = await this.#completeLease("factory_deferred_decisions", identity, now);
805
- return row ? toDeferredDecision(row) : null;
806
- }
807
- async failDeferredDecision(input) {
808
- const row = await this.#failLease("factory_deferred_decisions", input);
809
- return row ? toDeferredDecision(row) : null;
810
- }
811
- /** Requeue the same idempotent terminal effect; non-failed decisions are never rerun. */
812
- async retryDeferredDecision(orgId, factoryProjectId, decisionId, now) {
813
- let retried = false;
814
- const row = await this.#db.updateAtomic(
815
- "factory_deferred_decisions",
816
- { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },
817
- (current) => {
818
- if (current.status !== "failed") return null;
819
- retried = true;
820
- return {
821
- status: "retry",
822
- attempts: 0,
823
- available_at: now,
824
- lease_owner: null,
825
- lease_expires_at: null,
826
- last_error: null,
827
- completed_at: null,
828
- updated_at: now
829
- };
830
- }
831
- );
832
- return retried && row ? toDeferredDecision(row) : null;
833
- }
834
- /** Resolve exact active agent authority; partial session matches never authorize. */
835
- async findActiveRunBinding(address) {
836
- const row = await this.#db.findOne("factory_run_bindings", {
837
- org_id: address.orgId,
838
- factory_project_id: address.factoryProjectId,
839
- thread_id: address.threadId,
840
- resource_id: address.resourceId,
841
- session_id: address.sessionId,
842
- status: "active"
843
- });
844
- return row ? toBinding(row) : null;
845
- }
846
- /** Resolve exact bound-session state for processor awareness; ambiguous cross-tenant matches return null. */
847
- async findRunBindingBySession(address) {
848
- const rows = await this.#db.findMany("factory_run_bindings", {
849
- factory_project_id: address.factoryProjectId,
850
- thread_id: address.threadId,
851
- resource_id: address.resourceId,
852
- session_id: address.sessionId
853
- });
854
- if (new Set(rows.map((row2) => row2.org_id)).size !== 1) return null;
855
- const row = rows.sort((left, right) => {
856
- if (left.status === "active" && right.status !== "active") return -1;
857
- if (right.status === "active" && left.status !== "active") return 1;
858
- return right.created_at.getTime() - left.created_at.getTime();
859
- })[0];
860
- return row ? toBinding(row) : null;
861
- }
862
- /** Revoke one exact tenant-scoped binding. */
863
- async revokeRunBinding(input) {
864
- let revoked = false;
865
- const row = await this.#db.updateAtomic(
866
- "factory_run_bindings",
867
- { id: input.bindingId, org_id: input.orgId, factory_project_id: input.factoryProjectId },
868
- (current) => {
869
- if (current.status !== "active") return null;
870
- revoked = true;
871
- return { status: "revoked", revoked_at: input.revokedAt };
872
- }
873
- );
874
- return revoked && row ? toBinding(row) : null;
875
- }
876
- /** Enumerate active bindings for the server-owned restart reconciler. */
877
- async listActiveRunBindings() {
878
- return (await this.#db.findMany("factory_run_bindings", { status: "active" })).map(toBinding);
879
- }
880
- /** List binding history, optionally narrowed to one work item. */
881
- async listRunBindings(orgId, factoryProjectId, workItemId) {
882
- return (await this.#db.findMany(
883
- "factory_run_bindings",
884
- {
885
- org_id: orgId,
886
- factory_project_id: factoryProjectId,
887
- ...workItemId ? { work_item_id: workItemId } : {}
888
- },
889
- { orderBy: [["created_at", "asc"]] }
890
- )).map(toBinding);
891
- }
892
- async listPendingStarts(orgId, factoryProjectId) {
893
- return (await this.#db.findMany(
894
- "factory_pending_starts",
895
- { org_id: orgId, factory_project_id: factoryProjectId },
896
- { orderBy: [["created_at", "asc"]] }
897
- )).map(toPendingStart);
898
- }
899
- async claimPendingStarts(input) {
900
- return this.#claimLeases("factory_pending_starts", input, toPendingStart);
901
- }
902
- async renewPendingStartLease(identity, leaseExpiresAt) {
903
- return this.#renewLease("factory_pending_starts", identity, leaseExpiresAt);
904
- }
905
- async completePendingStart(identity, now) {
906
- const row = await this.#completeLease("factory_pending_starts", identity, now);
907
- return row ? toPendingStart(row) : null;
908
- }
909
- async failPendingStart(input) {
910
- const row = await this.#failLease("factory_pending_starts", input);
911
- return row ? toPendingStart(row) : null;
912
- }
913
- async prepareRunStart(input) {
914
- const prepare = () => this.storage.withTransaction(async (ops) => {
915
- const prior = await ops.findOne("factory_pending_starts", {
916
- org_id: input.orgId,
917
- factory_project_id: input.factoryProjectId,
918
- kickoff_key: input.kickoffKey
919
- });
920
- if (prior) {
921
- const bindingRow2 = await ops.findOne("factory_run_bindings", {
922
- id: String(prior.binding_id),
923
- org_id: input.orgId,
924
- factory_project_id: input.factoryProjectId
925
- });
926
- const itemRow = bindingRow2 && await ops.findOne("work_items", {
927
- id: String(bindingRow2.work_item_id),
928
- org_id: input.orgId,
929
- factory_project_id: input.factoryProjectId
930
- });
931
- if (!bindingRow2 || !itemRow) throw new Error("Factory start replay references missing state.");
932
- return {
933
- item: toRow(itemRow),
934
- binding: toBinding(bindingRow2),
935
- pendingStart: toPendingStart(prior),
936
- replayed: true
937
- };
938
- }
939
- const now = /* @__PURE__ */ new Date();
940
- const create = input.workItem.input;
941
- let row = input.workItem.id ? await ops.findOne("work_items", {
942
- id: input.workItem.id,
943
- org_id: input.orgId,
944
- factory_project_id: input.factoryProjectId
945
- }) : sourceKey(create.externalSource) ? await ops.findOne("work_items", {
946
- org_id: input.orgId,
947
- factory_project_id: input.factoryProjectId,
948
- source_key: sourceKey(create.externalSource)
949
- }) : null;
950
- let item;
951
- if (row) {
952
- row = await ops.updateAtomic("work_items", { id: row.id }, (current) => {
953
- const roles = /* @__PURE__ */ new Set([...Object.keys(current.sessions), input.role]);
954
- const sessions = Object.fromEntries([...roles].map((role) => [role, input.session]));
955
- return applyUpdate({ current, userId: input.userId, input: { sessions } });
956
- });
957
- item = toRow(row);
958
- } else {
959
- if (create.parentWorkItemId)
960
- validateParentRelation(
961
- (await ops.findMany("work_items", {
962
- org_id: input.orgId,
963
- factory_project_id: input.factoryProjectId
964
- })).map(toRow),
965
- void 0,
966
- create.parentWorkItemId
967
- );
968
- row = await ops.insertOne("work_items", {
969
- org_id: input.orgId,
970
- created_by: input.userId,
971
- factory_project_id: input.factoryProjectId,
972
- external_source: create.externalSource ?? null,
973
- source_key: sourceKey(create.externalSource),
974
- parent_work_item_id: create.parentWorkItemId ?? null,
975
- title: create.title,
976
- stages: create.stages ?? [],
977
- stage_history: applyStageTransition([], [], create.stages ?? [], input.userId, now),
978
- sessions: stampSessions({ [input.role]: input.session }, input.userId),
979
- metadata: create.metadata ?? null,
980
- revision: 1,
981
- created_at: now,
982
- updated_at: now
983
- });
984
- item = toRow(row);
985
- }
986
- await ops.updateMany(
987
- "factory_run_bindings",
988
- {
989
- org_id: input.orgId,
990
- factory_project_id: input.factoryProjectId,
991
- work_item_id: item.id,
992
- role: input.role,
993
- status: "active"
994
- },
995
- { status: "revoked", revoked_at: now }
996
- );
997
- const bindingRow = await ops.insertOne("factory_run_bindings", {
998
- org_id: input.orgId,
999
- factory_project_id: input.factoryProjectId,
1000
- work_item_id: item.id,
1001
- role: input.role,
1002
- thread_id: input.session.threadId,
1003
- resource_id: input.resourceId,
1004
- session_id: input.session.sessionId,
1005
- branch: input.session.branch,
1006
- status: "active",
1007
- created_at: now,
1008
- revoked_at: null
1009
- });
1010
- const pendingRow = await ops.insertOne("factory_pending_starts", {
1011
- org_id: input.orgId,
1012
- factory_project_id: input.factoryProjectId,
1013
- binding_id: bindingRow.id,
1014
- kickoff_key: input.kickoffKey,
1015
- message: input.kickoffMessage,
1016
- status: "pending",
1017
- attempts: 0,
1018
- available_at: now,
1019
- lease_owner: null,
1020
- lease_expires_at: null,
1021
- last_error: null,
1022
- completed_at: null,
1023
- created_at: now,
1024
- updated_at: now
1025
- });
1026
- return { item, binding: toBinding(bindingRow), pendingStart: toPendingStart(pendingRow), replayed: false };
1027
- });
1028
- try {
1029
- return await prepare();
1030
- } catch (error) {
1031
- if (!(error instanceof UniqueViolationError)) throw error;
1032
- return prepare();
1033
- }
1034
- }
1035
- async markPendingStart(bindingId, status, lastError) {
1036
- const row = await this.#db.updateAtomic(
1037
- "factory_pending_starts",
1038
- { binding_id: bindingId },
1039
- () => ({ status, last_error: lastError ?? null, updated_at: /* @__PURE__ */ new Date() })
1040
- );
1041
- return row ? toPendingStart(row) : null;
1042
- }
1043
- /**
1044
- * Create a work item, reusing the existing record when `sourceKey` already
1045
- * has one for the project (acting twice on the same issue must not duplicate
1046
- * the card). On reuse the provided stages replace the current ones (with the
1047
- * transition recorded in history) and sessions/metadata are merged in. The
1048
- * result discriminates insert from reuse so callers can audit the actual
1049
- * outcome.
1050
- */
1051
- async upsert(params) {
1052
- const run = (ops) => this.#upsert(params, ops);
1053
- const execute = () => params.input.parentWorkItemId ? this.#withProjectRelationTransaction(params.orgId, params.factoryProjectId, run) : run(this.#db);
1054
- try {
1055
- return await execute();
1056
- } catch (error) {
1057
- if (!(error instanceof UniqueViolationError)) throw error;
1058
- return execute();
1059
- }
1060
- }
1061
- async #upsert({
1062
- orgId,
1063
- userId,
1064
- factoryProjectId,
1065
- input,
1066
- reuseMode = "update"
1067
- }, ops) {
1068
- const key = sourceKey(input.externalSource);
1069
- const reuse = async () => {
1070
- if (!key) return null;
1071
- const existing = await ops.findOne("work_items", {
1072
- org_id: orgId,
1073
- factory_project_id: factoryProjectId,
1074
- source_key: key
1075
- });
1076
- if (!existing) return null;
1077
- if (reuseMode === "preserve") {
1078
- const item = toWorkItem(existing);
1079
- return { created: false, item, previous: priorState(existing) };
1080
- }
1081
- let previous = emptyPrior();
1082
- const updated = await ops.updateAtomic(
1083
- "work_items",
1084
- { org_id: orgId, factory_project_id: factoryProjectId, source_key: key },
1085
- async (current) => {
1086
- previous = priorState(current);
1087
- const fullPatch = input.parentWorkItemId === null ? { ...input, parentWorkItemId: void 0 } : input;
1088
- const patch = reuseMode === "non-stage" ? {
1089
- title: input.title,
1090
- parentWorkItemId: input.parentWorkItemId ?? void 0,
1091
- metadata: input.metadata
1092
- } : fullPatch;
1093
- if (patch.parentWorkItemId !== void 0) {
1094
- validateParentRelation(
1095
- await this.#listWithOps(ops, orgId, factoryProjectId),
1096
- current.id,
1097
- patch.parentWorkItemId
1098
- );
1099
- }
1100
- return {
1101
- external_source: input.externalSource ?? null,
1102
- ...applyUpdate({ current, userId, input: patch })
1103
- };
1104
- }
1105
- );
1106
- return updated ? { item: toWorkItem(updated), created: false, previous } : null;
1107
- };
1108
- const reused = await reuse();
1109
- if (reused) return reused;
1110
- const now = /* @__PURE__ */ new Date();
1111
- const stages = input.stages ?? ["intake"];
1112
- validateParentRelation(
1113
- await this.#listWithOps(ops, orgId, factoryProjectId),
1114
- void 0,
1115
- input.parentWorkItemId ?? null
1116
- );
1117
- const row = await ops.insertOne("work_items", {
1118
- org_id: orgId,
1119
- factory_project_id: factoryProjectId,
1120
- external_source: input.externalSource ?? null,
1121
- source_key: key,
1122
- parent_work_item_id: input.parentWorkItemId ?? null,
1123
- title: input.title,
1124
- stages,
1125
- stage_history: stages.map((stage) => ({ stage, enteredAt: now.toISOString(), by: userId })),
1126
- sessions: stampSessions(input.sessions ?? {}, userId),
1127
- metadata: input.metadata ?? null,
1128
- revision: 1,
1129
- created_by: userId,
1130
- created_at: now,
1131
- updated_at: now
1132
- });
1133
- return { item: toWorkItem(row), created: true, previous: emptyPrior() };
1134
- }
1135
- async update({
1136
- orgId,
1137
- id,
1138
- userId,
1139
- patch
1140
- }) {
1141
- const run = async (ops) => {
1142
- let previous = emptyPrior();
1143
- const row = await ops.updateAtomic("work_items", { org_id: orgId, id }, async (current) => {
1144
- previous = priorState(current);
1145
- if (patch.parentWorkItemId !== void 0) {
1146
- validateParentRelation(
1147
- await this.#listWithOps(ops, orgId, current.factory_project_id),
1148
- current.id,
1149
- patch.parentWorkItemId
1150
- );
1151
- }
1152
- return applyUpdate({ current, userId, input: patch });
1153
- });
1154
- return row ? { item: toWorkItem(row), previous } : null;
1155
- };
1156
- if (patch.parentWorkItemId === void 0) return run(this.#db);
1157
- const candidate = await this.#db.findOne("work_items", { org_id: orgId, id });
1158
- if (!candidate) return null;
1159
- return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, run);
1160
- }
1161
- async delete({ orgId, id }) {
1162
- const candidate = await this.#db.findOne("work_items", { org_id: orgId, id });
1163
- if (!candidate) return null;
1164
- return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async (ops) => {
1165
- const existing = await ops.findOne("work_items", { org_id: orgId, id });
1166
- if (!existing) return null;
1167
- const deleted = await ops.deleteMany("work_items", { org_id: orgId, id });
1168
- if (deleted === 0) return null;
1169
- await ops.updateMany(
1170
- "work_items",
1171
- { org_id: orgId, parent_work_item_id: id },
1172
- { parent_work_item_id: null, updated_at: /* @__PURE__ */ new Date() }
1173
- );
1174
- return toWorkItem(existing);
1175
- });
1176
- }
1177
- };
1178
- export {
1179
- AUTOMATION_ACTORS,
1180
- WORK_ITEMS_SCHEMA,
1181
- WorkItemRelationError,
1182
- WorkItemsStorage,
1183
- applyStageTransition,
1184
- factoryDecisionHash,
1185
- isAutomationActor,
1186
- stampSessions,
1187
- validateParentRelation
484
+ constructor() {
485
+ super("work-items");
486
+ }
487
+ async init() {
488
+ await this.ensureCollections([WORK_ITEMS_SCHEMA, ...FACTORY_GOVERNANCE_SCHEMAS]);
489
+ }
490
+ async dangerouslyClearAll() {
491
+ await this.ops.deleteMany("work_items", {});
492
+ }
493
+ get #db() {
494
+ return this.ops;
495
+ }
496
+ async #withProjectRelationTransaction(orgId, factoryProjectId, fn) {
497
+ return withInProcessProjectLock(`work-items:${orgId}:${factoryProjectId}`, () => this.storage.withTransaction(fn, { isolationLevel: "serializable" }));
498
+ }
499
+ async #claimLeases(table, input, map) {
500
+ const claim = () => this.storage.withTransaction(async (ops) => {
501
+ const candidates = await ops.findMany(table, { status: { in: [
502
+ "pending",
503
+ "retry",
504
+ "leased"
505
+ ] } }, {
506
+ orderBy: [["created_at", "asc"]],
507
+ limit: Math.max(input.limit * 5, 50)
508
+ });
509
+ const claimed = [];
510
+ for (const candidate of candidates) {
511
+ if (claimed.length >= input.limit) break;
512
+ const availableAt = new Date(candidate.available_at).getTime();
513
+ const leaseExpiresAt = candidate.lease_expires_at ? new Date(candidate.lease_expires_at).getTime() : 0;
514
+ const claimable = (candidate.status === "pending" || candidate.status === "retry") && availableAt <= input.now.getTime();
515
+ const expired = candidate.status === "leased" && leaseExpiresAt <= input.now.getTime();
516
+ if (!claimable && !expired) continue;
517
+ let didClaim = false;
518
+ const row = await ops.updateAtomic(table, { id: candidate.id }, (current) => {
519
+ const currentAvailable = new Date(current.available_at).getTime();
520
+ const currentExpiry = current.lease_expires_at ? new Date(current.lease_expires_at).getTime() : 0;
521
+ const currentClaimable = (current.status === "pending" || current.status === "retry") && currentAvailable <= input.now.getTime();
522
+ const currentExpired = current.status === "leased" && currentExpiry <= input.now.getTime();
523
+ if (!currentClaimable && !currentExpired) return null;
524
+ didClaim = true;
525
+ return {
526
+ status: "leased",
527
+ attempts: Number(current.attempts) + 1,
528
+ lease_owner: input.ownerId,
529
+ lease_expires_at: input.leaseExpiresAt,
530
+ updated_at: input.now
531
+ };
532
+ });
533
+ if (didClaim && row) claimed.push(map(row));
534
+ }
535
+ return claimed;
536
+ });
537
+ return claim();
538
+ }
539
+ async #renewLease(table, identity, leaseExpiresAt) {
540
+ let renewed = false;
541
+ await this.#db.updateAtomic(table, {
542
+ id: identity.id,
543
+ org_id: identity.orgId,
544
+ factory_project_id: identity.factoryProjectId
545
+ }, (current) => {
546
+ if (current.status !== "leased" || current.lease_owner !== identity.ownerId) return null;
547
+ renewed = true;
548
+ return {
549
+ lease_expires_at: leaseExpiresAt,
550
+ updated_at: /* @__PURE__ */ new Date()
551
+ };
552
+ });
553
+ return renewed;
554
+ }
555
+ async #completeLease(table, identity, now) {
556
+ let completed = false;
557
+ const row = await this.#db.updateAtomic(table, {
558
+ id: identity.id,
559
+ org_id: identity.orgId,
560
+ factory_project_id: identity.factoryProjectId
561
+ }, (current) => {
562
+ if (current.status !== "leased" || current.lease_owner !== identity.ownerId) return null;
563
+ completed = true;
564
+ return {
565
+ status: table === "factory_pending_starts" ? "sent" : "succeeded",
566
+ lease_owner: null,
567
+ lease_expires_at: null,
568
+ completed_at: now,
569
+ updated_at: now
570
+ };
571
+ });
572
+ return completed ? row : null;
573
+ }
574
+ async #failLease(table, input) {
575
+ let failed = false;
576
+ const row = await this.#db.updateAtomic(table, {
577
+ id: input.id,
578
+ org_id: input.orgId,
579
+ factory_project_id: input.factoryProjectId
580
+ }, (current) => {
581
+ if (current.status !== "leased" || current.lease_owner !== input.ownerId) return null;
582
+ failed = true;
583
+ return {
584
+ status: input.terminal ? "failed" : "retry",
585
+ available_at: input.availableAt,
586
+ lease_owner: null,
587
+ lease_expires_at: null,
588
+ last_error: input.lastError,
589
+ completed_at: input.terminal ? input.now : null,
590
+ updated_at: input.now
591
+ };
592
+ });
593
+ return failed ? row : null;
594
+ }
595
+ async #listWithOps(ops, orgId, factoryProjectId) {
596
+ return (await ops.findMany("work_items", {
597
+ org_id: orgId,
598
+ factory_project_id: factoryProjectId
599
+ }, { orderBy: [["updated_at", "desc"]] })).map(toWorkItem);
600
+ }
601
+ /** List the org's work items for a project, newest first. */
602
+ async list({ orgId, factoryProjectId }) {
603
+ return this.#listWithOps(this.#db, orgId, factoryProjectId);
604
+ }
605
+ async get({ orgId, id }) {
606
+ const row = await this.#db.findOne("work_items", {
607
+ org_id: orgId,
608
+ id
609
+ });
610
+ return row ? toWorkItem(row) : null;
611
+ }
612
+ async getForProject(orgId, factoryProjectId, id) {
613
+ const row = await this.#db.findOne("work_items", {
614
+ id,
615
+ org_id: orgId,
616
+ factory_project_id: factoryProjectId
617
+ });
618
+ return row ? toRow(row) : null;
619
+ }
620
+ async getTransitionResultByIngress(orgId, factoryProjectId, identity) {
621
+ return (await this.#db.findOne("factory_rule_ingress", {
622
+ org_id: orgId,
623
+ factory_project_id: factoryProjectId,
624
+ identity
625
+ }))?.result ?? null;
626
+ }
627
+ async commitTransition(input) {
628
+ const commit = () => this.storage.withTransaction(async (ops) => {
629
+ const prior = await ops.findOne("factory_rule_ingress", {
630
+ org_id: input.orgId,
631
+ factory_project_id: input.factoryProjectId,
632
+ identity: input.ingress.identity
633
+ });
634
+ if (prior) return {
635
+ status: "replayed",
636
+ item: await this.getForProject(input.orgId, input.factoryProjectId, input.workItemId),
637
+ result: prior.result
638
+ };
639
+ const now = /* @__PURE__ */ new Date();
640
+ let item = null;
641
+ let code = null;
642
+ let reason = null;
643
+ let result;
644
+ const updated = await ops.updateAtomic("work_items", {
645
+ id: input.workItemId,
646
+ org_id: input.orgId,
647
+ factory_project_id: input.factoryProjectId
648
+ }, (row) => {
649
+ const existing = toRow(row);
650
+ item = existing;
651
+ if (existing.revision !== input.expectedRevision) {
652
+ code = "stale";
653
+ reason = "The work item changed before this transition committed.";
654
+ return null;
655
+ }
656
+ if (input.evaluation.outcome === "rejected") {
657
+ code = input.evaluation.code;
658
+ reason = input.evaluation.reason;
659
+ return null;
660
+ }
661
+ if (existing.stages.length === 1 && existing.stages[0] === input.destinationStage) return null;
662
+ return patchColumns({
663
+ stages: [input.destinationStage],
664
+ stageHistory: applyStageTransition(existing.stageHistory, existing.stages, [input.destinationStage], input.actorId, now),
665
+ revision: existing.revision + 1,
666
+ updatedAt: now
667
+ });
668
+ });
669
+ if (updated) item = toRow(updated);
670
+ if (!item) {
671
+ code = input.evaluation.outcome === "rejected" ? input.evaluation.code : "invalid_transition";
672
+ reason = input.evaluation.outcome === "rejected" ? input.evaluation.reason : "Work item not found.";
673
+ }
674
+ const outcome = item && code === null && input.evaluation.outcome === "accepted" ? "accepted" : "rejected";
675
+ result = outcome === "accepted" ? {
676
+ status: "accepted",
677
+ transitionId: input.ingress.transitionId,
678
+ itemId: item.id,
679
+ revision: item.revision,
680
+ stage: input.destinationStage,
681
+ decisions: input.evaluation.outcome === "accepted" ? input.evaluation.decisions : []
682
+ } : {
683
+ status: "rejected",
684
+ transitionId: input.ingress.transitionId,
685
+ itemId: input.workItemId,
686
+ code,
687
+ reason
688
+ };
689
+ const ingress = await ops.insertOne("factory_rule_ingress", {
690
+ org_id: input.orgId,
691
+ factory_project_id: input.factoryProjectId,
692
+ identity: input.ingress.identity,
693
+ trigger_type: input.ingress.triggerType,
694
+ transition_id: input.ingress.transitionId,
695
+ result,
696
+ created_at: now
697
+ });
698
+ if (item) {
699
+ const evaluation = await ops.insertOne("factory_rule_evaluations", {
700
+ ingress_id: ingress.id,
701
+ work_item_id: item.id,
702
+ rule_set_version: input.ruleSetVersion,
703
+ expected_revision: input.expectedRevision,
704
+ outcome,
705
+ code,
706
+ reason,
707
+ causal_chain: input.causalChain,
708
+ created_at: now
709
+ });
710
+ if (outcome === "accepted" && input.evaluation.outcome === "accepted") for (const [index, decision] of input.evaluation.decisions.entries()) await ops.insertOne("factory_deferred_decisions", {
711
+ org_id: input.orgId,
712
+ factory_project_id: input.factoryProjectId,
713
+ evaluation_id: evaluation.id,
714
+ work_item_id: item.id,
715
+ idempotency_key: String(decision.idempotencyKey),
716
+ effect_ordinal: index,
717
+ effect_hash: factoryDecisionHash(decision),
718
+ causal_chain: input.causalChain,
719
+ actor: null,
720
+ decision,
721
+ status: "pending",
722
+ attempts: 0,
723
+ available_at: now,
724
+ lease_owner: null,
725
+ lease_expires_at: null,
726
+ last_error: null,
727
+ completed_at: null,
728
+ created_at: new Date(now.getTime() + index),
729
+ updated_at: now
730
+ });
731
+ }
732
+ return {
733
+ status: "committed",
734
+ item,
735
+ result
736
+ };
737
+ });
738
+ try {
739
+ return await commit();
740
+ } catch (error) {
741
+ if (!(error instanceof UniqueViolationError)) throw error;
742
+ return commit();
743
+ }
744
+ }
745
+ async commitRuleEvaluation(input) {
746
+ const commit = () => this.storage.withTransaction(async (ops) => {
747
+ const prior = await ops.findOne("factory_rule_ingress", {
748
+ org_id: input.orgId,
749
+ factory_project_id: input.factoryProjectId,
750
+ identity: input.ingress.identity
751
+ });
752
+ if (prior) {
753
+ const result = prior.result;
754
+ const decisions = Array.isArray(result.decisions) ? result.decisions : [];
755
+ const evaluation = await ops.findOne("factory_rule_evaluations", { ingress_id: prior.id });
756
+ for (const decision of decisions) {
757
+ if (!evaluation || !decision || typeof decision !== "object" || decision.type !== "upsertLinkedWorkItem" || typeof decision.sourceKey !== "string" || typeof decision.idempotencyKey !== "string") continue;
758
+ const materialization = decision;
759
+ if (await ops.findOne("work_items", {
760
+ org_id: input.orgId,
761
+ factory_project_id: input.factoryProjectId,
762
+ source_key: materialization.sourceKey
763
+ })) continue;
764
+ await ops.updateAtomic("factory_deferred_decisions", {
765
+ org_id: input.orgId,
766
+ factory_project_id: input.factoryProjectId,
767
+ evaluation_id: evaluation.id,
768
+ idempotency_key: materialization.idempotencyKey
769
+ }, (current) => current.status === "succeeded" ? {
770
+ status: "retry",
771
+ attempts: 0,
772
+ available_at: input.now,
773
+ lease_owner: null,
774
+ lease_expires_at: null,
775
+ last_error: null,
776
+ completed_at: null,
777
+ updated_at: input.now
778
+ } : null);
779
+ }
780
+ return {
781
+ status: "replayed",
782
+ result
783
+ };
784
+ }
785
+ const itemRow = input.workItemId ? await ops.findOne("work_items", {
786
+ id: input.workItemId,
787
+ org_id: input.orgId,
788
+ factory_project_id: input.factoryProjectId
789
+ }) : null;
790
+ if (input.workItemId !== null && !itemRow) return { status: "missing" };
791
+ const item = itemRow ? toRow(itemRow) : null;
792
+ const stale = item !== null && item.revision !== input.expectedRevision;
793
+ const outcome = stale ? "rejected" : input.outcome.status;
794
+ const code = stale ? "stale" : input.outcome.code ?? null;
795
+ const reason = stale ? "The work item changed before this rule evaluation committed." : input.outcome.reason ?? null;
796
+ const decisions = outcome === "accepted" ? input.decisions : [];
797
+ const result = {
798
+ status: outcome,
799
+ itemId: item?.id ?? null,
800
+ revision: item?.revision ?? null,
801
+ code,
802
+ reason,
803
+ decisions
804
+ };
805
+ const ingress = await ops.insertOne("factory_rule_ingress", {
806
+ org_id: input.orgId,
807
+ factory_project_id: input.factoryProjectId,
808
+ identity: input.ingress.identity,
809
+ trigger_type: input.ingress.triggerType,
810
+ transition_id: input.ingress.identity,
811
+ result,
812
+ created_at: input.now
813
+ });
814
+ const evaluation = await ops.insertOne("factory_rule_evaluations", {
815
+ ingress_id: ingress.id,
816
+ work_item_id: item?.id ?? null,
817
+ rule_set_version: input.ruleSetVersion,
818
+ expected_revision: input.expectedRevision,
819
+ outcome,
820
+ code,
821
+ reason,
822
+ causal_chain: input.causalChain,
823
+ created_at: input.now
824
+ });
825
+ for (const [effectOrdinal, decision] of decisions.entries()) await ops.insertOne("factory_deferred_decisions", {
826
+ org_id: input.orgId,
827
+ factory_project_id: input.factoryProjectId,
828
+ evaluation_id: evaluation.id,
829
+ work_item_id: item?.id ?? null,
830
+ idempotency_key: String(decision.idempotencyKey),
831
+ effect_ordinal: effectOrdinal,
832
+ effect_hash: factoryDecisionHash(decision),
833
+ causal_chain: input.causalChain,
834
+ actor: input.actor,
835
+ decision,
836
+ status: "pending",
837
+ attempts: 0,
838
+ available_at: input.now,
839
+ lease_owner: null,
840
+ lease_expires_at: null,
841
+ last_error: null,
842
+ completed_at: null,
843
+ created_at: new Date(input.now.getTime() + effectOrdinal),
844
+ updated_at: input.now
845
+ });
846
+ return {
847
+ status: "committed",
848
+ result
849
+ };
850
+ });
851
+ try {
852
+ return await commit();
853
+ } catch (error) {
854
+ if (!(error instanceof UniqueViolationError)) throw error;
855
+ return commit();
856
+ }
857
+ }
858
+ async getToolResultCursor(orgId, factoryProjectId, bindingId) {
859
+ const row = await this.#db.findOne("factory_tool_result_cursors", {
860
+ org_id: orgId,
861
+ factory_project_id: factoryProjectId,
862
+ binding_id: bindingId
863
+ });
864
+ return row ? {
865
+ bindingId: String(row.binding_id),
866
+ orgId: row.org_id,
867
+ factoryProjectId: String(row.factory_project_id),
868
+ lastMessageId: String(row.last_message_id),
869
+ lastMessageCreatedAt: row.last_message_created_at,
870
+ updatedAt: row.updated_at
871
+ } : null;
872
+ }
873
+ async advanceToolResultCursor(cursor) {
874
+ const current = await this.getToolResultCursor(cursor.orgId, cursor.factoryProjectId, cursor.bindingId);
875
+ if (current && current.lastMessageCreatedAt > cursor.lastMessageCreatedAt) return;
876
+ await this.#db.upsertOne("factory_tool_result_cursors", ["binding_id"], {
877
+ binding_id: cursor.bindingId,
878
+ org_id: cursor.orgId,
879
+ factory_project_id: cursor.factoryProjectId,
880
+ last_message_id: cursor.lastMessageId,
881
+ last_message_created_at: cursor.lastMessageCreatedAt,
882
+ updated_at: cursor.updatedAt
883
+ });
884
+ }
885
+ async listDeferredDecisions(orgId, factoryProjectId) {
886
+ return (await this.#db.findMany("factory_deferred_decisions", {
887
+ org_id: orgId,
888
+ factory_project_id: factoryProjectId
889
+ }, { orderBy: [["created_at", "asc"]] })).map(toDeferredDecision);
890
+ }
891
+ /** Read a bounded newest-first status page without exposing another tenant. */
892
+ async listDeferredDecisionPage(input) {
893
+ const rows = await this.#db.findMany("factory_deferred_decisions", {
894
+ org_id: input.orgId,
895
+ factory_project_id: input.factoryProjectId,
896
+ ...input.statuses ? { status: { in: input.statuses } } : {}
897
+ }, {
898
+ orderBy: [["created_at", "desc"], ["id", "desc"]],
899
+ limit: input.limit + 1,
900
+ ...input.before ? { cursor: { values: [input.before.createdAt, input.before.id] } } : {}
901
+ });
902
+ return {
903
+ decisions: rows.slice(0, input.limit).map(toDeferredDecision),
904
+ hasMore: rows.length > input.limit
905
+ };
906
+ }
907
+ async claimDeferredDecisions(input) {
908
+ return this.#claimLeases("factory_deferred_decisions", input, toDeferredDecision);
909
+ }
910
+ async renewDeferredDecisionLease(identity, leaseExpiresAt) {
911
+ return this.#renewLease("factory_deferred_decisions", identity, leaseExpiresAt);
912
+ }
913
+ async completeDeferredDecision(identity, now) {
914
+ const row = await this.#completeLease("factory_deferred_decisions", identity, now);
915
+ return row ? toDeferredDecision(row) : null;
916
+ }
917
+ async failDeferredDecision(input) {
918
+ const row = await this.#failLease("factory_deferred_decisions", input);
919
+ return row ? toDeferredDecision(row) : null;
920
+ }
921
+ /** Requeue the same idempotent terminal effect; non-failed decisions are never rerun. */
922
+ async retryDeferredDecision(orgId, factoryProjectId, decisionId, now) {
923
+ let retried = false;
924
+ const row = await this.#db.updateAtomic("factory_deferred_decisions", {
925
+ id: decisionId,
926
+ org_id: orgId,
927
+ factory_project_id: factoryProjectId
928
+ }, (current) => {
929
+ if (current.status !== "failed") return null;
930
+ retried = true;
931
+ return {
932
+ status: "retry",
933
+ attempts: 0,
934
+ available_at: now,
935
+ lease_owner: null,
936
+ lease_expires_at: null,
937
+ last_error: null,
938
+ completed_at: null,
939
+ updated_at: now
940
+ };
941
+ });
942
+ return retried && row ? toDeferredDecision(row) : null;
943
+ }
944
+ /** Resolve exact active agent authority; partial session matches never authorize. */
945
+ async findActiveRunBinding(address) {
946
+ const row = await this.#db.findOne("factory_run_bindings", {
947
+ org_id: address.orgId,
948
+ factory_project_id: address.factoryProjectId,
949
+ thread_id: address.threadId,
950
+ resource_id: address.resourceId,
951
+ session_id: address.sessionId,
952
+ status: "active"
953
+ });
954
+ return row ? toBinding(row) : null;
955
+ }
956
+ /** Resolve exact bound-session state for processor awareness; ambiguous cross-tenant matches return null. */
957
+ async findRunBindingBySession(address) {
958
+ const rows = await this.#db.findMany("factory_run_bindings", {
959
+ factory_project_id: address.factoryProjectId,
960
+ thread_id: address.threadId,
961
+ resource_id: address.resourceId,
962
+ session_id: address.sessionId
963
+ });
964
+ if (new Set(rows.map((row) => row.org_id)).size !== 1) return null;
965
+ const row = rows.sort((left, right) => {
966
+ if (left.status === "active" && right.status !== "active") return -1;
967
+ if (right.status === "active" && left.status !== "active") return 1;
968
+ return right.created_at.getTime() - left.created_at.getTime();
969
+ })[0];
970
+ return row ? toBinding(row) : null;
971
+ }
972
+ /** Revoke one exact tenant-scoped binding. */
973
+ async revokeRunBinding(input) {
974
+ let revoked = false;
975
+ const row = await this.#db.updateAtomic("factory_run_bindings", {
976
+ id: input.bindingId,
977
+ org_id: input.orgId,
978
+ factory_project_id: input.factoryProjectId
979
+ }, (current) => {
980
+ if (current.status !== "active") return null;
981
+ revoked = true;
982
+ return {
983
+ status: "revoked",
984
+ revoked_at: input.revokedAt
985
+ };
986
+ });
987
+ return revoked && row ? toBinding(row) : null;
988
+ }
989
+ /** Enumerate active bindings for the server-owned restart reconciler. */
990
+ async listActiveRunBindings() {
991
+ return (await this.#db.findMany("factory_run_bindings", { status: "active" })).map(toBinding);
992
+ }
993
+ /** List binding history, optionally narrowed to one work item. */
994
+ async listRunBindings(orgId, factoryProjectId, workItemId) {
995
+ return (await this.#db.findMany("factory_run_bindings", {
996
+ org_id: orgId,
997
+ factory_project_id: factoryProjectId,
998
+ ...workItemId ? { work_item_id: workItemId } : {}
999
+ }, { orderBy: [["created_at", "asc"]] })).map(toBinding);
1000
+ }
1001
+ async listPendingStarts(orgId, factoryProjectId) {
1002
+ return (await this.#db.findMany("factory_pending_starts", {
1003
+ org_id: orgId,
1004
+ factory_project_id: factoryProjectId
1005
+ }, { orderBy: [["created_at", "asc"]] })).map(toPendingStart);
1006
+ }
1007
+ async claimPendingStarts(input) {
1008
+ return this.#claimLeases("factory_pending_starts", input, toPendingStart);
1009
+ }
1010
+ async renewPendingStartLease(identity, leaseExpiresAt) {
1011
+ return this.#renewLease("factory_pending_starts", identity, leaseExpiresAt);
1012
+ }
1013
+ async completePendingStart(identity, now) {
1014
+ const row = await this.#completeLease("factory_pending_starts", identity, now);
1015
+ return row ? toPendingStart(row) : null;
1016
+ }
1017
+ async failPendingStart(input) {
1018
+ const row = await this.#failLease("factory_pending_starts", input);
1019
+ return row ? toPendingStart(row) : null;
1020
+ }
1021
+ async prepareRunStart(input) {
1022
+ const prepare = () => this.storage.withTransaction(async (ops) => {
1023
+ const prior = await ops.findOne("factory_pending_starts", {
1024
+ org_id: input.orgId,
1025
+ factory_project_id: input.factoryProjectId,
1026
+ kickoff_key: input.kickoffKey
1027
+ });
1028
+ if (prior) {
1029
+ const bindingRow = await ops.findOne("factory_run_bindings", {
1030
+ id: String(prior.binding_id),
1031
+ org_id: input.orgId,
1032
+ factory_project_id: input.factoryProjectId
1033
+ });
1034
+ const itemRow = bindingRow && await ops.findOne("work_items", {
1035
+ id: String(bindingRow.work_item_id),
1036
+ org_id: input.orgId,
1037
+ factory_project_id: input.factoryProjectId
1038
+ });
1039
+ if (!bindingRow || !itemRow) throw new Error("Factory start replay references missing state.");
1040
+ return {
1041
+ item: toRow(itemRow),
1042
+ binding: toBinding(bindingRow),
1043
+ pendingStart: toPendingStart(prior),
1044
+ replayed: true
1045
+ };
1046
+ }
1047
+ const now = /* @__PURE__ */ new Date();
1048
+ const create = input.workItem.input;
1049
+ let row = input.workItem.id ? await ops.findOne("work_items", {
1050
+ id: input.workItem.id,
1051
+ org_id: input.orgId,
1052
+ factory_project_id: input.factoryProjectId
1053
+ }) : sourceKey(create.externalSource) ? await ops.findOne("work_items", {
1054
+ org_id: input.orgId,
1055
+ factory_project_id: input.factoryProjectId,
1056
+ source_key: sourceKey(create.externalSource)
1057
+ }) : null;
1058
+ let item;
1059
+ if (row) {
1060
+ row = await ops.updateAtomic("work_items", { id: row.id }, (current) => {
1061
+ const roles = /* @__PURE__ */ new Set([...Object.keys(current.sessions), input.role]);
1062
+ const sessions = Object.fromEntries([...roles].map((role) => [role, input.session]));
1063
+ return applyUpdate({
1064
+ current,
1065
+ userId: input.userId,
1066
+ input: { sessions }
1067
+ });
1068
+ });
1069
+ item = toRow(row);
1070
+ } else {
1071
+ if (create.parentWorkItemId) validateParentRelation((await ops.findMany("work_items", {
1072
+ org_id: input.orgId,
1073
+ factory_project_id: input.factoryProjectId
1074
+ })).map(toRow), void 0, create.parentWorkItemId);
1075
+ row = await ops.insertOne("work_items", {
1076
+ org_id: input.orgId,
1077
+ created_by: input.userId,
1078
+ factory_project_id: input.factoryProjectId,
1079
+ external_source: create.externalSource ?? null,
1080
+ source_key: sourceKey(create.externalSource),
1081
+ parent_work_item_id: create.parentWorkItemId ?? null,
1082
+ title: create.title,
1083
+ stages: create.stages ?? [],
1084
+ stage_history: applyStageTransition([], [], create.stages ?? [], input.userId, now),
1085
+ sessions: stampSessions({ [input.role]: input.session }, input.userId),
1086
+ metadata: create.metadata ?? null,
1087
+ revision: 1,
1088
+ created_at: now,
1089
+ updated_at: now
1090
+ });
1091
+ item = toRow(row);
1092
+ }
1093
+ await ops.updateMany("factory_run_bindings", {
1094
+ org_id: input.orgId,
1095
+ factory_project_id: input.factoryProjectId,
1096
+ work_item_id: item.id,
1097
+ role: input.role,
1098
+ status: "active"
1099
+ }, {
1100
+ status: "revoked",
1101
+ revoked_at: now
1102
+ });
1103
+ const bindingRow = await ops.insertOne("factory_run_bindings", {
1104
+ org_id: input.orgId,
1105
+ factory_project_id: input.factoryProjectId,
1106
+ work_item_id: item.id,
1107
+ role: input.role,
1108
+ thread_id: input.session.threadId,
1109
+ resource_id: input.resourceId,
1110
+ session_id: input.session.sessionId,
1111
+ branch: input.session.branch,
1112
+ status: "active",
1113
+ created_at: now,
1114
+ revoked_at: null
1115
+ });
1116
+ const pendingRow = await ops.insertOne("factory_pending_starts", {
1117
+ org_id: input.orgId,
1118
+ factory_project_id: input.factoryProjectId,
1119
+ binding_id: bindingRow.id,
1120
+ kickoff_key: input.kickoffKey,
1121
+ message: input.kickoffMessage,
1122
+ status: "pending",
1123
+ attempts: 0,
1124
+ available_at: now,
1125
+ lease_owner: null,
1126
+ lease_expires_at: null,
1127
+ last_error: null,
1128
+ completed_at: null,
1129
+ created_at: now,
1130
+ updated_at: now
1131
+ });
1132
+ return {
1133
+ item,
1134
+ binding: toBinding(bindingRow),
1135
+ pendingStart: toPendingStart(pendingRow),
1136
+ replayed: false
1137
+ };
1138
+ });
1139
+ try {
1140
+ return await prepare();
1141
+ } catch (error) {
1142
+ if (!(error instanceof UniqueViolationError)) throw error;
1143
+ return prepare();
1144
+ }
1145
+ }
1146
+ async markPendingStart(bindingId, status, lastError) {
1147
+ const row = await this.#db.updateAtomic("factory_pending_starts", { binding_id: bindingId }, () => ({
1148
+ status,
1149
+ last_error: lastError ?? null,
1150
+ updated_at: /* @__PURE__ */ new Date()
1151
+ }));
1152
+ return row ? toPendingStart(row) : null;
1153
+ }
1154
+ /**
1155
+ * Create a work item, reusing the existing record when `sourceKey` already
1156
+ * has one for the project (acting twice on the same issue must not duplicate
1157
+ * the card). On reuse the provided stages replace the current ones (with the
1158
+ * transition recorded in history) and sessions/metadata are merged in. The
1159
+ * result discriminates insert from reuse so callers can audit the actual
1160
+ * outcome.
1161
+ */
1162
+ async upsert(params) {
1163
+ const run = (ops) => this.#upsert(params, ops);
1164
+ const execute = () => params.input.parentWorkItemId ? this.#withProjectRelationTransaction(params.orgId, params.factoryProjectId, run) : run(this.#db);
1165
+ try {
1166
+ return await execute();
1167
+ } catch (error) {
1168
+ if (!(error instanceof UniqueViolationError)) throw error;
1169
+ return execute();
1170
+ }
1171
+ }
1172
+ async #upsert({ orgId, userId, factoryProjectId, input, reuseMode = "update" }, ops) {
1173
+ const key = sourceKey(input.externalSource);
1174
+ const reuse = async () => {
1175
+ if (!key) return null;
1176
+ const existing = await ops.findOne("work_items", {
1177
+ org_id: orgId,
1178
+ factory_project_id: factoryProjectId,
1179
+ source_key: key
1180
+ });
1181
+ if (!existing) return null;
1182
+ if (reuseMode === "preserve") return {
1183
+ created: false,
1184
+ item: toWorkItem(existing),
1185
+ previous: priorState(existing)
1186
+ };
1187
+ let previous = emptyPrior();
1188
+ const updated = await ops.updateAtomic("work_items", {
1189
+ org_id: orgId,
1190
+ factory_project_id: factoryProjectId,
1191
+ source_key: key
1192
+ }, async (current) => {
1193
+ previous = priorState(current);
1194
+ const fullPatch = input.parentWorkItemId === null ? {
1195
+ ...input,
1196
+ parentWorkItemId: void 0
1197
+ } : input;
1198
+ const patch = reuseMode === "non-stage" ? {
1199
+ title: input.title,
1200
+ parentWorkItemId: input.parentWorkItemId ?? void 0,
1201
+ metadata: input.metadata
1202
+ } : fullPatch;
1203
+ if (patch.parentWorkItemId !== void 0) validateParentRelation(await this.#listWithOps(ops, orgId, factoryProjectId), current.id, patch.parentWorkItemId);
1204
+ return {
1205
+ external_source: input.externalSource ?? null,
1206
+ ...applyUpdate({
1207
+ current,
1208
+ userId,
1209
+ input: patch
1210
+ })
1211
+ };
1212
+ });
1213
+ return updated ? {
1214
+ item: toWorkItem(updated),
1215
+ created: false,
1216
+ previous
1217
+ } : null;
1218
+ };
1219
+ const reused = await reuse();
1220
+ if (reused) return reused;
1221
+ const now = /* @__PURE__ */ new Date();
1222
+ const stages = input.stages ?? ["intake"];
1223
+ validateParentRelation(await this.#listWithOps(ops, orgId, factoryProjectId), void 0, input.parentWorkItemId ?? null);
1224
+ return {
1225
+ item: toWorkItem(await ops.insertOne("work_items", {
1226
+ org_id: orgId,
1227
+ factory_project_id: factoryProjectId,
1228
+ external_source: input.externalSource ?? null,
1229
+ source_key: key,
1230
+ parent_work_item_id: input.parentWorkItemId ?? null,
1231
+ title: input.title,
1232
+ stages,
1233
+ stage_history: stages.map((stage) => ({
1234
+ stage,
1235
+ enteredAt: now.toISOString(),
1236
+ by: userId
1237
+ })),
1238
+ sessions: stampSessions(input.sessions ?? {}, userId),
1239
+ metadata: input.metadata ?? null,
1240
+ revision: 1,
1241
+ created_by: userId,
1242
+ created_at: now,
1243
+ updated_at: now
1244
+ })),
1245
+ created: true,
1246
+ previous: emptyPrior()
1247
+ };
1248
+ }
1249
+ async update({ orgId, id, userId, patch }) {
1250
+ const run = async (ops) => {
1251
+ let previous = emptyPrior();
1252
+ const row = await ops.updateAtomic("work_items", {
1253
+ org_id: orgId,
1254
+ id
1255
+ }, async (current) => {
1256
+ previous = priorState(current);
1257
+ if (patch.parentWorkItemId !== void 0) validateParentRelation(await this.#listWithOps(ops, orgId, current.factory_project_id), current.id, patch.parentWorkItemId);
1258
+ return applyUpdate({
1259
+ current,
1260
+ userId,
1261
+ input: patch
1262
+ });
1263
+ });
1264
+ return row ? {
1265
+ item: toWorkItem(row),
1266
+ previous
1267
+ } : null;
1268
+ };
1269
+ if (patch.parentWorkItemId === void 0) return run(this.#db);
1270
+ const candidate = await this.#db.findOne("work_items", {
1271
+ org_id: orgId,
1272
+ id
1273
+ });
1274
+ if (!candidate) return null;
1275
+ return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, run);
1276
+ }
1277
+ async delete({ orgId, id }) {
1278
+ const candidate = await this.#db.findOne("work_items", {
1279
+ org_id: orgId,
1280
+ id
1281
+ });
1282
+ if (!candidate) return null;
1283
+ return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async (ops) => {
1284
+ const existing = await ops.findOne("work_items", {
1285
+ org_id: orgId,
1286
+ id
1287
+ });
1288
+ if (!existing) return null;
1289
+ if (await ops.deleteMany("work_items", {
1290
+ org_id: orgId,
1291
+ id
1292
+ }) === 0) return null;
1293
+ await ops.updateMany("work_items", {
1294
+ org_id: orgId,
1295
+ parent_work_item_id: id
1296
+ }, {
1297
+ parent_work_item_id: null,
1298
+ updated_at: /* @__PURE__ */ new Date()
1299
+ });
1300
+ return toWorkItem(existing);
1301
+ });
1302
+ }
1188
1303
  };
1304
+ //#endregion
1305
+ export { AUTOMATION_ACTORS, WORK_ITEMS_SCHEMA, WorkItemRelationError, WorkItemsStorage, applyStageTransition, factoryDecisionHash, isAutomationActor, stampSessions, validateParentRelation };
1306
+
1189
1307
  //# sourceMappingURL=base.js.map