dxcomplete 0.1.0

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 (121) hide show
  1. package/.env.example +11 -0
  2. package/README.md +215 -0
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +212 -0
  5. package/dist/http/server.d.ts +7 -0
  6. package/dist/http/server.js +236 -0
  7. package/dist/http/service.d.ts +7 -0
  8. package/dist/http/service.js +725 -0
  9. package/dist/init.d.ts +13 -0
  10. package/dist/init.js +128 -0
  11. package/dist/install-manifest.d.ts +25 -0
  12. package/dist/install-manifest.js +96 -0
  13. package/dist/mcp/docs.d.ts +98 -0
  14. package/dist/mcp/docs.js +438 -0
  15. package/dist/mcp/server.d.ts +20 -0
  16. package/dist/mcp/server.js +2345 -0
  17. package/dist/package-root.d.ts +2 -0
  18. package/dist/package-root.js +28 -0
  19. package/dist/runtime/actor.d.ts +14 -0
  20. package/dist/runtime/actor.js +42 -0
  21. package/dist/runtime/auth.d.ts +162 -0
  22. package/dist/runtime/auth.js +394 -0
  23. package/dist/runtime/check.d.ts +7 -0
  24. package/dist/runtime/check.js +16 -0
  25. package/dist/runtime/config.d.ts +17 -0
  26. package/dist/runtime/config.js +93 -0
  27. package/dist/runtime/mongo.d.ts +9 -0
  28. package/dist/runtime/mongo.js +56 -0
  29. package/dist/runtime/records.d.ts +336 -0
  30. package/dist/runtime/records.js +1463 -0
  31. package/dist/runtime/workspace.d.ts +19 -0
  32. package/dist/runtime/workspace.js +102 -0
  33. package/dist/upgrade.d.ts +20 -0
  34. package/dist/upgrade.js +246 -0
  35. package/dist/validate.d.ts +10 -0
  36. package/dist/validate.js +119 -0
  37. package/dist/version.d.ts +3 -0
  38. package/dist/version.js +12 -0
  39. package/docs/codex-integration.md +29 -0
  40. package/docs/cost-model.md +61 -0
  41. package/docs/decision-basis.md +57 -0
  42. package/docs/diagrams.md +31 -0
  43. package/docs/glossary.md +147 -0
  44. package/docs/index.md +60 -0
  45. package/docs/model.md +110 -0
  46. package/docs/open-questions.md +61 -0
  47. package/docs/roles.md +42 -0
  48. package/docs/taxonomy.md +96 -0
  49. package/docs/workflows.md +60 -0
  50. package/package.json +62 -0
  51. package/scripts/check-env-surface.mjs +136 -0
  52. package/scripts/check-public-copy.mjs +263 -0
  53. package/scripts/check-service-boundary.mjs +63 -0
  54. package/scripts/dogfood-work-order.mjs +506 -0
  55. package/scripts/smoke-mcp-http.mjs +3572 -0
  56. package/src/cli.ts +268 -0
  57. package/src/http/server.ts +314 -0
  58. package/src/http/service.ts +934 -0
  59. package/src/init.ts +227 -0
  60. package/src/install-manifest.ts +144 -0
  61. package/src/mcp/docs.ts +557 -0
  62. package/src/mcp/server.ts +3525 -0
  63. package/src/package-root.ts +31 -0
  64. package/src/runtime/actor.ts +61 -0
  65. package/src/runtime/auth.ts +673 -0
  66. package/src/runtime/check.ts +18 -0
  67. package/src/runtime/config.ts +128 -0
  68. package/src/runtime/mongo.ts +89 -0
  69. package/src/runtime/records.ts +2303 -0
  70. package/src/runtime/workspace.ts +155 -0
  71. package/src/upgrade.ts +356 -0
  72. package/src/validate.ts +139 -0
  73. package/src/version.ts +16 -0
  74. package/templates/github/workflows/dxcomplete.yml +16 -0
  75. package/templates/next/pages/api/auth/callback/google.js +12 -0
  76. package/templates/next/pages/api/dxcomplete/[...path].js +12 -0
  77. package/templates/next/pages/api/dxcomplete.js +12 -0
  78. package/templates/next/pages/api/mcp.js +12 -0
  79. package/templates/next/vercel.json +18 -0
  80. package/templates/process/README.md +38 -0
  81. package/templates/process/controls.yml +113 -0
  82. package/templates/process/cost-model.yml +71 -0
  83. package/templates/process/decision-basis.yml +53 -0
  84. package/templates/process/decisions/.gitkeep +1 -0
  85. package/templates/process/diagrams/00-decision-basis.mmd +24 -0
  86. package/templates/process/diagrams/00-overview.mmd +20 -0
  87. package/templates/process/diagrams/01-intake-triage.mmd +20 -0
  88. package/templates/process/diagrams/02-product-definition.mmd +14 -0
  89. package/templates/process/diagrams/03-engineering-execution.mmd +15 -0
  90. package/templates/process/diagrams/04-qa-verification.mmd +12 -0
  91. package/templates/process/diagrams/05-product-validation.mmd +12 -0
  92. package/templates/process/diagrams/06-change-release-control.mmd +16 -0
  93. package/templates/process/diagrams/07-deployment-operations.mmd +16 -0
  94. package/templates/process/diagrams/08-support-incident-management.mmd +16 -0
  95. package/templates/process/diagrams/09-problem-improvement.mmd +14 -0
  96. package/templates/process/diagrams/10-risk-control-management.mmd +14 -0
  97. package/templates/process/diagrams/11-audit-evidence-capture.mmd +13 -0
  98. package/templates/process/evidence/.gitkeep +1 -0
  99. package/templates/process/risks/.gitkeep +1 -0
  100. package/templates/process/roles.yml +96 -0
  101. package/templates/process/taxonomy.yml +514 -0
  102. package/templates/process/workflows.yml +210 -0
  103. package/website/.well-known/oauth-authorization-server +22 -0
  104. package/website/.well-known/oauth-protected-resource/api/dxcomplete/mcp +10 -0
  105. package/website/.well-known/oauth-protected-resource/api/mcp +10 -0
  106. package/website/README.md +12 -0
  107. package/website/app.js +36 -0
  108. package/website/flow.html +85 -0
  109. package/website/glossary.html +280 -0
  110. package/website/index.html +90 -0
  111. package/website/objects.html +287 -0
  112. package/website/outcomes.html +117 -0
  113. package/website/phase-build.html +101 -0
  114. package/website/phase-elicit.html +102 -0
  115. package/website/phase-go-live.html +103 -0
  116. package/website/phase-measure.html +93 -0
  117. package/website/phase-operate.html +102 -0
  118. package/website/phase-orient.html +92 -0
  119. package/website/phase-weigh.html +98 -0
  120. package/website/roles.html +52 -0
  121. package/website/styles.css +1169 -0
