@jsb188/mday 1.1.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 (202) hide show
  1. package/package.json +142 -0
  2. package/src/constants/agentMemory.ts +166 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +22 -0
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +146 -0
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/inboundContact.ts +8 -0
  17. package/src/constants/integration.ts +13 -0
  18. package/src/constants/log.ts +21 -0
  19. package/src/constants/logDisplay/README.md +88 -0
  20. package/src/constants/logDisplay/defaults.ts +39 -0
  21. package/src/constants/logDisplay/index.ts +27 -0
  22. package/src/constants/logDisplay/operations/arable.ts +16 -0
  23. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  24. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  25. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  26. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  27. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  28. package/src/constants/logTaxonomy.generated.ts +2199 -0
  29. package/src/constants/noteDoc.ts +77 -0
  30. package/src/constants/organization.ts +60 -0
  31. package/src/constants/pageRoute.ts +23 -0
  32. package/src/constants/qrCode.ts +30 -0
  33. package/src/constants/sheet.ts +132 -0
  34. package/src/constants/sms.ts +18 -0
  35. package/src/constants/square.ts +16 -0
  36. package/src/constants/storage.ts +85 -0
  37. package/src/constants/usage.ts +82 -0
  38. package/src/constants/workflowSteps.ts +60 -0
  39. package/src/schemas/editLogEntry.ts +879 -0
  40. package/src/schemas/inboundContact.ts +77 -0
  41. package/src/schemas/logsQuery.ts +93 -0
  42. package/src/types/account.d.ts +81 -0
  43. package/src/types/agentMemory.d.ts +100 -0
  44. package/src/types/agentNote.d.ts +441 -0
  45. package/src/types/billing.d.ts +537 -0
  46. package/src/types/campaign.d.ts +1533 -0
  47. package/src/types/contact.d.ts +15 -0
  48. package/src/types/csvExport.d.ts +213 -0
  49. package/src/types/dataAnalysis.d.ts +44 -0
  50. package/src/types/dataTable.d.ts +159 -0
  51. package/src/types/definitionElement.d.ts +35 -0
  52. package/src/types/docAccess.d.ts +96 -0
  53. package/src/types/dt.d.ts +257 -0
  54. package/src/types/email.d.ts +231 -0
  55. package/src/types/emailReplyReport.d.ts +76 -0
  56. package/src/types/fieldDoc.d.ts +702 -0
  57. package/src/types/fieldDocContract.d.ts +90 -0
  58. package/src/types/inboundContact.d.ts +65 -0
  59. package/src/types/integration.d.ts +42 -0
  60. package/src/types/log.d.ts +338 -0
  61. package/src/types/logDisplay.types.ts +85 -0
  62. package/src/types/organization.d.ts +350 -0
  63. package/src/types/pageRoute.d.ts +48 -0
  64. package/src/types/qrCode.d.ts +96 -0
  65. package/src/types/richText.d.ts +81 -0
  66. package/src/types/sheet.d.ts +847 -0
  67. package/src/types/sms.d.ts +38 -0
  68. package/src/types/storage.d.ts +481 -0
  69. package/src/types/usage.d.ts +106 -0
  70. package/src/types/workflow.d.ts +435 -0
  71. package/src/utils/agentMemory.ts +15 -0
  72. package/src/utils/agentNote.ts +850 -0
  73. package/src/utils/aiChat.ts +43 -0
  74. package/src/utils/aiChatWork.ts +64 -0
  75. package/src/utils/billing.ts +37 -0
  76. package/src/utils/campaign.ts +1173 -0
  77. package/src/utils/campaignAI.ts +72 -0
  78. package/src/utils/campaignAccess.ts +239 -0
  79. package/src/utils/campaignEmail.ts +601 -0
  80. package/src/utils/campaignEmailCompiler.ts +372 -0
  81. package/src/utils/campaignEmailImages.ts +60 -0
  82. package/src/utils/campaignEmailStyles.ts +544 -0
  83. package/src/utils/campaignLifecycle.ts +104 -0
  84. package/src/utils/campaignPreview.ts +285 -0
  85. package/src/utils/contact.ts +50 -0
  86. package/src/utils/csvExport.ts +19 -0
  87. package/src/utils/dataTable.ts +311 -0
  88. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  89. package/src/utils/dataTableRelativeDate.ts +447 -0
  90. package/src/utils/definitionElement.ts +84 -0
  91. package/src/utils/docAccess.ts +383 -0
  92. package/src/utils/documentName.ts +53 -0
  93. package/src/utils/email.ts +379 -0
  94. package/src/utils/emailReplyReport.test.ts +187 -0
  95. package/src/utils/emailReplyReport.ts +143 -0
  96. package/src/utils/fieldDoc.ts +157 -0
  97. package/src/utils/fieldDocAnswers.ts +128 -0
  98. package/src/utils/fieldDocDefaults.ts +36 -0
  99. package/src/utils/fieldDocProgram.ts +36 -0
  100. package/src/utils/fieldDocSummary.ts +30 -0
  101. package/src/utils/log.ts +357 -0
  102. package/src/utils/logDisplay.helpers.ts +177 -0
  103. package/src/utils/logDisplay.ts +87 -0
  104. package/src/utils/logRegistryValue.ts +90 -0
  105. package/src/utils/logStoreRead.ts +262 -0
  106. package/src/utils/logTaxonomy.helpers.ts +17 -0
  107. package/src/utils/logTaxonomy.ts +76 -0
  108. package/src/utils/logTaxonomyDisplay.ts +395 -0
  109. package/src/utils/noteDoc.ts +609 -0
  110. package/src/utils/organization.ts +669 -0
  111. package/src/utils/pageRoute.ts +71 -0
  112. package/src/utils/qrCode.helpers.ts +189 -0
  113. package/src/utils/qrCode.test.ts +519 -0
  114. package/src/utils/qrCode.ts +273 -0
  115. package/src/utils/richTextHTML.ts +385 -0
  116. package/src/utils/sheet.ts +262 -0
  117. package/src/utils/sheetAxisMove.ts +616 -0
  118. package/src/utils/sheetBootstrap.ts +1402 -0
  119. package/src/utils/sheetCellLiteral.ts +101 -0
  120. package/src/utils/sheetCommand.ts +358 -0
  121. package/src/utils/sheetDesign.ts +705 -0
  122. package/src/utils/sheetExport.ts +186 -0
  123. package/src/utils/sheetFeatureReference.ts +183 -0
  124. package/src/utils/sheetFormulaArgs.ts +168 -0
  125. package/src/utils/sheetFormulaCompile.ts +475 -0
  126. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  127. package/src/utils/sheetFormulaCriteria.ts +656 -0
  128. package/src/utils/sheetFormulaDate.ts +444 -0
  129. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  130. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  131. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  132. package/src/utils/sheetFormulaLogical.ts +116 -0
  133. package/src/utils/sheetFormulaLookup.ts +488 -0
  134. package/src/utils/sheetFormulaMath.ts +48 -0
  135. package/src/utils/sheetFormulaParser.ts +729 -0
  136. package/src/utils/sheetFormulaRange.ts +330 -0
  137. package/src/utils/sheetFormulaReference.ts +703 -0
  138. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  139. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  140. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  141. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  142. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  143. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  144. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  145. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  146. package/src/utils/sheetFormulaText.ts +430 -0
  147. package/src/utils/sheetJournal.ts +200 -0
  148. package/src/utils/sheetNumberFormat.ts +1012 -0
  149. package/src/utils/sheetPreview.ts +68 -0
  150. package/src/utils/sheetSequence.ts +118 -0
  151. package/src/utils/sheetSnapshot.ts +739 -0
  152. package/src/utils/sheetStructureEdit.ts +914 -0
  153. package/src/utils/sheetStructureReferences.ts +389 -0
  154. package/src/utils/square.ts +32 -0
  155. package/src/utils/storage.ts +198 -0
  156. package/src/utils/table-route.ts +262 -0
  157. package/src/utils/time.ts +12 -0
  158. package/src/utils/workflow.ts +506 -0
  159. package/src/utils/workflowLogFingerprint.ts +302 -0
  160. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  161. package/src/utils/workflowProgress.ts +280 -0
  162. package/src/utils/workflowTriggers.ts +61 -0
  163. package/tests/agentNote.test.ts +395 -0
  164. package/tests/campaignAI.test.ts +119 -0
  165. package/tests/campaignAccess.test.ts +239 -0
  166. package/tests/campaignEmail.test.ts +441 -0
  167. package/tests/campaignLifecycle.test.ts +134 -0
  168. package/tests/campaignPublication.test.ts +309 -0
  169. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  170. package/tests/dataTableRelativeDate.test.ts +412 -0
  171. package/tests/docAccess.test.ts +525 -0
  172. package/tests/editLogEntry.test.ts +112 -0
  173. package/tests/email.test.ts +39 -0
  174. package/tests/fieldDocProgram.test.ts +114 -0
  175. package/tests/logDisplay.fixtures.ts +67 -0
  176. package/tests/logDisplay.test.ts +227 -0
  177. package/tests/noteDoc.test.ts +514 -0
  178. package/tests/richTextHTML.test.ts +185 -0
  179. package/tests/sheetAxisMove.test.ts +352 -0
  180. package/tests/sheetBootstrap.test.ts +1967 -0
  181. package/tests/sheetFeatureReference.test.ts +22 -0
  182. package/tests/sheetFormulaCriteria.test.ts +269 -0
  183. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  184. package/tests/sheetFormulaFunctions.test.ts +538 -0
  185. package/tests/sheetFormulaLanguage.test.ts +361 -0
  186. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  187. package/tests/sheetFormulaParity.test.ts +188 -0
  188. package/tests/sheetFormulaRange.test.ts +167 -0
  189. package/tests/sheetFormulaReference.test.ts +78 -0
  190. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  191. package/tests/sheetFormulaTextDate.test.ts +512 -0
  192. package/tests/sheetSequence.test.ts +22 -0
  193. package/tests/sheetSnapshot.test.ts +134 -0
  194. package/tests/sheetStructureEdit.test.ts +537 -0
  195. package/tests/sheetStructureReferences.test.ts +589 -0
  196. package/tests/workflowLifecycleStatus.test.ts +60 -0
  197. package/tests/workflowLogFingerprint.test.ts +203 -0
  198. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  199. package/tests/workflowProgress.test.ts +180 -0
  200. package/tests/workflowTriggers.test.ts +29 -0
  201. package/tsconfig.json +12 -0
  202. package/vitest.config.ts +8 -0