@@ -0,0 +1,2303 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { ClientSession, Db } from "mongodb";
3
+ import type { ActorContext } from "./actor.js";
4
+
5
+ export const COLLECTION_NAMES = [
6
+ "workspaces",
7
+ "statements",
8
+ "journal_entries",
9
+ "environments",
10
+ "components",
11
+ "estimates",
12
+ "benefits",
13
+ "expectations",
14
+ "requirements",
15
+ "tasks",
16
+ "commitments",
17
+ "deferrals",
18
+ "changes",
19
+ "decisions",
20
+ "risks"
21
+ ] as const;
22
+
23
+ export const LEGACY_COLLECTION_NAMES = [
24
+ "engagements",
25
+ "initiatives",
26
+ "service_charters",
27
+ "cost_baselines",
28
+ "cost_actuals",
29
+ "benefit_measurements"
30
+ ] as const;
31
+ export const DXCOMPLETE_TICKET_COLLECTION_NAME = "dxcomplete_tickets";
32
+ export const LEGACY_INTAKE_COLLECTION_NAME = "intake_items";
33
+ export const LEGACY_PRIVATE_COLLECTION_NAMES = [LEGACY_INTAKE_COLLECTION_NAME] as const;
34
+ export const INDEX_COLLECTION_NAMES = [...COLLECTION_NAMES, DXCOMPLETE_TICKET_COLLECTION_NAME] as const;
35
+ export const LINK_SCAN_COLLECTION_NAMES = [...COLLECTION_NAMES, ...LEGACY_COLLECTION_NAMES] as const;
36
+ export const READABLE_ID_SEQUENCES_COLLECTION = "readable_id_sequences";
37
+ export const READABLE_ID_TYPE_CODES = {
38
+ statements: "STM",
39
+ journal_entries: "JRN",
40
+ environments: "ENV",
41
+ components: "CMP",
42
+ expectations: "EXP",
43
+ requirements: "REQ",
44
+ tasks: "TSK",
45
+ commitments: "CMT",
46
+ deferrals: "DFR",
47
+ decisions: "DEC",
48
+ changes: "CHG",
49
+ risks: "RSK",
50
+ estimates: "EST",
51
+ benefits: "BFT"
52
+ } as const;
53
+ export const READABLE_ID_COLLECTION_NAMES = Object.keys(READABLE_ID_TYPE_CODES) as ReadableIdCollectionName[];
54
+
55
+ export type CollectionName = (typeof COLLECTION_NAMES)[number];
56
+ export type ReadableIdCollectionName = keyof typeof READABLE_ID_TYPE_CODES;
57
+ export type PrivateCollectionName = typeof DXCOMPLETE_TICKET_COLLECTION_NAME;
58
+ export type RuntimeCollectionName =
59
+ | CollectionName
60
+ | PrivateCollectionName
61
+ | (typeof LEGACY_COLLECTION_NAMES)[number]
62
+ | (typeof LEGACY_PRIVATE_COLLECTION_NAMES)[number];
63
+
64
+ export type RecordLink = {
65
+ toType: RuntimeCollectionName;
66
+ toId: string;
67
+ relationship: string;
68
+ createdAt: string;
69
+ createdBy: string;
70
+ };
71
+
72
+ export type RecordEdge = RecordLink & {
73
+ fromType: RuntimeCollectionName;
74
+ fromId: string;
75
+ };
76
+
77
+ export type DxcRecord = {
78
+ _id: string;
79
+ recordType: RuntimeCollectionName;
80
+ readableId?: string;
81
+ workspaceId?: string;
82
+ title?: string;
83
+ summary?: string;
84
+ fields: Record<string, unknown>;
85
+ links: RecordLink[];
86
+ archivedAt?: string;
87
+ archivedBy?: string;
88
+ archiveReason?: string;
89
+ createdAt: string;
90
+ createdBy: string;
91
+ updatedAt: string;
92
+ updatedBy: string;
93
+ };
94
+
95
+ export type ReviewableRecordType = "expectations" | "requirements";
96
+
97
+ export type ReviewNote = {
98
+ id: string;
99
+ body: string;
100
+ createdAt: string;
101
+ createdBy: string;
102
+ important?: true;
103
+ };
104
+
105
+ export type RecordVersionSnapshot = {
106
+ title?: string;
107
+ summary?: string;
108
+ fields: Record<string, unknown>;
109
+ };
110
+
111
+ export type RecordVersionHistoryEntry = {
112
+ id: string;
113
+ fromVersion: number;
114
+ toVersion: number;
115
+ createdAt: string;
116
+ createdBy: string;
117
+ changedFields: string[];
118
+ previousSnapshot: RecordVersionSnapshot;
119
+ nextSnapshot: RecordVersionSnapshot;
120
+ revisionNote?: string;
121
+ };
122
+
123
+ export type ChangeEventType =
124
+ | "notice_given"
125
+ | "veto_recorded"
126
+ | "emergency_declared"
127
+ | "decision_recorded"
128
+ | "result_reported"
129
+ | "recovery_recorded"
130
+ | "plan_revised"
131
+ | "note_added";
132
+
133
+ export type ChangeEvent = {
134
+ id: string;
135
+ eventType: ChangeEventType;
136
+ createdAt: string;
137
+ createdBy: string;
138
+ } & Record<string, unknown>;
139
+
140
+ export type DeferralEventType =
141
+ | "condition_addressed"
142
+ | "condition_reopened"
143
+ | "condition_note_added"
144
+ | "deferral_resolved"
145
+ | "deferral_abandoned";
146
+
147
+ export type DeferralCondition = {
148
+ id: string;
149
+ statement: string;
150
+ state: "open" | "addressed";
151
+ createdAt: string;
152
+ createdBy: string;
153
+ updatedAt: string;
154
+ updatedBy: string;
155
+ };
156
+
157
+ export type DeferralEvent = {
158
+ id: string;
159
+ eventType: DeferralEventType;
160
+ createdAt: string;
161
+ createdBy: string;
162
+ } & Record<string, unknown>;
163
+
164
+ export type DecisionEntryType = "argument" | "decision" | "note";
165
+
166
+ export type DecisionEntry = {
167
+ id: string;
168
+ entryType: DecisionEntryType;
169
+ body: string;
170
+ createdAt: string;
171
+ createdBy: string;
172
+ decidedBy?: string;
173
+ rationale?: string;
174
+ };
175
+
176
+ export type TaskEntryType = "comment" | "status_change" | "note";
177
+ export type TaskStatus = "open" | "in_progress" | "blocked" | "done";
178
+
179
+ export type TaskEntry = {
180
+ id: string;
181
+ entryType: TaskEntryType;
182
+ body: string;
183
+ createdAt: string;
184
+ createdBy: string;
185
+ status?: TaskStatus;
186
+ };
187
+
188
+ export type JournalEntryKind = "note" | "summary";
189
+
190
+ export type AppendJournalNoteInput = {
191
+ workspaceId: string;
192
+ body: string;
193
+ tag?: string;
194
+ };
195
+
196
+ export type ReadJournalInput = {
197
+ workspaceId: string;
198
+ limit?: number;
199
+ includeArchived?: boolean;
200
+ };
201
+
202
+ export type ReadJournalResult = {
203
+ workspaceId: string;
204
+ readTier: "hot" | "cold";
205
+ compaction: {
206
+ activeRawNoteCount: number;
207
+ threshold: number;
208
+ recommended: boolean;
209
+ };
210
+ entries: DxcRecord[];
211
+ };
212
+
213
+ export type GetJournalEntryInput = {
214
+ workspaceId: string;
215
+ id: string;
216
+ };
217
+
218
+ export type AppendJournalSummaryInput = {
219
+ workspaceId: string;
220
+ body: string;
221
+ covers: string[];
222
+ tag?: string;
223
+ };
224
+
225
+ export type CreateRecordInput = {
226
+ id?: string;
227
+ workspaceId?: string;
228
+ title?: string;
229
+ summary?: string;
230
+ fields?: Record<string, unknown>;
231
+ allowManagedFields?: boolean;
232
+ };
233
+
234
+ export type UpdateRecordInput = {
235
+ recordType: CollectionName;
236
+ id: string;
237
+ workspaceId?: string;
238
+ title?: string;
239
+ summary?: string;
240
+ fields?: Record<string, unknown>;
241
+ unsetFields?: string[];
242
+ allowManagedFields?: boolean;
243
+ revisionNote?: string;
244
+ };
245
+
246
+ export type AppendReviewNoteInput = {
247
+ recordType: ReviewableRecordType;
248
+ id: string;
249
+ workspaceId: string;
250
+ body: string;
251
+ important?: boolean;
252
+ };
253
+
254
+ export type AppendChangeEventInput = {
255
+ workspaceId: string;
256
+ changeId: string;
257
+ eventType: ChangeEventType;
258
+ event: Record<string, unknown>;
259
+ };
260
+
261
+ export type AppendDeferralEventInput = {
262
+ workspaceId: string;
263
+ deferralId: string;
264
+ eventType: DeferralEventType;
265
+ event: Record<string, unknown>;
266
+ };
267
+
268
+ export type AppendDecisionEntryInput = {
269
+ workspaceId: string;
270
+ decisionId: string;
271
+ entryType: DecisionEntryType;
272
+ body: string;
273
+ decidedBy?: string;
274
+ rationale?: string;
275
+ };
276
+
277
+ export type AppendTaskEntryInput = {
278
+ workspaceId: string;
279
+ taskId: string;
280
+ entryType: TaskEntryType;
281
+ body: string;
282
+ status?: TaskStatus;
283
+ };
284
+
285
+ export type UnlinkRecordsInput = {
286
+ fromType: CollectionName;
287
+ fromId: string;
288
+ toType: CollectionName;
289
+ toId: string;
290
+ workspaceId?: string;
291
+ relationship?: string;
292
+ };
293
+
294
+ export type ArchiveRecordInput = {
295
+ recordType: CollectionName;
296
+ id: string;
297
+ workspaceId?: string;
298
+ reason?: string;
299
+ supersededByType?: CollectionName;
300
+ supersededById?: string;
301
+ };
302
+
303
+ export type LinkedRecordsResult = {
304
+ source: DxcRecord;
305
+ outbound: Array<{
306
+ edge: RecordEdge;
307
+ record: DxcRecord;
308
+ }>;
309
+ inbound: Array<{
310
+ edge: RecordEdge;
311
+ record: DxcRecord;
312
+ }>;
313
+ };
314
+
315
+ export type DxcompleteTicketEntryDirection = "submitter_entry" | "dxcomplete_reply";
316
+
317
+ export type DxcompleteTicketEntry = {
318
+ id: string;
319
+ body: string;
320
+ createdAt: string;
321
+ createdBy: string;
322
+ direction: DxcompleteTicketEntryDirection;
323
+ addressedToActorId?: string;
324
+ readAt?: string;
325
+ };
326
+
327
+ export type CreateDxcompleteTicketInput = {
328
+ title: string;
329
+ body: string;
330
+ };
331
+
332
+ export type AppendDxcompleteTicketInput = {
333
+ id: string;
334
+ body: string;
335
+ };
336
+
337
+ export type AppendDxcompleteTicketReplyInput = {
338
+ id: string;
339
+ body: string;
340
+ addressedToActorId: string;
341
+ };
342
+
343
+ export type ArchiveDxcompleteTicketInput = {
344
+ id: string;
345
+ };
346
+
347
+ export type ReadDxcompleteTicketInput = {
348
+ id: string;
349
+ };
350
+
351
+ export type DxcompleteTicketUnreadReplySummary = {
352
+ id: string;
353
+ createdAt: string;
354
+ createdBy: string;
355
+ direction: "dxcomplete_reply";
356
+ addressedToActorId?: string;
357
+ };
358
+
359
+ export type DxcompleteTicketUnreadReplyResult = {
360
+ ticketId: string;
361
+ title?: string;
362
+ updatedAt: string;
363
+ unreadReplyCount: number;
364
+ newestReplyAt?: string;
365
+ replies: DxcompleteTicketUnreadReplySummary[];
366
+ };
367
+
368
+ export const RUNTIME_ACTOR_ID = "dxcomplete-runtime";
369
+ const REVIEW_NOTE_RECORD_TYPES = ["expectations", "requirements"] as const;
370
+ const VERSIONED_RECORD_TYPES = [
371
+ "statements",
372
+ "environments",
373
+ "components",
374
+ "expectations",
375
+ "requirements",
376
+ "estimates",
377
+ "benefits"
378
+ ] as const;
379
+ const VERSION_HISTORY_FIELD = "versionHistory";
380
+ const CHANGE_MANAGED_FIELDS = [
381
+ "changePlan",
382
+ "executionSteps",
383
+ "rollbackPlan",
384
+ "riskImpact",
385
+ "plannedFor",
386
+ "events"
387
+ ] as const;
388
+ const COMMITMENT_MANAGED_FIELDS = ["commitmentStatement", "reservations"] as const;
389
+ const DEFERRAL_MANAGED_FIELDS = ["reason", "status", "conditions", "conditionEvents"] as const;
390
+ const ESTIMATE_MANAGED_FIELDS = ["lineItems", "rollup"] as const;
391
+ const BENEFITS_MANAGED_FIELDS = ["benefitItems", "rollup"] as const;
392
+ const ENVIRONMENT_MANAGED_FIELDS = ["name", "description"] as const;
393
+ const COMPONENT_MANAGED_FIELDS = [
394
+ "name",
395
+ "environmentId",
396
+ "kind",
397
+ "locator",
398
+ "identifiers",
399
+ "secretPointers",
400
+ "notes"
401
+ ] as const;
402
+ const DECISION_LEDGER_MANAGED_FIELDS = [
403
+ "matter",
404
+ "entries",
405
+ "currentDecision",
406
+ "question",
407
+ "decision",
408
+ "decidedBy",
409
+ "rationale",
410
+ "argumentsConsidered",
411
+ "concerns",
412
+ "status"
413
+ ] as const;
414
+ const TASK_LEDGER_MANAGED_FIELDS = [
415
+ "description",
416
+ "assignee",
417
+ "assignor",
418
+ "entries",
419
+ "currentStatus",
420
+ "details",
421
+ "status"
422
+ ] as const;
423
+ const DECISION_INPUT_MANAGED_FIELDS = ["informedBy", "informedByIds", "inputRecords"] as const;
424
+ const JOURNAL_ENTRY_MANAGED_FIELDS = ["kind", "body", "tag", "covers", "coveredBySummaryId"] as const;
425
+ const JOURNAL_COMPACTION_THRESHOLD = 200;
426
+ const VERSIONED_TYPED_FIELDS: Partial<Record<CollectionName, string[]>> = {
427
+ statements: ["statement", "source"],
428
+ expectations: ["statement", "successRecognition", "approvalState", "approvedBy", "approvedAt", "source"],
429
+ requirements: ["statement", "acceptanceCriteria", "priority", "status"],
430
+ estimates: ["lineItems", "rollup"],
431
+ benefits: ["benefitItems", "rollup"],
432
+ environments: ["name", "description"],
433
+ components: ["name", "environmentId", "kind", "locator", "identifiers", "secretPointers", "notes"]
434
+ };
435
+
436
+ const RESERVED_RELATIONSHIP_FIELDS: Partial<Record<CollectionName, string[]>> = {
437
+ changes: ["requirementId"],
438
+ commitments: ["requirementIds", "expectationIds", "deferralId"],
439
+ deferrals: ["requirementIds", "expectationIds"],
440
+ estimates: ["requirementIds", "expectationIds"],
441
+ benefits: ["requirementIds", "expectationIds"],
442
+ expectations: ["statementId"],
443
+ requirements: ["expectationId"],
444
+ tasks: ["requirementId"]
445
+ };
446
+
447
+ const REMOVED_INITIATIVE_FIELD_RECORD_TYPES: CollectionName[] = [
448
+ "changes",
449
+ "estimates",
450
+ "benefits",
451
+ "expectations"
452
+ ];
453
+
454
+ export function assertCollectionName(value: string): CollectionName {
455
+ if ((COLLECTION_NAMES as readonly string[]).includes(value)) {
456
+ return value as CollectionName;
457
+ }
458
+
459
+ throw new Error(`Unsupported record type "${value}".`);
460
+ }
461
+
462
+ export async function createRecord(
463
+ db: Db,
464
+ recordType: CollectionName,
465
+ input: CreateRecordInput,
466
+ actorId: string
467
+ ): Promise<DxcRecord> {
468
+ assertNoReservedRelationshipFields(recordType, input.fields);
469
+ if (input.allowManagedFields) {
470
+ assertNoReviewNotesField(recordType, input.fields);
471
+ } else {
472
+ assertNoManagedField(recordType, input.fields);
473
+ }
474
+
475
+ const now = new Date().toISOString();
476
+ const workspaceId = workspaceIdForCreate(recordType, input.workspaceId);
477
+
478
+ if (workspaceId) {
479
+ await assertWorkspaceExists(db, workspaceId);
480
+ }
481
+
482
+ const record: DxcRecord = {
483
+ _id: input.id ?? randomUUID(),
484
+ recordType,
485
+ ...(workspaceId ? { workspaceId } : {}),
486
+ title: input.title,
487
+ summary: input.summary,
488
+ fields: input.fields ?? {},
489
+ links: [],
490
+ createdAt: now,
491
+ createdBy: actorId,
492
+ updatedAt: now,
493
+ updatedBy: actorId
494
+ };
495
+
496
+ if (recordTypeSupportsReadableId(recordType)) {
497
+ const session = db.client.startSession();
498
+ try {
499
+ await session.withTransaction(async () => {
500
+ record.readableId = await allocateReadableId(db, recordType, workspaceId, actorId, now, session);
501
+ await db.collection<DxcRecord>(recordType).insertOne(record, { session });
502
+ });
503
+ } finally {
504
+ await session.endSession();
505
+ }
506
+ return record;
507
+ }
508
+
509
+ await db.collection<DxcRecord>(recordType).insertOne(record);
510
+ return record;
511
+ }
512
+
513
+ export async function listRecords(
514
+ db: Db,
515
+ recordType: CollectionName,
516
+ limit: number,
517
+ options: { includeArchived?: boolean; workspaceId?: string } = {}
518
+ ): Promise<DxcRecord[]> {
519
+ const filter: Record<string, unknown> = {};
520
+
521
+ if (recordTypeRequiresWorkspace(recordType)) {
522
+ filter.workspaceId = readRequiredWorkspaceId(options.workspaceId, recordType);
523
+ }
524
+
525
+ if (!options.includeArchived) {
526
+ filter.archivedAt = { $exists: false };
527
+ }
528
+
529
+ return db
530
+ .collection<DxcRecord>(recordType)
531
+ .find(filter)
532
+ .sort({ createdAt: -1 })
533
+ .limit(limit)
534
+ .toArray();
535
+ }
536
+
537
+ export async function getRecord(
538
+ db: Db,
539
+ recordType: RuntimeCollectionName,
540
+ id: string,
541
+ options: { workspaceId?: string; allowAnyWorkspace?: boolean } = {}
542
+ ): Promise<DxcRecord | null> {
543
+ const filter = recordIdentityFilter(recordType, id);
544
+
545
+ if (
546
+ recordTypeRequiresWorkspace(recordType) &&
547
+ !options.allowAnyWorkspace &&
548
+ isCurrentCollection(recordType)
549
+ ) {
550
+ filter.workspaceId = readRequiredWorkspaceId(options.workspaceId, recordType);
551
+ }
552
+
553
+ return db.collection<DxcRecord>(recordType).findOne(filter);
554
+ }
555
+
556
+ export async function listLinkedRecords(
557
+ db: Db,
558
+ input: {
559
+ recordType: CollectionName;
560
+ id: string;
561
+ workspaceId?: string;
562
+ direction?: "outbound" | "inbound" | "both";
563
+ relationship?: string;
564
+ includeArchived?: boolean;
565
+ }
566
+ ): Promise<LinkedRecordsResult> {
567
+ const source = await getRecord(db, input.recordType, input.id, { workspaceId: input.workspaceId });
568
+
569
+ if (!source) {
570
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
571
+ }
572
+
573
+ const direction = input.direction ?? "both";
574
+ const result: LinkedRecordsResult = {
575
+ source,
576
+ outbound: [],
577
+ inbound: []
578
+ };
579
+
580
+ if (direction === "outbound" || direction === "both") {
581
+ for (const link of source.links.filter((link) => linkMatches(link, input.relationship))) {
582
+ const target = await getRecord(db, link.toType, link.toId, {
583
+ workspaceId: source.workspaceId,
584
+ allowAnyWorkspace: !source.workspaceId
585
+ });
586
+
587
+ if (
588
+ !target ||
589
+ (!input.includeArchived && target.archivedAt) ||
590
+ !recordBelongsToWorkspace(target, source.workspaceId)
591
+ ) {
592
+ continue;
593
+ }
594
+
595
+ result.outbound.push({
596
+ edge: {
597
+ fromType: source.recordType,
598
+ fromId: source._id,
599
+ ...link
600
+ },
601
+ record: target
602
+ });
603
+ }
604
+ }
605
+
606
+ if (direction === "inbound" || direction === "both") {
607
+ for (const collectionName of LINK_SCAN_COLLECTION_NAMES) {
608
+ const filter: Record<string, unknown> = {
609
+ links: {
610
+ $elemMatch: {
611
+ toType: input.recordType,
612
+ toId: source._id,
613
+ ...(input.relationship ? { relationship: input.relationship } : {})
614
+ }
615
+ }
616
+ };
617
+
618
+ if (source.workspaceId && recordTypeRequiresWorkspace(collectionName)) {
619
+ filter.workspaceId = source.workspaceId;
620
+ }
621
+
622
+ if (!input.includeArchived) {
623
+ filter.archivedAt = { $exists: false };
624
+ }
625
+
626
+ const records = await db.collection<DxcRecord>(collectionName).find(filter).toArray();
627
+
628
+ for (const record of records) {
629
+ for (const link of record.links.filter(
630
+ (link) =>
631
+ link.toType === input.recordType &&
632
+ link.toId === source._id &&
633
+ linkMatches(link, input.relationship)
634
+ )) {
635
+ result.inbound.push({
636
+ edge: {
637
+ fromType: record.recordType,
638
+ fromId: record._id,
639
+ ...link
640
+ },
641
+ record
642
+ });
643
+ }
644
+ }
645
+ }
646
+ }
647
+
648
+ return result;
649
+ }
650
+
651
+ export async function migrateLegacyIntakeItemsToDxcompleteTickets(db: Db): Promise<{ copied: number; skipped: number }> {
652
+ const legacyCollection = db.collection<DxcRecord>(LEGACY_INTAKE_COLLECTION_NAME);
653
+ const ticketCollection = db.collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME);
654
+ const legacyRecords = await legacyCollection.find({}).toArray();
655
+ let copied = 0;
656
+ let skipped = 0;
657
+
658
+ for (const legacyRecord of legacyRecords) {
659
+ const existing = await ticketCollection.findOne({ _id: legacyRecord._id });
660
+
661
+ if (existing) {
662
+ skipped += 1;
663
+ continue;
664
+ }
665
+
666
+ const migratedRecord: DxcRecord = {
667
+ ...legacyRecord,
668
+ recordType: DXCOMPLETE_TICKET_COLLECTION_NAME,
669
+ fields: {
670
+ ...legacyRecord.fields,
671
+ entries: normalizeTicketEntries(legacyRecord.fields.entries)
672
+ }
673
+ };
674
+
675
+ await ticketCollection.insertOne(migratedRecord);
676
+ copied += 1;
677
+ }
678
+
679
+ return { copied, skipped };
680
+ }
681
+
682
+ export async function createDxcompleteTicket(
683
+ db: Db,
684
+ input: CreateDxcompleteTicketInput,
685
+ actor: ActorContext
686
+ ): Promise<DxcRecord> {
687
+ const now = new Date().toISOString();
688
+ const entry: DxcompleteTicketEntry = {
689
+ id: randomUUID(),
690
+ body: input.body,
691
+ createdAt: now,
692
+ createdBy: actor.actorId,
693
+ direction: "submitter_entry"
694
+ };
695
+ const record: DxcRecord = {
696
+ _id: randomUUID(),
697
+ recordType: DXCOMPLETE_TICKET_COLLECTION_NAME,
698
+ title: input.title,
699
+ fields: {
700
+ ownerActorId: actor.actorId,
701
+ entries: [entry]
702
+ },
703
+ links: [],
704
+ createdAt: now,
705
+ createdBy: actor.actorId,
706
+ updatedAt: now,
707
+ updatedBy: actor.actorId
708
+ };
709
+
710
+ await db.collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME).insertOne(record);
711
+ return record;
712
+ }
713
+
714
+ export async function getDxcompleteTicket(db: Db, id: string, actor: ActorContext): Promise<DxcRecord> {
715
+ const record = await db.collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME).findOne(ticketOwnerFilter(id, actor));
716
+
717
+ if (!record) {
718
+ throw new Error(`DX Complete Ticket not found: ${id}`);
719
+ }
720
+
721
+ return record;
722
+ }
723
+
724
+ export async function listDxcompleteTickets(
725
+ db: Db,
726
+ actor: ActorContext,
727
+ limit: number,
728
+ options: { includeArchived?: boolean } = {}
729
+ ): Promise<DxcRecord[]> {
730
+ const filter: Record<string, unknown> = {
731
+ "fields.ownerActorId": actor.actorId
732
+ };
733
+
734
+ if (!options.includeArchived) {
735
+ filter.archivedAt = { $exists: false };
736
+ }
737
+
738
+ return db
739
+ .collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME)
740
+ .find(filter)
741
+ .sort({ updatedAt: -1 })
742
+ .limit(limit)
743
+ .toArray();
744
+ }
745
+
746
+ export async function appendDxcompleteTicket(
747
+ db: Db,
748
+ input: AppendDxcompleteTicketInput,
749
+ actor: ActorContext
750
+ ): Promise<DxcRecord> {
751
+ const collection = db.collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME);
752
+ const existing = await collection.findOne({
753
+ ...ticketOwnerFilter(input.id, actor),
754
+ archivedAt: { $exists: false }
755
+ });
756
+
757
+ if (!existing) {
758
+ throw new Error(`Active DX Complete Ticket not found: ${input.id}`);
759
+ }
760
+
761
+ const now = new Date().toISOString();
762
+ const entry: DxcompleteTicketEntry = {
763
+ id: randomUUID(),
764
+ body: input.body,
765
+ createdAt: now,
766
+ createdBy: actor.actorId,
767
+ direction: "submitter_entry"
768
+ };
769
+
770
+ await collection.updateOne(
771
+ ticketOwnerFilter(input.id, actor),
772
+ {
773
+ $push: {
774
+ "fields.entries": entry
775
+ },
776
+ $set: {
777
+ updatedAt: now,
778
+ updatedBy: actor.actorId
779
+ }
780
+ }
781
+ );
782
+
783
+ return getDxcompleteTicket(db, input.id, actor);
784
+ }
785
+
786
+ export async function appendDxcompleteTicketReply(
787
+ db: Db,
788
+ input: AppendDxcompleteTicketReplyInput,
789
+ actorId: string = RUNTIME_ACTOR_ID
790
+ ): Promise<DxcRecord> {
791
+ const collection = db.collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME);
792
+ const existing = await collection.findOne({
793
+ _id: input.id,
794
+ "fields.ownerActorId": input.addressedToActorId,
795
+ archivedAt: { $exists: false }
796
+ });
797
+
798
+ if (!existing) {
799
+ throw new Error(`Active DX Complete Ticket not found for addressed actor: ${input.id}`);
800
+ }
801
+
802
+ const now = new Date().toISOString();
803
+ const entry: DxcompleteTicketEntry = {
804
+ id: randomUUID(),
805
+ body: input.body,
806
+ createdAt: now,
807
+ createdBy: actorId,
808
+ direction: "dxcomplete_reply",
809
+ addressedToActorId: input.addressedToActorId
810
+ };
811
+
812
+ await collection.updateOne(
813
+ { _id: input.id },
814
+ {
815
+ $push: {
816
+ "fields.entries": entry
817
+ },
818
+ $set: {
819
+ updatedAt: now,
820
+ updatedBy: actorId
821
+ }
822
+ }
823
+ );
824
+
825
+ const record = await collection.findOne({ _id: input.id });
826
+
827
+ if (!record) {
828
+ throw new Error(`DX Complete Ticket not found after reply append: ${input.id}`);
829
+ }
830
+
831
+ return record;
832
+ }
833
+
834
+ export async function appendJournalNote(
835
+ db: Db,
836
+ input: AppendJournalNoteInput,
837
+ actorId: string
838
+ ): Promise<DxcRecord> {
839
+ return createRecord(
840
+ db,
841
+ "journal_entries",
842
+ {
843
+ workspaceId: input.workspaceId,
844
+ title: input.tag ? `Journal note: ${input.tag}` : "Journal note",
845
+ summary: input.body,
846
+ allowManagedFields: true,
847
+ fields: {
848
+ kind: "note",
849
+ body: input.body,
850
+ ...(input.tag ? { tag: input.tag } : {})
851
+ }
852
+ },
853
+ actorId
854
+ );
855
+ }
856
+
857
+ export async function readJournal(db: Db, input: ReadJournalInput): Promise<ReadJournalResult> {
858
+ const limit = clampJournalReadLimit(input.limit);
859
+ const filter: Record<string, unknown> = {
860
+ workspaceId: readRequiredWorkspaceId(input.workspaceId, "journal_entries")
861
+ };
862
+
863
+ if (!input.includeArchived) {
864
+ filter.archivedAt = { $exists: false };
865
+ filter["fields.kind"] = { $in: ["note", "summary"] };
866
+ }
867
+
868
+ const [entries, activeRawNoteCount] = await Promise.all([
869
+ db
870
+ .collection<DxcRecord>("journal_entries")
871
+ .find(filter)
872
+ .sort({ createdAt: 1 })
873
+ .limit(limit)
874
+ .toArray(),
875
+ db.collection<DxcRecord>("journal_entries").countDocuments({
876
+ workspaceId: input.workspaceId,
877
+ archivedAt: { $exists: false },
878
+ "fields.kind": "note"
879
+ })
880
+ ]);
881
+
882
+ return {
883
+ workspaceId: input.workspaceId,
884
+ readTier: input.includeArchived ? "cold" : "hot",
885
+ compaction: {
886
+ activeRawNoteCount,
887
+ threshold: JOURNAL_COMPACTION_THRESHOLD,
888
+ recommended: activeRawNoteCount >= JOURNAL_COMPACTION_THRESHOLD
889
+ },
890
+ entries
891
+ };
892
+ }
893
+
894
+ export async function getJournalEntry(db: Db, input: GetJournalEntryInput): Promise<DxcRecord> {
895
+ const entry = await getRecord(db, "journal_entries", input.id, { workspaceId: input.workspaceId });
896
+
897
+ if (!entry) {
898
+ throw new Error(`Journal entry not found: journal_entries/${input.id}`);
899
+ }
900
+
901
+ return entry;
902
+ }
903
+
904
+ export async function appendJournalSummary(
905
+ db: Db,
906
+ input: AppendJournalSummaryInput,
907
+ actorId: string
908
+ ): Promise<DxcRecord> {
909
+ const coveredIds = [...new Set(input.covers.map((id) => id.trim()).filter(Boolean))];
910
+
911
+ if (coveredIds.length === 0) {
912
+ throw new Error("append_journal_summary requires at least one covered journal entry id.");
913
+ }
914
+
915
+ const coveredEntries: DxcRecord[] = [];
916
+ for (const id of coveredIds) {
917
+ const entry = await getRecord(db, "journal_entries", id, { workspaceId: input.workspaceId });
918
+
919
+ if (!entry) {
920
+ throw new Error(`Covered journal entry not found: journal_entries/${id}`);
921
+ }
922
+
923
+ const kind = readJournalEntryKind(entry);
924
+ if (!kind) {
925
+ throw new Error(`Covered record is not a journal note or summary: journal_entries/${id}`);
926
+ }
927
+
928
+ coveredEntries.push(entry);
929
+ }
930
+
931
+ const summary = await createRecord(
932
+ db,
933
+ "journal_entries",
934
+ {
935
+ workspaceId: input.workspaceId,
936
+ title: input.tag ? `Journal summary: ${input.tag}` : "Journal summary",
937
+ summary: input.body,
938
+ allowManagedFields: true,
939
+ fields: {
940
+ kind: "summary",
941
+ body: input.body,
942
+ covers: coveredEntries.map((entry) => entry._id),
943
+ ...(input.tag ? { tag: input.tag } : {})
944
+ }
945
+ },
946
+ actorId
947
+ );
948
+
949
+ const now = new Date().toISOString();
950
+ await db.collection<DxcRecord>("journal_entries").updateMany(
951
+ {
952
+ workspaceId: input.workspaceId,
953
+ _id: { $in: coveredEntries.map((entry) => entry._id) },
954
+ archivedAt: { $exists: false }
955
+ },
956
+ {
957
+ $set: {
958
+ archivedAt: now,
959
+ archivedBy: actorId,
960
+ archiveReason: `Covered by journal summary ${summary._id}`,
961
+ "fields.coveredBySummaryId": summary._id,
962
+ updatedAt: now,
963
+ updatedBy: actorId
964
+ }
965
+ }
966
+ );
967
+
968
+ return summary;
969
+ }
970
+
971
+ function clampJournalReadLimit(limit: number | undefined): number {
972
+ if (!limit) {
973
+ return 100;
974
+ }
975
+
976
+ return Math.min(Math.max(limit, 1), 500);
977
+ }
978
+
979
+ function readJournalEntryKind(record: DxcRecord): JournalEntryKind | undefined {
980
+ if (record.fields.kind === "note" || record.fields.kind === "summary") {
981
+ return record.fields.kind;
982
+ }
983
+
984
+ return undefined;
985
+ }
986
+
987
+ export async function appendReviewNote(
988
+ db: Db,
989
+ input: AppendReviewNoteInput,
990
+ actorId: string
991
+ ): Promise<DxcRecord> {
992
+ const collection = db.collection<DxcRecord>(input.recordType);
993
+ const filter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
994
+ const existing = await collection.findOne(filter);
995
+
996
+ if (!existing) {
997
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
998
+ }
999
+
1000
+ const now = new Date().toISOString();
1001
+ const note: ReviewNote = {
1002
+ id: randomUUID(),
1003
+ body: input.body,
1004
+ createdAt: now,
1005
+ createdBy: actorId,
1006
+ ...(input.important ? { important: true } : {})
1007
+ };
1008
+
1009
+ await collection.updateOne(filter, {
1010
+ $push: {
1011
+ "fields.reviewNotes": note
1012
+ },
1013
+ $set: {
1014
+ updatedAt: now,
1015
+ updatedBy: actorId
1016
+ }
1017
+ });
1018
+
1019
+ const updated = await getRecord(db, input.recordType, input.id, { workspaceId: input.workspaceId });
1020
+ if (!updated) {
1021
+ throw new Error(`Record not found after review note append: ${input.recordType}/${input.id}`);
1022
+ }
1023
+
1024
+ return updated;
1025
+ }
1026
+
1027
+ export async function appendChangeEvent(
1028
+ db: Db,
1029
+ input: AppendChangeEventInput,
1030
+ actorId: string
1031
+ ): Promise<DxcRecord> {
1032
+ const collection = db.collection<DxcRecord>("changes");
1033
+ const filter = scopedRecordFilter("changes", input.changeId, input.workspaceId);
1034
+ const existing = await collection.findOne(filter);
1035
+
1036
+ if (!existing) {
1037
+ throw new Error(`Record not found: changes/${input.changeId}`);
1038
+ }
1039
+
1040
+ const now = new Date().toISOString();
1041
+ const event: ChangeEvent = {
1042
+ ...input.event,
1043
+ id: randomUUID(),
1044
+ eventType: input.eventType,
1045
+ createdAt: now,
1046
+ createdBy: actorId
1047
+ };
1048
+
1049
+ await collection.updateOne(filter, {
1050
+ $push: {
1051
+ "fields.events": event
1052
+ },
1053
+ $set: {
1054
+ updatedAt: now,
1055
+ updatedBy: actorId
1056
+ }
1057
+ });
1058
+
1059
+ const updated = await getRecord(db, "changes", input.changeId, { workspaceId: input.workspaceId });
1060
+ if (!updated) {
1061
+ throw new Error(`Record not found after change event append: changes/${input.changeId}`);
1062
+ }
1063
+
1064
+ return updated;
1065
+ }
1066
+
1067
+ export async function appendDeferralEvent(
1068
+ db: Db,
1069
+ input: AppendDeferralEventInput,
1070
+ actorId: string
1071
+ ): Promise<DxcRecord> {
1072
+ const collection = db.collection<DxcRecord>("deferrals");
1073
+ const filter = scopedRecordFilter("deferrals", input.deferralId, input.workspaceId);
1074
+ const existing = await collection.findOne(filter);
1075
+
1076
+ if (!existing) {
1077
+ throw new Error(`Record not found: deferrals/${input.deferralId}`);
1078
+ }
1079
+
1080
+ const now = new Date().toISOString();
1081
+ const event: DeferralEvent = {
1082
+ ...input.event,
1083
+ id: randomUUID(),
1084
+ eventType: input.eventType,
1085
+ createdAt: now,
1086
+ createdBy: actorId
1087
+ };
1088
+ const { conditions, status } = applyDeferralEventState(existing, event, actorId, now);
1089
+
1090
+ await collection.updateOne(filter, {
1091
+ $push: {
1092
+ "fields.conditionEvents": event
1093
+ },
1094
+ $set: {
1095
+ "fields.conditions": conditions,
1096
+ "fields.status": status,
1097
+ updatedAt: now,
1098
+ updatedBy: actorId
1099
+ }
1100
+ });
1101
+
1102
+ const updated = await getRecord(db, "deferrals", input.deferralId, { workspaceId: input.workspaceId });
1103
+ if (!updated) {
1104
+ throw new Error(`Record not found after deferral event append: deferrals/${input.deferralId}`);
1105
+ }
1106
+
1107
+ return updated;
1108
+ }
1109
+
1110
+ export async function appendDecisionEntry(
1111
+ db: Db,
1112
+ input: AppendDecisionEntryInput,
1113
+ actorId: string
1114
+ ): Promise<DxcRecord> {
1115
+ const collection = db.collection<DxcRecord>("decisions");
1116
+ const filter = scopedRecordFilter("decisions", input.decisionId, input.workspaceId);
1117
+ const existing = await collection.findOne(filter);
1118
+
1119
+ if (!existing) {
1120
+ throw new Error(`Record not found: decisions/${input.decisionId}`);
1121
+ }
1122
+
1123
+ assertDecisionEntryInput(input);
1124
+
1125
+ const now = new Date().toISOString();
1126
+ const entry: DecisionEntry = {
1127
+ id: randomUUID(),
1128
+ entryType: input.entryType,
1129
+ body: input.body,
1130
+ createdAt: now,
1131
+ createdBy: actorId,
1132
+ ...(input.decidedBy ? { decidedBy: input.decidedBy } : {}),
1133
+ ...(input.rationale ? { rationale: input.rationale } : {})
1134
+ };
1135
+ const update: Record<string, unknown> = {
1136
+ $push: {
1137
+ "fields.entries": entry
1138
+ },
1139
+ $set: {
1140
+ updatedAt: now,
1141
+ updatedBy: actorId
1142
+ }
1143
+ };
1144
+
1145
+ if (entry.entryType === "decision") {
1146
+ (update.$set as Record<string, unknown>)["fields.currentDecision"] = decisionEntryToCurrentDecision(entry);
1147
+ }
1148
+
1149
+ await collection.updateOne(filter, update);
1150
+
1151
+ const updated = await getRecord(db, "decisions", input.decisionId, { workspaceId: input.workspaceId });
1152
+ if (!updated) {
1153
+ throw new Error(`Record not found after decision entry append: decisions/${input.decisionId}`);
1154
+ }
1155
+
1156
+ return updated;
1157
+ }
1158
+
1159
+ export async function appendTaskEntry(
1160
+ db: Db,
1161
+ input: AppendTaskEntryInput,
1162
+ actorId: string
1163
+ ): Promise<DxcRecord> {
1164
+ const collection = db.collection<DxcRecord>("tasks");
1165
+ const filter = scopedRecordFilter("tasks", input.taskId, input.workspaceId);
1166
+ const existing = await collection.findOne(filter);
1167
+
1168
+ if (!existing) {
1169
+ throw new Error(`Record not found: tasks/${input.taskId}`);
1170
+ }
1171
+
1172
+ assertTaskEntryInput(input);
1173
+
1174
+ const now = new Date().toISOString();
1175
+ const entry: TaskEntry = {
1176
+ id: randomUUID(),
1177
+ entryType: input.entryType,
1178
+ body: input.body,
1179
+ createdAt: now,
1180
+ createdBy: actorId,
1181
+ ...(input.status ? { status: input.status } : {})
1182
+ };
1183
+ const update: Record<string, unknown> = {
1184
+ $push: {
1185
+ "fields.entries": entry
1186
+ },
1187
+ $set: {
1188
+ updatedAt: now,
1189
+ updatedBy: actorId
1190
+ }
1191
+ };
1192
+
1193
+ if (entry.entryType === "status_change") {
1194
+ (update.$set as Record<string, unknown>)["fields.currentStatus"] = taskEntryToCurrentStatus(entry);
1195
+ }
1196
+
1197
+ await collection.updateOne(filter, update);
1198
+
1199
+ const updated = await getRecord(db, "tasks", input.taskId, { workspaceId: input.workspaceId });
1200
+ if (!updated) {
1201
+ throw new Error(`Record not found after task entry append: tasks/${input.taskId}`);
1202
+ }
1203
+
1204
+ return updated;
1205
+ }
1206
+
1207
+ export function decisionEntryToCurrentDecision(entry: DecisionEntry): Record<string, unknown> {
1208
+ return {
1209
+ entryId: entry.id,
1210
+ body: entry.body,
1211
+ createdAt: entry.createdAt,
1212
+ createdBy: entry.createdBy,
1213
+ ...(entry.decidedBy ? { decidedBy: entry.decidedBy } : {}),
1214
+ ...(entry.rationale ? { rationale: entry.rationale } : {})
1215
+ };
1216
+ }
1217
+
1218
+ export function taskEntryToCurrentStatus(entry: TaskEntry): Record<string, unknown> {
1219
+ if (entry.entryType !== "status_change" || !entry.status) {
1220
+ throw new Error("Task current status can only derive from a status_change entry.");
1221
+ }
1222
+
1223
+ return {
1224
+ entryId: entry.id,
1225
+ status: entry.status,
1226
+ body: entry.body,
1227
+ createdAt: entry.createdAt,
1228
+ createdBy: entry.createdBy
1229
+ };
1230
+ }
1231
+
1232
+ function assertDecisionEntryInput(input: AppendDecisionEntryInput): void {
1233
+ if (input.entryType !== "decision" && (input.decidedBy || input.rationale)) {
1234
+ throw new Error("decidedBy and rationale are only valid on decision entries.");
1235
+ }
1236
+ }
1237
+
1238
+ function assertTaskEntryInput(input: AppendTaskEntryInput): void {
1239
+ if (input.entryType === "status_change" && !input.status) {
1240
+ throw new Error("status_change entries require status.");
1241
+ }
1242
+
1243
+ if (input.entryType !== "status_change" && input.status) {
1244
+ throw new Error("status is only valid on status_change entries.");
1245
+ }
1246
+ }
1247
+
1248
+ function applyDeferralEventState(
1249
+ existing: DxcRecord,
1250
+ event: DeferralEvent,
1251
+ actorId: string,
1252
+ now: string
1253
+ ): { conditions: DeferralCondition[]; status: string } {
1254
+ const conditions = normalizeDeferralConditions(existing.fields.conditions);
1255
+ let status = typeof existing.fields.status === "string" ? existing.fields.status : "open";
1256
+
1257
+ switch (event.eventType) {
1258
+ case "condition_addressed":
1259
+ return {
1260
+ conditions: updateDeferralConditionState(conditions, event, "addressed", actorId, now),
1261
+ status
1262
+ };
1263
+ case "condition_reopened":
1264
+ return {
1265
+ conditions: updateDeferralConditionState(conditions, event, "open", actorId, now),
1266
+ status
1267
+ };
1268
+ case "condition_note_added":
1269
+ assertDeferralConditionExists(conditions, event);
1270
+ return { conditions, status };
1271
+ case "deferral_resolved":
1272
+ status = "resolved";
1273
+ return { conditions, status };
1274
+ case "deferral_abandoned":
1275
+ status = "abandoned";
1276
+ return { conditions, status };
1277
+ }
1278
+ }
1279
+
1280
+ function normalizeDeferralConditions(value: unknown): DeferralCondition[] {
1281
+ if (!Array.isArray(value)) {
1282
+ return [];
1283
+ }
1284
+
1285
+ return value.filter(isDeferralCondition);
1286
+ }
1287
+
1288
+ function isDeferralCondition(value: unknown): value is DeferralCondition {
1289
+ if (!value || typeof value !== "object") {
1290
+ return false;
1291
+ }
1292
+
1293
+ const condition = value as DeferralCondition;
1294
+ return (
1295
+ typeof condition.id === "string" &&
1296
+ typeof condition.statement === "string" &&
1297
+ (condition.state === "open" || condition.state === "addressed") &&
1298
+ typeof condition.createdAt === "string" &&
1299
+ typeof condition.createdBy === "string" &&
1300
+ typeof condition.updatedAt === "string" &&
1301
+ typeof condition.updatedBy === "string"
1302
+ );
1303
+ }
1304
+
1305
+ function updateDeferralConditionState(
1306
+ conditions: DeferralCondition[],
1307
+ event: DeferralEvent,
1308
+ state: "open" | "addressed",
1309
+ actorId: string,
1310
+ now: string
1311
+ ): DeferralCondition[] {
1312
+ const conditionId = readRequiredDeferralEventString(event, "conditionId");
1313
+ let found = false;
1314
+ const updated = conditions.map((condition) => {
1315
+ if (condition.id !== conditionId) {
1316
+ return condition;
1317
+ }
1318
+
1319
+ found = true;
1320
+ return {
1321
+ ...condition,
1322
+ state,
1323
+ updatedAt: now,
1324
+ updatedBy: actorId
1325
+ };
1326
+ });
1327
+
1328
+ if (!found) {
1329
+ throw new Error(`Deferral condition not found: ${conditionId}`);
1330
+ }
1331
+
1332
+ return updated;
1333
+ }
1334
+
1335
+ function assertDeferralConditionExists(conditions: DeferralCondition[], event: DeferralEvent): void {
1336
+ const conditionId = readRequiredDeferralEventString(event, "conditionId");
1337
+ if (!conditions.some((condition) => condition.id === conditionId)) {
1338
+ throw new Error(`Deferral condition not found: ${conditionId}`);
1339
+ }
1340
+ }
1341
+
1342
+ function readRequiredDeferralEventString(event: DeferralEvent, key: string): string {
1343
+ const value = event[key];
1344
+ if (typeof value !== "string" || !value.trim()) {
1345
+ throw new Error(`${event.eventType} requires ${key}.`);
1346
+ }
1347
+ return value;
1348
+ }
1349
+
1350
+ export async function listUnreadDxcompleteTicketReplies(
1351
+ db: Db,
1352
+ actor: ActorContext,
1353
+ limit: number
1354
+ ): Promise<DxcompleteTicketUnreadReplyResult[]> {
1355
+ const records = await db
1356
+ .collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME)
1357
+ .find({
1358
+ "fields.ownerActorId": actor.actorId,
1359
+ archivedAt: { $exists: false },
1360
+ "fields.entries": {
1361
+ $elemMatch: {
1362
+ direction: "dxcomplete_reply",
1363
+ addressedToActorId: actor.actorId,
1364
+ readAt: { $exists: false }
1365
+ }
1366
+ }
1367
+ })
1368
+ .sort({ updatedAt: -1 })
1369
+ .limit(limit)
1370
+ .toArray();
1371
+
1372
+ return records.map((record) => {
1373
+ const replies = normalizeTicketEntries(record.fields.entries).filter(
1374
+ (entry) =>
1375
+ entry.direction === "dxcomplete_reply" &&
1376
+ entry.addressedToActorId === actor.actorId &&
1377
+ !entry.readAt
1378
+ );
1379
+ const replySummaries = replies.map((entry) => ({
1380
+ id: entry.id,
1381
+ createdAt: entry.createdAt,
1382
+ createdBy: entry.createdBy,
1383
+ direction: "dxcomplete_reply" as const,
1384
+ ...(entry.addressedToActorId ? { addressedToActorId: entry.addressedToActorId } : {})
1385
+ }));
1386
+ const newestReplyAt = replySummaries.reduce<string | undefined>(
1387
+ (current, entry) => (!current || entry.createdAt > current ? entry.createdAt : current),
1388
+ undefined
1389
+ );
1390
+
1391
+ return {
1392
+ ticketId: record._id,
1393
+ ...(record.title ? { title: record.title } : {}),
1394
+ updatedAt: record.updatedAt,
1395
+ unreadReplyCount: replySummaries.length,
1396
+ ...(newestReplyAt ? { newestReplyAt } : {}),
1397
+ replies: replySummaries
1398
+ };
1399
+ });
1400
+ }
1401
+
1402
+ export async function readDxcompleteTicket(
1403
+ db: Db,
1404
+ input: ReadDxcompleteTicketInput,
1405
+ actor: ActorContext
1406
+ ): Promise<DxcRecord> {
1407
+ const collection = db.collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME);
1408
+ const existing = await collection.findOne(ticketOwnerFilter(input.id, actor));
1409
+
1410
+ if (!existing) {
1411
+ throw new Error(`DX Complete Ticket not found: ${input.id}`);
1412
+ }
1413
+
1414
+ const now = new Date().toISOString();
1415
+ const entries = normalizeTicketEntries(existing.fields.entries);
1416
+ let changed = false;
1417
+ const nextEntries = entries.map((entry) => {
1418
+ const shouldMark =
1419
+ entry.direction === "dxcomplete_reply" &&
1420
+ entry.addressedToActorId === actor.actorId &&
1421
+ !entry.readAt;
1422
+
1423
+ if (!shouldMark) {
1424
+ return entry;
1425
+ }
1426
+
1427
+ changed = true;
1428
+ return {
1429
+ ...entry,
1430
+ readAt: now
1431
+ };
1432
+ });
1433
+
1434
+ if (!changed) {
1435
+ return existing;
1436
+ }
1437
+
1438
+ await collection.updateOne(ticketOwnerFilter(input.id, actor), {
1439
+ $set: {
1440
+ "fields.entries": nextEntries,
1441
+ updatedAt: now,
1442
+ updatedBy: actor.actorId
1443
+ }
1444
+ });
1445
+
1446
+ return getDxcompleteTicket(db, input.id, actor);
1447
+ }
1448
+
1449
+ export async function archiveDxcompleteTicket(
1450
+ db: Db,
1451
+ input: ArchiveDxcompleteTicketInput,
1452
+ actor: ActorContext
1453
+ ): Promise<DxcRecord> {
1454
+ const collection = db.collection<DxcRecord>(DXCOMPLETE_TICKET_COLLECTION_NAME);
1455
+ const existing = await collection.findOne(ticketOwnerFilter(input.id, actor));
1456
+
1457
+ if (!existing) {
1458
+ throw new Error(`DX Complete Ticket not found: ${input.id}`);
1459
+ }
1460
+
1461
+ if (existing.archivedAt) {
1462
+ return existing;
1463
+ }
1464
+
1465
+ const now = new Date().toISOString();
1466
+ await collection.updateOne(ticketOwnerFilter(input.id, actor), {
1467
+ $set: {
1468
+ archivedAt: now,
1469
+ updatedAt: now,
1470
+ updatedBy: actor.actorId
1471
+ }
1472
+ });
1473
+
1474
+ return getDxcompleteTicket(db, input.id, actor);
1475
+ }
1476
+
1477
+ export async function updateRecord(db: Db, input: UpdateRecordInput, actorId: string): Promise<DxcRecord> {
1478
+ const collection = db.collection<DxcRecord>(input.recordType);
1479
+ const recordFilter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
1480
+ const existing = await collection.findOne(recordFilter);
1481
+
1482
+ if (!existing) {
1483
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
1484
+ }
1485
+
1486
+ const now = new Date().toISOString();
1487
+ const set: Record<string, unknown> = {
1488
+ updatedAt: now,
1489
+ updatedBy: actorId
1490
+ };
1491
+ const unset: Record<string, ""> = {};
1492
+ const versioned = recordTypeSupportsVersionHistory(input.recordType);
1493
+
1494
+ if (input.title !== undefined) {
1495
+ set.title = input.title;
1496
+ }
1497
+
1498
+ if (input.summary !== undefined) {
1499
+ set.summary = input.summary;
1500
+ }
1501
+
1502
+ for (const [key, value] of Object.entries(input.fields ?? {})) {
1503
+ assertFieldName(key);
1504
+ assertNotReservedRelationshipField(input.recordType, key);
1505
+ if (input.allowManagedFields) {
1506
+ assertNotReviewNotesField(input.recordType, key);
1507
+ assertNotVersionHistoryField(input.recordType, key);
1508
+ } else {
1509
+ assertNotManagedField(input.recordType, key);
1510
+ assertNotVersionedTypedField(input.recordType, key);
1511
+ }
1512
+ set[`fields.${key}`] = value;
1513
+ }
1514
+
1515
+ for (const key of input.unsetFields ?? []) {
1516
+ assertFieldName(key);
1517
+ if (input.allowManagedFields) {
1518
+ assertNotReviewNotesField(input.recordType, key);
1519
+ assertNotVersionHistoryField(input.recordType, key);
1520
+ } else {
1521
+ assertNotManagedField(input.recordType, key);
1522
+ assertNotVersionedTypedField(input.recordType, key);
1523
+ }
1524
+ unset[`fields.${key}`] = "";
1525
+ }
1526
+
1527
+ if (versioned) {
1528
+ const previousSnapshot = createRecordVersionSnapshot(existing);
1529
+ const nextSnapshot = createRecordVersionSnapshot(applyRecordUpdate(existing, input));
1530
+ const changedFields = listSnapshotChanges(previousSnapshot, nextSnapshot);
1531
+ const existingVersionHistory = normalizeVersionHistory(existing.fields.versionHistory);
1532
+
1533
+ if (changedFields.length === 0) {
1534
+ return existing;
1535
+ }
1536
+
1537
+ set["fields.versionHistory"] = [
1538
+ ...existingVersionHistory,
1539
+ createVersionHistoryEntry({
1540
+ existingVersionHistory,
1541
+ previousSnapshot,
1542
+ nextSnapshot,
1543
+ changedFields,
1544
+ actorId,
1545
+ createdAt: now,
1546
+ revisionNote: input.revisionNote
1547
+ })
1548
+ ];
1549
+ }
1550
+
1551
+ const update = Object.keys(unset).length > 0 ? { $set: set, $unset: unset } : { $set: set };
1552
+ await collection.updateOne(recordFilter, update);
1553
+
1554
+ const updated = await collection.findOne(recordFilter);
1555
+ if (!updated) {
1556
+ throw new Error(`Updated record not found: ${input.recordType}/${input.id}`);
1557
+ }
1558
+
1559
+ return updated;
1560
+ }
1561
+
1562
+ function applyRecordUpdate(record: DxcRecord, input: UpdateRecordInput): DxcRecord {
1563
+ const fields = { ...record.fields };
1564
+
1565
+ for (const [key, value] of Object.entries(input.fields ?? {})) {
1566
+ fields[key] = value;
1567
+ }
1568
+
1569
+ for (const key of input.unsetFields ?? []) {
1570
+ delete fields[key];
1571
+ }
1572
+
1573
+ return {
1574
+ ...record,
1575
+ ...(input.title !== undefined ? { title: input.title } : {}),
1576
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
1577
+ fields
1578
+ };
1579
+ }
1580
+
1581
+ function createRecordVersionSnapshot(record: DxcRecord): RecordVersionSnapshot {
1582
+ return {
1583
+ ...(record.title !== undefined ? { title: record.title } : {}),
1584
+ ...(record.summary !== undefined ? { summary: record.summary } : {}),
1585
+ fields: Object.fromEntries(
1586
+ Object.entries(record.fields)
1587
+ .filter(([key]) => key !== VERSION_HISTORY_FIELD && key !== "reviewNotes")
1588
+ .map(([key, value]) => [key, cloneSnapshotValue(value)])
1589
+ )
1590
+ };
1591
+ }
1592
+
1593
+ function listSnapshotChanges(
1594
+ previousSnapshot: RecordVersionSnapshot,
1595
+ nextSnapshot: RecordVersionSnapshot
1596
+ ): string[] {
1597
+ const changedFields: string[] = [];
1598
+
1599
+ if (!valuesEqual(previousSnapshot.title, nextSnapshot.title)) {
1600
+ changedFields.push("title");
1601
+ }
1602
+
1603
+ if (!valuesEqual(previousSnapshot.summary, nextSnapshot.summary)) {
1604
+ changedFields.push("summary");
1605
+ }
1606
+
1607
+ const fieldNames = new Set([
1608
+ ...Object.keys(previousSnapshot.fields),
1609
+ ...Object.keys(nextSnapshot.fields)
1610
+ ]);
1611
+
1612
+ for (const fieldName of [...fieldNames].sort()) {
1613
+ if (!valuesEqual(previousSnapshot.fields[fieldName], nextSnapshot.fields[fieldName])) {
1614
+ changedFields.push(`fields.${fieldName}`);
1615
+ }
1616
+ }
1617
+
1618
+ return changedFields;
1619
+ }
1620
+
1621
+ function normalizeVersionHistory(value: unknown): RecordVersionHistoryEntry[] {
1622
+ if (!Array.isArray(value)) {
1623
+ return [];
1624
+ }
1625
+
1626
+ return value.filter(isVersionHistoryEntry);
1627
+ }
1628
+
1629
+ function createVersionHistoryEntry(input: {
1630
+ existingVersionHistory: RecordVersionHistoryEntry[];
1631
+ previousSnapshot: RecordVersionSnapshot;
1632
+ nextSnapshot: RecordVersionSnapshot;
1633
+ changedFields: string[];
1634
+ actorId: string;
1635
+ createdAt: string;
1636
+ revisionNote?: string;
1637
+ }): RecordVersionHistoryEntry {
1638
+ const fromVersion = input.existingVersionHistory.reduce(
1639
+ (currentVersion, entry) => Math.max(currentVersion, entry.toVersion),
1640
+ 1
1641
+ );
1642
+
1643
+ return {
1644
+ id: randomUUID(),
1645
+ fromVersion,
1646
+ toVersion: fromVersion + 1,
1647
+ createdAt: input.createdAt,
1648
+ createdBy: input.actorId,
1649
+ changedFields: input.changedFields,
1650
+ previousSnapshot: input.previousSnapshot,
1651
+ nextSnapshot: input.nextSnapshot,
1652
+ ...(input.revisionNote ? { revisionNote: input.revisionNote } : {})
1653
+ };
1654
+ }
1655
+
1656
+ function isVersionHistoryEntry(value: unknown): value is RecordVersionHistoryEntry {
1657
+ if (!value || typeof value !== "object") {
1658
+ return false;
1659
+ }
1660
+
1661
+ const candidate = value as Partial<RecordVersionHistoryEntry>;
1662
+ return (
1663
+ typeof candidate.id === "string" &&
1664
+ typeof candidate.fromVersion === "number" &&
1665
+ typeof candidate.toVersion === "number" &&
1666
+ typeof candidate.createdAt === "string" &&
1667
+ typeof candidate.createdBy === "string" &&
1668
+ Array.isArray(candidate.changedFields) &&
1669
+ typeof candidate.previousSnapshot === "object" &&
1670
+ typeof candidate.nextSnapshot === "object"
1671
+ );
1672
+ }
1673
+
1674
+ function cloneSnapshotValue(value: unknown): unknown {
1675
+ if (Array.isArray(value)) {
1676
+ return value.map((entry) => cloneSnapshotValue(entry));
1677
+ }
1678
+
1679
+ if (value && typeof value === "object") {
1680
+ return Object.fromEntries(
1681
+ Object.entries(value as Record<string, unknown>)
1682
+ .sort(([left], [right]) => left.localeCompare(right))
1683
+ .map(([key, entry]) => [key, cloneSnapshotValue(entry)])
1684
+ );
1685
+ }
1686
+
1687
+ return value;
1688
+ }
1689
+
1690
+ function valuesEqual(left: unknown, right: unknown): boolean {
1691
+ return stableStringify(left) === stableStringify(right);
1692
+ }
1693
+
1694
+ function stableStringify(value: unknown): string {
1695
+ return JSON.stringify(cloneSnapshotValue(value));
1696
+ }
1697
+
1698
+ export async function archiveRecord(db: Db, input: ArchiveRecordInput, actorId: string): Promise<DxcRecord> {
1699
+ const collection = db.collection<DxcRecord>(input.recordType);
1700
+ const recordFilter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
1701
+ const existing = await collection.findOne(recordFilter);
1702
+
1703
+ if (!existing) {
1704
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
1705
+ }
1706
+
1707
+ if ((input.supersededByType && !input.supersededById) || (!input.supersededByType && input.supersededById)) {
1708
+ throw new Error("supersededByType and supersededById must be provided together.");
1709
+ }
1710
+
1711
+ const supersedingRecord =
1712
+ input.supersededByType && input.supersededById
1713
+ ? await getRecord(db, input.supersededByType, input.supersededById, {
1714
+ workspaceId: existing.workspaceId
1715
+ })
1716
+ : null;
1717
+
1718
+ if (input.supersededByType && input.supersededById && !supersedingRecord) {
1719
+ throw new Error(`Superseding record not found: ${input.supersededByType}/${input.supersededById}`);
1720
+ }
1721
+
1722
+ const now = new Date().toISOString();
1723
+ const links = [...existing.links];
1724
+
1725
+ if (input.supersededByType && input.supersededById) {
1726
+ links.push({
1727
+ toType: input.supersededByType,
1728
+ toId: supersedingRecord?._id ?? input.supersededById,
1729
+ relationship: "superseded_by",
1730
+ createdAt: now,
1731
+ createdBy: actorId
1732
+ });
1733
+ }
1734
+
1735
+ await collection.updateOne(
1736
+ recordFilter,
1737
+ {
1738
+ $set: {
1739
+ links,
1740
+ archivedAt: now,
1741
+ archivedBy: actorId,
1742
+ archiveReason: input.reason ?? "Archived",
1743
+ updatedAt: now,
1744
+ updatedBy: actorId
1745
+ }
1746
+ }
1747
+ );
1748
+
1749
+ const updated = await collection.findOne(recordFilter);
1750
+ if (!updated) {
1751
+ throw new Error(`Archived record not found: ${input.recordType}/${input.id}`);
1752
+ }
1753
+
1754
+ return updated;
1755
+ }
1756
+
1757
+ export async function linkRecords(
1758
+ db: Db,
1759
+ input: {
1760
+ fromType: CollectionName;
1761
+ fromId: string;
1762
+ toType: CollectionName;
1763
+ toId: string;
1764
+ workspaceId?: string;
1765
+ relationship?: string;
1766
+ },
1767
+ actorId: string
1768
+ ): Promise<DxcRecord> {
1769
+ const sourceCollection = db.collection<DxcRecord>(input.fromType);
1770
+ const source = await getRecord(db, input.fromType, input.fromId, {
1771
+ workspaceId: input.workspaceId
1772
+ });
1773
+ const target = await getRecord(db, input.toType, input.toId, {
1774
+ workspaceId: input.workspaceId
1775
+ });
1776
+
1777
+ if (!source) {
1778
+ throw new Error(`Source record not found: ${input.fromType}/${input.fromId}`);
1779
+ }
1780
+
1781
+ if (!target) {
1782
+ throw new Error(`Target record not found: ${input.toType}/${input.toId}`);
1783
+ }
1784
+
1785
+ assertLinkWorkspaceBoundary(source, target);
1786
+
1787
+ const now = new Date().toISOString();
1788
+ const link: RecordLink = {
1789
+ toType: input.toType,
1790
+ toId: target._id,
1791
+ relationship: input.relationship ?? "related_to",
1792
+ createdAt: now,
1793
+ createdBy: actorId
1794
+ };
1795
+
1796
+ await sourceCollection.updateOne(
1797
+ scopedRecordFilter(input.fromType, source._id, input.workspaceId),
1798
+ {
1799
+ $push: { links: link },
1800
+ $set: {
1801
+ updatedAt: now,
1802
+ updatedBy: actorId
1803
+ }
1804
+ }
1805
+ );
1806
+
1807
+ const updated = await sourceCollection.findOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId));
1808
+ if (!updated) {
1809
+ throw new Error(`Updated source record not found: ${input.fromType}/${input.fromId}`);
1810
+ }
1811
+
1812
+ return updated;
1813
+ }
1814
+
1815
+ export async function unlinkRecords(
1816
+ db: Db,
1817
+ input: UnlinkRecordsInput,
1818
+ actorId: string
1819
+ ): Promise<DxcRecord> {
1820
+ const sourceCollection = db.collection<DxcRecord>(input.fromType);
1821
+ const source = await getRecord(db, input.fromType, input.fromId, {
1822
+ workspaceId: input.workspaceId
1823
+ });
1824
+ const target = await getRecord(db, input.toType, input.toId, {
1825
+ workspaceId: input.workspaceId
1826
+ });
1827
+
1828
+ if (!source) {
1829
+ throw new Error(`Source record not found: ${input.fromType}/${input.fromId}`);
1830
+ }
1831
+
1832
+ if (!target) {
1833
+ throw new Error(`Target record not found: ${input.toType}/${input.toId}`);
1834
+ }
1835
+
1836
+ assertLinkWorkspaceBoundary(source, target);
1837
+
1838
+ const relationship = input.relationship ?? "related_to";
1839
+ const remainingLinks = source.links.filter(
1840
+ (link) =>
1841
+ !(
1842
+ link.toType === input.toType &&
1843
+ link.toId === target._id &&
1844
+ link.relationship === relationship
1845
+ )
1846
+ );
1847
+
1848
+ if (remainingLinks.length === source.links.length) {
1849
+ return source;
1850
+ }
1851
+
1852
+ const now = new Date().toISOString();
1853
+ await sourceCollection.updateOne(
1854
+ scopedRecordFilter(input.fromType, source._id, input.workspaceId),
1855
+ {
1856
+ $set: {
1857
+ links: remainingLinks,
1858
+ updatedAt: now,
1859
+ updatedBy: actorId
1860
+ }
1861
+ }
1862
+ );
1863
+
1864
+ const updated = await sourceCollection.findOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId));
1865
+ if (!updated) {
1866
+ throw new Error(`Updated source record not found: ${input.fromType}/${input.fromId}`);
1867
+ }
1868
+
1869
+ return updated;
1870
+ }
1871
+
1872
+ function assertFieldName(key: string): void {
1873
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {
1874
+ throw new Error(`Invalid field name "${key}". Field updates only support top-level field names.`);
1875
+ }
1876
+ }
1877
+
1878
+ function assertNoReservedRelationshipFields(
1879
+ recordType: CollectionName,
1880
+ fields: Record<string, unknown> | undefined
1881
+ ): void {
1882
+ for (const key of Object.keys(fields ?? {})) {
1883
+ assertNotReservedRelationshipField(recordType, key);
1884
+ }
1885
+ }
1886
+
1887
+ function assertNoReviewNotesField(recordType: CollectionName, fields: Record<string, unknown> | undefined): void {
1888
+ for (const key of Object.keys(fields ?? {})) {
1889
+ assertNotReviewNotesField(recordType, key);
1890
+ }
1891
+ }
1892
+
1893
+ function assertNoManagedField(recordType: CollectionName, fields: Record<string, unknown> | undefined): void {
1894
+ for (const key of Object.keys(fields ?? {})) {
1895
+ assertNotManagedField(recordType, key);
1896
+ }
1897
+ }
1898
+
1899
+ function assertNotReservedRelationshipField(recordType: CollectionName, key: string): void {
1900
+ if (key === "workspaceId" && recordTypeRequiresWorkspace(recordType)) {
1901
+ throw new Error(
1902
+ `fields.${key} is reserved for the workspace boundary on ${recordType}. Use the top-level ${key} argument instead.`
1903
+ );
1904
+ }
1905
+
1906
+ if (key === "initiativeId" && REMOVED_INITIATIVE_FIELD_RECORD_TYPES.includes(recordType)) {
1907
+ throw new Error(
1908
+ `fields.${key} belongs to the removed Initiative layer on ${recordType}. Records are scoped directly to workspace now.`
1909
+ );
1910
+ }
1911
+
1912
+ if ((RESERVED_RELATIONSHIP_FIELDS[recordType] ?? []).includes(key)) {
1913
+ throw new Error(
1914
+ `fields.${key} is reserved for relationships on ${recordType}. Use the typed relationship argument or link_records instead.`
1915
+ );
1916
+ }
1917
+ }
1918
+
1919
+ function assertNotManagedField(recordType: CollectionName, key: string): void {
1920
+ assertNotReviewNotesField(recordType, key);
1921
+ assertNotVersionHistoryField(recordType, key);
1922
+ assertNotChangeManagedField(recordType, key);
1923
+ assertNotCommitmentManagedField(recordType, key);
1924
+ assertNotDeferralManagedField(recordType, key);
1925
+ assertNotEstimateManagedField(recordType, key);
1926
+ assertNotBenefitsManagedField(recordType, key);
1927
+ assertNotEnvironmentManagedField(recordType, key);
1928
+ assertNotComponentManagedField(recordType, key);
1929
+ assertNotDecisionLedgerManagedField(recordType, key);
1930
+ assertNotTaskLedgerManagedField(recordType, key);
1931
+ assertNotDecisionInputManagedField(recordType, key);
1932
+ assertNotJournalEntryManagedField(recordType, key);
1933
+ }
1934
+
1935
+ function assertNotVersionedTypedField(recordType: CollectionName, key: string): void {
1936
+ if (!(VERSIONED_TYPED_FIELDS[recordType] ?? []).includes(key)) {
1937
+ return;
1938
+ }
1939
+
1940
+ throw new Error(`fields.${key} is managed on ${recordType}. Use ${versionedUpdateToolName(recordType)} to change it.`);
1941
+ }
1942
+
1943
+ function assertNotReviewNotesField(recordType: CollectionName, key: string): void {
1944
+ if (key !== "reviewNotes" || !recordTypeSupportsReviewNotes(recordType)) {
1945
+ return;
1946
+ }
1947
+
1948
+ throw new Error(
1949
+ `fields.reviewNotes is append-only on ${recordType}. Use append_review_note instead of setting or unsetting it directly.`
1950
+ );
1951
+ }
1952
+
1953
+ function assertNotVersionHistoryField(recordType: CollectionName, key: string): void {
1954
+ if (key !== VERSION_HISTORY_FIELD || !recordTypeSupportsVersionHistory(recordType)) {
1955
+ return;
1956
+ }
1957
+
1958
+ throw new Error(
1959
+ `fields.versionHistory is append-only on ${recordType}. Current content changes record version history automatically.`
1960
+ );
1961
+ }
1962
+
1963
+ function assertNotChangeManagedField(recordType: CollectionName, key: string): void {
1964
+ if (recordType !== "changes" || !(CHANGE_MANAGED_FIELDS as readonly string[]).includes(key)) {
1965
+ return;
1966
+ }
1967
+
1968
+ throw new Error(
1969
+ `fields.${key} is managed on changes. Use create_change for the baseline and append_change_event for event history or plan revisions.`
1970
+ );
1971
+ }
1972
+
1973
+ function assertNotCommitmentManagedField(recordType: CollectionName, key: string): void {
1974
+ if (recordType !== "commitments" || !(COMMITMENT_MANAGED_FIELDS as readonly string[]).includes(key)) {
1975
+ return;
1976
+ }
1977
+
1978
+ throw new Error(
1979
+ `fields.${key} is managed on commitments. Use create_commitment instead of setting or unsetting it directly.`
1980
+ );
1981
+ }
1982
+
1983
+ function assertNotDeferralManagedField(recordType: CollectionName, key: string): void {
1984
+ if (recordType !== "deferrals" || !(DEFERRAL_MANAGED_FIELDS as readonly string[]).includes(key)) {
1985
+ return;
1986
+ }
1987
+
1988
+ throw new Error(
1989
+ `fields.${key} is managed on deferrals. Use create_deferral for the baseline and append_deferral_event for condition history or resolution.`
1990
+ );
1991
+ }
1992
+
1993
+ function assertNotEstimateManagedField(recordType: CollectionName, key: string): void {
1994
+ if (recordType !== "estimates" || !(ESTIMATE_MANAGED_FIELDS as readonly string[]).includes(key)) {
1995
+ return;
1996
+ }
1997
+
1998
+ throw new Error(
1999
+ `fields.${key} is managed on estimates. Use create_estimate or update_estimate instead of setting or unsetting it directly.`
2000
+ );
2001
+ }
2002
+
2003
+ function assertNotBenefitsManagedField(recordType: CollectionName, key: string): void {
2004
+ if (recordType !== "benefits" || !(BENEFITS_MANAGED_FIELDS as readonly string[]).includes(key)) {
2005
+ return;
2006
+ }
2007
+
2008
+ throw new Error(
2009
+ `fields.${key} is managed on benefits. Use create_benefits or update_benefits instead of setting or unsetting it directly.`
2010
+ );
2011
+ }
2012
+
2013
+ function assertNotEnvironmentManagedField(recordType: CollectionName, key: string): void {
2014
+ if (recordType !== "environments" || !(ENVIRONMENT_MANAGED_FIELDS as readonly string[]).includes(key)) {
2015
+ return;
2016
+ }
2017
+
2018
+ throw new Error(
2019
+ `fields.${key} is managed on environments. Use create_environment or update_environment instead of setting or unsetting it directly.`
2020
+ );
2021
+ }
2022
+
2023
+ function assertNotComponentManagedField(recordType: CollectionName, key: string): void {
2024
+ if (recordType !== "components" || !(COMPONENT_MANAGED_FIELDS as readonly string[]).includes(key)) {
2025
+ return;
2026
+ }
2027
+
2028
+ throw new Error(
2029
+ `fields.${key} is managed on components. Use create_component or update_component instead of setting or unsetting it directly.`
2030
+ );
2031
+ }
2032
+
2033
+ function assertNotDecisionLedgerManagedField(recordType: CollectionName, key: string): void {
2034
+ if (recordType !== "decisions" || !(DECISION_LEDGER_MANAGED_FIELDS as readonly string[]).includes(key)) {
2035
+ return;
2036
+ }
2037
+
2038
+ throw new Error(
2039
+ `fields.${key} is managed on decisions. Use create_decision or append_decision_entry instead of setting or unsetting it directly.`
2040
+ );
2041
+ }
2042
+
2043
+ function assertNotTaskLedgerManagedField(recordType: CollectionName, key: string): void {
2044
+ if (recordType !== "tasks" || !(TASK_LEDGER_MANAGED_FIELDS as readonly string[]).includes(key)) {
2045
+ return;
2046
+ }
2047
+
2048
+ throw new Error(
2049
+ `fields.${key} is managed on tasks. Use create_task or append_task_entry instead of setting or unsetting it directly.`
2050
+ );
2051
+ }
2052
+
2053
+ function assertNotDecisionInputManagedField(recordType: CollectionName, key: string): void {
2054
+ if (recordType !== "decisions" || !(DECISION_INPUT_MANAGED_FIELDS as readonly string[]).includes(key)) {
2055
+ return;
2056
+ }
2057
+
2058
+ throw new Error(
2059
+ `fields.${key} is managed on decisions. Use link_decision_input to record decision inputs.`
2060
+ );
2061
+ }
2062
+
2063
+ function assertNotJournalEntryManagedField(recordType: CollectionName, key: string): void {
2064
+ if (recordType !== "journal_entries" || !(JOURNAL_ENTRY_MANAGED_FIELDS as readonly string[]).includes(key)) {
2065
+ return;
2066
+ }
2067
+
2068
+ throw new Error(
2069
+ `fields.${key} is managed on journal entries. Use append_journal_note or append_journal_summary instead of setting or unsetting it directly.`
2070
+ );
2071
+ }
2072
+
2073
+ function linkMatches(link: RecordLink, relationship: string | undefined): boolean {
2074
+ return !relationship || link.relationship === relationship;
2075
+ }
2076
+
2077
+ function recordTypeSupportsReviewNotes(recordType: CollectionName): recordType is ReviewableRecordType {
2078
+ return (REVIEW_NOTE_RECORD_TYPES as readonly string[]).includes(recordType);
2079
+ }
2080
+
2081
+ function recordTypeSupportsVersionHistory(recordType: CollectionName): boolean {
2082
+ return (VERSIONED_RECORD_TYPES as readonly string[]).includes(recordType);
2083
+ }
2084
+
2085
+ function versionedUpdateToolName(recordType: CollectionName): string {
2086
+ if (recordType === "environments") {
2087
+ return "update_environment";
2088
+ }
2089
+
2090
+ if (recordType === "components") {
2091
+ return "update_component";
2092
+ }
2093
+
2094
+ if (recordType === "estimates") {
2095
+ return "update_estimate";
2096
+ }
2097
+
2098
+ if (recordType === "benefits") {
2099
+ return "update_benefits";
2100
+ }
2101
+
2102
+ if (recordType === "statements") {
2103
+ return "update_statement";
2104
+ }
2105
+
2106
+ return recordType === "expectations" ? "update_expectation" : "update_requirement";
2107
+ }
2108
+
2109
+ function isCurrentCollection(recordType: RuntimeCollectionName): recordType is CollectionName {
2110
+ return (COLLECTION_NAMES as readonly string[]).includes(recordType);
2111
+ }
2112
+
2113
+ function recordTypeRequiresWorkspace(recordType: RuntimeCollectionName): boolean {
2114
+ return recordType !== "workspaces" && recordType !== DXCOMPLETE_TICKET_COLLECTION_NAME;
2115
+ }
2116
+
2117
+ function readRequiredWorkspaceId(workspaceId: string | undefined, recordType: RuntimeCollectionName): string {
2118
+ const trimmed = workspaceId?.trim();
2119
+
2120
+ if (!trimmed) {
2121
+ throw new Error(`${recordType} records require workspaceId.`);
2122
+ }
2123
+
2124
+ return trimmed;
2125
+ }
2126
+
2127
+ function workspaceIdForCreate(recordType: CollectionName, workspaceId: string | undefined): string | undefined {
2128
+ if (!recordTypeRequiresWorkspace(recordType)) {
2129
+ if (workspaceId?.trim()) {
2130
+ throw new Error("Workspace records do not accept workspaceId.");
2131
+ }
2132
+ return undefined;
2133
+ }
2134
+
2135
+ return readRequiredWorkspaceId(workspaceId, recordType);
2136
+ }
2137
+
2138
+ async function allocateReadableId(
2139
+ db: Db,
2140
+ recordType: ReadableIdCollectionName,
2141
+ workspaceId: string | undefined,
2142
+ actorId: string,
2143
+ now: string,
2144
+ session: ClientSession
2145
+ ): Promise<string> {
2146
+ const scopedWorkspaceId = readRequiredWorkspaceId(workspaceId, recordType);
2147
+ const sequenceId = `${scopedWorkspaceId}:${recordType}`;
2148
+ const sequence = await db.collection<ReadableIdSequenceRecord>(READABLE_ID_SEQUENCES_COLLECTION).findOneAndUpdate(
2149
+ { _id: sequenceId },
2150
+ {
2151
+ $inc: { nextNumber: 1 },
2152
+ $set: {
2153
+ updatedAt: now,
2154
+ updatedBy: actorId
2155
+ },
2156
+ $setOnInsert: {
2157
+ _id: sequenceId,
2158
+ workspaceId: scopedWorkspaceId,
2159
+ recordType,
2160
+ createdAt: now,
2161
+ createdBy: actorId
2162
+ }
2163
+ },
2164
+ {
2165
+ upsert: true,
2166
+ returnDocument: "after",
2167
+ session
2168
+ }
2169
+ );
2170
+
2171
+ if (!sequence || !Number.isInteger(sequence.nextNumber) || sequence.nextNumber < 1) {
2172
+ throw new Error(`Readable ID sequence was not allocated for ${recordType}.`);
2173
+ }
2174
+
2175
+ return `${READABLE_ID_TYPE_CODES[recordType]}-${String(sequence.nextNumber).padStart(4, "0")}`;
2176
+ }
2177
+
2178
+ type ReadableIdSequenceRecord = {
2179
+ _id: string;
2180
+ workspaceId: string;
2181
+ recordType: ReadableIdCollectionName;
2182
+ nextNumber: number;
2183
+ createdAt: string;
2184
+ createdBy: string;
2185
+ updatedAt: string;
2186
+ updatedBy: string;
2187
+ };
2188
+
2189
+ function recordTypeSupportsReadableId(recordType: RuntimeCollectionName): recordType is ReadableIdCollectionName {
2190
+ return Object.hasOwn(READABLE_ID_TYPE_CODES, recordType);
2191
+ }
2192
+
2193
+ function normalizeReadableId(value: string): string {
2194
+ return value.trim().toUpperCase();
2195
+ }
2196
+
2197
+ function recordIdentityFilter(recordType: RuntimeCollectionName, id: string): Record<string, unknown> {
2198
+ if (!recordTypeSupportsReadableId(recordType)) {
2199
+ return { _id: id };
2200
+ }
2201
+
2202
+ return {
2203
+ $or: [
2204
+ { _id: id },
2205
+ { readableId: normalizeReadableId(id) }
2206
+ ]
2207
+ };
2208
+ }
2209
+
2210
+ function scopedRecordFilter(
2211
+ recordType: CollectionName,
2212
+ id: string,
2213
+ workspaceId: string | undefined
2214
+ ): Record<string, unknown> {
2215
+ const filter = recordIdentityFilter(recordType, id);
2216
+
2217
+ if (recordTypeRequiresWorkspace(recordType)) {
2218
+ filter.workspaceId = readRequiredWorkspaceId(workspaceId, recordType);
2219
+ }
2220
+
2221
+ return filter;
2222
+ }
2223
+
2224
+ async function assertWorkspaceExists(db: Db, workspaceId: string): Promise<DxcRecord> {
2225
+ const workspace = await db.collection<DxcRecord>("workspaces").findOne({
2226
+ _id: workspaceId,
2227
+ archivedAt: { $exists: false }
2228
+ });
2229
+
2230
+ if (!workspace) {
2231
+ throw new Error(`Workspace not found: workspaces/${workspaceId}`);
2232
+ }
2233
+
2234
+ return workspace;
2235
+ }
2236
+
2237
+ function recordBelongsToWorkspace(record: DxcRecord, workspaceId: string | undefined): boolean {
2238
+ return !workspaceId || record.recordType === "workspaces" || record.workspaceId === workspaceId;
2239
+ }
2240
+
2241
+ function assertLinkWorkspaceBoundary(source: DxcRecord, target: DxcRecord): void {
2242
+ if (!source.workspaceId || !target.workspaceId) {
2243
+ return;
2244
+ }
2245
+
2246
+ if (source.workspaceId !== target.workspaceId) {
2247
+ throw new Error(
2248
+ `Cannot link records across workspaces: ${source.recordType}/${source._id} is in ${source.workspaceId}, while ${target.recordType}/${target._id} is in ${target.workspaceId}.`
2249
+ );
2250
+ }
2251
+ }
2252
+
2253
+ function ticketOwnerFilter(id: string, actor: ActorContext): Record<string, unknown> {
2254
+ return {
2255
+ _id: id,
2256
+ "fields.ownerActorId": actor.actorId
2257
+ };
2258
+ }
2259
+
2260
+ function normalizeTicketEntries(value: unknown): DxcompleteTicketEntry[] {
2261
+ if (!Array.isArray(value)) {
2262
+ return [];
2263
+ }
2264
+
2265
+ return value.flatMap((entry, index) => normalizeTicketEntry(entry, index));
2266
+ }
2267
+
2268
+ function normalizeTicketEntry(entry: unknown, index: number): DxcompleteTicketEntry[] {
2269
+ if (!entry || typeof entry !== "object") {
2270
+ return [];
2271
+ }
2272
+
2273
+ const candidate = entry as Record<string, unknown>;
2274
+ const body = typeof candidate.body === "string" ? candidate.body : "";
2275
+
2276
+ if (!body) {
2277
+ return [];
2278
+ }
2279
+
2280
+ const createdAt = typeof candidate.createdAt === "string" ? candidate.createdAt : new Date(0).toISOString();
2281
+ const createdBy = typeof candidate.createdBy === "string" ? candidate.createdBy : RUNTIME_ACTOR_ID;
2282
+ const direction =
2283
+ candidate.direction === "dxcomplete_reply" || candidate.direction === "submitter_entry"
2284
+ ? candidate.direction
2285
+ : "submitter_entry";
2286
+ const normalized: DxcompleteTicketEntry = {
2287
+ id: typeof candidate.id === "string" && candidate.id ? candidate.id : `legacy-entry-${index + 1}`,
2288
+ body,
2289
+ createdAt,
2290
+ createdBy,
2291
+ direction
2292
+ };
2293
+
2294
+ if (typeof candidate.addressedToActorId === "string" && candidate.addressedToActorId) {
2295
+ normalized.addressedToActorId = candidate.addressedToActorId;
2296
+ }
2297
+
2298
+ if (typeof candidate.readAt === "string" && candidate.readAt) {
2299
+ normalized.readAt = candidate.readAt;
2300
+ }
2301
+
2302
+ return [normalized];
2303
+ }