@@ -0,0 +1,424 @@
1
+ import type { LogEntryData } from '../types/log.d.ts';
2
+ import {
3
+ type CanonicalWorkflowFingerprintValue,
4
+ canonicalizeWorkflowFingerprintValue,
5
+ getWorkflowLogFingerprintProjections,
6
+ serializeWorkflowFingerprintProjection,
7
+ type WorkflowLogFingerprintProjections,
8
+ } from './workflowLogFingerprint.ts';
9
+
10
+ export const WORKFLOW_LOG_REVISION_SNAPSHOT_VERSION =
11
+ 'workflow-log-revision:v1' as const;
12
+
13
+ type WorkflowLogRevisionSnapshotRelationship = {
14
+ id: string;
15
+ name: string | null;
16
+ operation?: string | null;
17
+ };
18
+
19
+ type WorkflowLogRevisionSnapshotLog = {
20
+ __table: 'logs';
21
+ id: string;
22
+ organizationId: string;
23
+ accountId: string | null;
24
+ childOrgId: string | null;
25
+ inboundContactId: string | null;
26
+ emailId: string | null;
27
+ fieldDocId: string | null;
28
+ fieldDocSubmissionId: string | null;
29
+ siteId: string | null;
30
+ summary: string;
31
+ source: string | null;
32
+ confidence: number | null;
33
+ originalMessage: string | null;
34
+ date: string;
35
+ createdAt: string;
36
+ updatedAt: string;
37
+ childOrg: WorkflowLogRevisionSnapshotRelationship | null;
38
+ inboundContact: WorkflowLogRevisionSnapshotRelationship | null;
39
+ location: { name: string | null } | null;
40
+ account: {
41
+ id: string;
42
+ profile: {
43
+ firstName: string | null;
44
+ lastName: string | null;
45
+ };
46
+ } | null;
47
+ details: {
48
+ __table: 'log_entry_details';
49
+ id: string;
50
+ activity: string;
51
+ logType: string | null;
52
+ notes: string | null;
53
+ translation: string | null;
54
+ metadata: CanonicalWorkflowFingerprintValue;
55
+ fields: CanonicalWorkflowFingerprintValue[] | null;
56
+ };
57
+ };
58
+
59
+ export type WorkflowLogRevisionSnapshot = {
60
+ version: typeof WORKFLOW_LOG_REVISION_SNAPSHOT_VERSION;
61
+ log: WorkflowLogRevisionSnapshotLog;
62
+ projections: WorkflowLogFingerprintProjections;
63
+ };
64
+
65
+ export type ResolvedWorkflowLogRevisionSnapshot = {
66
+ log: LogEntryData;
67
+ projections: WorkflowLogFingerprintProjections;
68
+ };
69
+
70
+ /*
71
+ * Return whether one unknown value is a non-array object.
72
+ */
73
+ function isRecord(value: unknown): value is Record<string, unknown> {
74
+ return !!value && typeof value === 'object' && !Array.isArray(value);
75
+ }
76
+
77
+ /*
78
+ * Normalize one optional database identifier for JSONB storage.
79
+ */
80
+ function serializeOptionalId(value: unknown): string | null {
81
+ if (value === null || value === undefined || value === '') {
82
+ return null;
83
+ }
84
+
85
+ return String(value);
86
+ }
87
+
88
+ /*
89
+ * Require one positive decimal database identifier from a stored snapshot.
90
+ */
91
+ function requireSnapshotId(value: unknown, field: string): string {
92
+ if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
93
+ throw new Error(`Workflow log revision snapshot has invalid ${field}.`);
94
+ }
95
+
96
+ return value;
97
+ }
98
+
99
+ /*
100
+ * Parse one optional positive database identifier from a stored snapshot.
101
+ */
102
+ function parseOptionalSnapshotId(value: unknown, field: string): bigint | null {
103
+ if (value === null) {
104
+ return null;
105
+ }
106
+
107
+ return BigInt(requireSnapshotId(value, field));
108
+ }
109
+
110
+ /*
111
+ * Require one valid ISO-compatible timestamp and hydrate it as a Date.
112
+ */
113
+ function requireSnapshotDate(value: unknown, field: string): Date {
114
+ if (typeof value !== 'string') {
115
+ throw new Error(`Workflow log revision snapshot has invalid ${field}.`);
116
+ }
117
+ const parsed = new Date(value);
118
+ if (Number.isNaN(parsed.getTime())) {
119
+ throw new Error(`Workflow log revision snapshot has invalid ${field}.`);
120
+ }
121
+
122
+ return parsed;
123
+ }
124
+
125
+ /*
126
+ * Normalize one optional string without exposing non-whitelisted object data.
127
+ */
128
+ function serializeOptionalText(value: unknown): string | null {
129
+ return typeof value === 'string' ? value : null;
130
+ }
131
+
132
+ /*
133
+ * Build one minimal organization, contact, or site relationship snapshot.
134
+ */
135
+ function makeRelationshipSnapshot(
136
+ value: unknown,
137
+ options: { includeOperation?: boolean } = {},
138
+ ): WorkflowLogRevisionSnapshotRelationship | null {
139
+ if (!isRecord(value) || !serializeOptionalId(value.id)) {
140
+ return null;
141
+ }
142
+
143
+ return {
144
+ id: String(value.id),
145
+ name: serializeOptionalText(value.name ?? value.personName),
146
+ ...(options.includeOperation
147
+ ? { operation: serializeOptionalText(value.operation) }
148
+ : {}),
149
+ };
150
+ }
151
+
152
+ /*
153
+ * Parse one minimal organization or contact relationship from JSONB.
154
+ */
155
+ function parseRelationshipSnapshot(
156
+ value: unknown,
157
+ field: string,
158
+ options: { includeOperation?: boolean } = {},
159
+ ): Record<string, unknown> | null {
160
+ if (value === null) {
161
+ return null;
162
+ }
163
+ if (!isRecord(value)) {
164
+ throw new Error(`Workflow log revision snapshot has invalid ${field}.`);
165
+ }
166
+ const name = value.name;
167
+ const operation = value.operation;
168
+ if (
169
+ (name !== null && typeof name !== 'string') ||
170
+ (options.includeOperation &&
171
+ operation !== null &&
172
+ typeof operation !== 'string')
173
+ ) {
174
+ throw new Error(`Workflow log revision snapshot has invalid ${field}.`);
175
+ }
176
+
177
+ return {
178
+ id: BigInt(requireSnapshotId(value.id, `${field}.id`)),
179
+ name,
180
+ ...(options.includeOperation ? { operation } : {}),
181
+ };
182
+ }
183
+
184
+ /*
185
+ * Build the whitelisted, JSON-safe log document used by one workflow revision.
186
+ */
187
+ function makeWorkflowLogRevisionSnapshotLog(
188
+ log: LogEntryData,
189
+ ): WorkflowLogRevisionSnapshotLog {
190
+ const details = log.details;
191
+ const account =
192
+ isRecord(log.account) && serializeOptionalId(log.account.id)
193
+ ? {
194
+ id: String(log.account.id),
195
+ profile: {
196
+ firstName: serializeOptionalText(log.account.profile?.firstName),
197
+ lastName: serializeOptionalText(log.account.profile?.lastName),
198
+ },
199
+ }
200
+ : null;
201
+ const location = isRecord(log.location)
202
+ ? { name: serializeOptionalText(log.location.name) }
203
+ : null;
204
+ const metadataSource = isRecord(details.metadata)
205
+ ? Object.fromEntries(
206
+ Object.entries(details.metadata).filter(([key]) => key !== '__before'),
207
+ )
208
+ : {};
209
+ const metadata = canonicalizeWorkflowFingerprintValue(metadataSource);
210
+ const fields = canonicalizeWorkflowFingerprintValue(details.fields || null);
211
+
212
+ return {
213
+ __table: 'logs',
214
+ id: String(log.id),
215
+ organizationId: String(log.organizationId),
216
+ accountId: serializeOptionalId(log.accountId),
217
+ childOrgId: serializeOptionalId(log.childOrgId),
218
+ inboundContactId: serializeOptionalId(log.inboundContactId),
219
+ emailId: serializeOptionalId(log.emailId),
220
+ fieldDocId: serializeOptionalId(log.fieldDocId),
221
+ fieldDocSubmissionId: serializeOptionalId(log.fieldDocSubmissionId),
222
+ siteId: serializeOptionalId(log.siteId),
223
+ summary: typeof log.summary === 'string' ? log.summary : '',
224
+ source: serializeOptionalText(log.source),
225
+ confidence:
226
+ typeof log.confidence === 'number' && Number.isFinite(log.confidence)
227
+ ? log.confidence
228
+ : null,
229
+ originalMessage: serializeOptionalText(log.originalMessage),
230
+ date: new Date(log.date).toISOString(),
231
+ createdAt: new Date(log.createdAt).toISOString(),
232
+ updatedAt: new Date(log.updatedAt).toISOString(),
233
+ childOrg: makeRelationshipSnapshot(log.childOrg, {
234
+ includeOperation: true,
235
+ }),
236
+ inboundContact: makeRelationshipSnapshot(log.inboundContact),
237
+ location,
238
+ account,
239
+ details: {
240
+ __table: 'log_entry_details',
241
+ id: String(details.id ?? log.id),
242
+ activity: details.activity,
243
+ logType: serializeOptionalText(details.logType),
244
+ notes: serializeOptionalText(details.notes),
245
+ // Translations are a mutable display cache and do not belong in the
246
+ // immutable workflow input snapshot.
247
+ translation: null,
248
+ metadata,
249
+ fields: Array.isArray(fields) ? fields : null,
250
+ },
251
+ };
252
+ }
253
+
254
+ /*
255
+ * Create one immutable workflow revision snapshot from a committed log row.
256
+ */
257
+ export function makeWorkflowLogRevisionSnapshot(
258
+ log: LogEntryData,
259
+ ): WorkflowLogRevisionSnapshot {
260
+ return {
261
+ version: WORKFLOW_LOG_REVISION_SNAPSHOT_VERSION,
262
+ log: makeWorkflowLogRevisionSnapshotLog(log),
263
+ projections: getWorkflowLogFingerprintProjections(log),
264
+ };
265
+ }
266
+
267
+ /*
268
+ * Parse and validate one persisted workflow revision snapshot for execution.
269
+ */
270
+ export function parseWorkflowLogRevisionSnapshot(
271
+ value: unknown,
272
+ ): ResolvedWorkflowLogRevisionSnapshot {
273
+ if (
274
+ !isRecord(value) ||
275
+ value.version !== WORKFLOW_LOG_REVISION_SNAPSHOT_VERSION ||
276
+ !isRecord(value.log)
277
+ ) {
278
+ throw new Error(
279
+ 'Workflow log revision snapshot is invalid or unsupported.',
280
+ );
281
+ }
282
+ const snapshotLog = value.log;
283
+ if (
284
+ snapshotLog.__table !== 'logs' ||
285
+ typeof snapshotLog.summary !== 'string' ||
286
+ (snapshotLog.source !== null && typeof snapshotLog.source !== 'string') ||
287
+ (snapshotLog.confidence !== null &&
288
+ (typeof snapshotLog.confidence !== 'number' ||
289
+ !Number.isFinite(snapshotLog.confidence))) ||
290
+ (snapshotLog.originalMessage !== null &&
291
+ typeof snapshotLog.originalMessage !== 'string') ||
292
+ !isRecord(snapshotLog.details) ||
293
+ snapshotLog.details.__table !== 'log_entry_details' ||
294
+ typeof snapshotLog.details.activity !== 'string' ||
295
+ (snapshotLog.details.logType !== null &&
296
+ typeof snapshotLog.details.logType !== 'string') ||
297
+ (snapshotLog.details.notes !== null &&
298
+ typeof snapshotLog.details.notes !== 'string') ||
299
+ (snapshotLog.details.translation !== null &&
300
+ typeof snapshotLog.details.translation !== 'string') ||
301
+ !isRecord(snapshotLog.details.metadata) ||
302
+ (snapshotLog.details.fields !== null &&
303
+ !Array.isArray(snapshotLog.details.fields))
304
+ ) {
305
+ throw new Error(
306
+ 'Workflow log revision snapshot contains an invalid log document.',
307
+ );
308
+ }
309
+ const childOrg = parseRelationshipSnapshot(
310
+ snapshotLog.childOrg,
311
+ 'log.childOrg',
312
+ {
313
+ includeOperation: true,
314
+ },
315
+ );
316
+ const inboundContact = parseRelationshipSnapshot(
317
+ snapshotLog.inboundContact,
318
+ 'log.inboundContact',
319
+ );
320
+ const location =
321
+ snapshotLog.location === null
322
+ ? null
323
+ : isRecord(snapshotLog.location) &&
324
+ (snapshotLog.location.name === null ||
325
+ typeof snapshotLog.location.name === 'string')
326
+ ? { name: snapshotLog.location.name }
327
+ : null;
328
+ if (snapshotLog.location !== null && !location) {
329
+ throw new Error('Workflow log revision snapshot has invalid log.location.');
330
+ }
331
+ let account: LogEntryData['account'];
332
+ if (snapshotLog.account !== null) {
333
+ if (
334
+ !isRecord(snapshotLog.account) ||
335
+ !isRecord(snapshotLog.account.profile) ||
336
+ (snapshotLog.account.profile.firstName !== null &&
337
+ typeof snapshotLog.account.profile.firstName !== 'string') ||
338
+ (snapshotLog.account.profile.lastName !== null &&
339
+ typeof snapshotLog.account.profile.lastName !== 'string')
340
+ ) {
341
+ throw new Error(
342
+ 'Workflow log revision snapshot has invalid log.account.',
343
+ );
344
+ }
345
+ account = {
346
+ id: BigInt(requireSnapshotId(snapshotLog.account.id, 'log.account.id')),
347
+ settings: {},
348
+ profile: {
349
+ firstName: snapshotLog.account.profile.firstName || undefined,
350
+ lastName: snapshotLog.account.profile.lastName || undefined,
351
+ },
352
+ };
353
+ }
354
+ const log = {
355
+ __table: 'logs',
356
+ id: BigInt(requireSnapshotId(snapshotLog.id, 'log.id')),
357
+ organizationId: BigInt(
358
+ requireSnapshotId(snapshotLog.organizationId, 'log.organizationId'),
359
+ ),
360
+ accountId: parseOptionalSnapshotId(snapshotLog.accountId, 'log.accountId'),
361
+ childOrgId: parseOptionalSnapshotId(
362
+ snapshotLog.childOrgId,
363
+ 'log.childOrgId',
364
+ ),
365
+ inboundContactId: parseOptionalSnapshotId(
366
+ snapshotLog.inboundContactId,
367
+ 'log.inboundContactId',
368
+ ),
369
+ emailId: parseOptionalSnapshotId(snapshotLog.emailId, 'log.emailId'),
370
+ fieldDocId: parseOptionalSnapshotId(
371
+ snapshotLog.fieldDocId,
372
+ 'log.fieldDocId',
373
+ ),
374
+ fieldDocSubmissionId: parseOptionalSnapshotId(
375
+ snapshotLog.fieldDocSubmissionId,
376
+ 'log.fieldDocSubmissionId',
377
+ ),
378
+ siteId: parseOptionalSnapshotId(snapshotLog.siteId, 'log.siteId'),
379
+ summary: snapshotLog.summary,
380
+ source: snapshotLog.source,
381
+ confidence: snapshotLog.confidence,
382
+ originalMessage: snapshotLog.originalMessage,
383
+ date: requireSnapshotDate(snapshotLog.date, 'log.date'),
384
+ createdAt: requireSnapshotDate(snapshotLog.createdAt, 'log.createdAt'),
385
+ updatedAt: requireSnapshotDate(snapshotLog.updatedAt, 'log.updatedAt'),
386
+ childOrg: childOrg as LogEntryData['childOrg'],
387
+ inboundContact: inboundContact
388
+ ? {
389
+ id: inboundContact.id as bigint,
390
+ personName: inboundContact.name as string | null,
391
+ }
392
+ : null,
393
+ location,
394
+ account,
395
+ details: {
396
+ __table: 'log_entry_details',
397
+ id: BigInt(requireSnapshotId(snapshotLog.details.id, 'log.details.id')),
398
+ activity: snapshotLog.details.activity,
399
+ logType: snapshotLog.details.logType,
400
+ notes: snapshotLog.details.notes,
401
+ // Historical v1 snapshots may contain the former translation string,
402
+ // but workflows should always execute against original log text.
403
+ translation: null,
404
+ metadata: snapshotLog.details.metadata,
405
+ fields: snapshotLog.details.fields,
406
+ },
407
+ } as LogEntryData;
408
+ if (!isRecord(value.projections)) {
409
+ throw new Error('Workflow log revision snapshot has invalid projections.');
410
+ }
411
+ const projections =
412
+ value.projections as unknown as WorkflowLogFingerprintProjections;
413
+ const rebuiltProjections = getWorkflowLogFingerprintProjections(log);
414
+ if (
415
+ serializeWorkflowFingerprintProjection(projections) !==
416
+ serializeWorkflowFingerprintProjection(rebuiltProjections)
417
+ ) {
418
+ throw new Error(
419
+ 'Workflow log revision snapshot projections do not match its log document.',
420
+ );
421
+ }
422
+
423
+ return { log, projections };
424
+ }
@@ -0,0 +1,280 @@
1
+ import {
2
+ canonicalizeWorkflowFingerprintValue,
3
+ serializeWorkflowFingerprintProjection,
4
+ } from './workflowLogFingerprint.ts';
5
+
6
+ export const WORKFLOW_ASYNC_OUTCOME_KINDS = [
7
+ 'sentEmails',
8
+ 'sentSMS',
9
+ 'sentReminders',
10
+ 'sentFollowUps',
11
+ 'sentWaits',
12
+ ] as const;
13
+
14
+ export const WORKFLOW_SENT_EMAIL_STATUS_ENUMS = [
15
+ 'QUEUED',
16
+ 'SENT',
17
+ 'DELIVERED',
18
+ 'FAILED',
19
+ 'DELIVERY_UNKNOWN',
20
+ 'BOUNCED',
21
+ 'BLOCKED',
22
+ ] as const;
23
+
24
+ export const WORKFLOW_SENT_SMS_STATUS_ENUMS = [
25
+ 'QUEUED',
26
+ 'SENT',
27
+ 'DELIVERED',
28
+ 'FAILED',
29
+ 'DELIVERY_UNKNOWN',
30
+ 'BOUNCED',
31
+ 'BLOCKED',
32
+ ] as const;
33
+
34
+ export const WORKFLOW_SENT_REMINDER_STATUS_ENUMS = [
35
+ 'SCHEDULED',
36
+ 'IN_PROGRESS',
37
+ 'COMPLETED',
38
+ 'FAILED',
39
+ 'CANCELED',
40
+ ] as const;
41
+
42
+ export const WORKFLOW_SENT_FOLLOW_UP_STATUS_ENUMS = [
43
+ 'SCHEDULED',
44
+ 'FIRED',
45
+ 'REPLACED',
46
+ 'CANCELED',
47
+ ] as const;
48
+
49
+ export const WORKFLOW_SENT_WAIT_STATUS_ENUMS = [
50
+ 'WAITING',
51
+ 'REPLIED',
52
+ 'EXPIRED',
53
+ 'CANCELED',
54
+ ] as const;
55
+
56
+ export const WORKFLOW_PROGRESS_ASYNC_OUTCOMES_START =
57
+ '<<<START_SERVER_WORKFLOW_ASYNC_OUTCOMES_V1>>>';
58
+ export const WORKFLOW_PROGRESS_ASYNC_OUTCOMES_END =
59
+ '<<<END_SERVER_WORKFLOW_ASYNC_OUTCOMES_V1>>>';
60
+
61
+ export type WorkflowAsyncOutcomeKind =
62
+ (typeof WORKFLOW_ASYNC_OUTCOME_KINDS)[number];
63
+ export type WorkflowSentEmailStatus =
64
+ (typeof WORKFLOW_SENT_EMAIL_STATUS_ENUMS)[number];
65
+ export type WorkflowSentSMSStatus =
66
+ (typeof WORKFLOW_SENT_SMS_STATUS_ENUMS)[number];
67
+ export type WorkflowSentReminderStatus =
68
+ (typeof WORKFLOW_SENT_REMINDER_STATUS_ENUMS)[number];
69
+ export type WorkflowSentFollowUpStatus =
70
+ (typeof WORKFLOW_SENT_FOLLOW_UP_STATUS_ENUMS)[number];
71
+ export type WorkflowSentWaitStatus =
72
+ (typeof WORKFLOW_SENT_WAIT_STATUS_ENUMS)[number];
73
+
74
+ export type WorkflowAsyncOutcome<TStatus extends string> = {
75
+ status: TStatus;
76
+ recipient?: string | null;
77
+ occurredAt?: Date | string | null;
78
+ contentFingerprint?: string | null;
79
+ detail?: string | null;
80
+ };
81
+
82
+ export type WorkflowSentEmailOutcome =
83
+ WorkflowAsyncOutcome<WorkflowSentEmailStatus>;
84
+ export type WorkflowSentSMSOutcome =
85
+ WorkflowAsyncOutcome<WorkflowSentSMSStatus>;
86
+ export type WorkflowSentReminderOutcome =
87
+ WorkflowAsyncOutcome<WorkflowSentReminderStatus>;
88
+ export type WorkflowSentFollowUpOutcome =
89
+ WorkflowAsyncOutcome<WorkflowSentFollowUpStatus>;
90
+ export type WorkflowSentWaitOutcome =
91
+ WorkflowAsyncOutcome<WorkflowSentWaitStatus>;
92
+
93
+ type WorkflowAsyncOutcomeByKind = {
94
+ sentEmails: WorkflowSentEmailOutcome;
95
+ sentSMS: WorkflowSentSMSOutcome;
96
+ sentReminders: WorkflowSentReminderOutcome;
97
+ sentFollowUps: WorkflowSentFollowUpOutcome;
98
+ sentWaits: WorkflowSentWaitOutcome;
99
+ };
100
+
101
+ export type WorkflowAsyncOutcomeForKind<
102
+ TKind extends WorkflowAsyncOutcomeKind,
103
+ > = WorkflowAsyncOutcomeByKind[TKind];
104
+
105
+ export type WorkflowAsyncOutcomeMaps = {
106
+ [TKind in WorkflowAsyncOutcomeKind]: Record<
107
+ string,
108
+ WorkflowAsyncOutcomeByKind[TKind]
109
+ >;
110
+ };
111
+
112
+ export type WorkflowProgressValues = Partial<WorkflowAsyncOutcomeMaps> & {
113
+ progressReport?: string | null;
114
+ [key: string]: unknown;
115
+ };
116
+
117
+ const FILE_CONSTANTS = {
118
+ completeSectionPattern: new RegExp(
119
+ `${WORKFLOW_PROGRESS_ASYNC_OUTCOMES_START}[\\s\\S]*?${WORKFLOW_PROGRESS_ASYNC_OUTCOMES_END}`,
120
+ 'g',
121
+ ),
122
+ };
123
+
124
+ /*
125
+ * Normalize one source identifier for use as both a values-map key and a
126
+ * stable progress-report line key.
127
+ */
128
+ function normalizeWorkflowAsyncOutcomeSourceId(
129
+ sourceId: string | number | bigint,
130
+ ) {
131
+ const normalized = String(sourceId).trim();
132
+ if (!normalized) {
133
+ throw new Error('Workflow async outcomes require a nonempty source ID.');
134
+ }
135
+
136
+ return normalized;
137
+ }
138
+
139
+ /*
140
+ * Sort source identifiers numerically when both are positive integer strings,
141
+ * otherwise use deterministic lexical ordering.
142
+ */
143
+ function compareWorkflowAsyncOutcomeSourceIds(left: string, right: string) {
144
+ if (/^\d+$/.test(left) && /^\d+$/.test(right)) {
145
+ const leftId = BigInt(left);
146
+ const rightId = BigInt(right);
147
+ if (leftId !== rightId) {
148
+ return leftId < rightId ? -1 : 1;
149
+ }
150
+ }
151
+
152
+ if (left === right) {
153
+ return 0;
154
+ }
155
+
156
+ return left < right ? -1 : 1;
157
+ }
158
+
159
+ /*
160
+ * Remove empty async-outcome maps while preserving populated maps and every
161
+ * unrelated value. Callers may safely treat a missing map as empty.
162
+ */
163
+ export function compactWorkflowProgressValues(
164
+ values: WorkflowProgressValues | null | undefined,
165
+ ): WorkflowProgressValues {
166
+ const compacted = { ...(values || {}) };
167
+ for (const sourceKind of WORKFLOW_ASYNC_OUTCOME_KINDS) {
168
+ const entries = values?.[sourceKind];
169
+ if (entries && Object.keys(entries).length) {
170
+ Object.assign(compacted, { [sourceKind]: { ...entries } });
171
+ } else {
172
+ delete compacted[sourceKind];
173
+ }
174
+ }
175
+
176
+ return compacted;
177
+ }
178
+
179
+ /*
180
+ * Serialize one outcome as single-line JSON while escaping marker characters
181
+ * so provider text can never terminate the reserved server section.
182
+ */
183
+ function serializeWorkflowAsyncOutcome(outcome: unknown) {
184
+ return serializeWorkflowFingerprintProjection(outcome)
185
+ .replaceAll('<', '\\u003c')
186
+ .replaceAll('>', '\\u003e')
187
+ .replaceAll('\u2028', '\\u2028')
188
+ .replaceAll('\u2029', '\\u2029');
189
+ }
190
+
191
+ /*
192
+ * Serialize the authoritative server-generated async outcome section with one
193
+ * stable, replaceable line per source kind and source ID.
194
+ */
195
+ export function serializeWorkflowAsyncOutcomeSection(
196
+ outcomes: Partial<WorkflowAsyncOutcomeMaps> | null | undefined,
197
+ ) {
198
+ const lines: string[] = [];
199
+ for (const sourceKind of WORKFLOW_ASYNC_OUTCOME_KINDS) {
200
+ const entries = outcomes?.[sourceKind] || {};
201
+ for (const sourceId of Object.keys(entries).sort(
202
+ compareWorkflowAsyncOutcomeSourceIds,
203
+ )) {
204
+ const lineKey = `${sourceKind}:${encodeURIComponent(sourceId)}`;
205
+ const serializedOutcome = serializeWorkflowAsyncOutcome(
206
+ entries[sourceId],
207
+ );
208
+ lines.push(`${lineKey}\t${serializedOutcome}`);
209
+ }
210
+ }
211
+
212
+ return [
213
+ WORKFLOW_PROGRESS_ASYNC_OUTCOMES_START,
214
+ ...lines,
215
+ WORKFLOW_PROGRESS_ASYNC_OUTCOMES_END,
216
+ ].join('\n');
217
+ }
218
+
219
+ /*
220
+ * Replace every complete server outcome section while leaving all AI-written
221
+ * narrative bytes outside those reserved sentinels unchanged.
222
+ */
223
+ export function replaceWorkflowProgressAsyncOutcomeSection(
224
+ progressReport: string | null | undefined,
225
+ outcomes: Partial<WorkflowAsyncOutcomeMaps> | null | undefined,
226
+ ) {
227
+ const report = progressReport || '';
228
+ const section = serializeWorkflowAsyncOutcomeSection(outcomes);
229
+ let replaced = false;
230
+ const withoutDuplicateSections = report.replace(
231
+ FILE_CONSTANTS.completeSectionPattern,
232
+ () => {
233
+ if (replaced) {
234
+ return '';
235
+ }
236
+ replaced = true;
237
+ return section;
238
+ },
239
+ );
240
+
241
+ if (replaced) {
242
+ return withoutDuplicateSections;
243
+ }
244
+ if (!report) {
245
+ return section;
246
+ }
247
+
248
+ return `${report}${report.endsWith('\n') ? '\n' : '\n\n'}${section}`;
249
+ }
250
+
251
+ /*
252
+ * Upsert one source outcome, rebuild the authoritative section, and preserve
253
+ * unrelated workflow values plus the AI-authored progress narrative.
254
+ */
255
+ export function updateWorkflowProgressAsyncOutcome<
256
+ TKind extends WorkflowAsyncOutcomeKind,
257
+ >(
258
+ values: WorkflowProgressValues | null | undefined,
259
+ sourceKind: TKind,
260
+ sourceId: string | number | bigint,
261
+ outcome: WorkflowAsyncOutcomeForKind<TKind>,
262
+ ): WorkflowProgressValues {
263
+ const normalizedSourceId = normalizeWorkflowAsyncOutcomeSourceId(sourceId);
264
+ const nextValues = compactWorkflowProgressValues(values);
265
+ const sourceOutcomes = {
266
+ ...(values?.[sourceKind] || {}),
267
+ } as Record<string, WorkflowAsyncOutcomeForKind<TKind>>;
268
+ sourceOutcomes[normalizedSourceId] = canonicalizeWorkflowFingerprintValue(
269
+ outcome,
270
+ ) as WorkflowAsyncOutcomeForKind<TKind>;
271
+ Object.assign(nextValues, { [sourceKind]: sourceOutcomes });
272
+
273
+ return {
274
+ ...nextValues,
275
+ progressReport: replaceWorkflowProgressAsyncOutcomeSection(
276
+ values?.progressReport,
277
+ nextValues,
278
+ ),
279
+ };
280
+ }