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,1463 @@
1
+ import { randomUUID } from "node:crypto";
2
+ export const COLLECTION_NAMES = [
3
+ "workspaces",
4
+ "statements",
5
+ "journal_entries",
6
+ "environments",
7
+ "components",
8
+ "estimates",
9
+ "benefits",
10
+ "expectations",
11
+ "requirements",
12
+ "tasks",
13
+ "commitments",
14
+ "deferrals",
15
+ "changes",
16
+ "decisions",
17
+ "risks"
18
+ ];
19
+ export const LEGACY_COLLECTION_NAMES = [
20
+ "engagements",
21
+ "initiatives",
22
+ "service_charters",
23
+ "cost_baselines",
24
+ "cost_actuals",
25
+ "benefit_measurements"
26
+ ];
27
+ export const DXCOMPLETE_TICKET_COLLECTION_NAME = "dxcomplete_tickets";
28
+ export const LEGACY_INTAKE_COLLECTION_NAME = "intake_items";
29
+ export const LEGACY_PRIVATE_COLLECTION_NAMES = [LEGACY_INTAKE_COLLECTION_NAME];
30
+ export const INDEX_COLLECTION_NAMES = [...COLLECTION_NAMES, DXCOMPLETE_TICKET_COLLECTION_NAME];
31
+ export const LINK_SCAN_COLLECTION_NAMES = [...COLLECTION_NAMES, ...LEGACY_COLLECTION_NAMES];
32
+ export const READABLE_ID_SEQUENCES_COLLECTION = "readable_id_sequences";
33
+ export const READABLE_ID_TYPE_CODES = {
34
+ statements: "STM",
35
+ journal_entries: "JRN",
36
+ environments: "ENV",
37
+ components: "CMP",
38
+ expectations: "EXP",
39
+ requirements: "REQ",
40
+ tasks: "TSK",
41
+ commitments: "CMT",
42
+ deferrals: "DFR",
43
+ decisions: "DEC",
44
+ changes: "CHG",
45
+ risks: "RSK",
46
+ estimates: "EST",
47
+ benefits: "BFT"
48
+ };
49
+ export const READABLE_ID_COLLECTION_NAMES = Object.keys(READABLE_ID_TYPE_CODES);
50
+ export const RUNTIME_ACTOR_ID = "dxcomplete-runtime";
51
+ const REVIEW_NOTE_RECORD_TYPES = ["expectations", "requirements"];
52
+ const VERSIONED_RECORD_TYPES = [
53
+ "statements",
54
+ "environments",
55
+ "components",
56
+ "expectations",
57
+ "requirements",
58
+ "estimates",
59
+ "benefits"
60
+ ];
61
+ const VERSION_HISTORY_FIELD = "versionHistory";
62
+ const CHANGE_MANAGED_FIELDS = [
63
+ "changePlan",
64
+ "executionSteps",
65
+ "rollbackPlan",
66
+ "riskImpact",
67
+ "plannedFor",
68
+ "events"
69
+ ];
70
+ const COMMITMENT_MANAGED_FIELDS = ["commitmentStatement", "reservations"];
71
+ const DEFERRAL_MANAGED_FIELDS = ["reason", "status", "conditions", "conditionEvents"];
72
+ const ESTIMATE_MANAGED_FIELDS = ["lineItems", "rollup"];
73
+ const BENEFITS_MANAGED_FIELDS = ["benefitItems", "rollup"];
74
+ const ENVIRONMENT_MANAGED_FIELDS = ["name", "description"];
75
+ const COMPONENT_MANAGED_FIELDS = [
76
+ "name",
77
+ "environmentId",
78
+ "kind",
79
+ "locator",
80
+ "identifiers",
81
+ "secretPointers",
82
+ "notes"
83
+ ];
84
+ const DECISION_LEDGER_MANAGED_FIELDS = [
85
+ "matter",
86
+ "entries",
87
+ "currentDecision",
88
+ "question",
89
+ "decision",
90
+ "decidedBy",
91
+ "rationale",
92
+ "argumentsConsidered",
93
+ "concerns",
94
+ "status"
95
+ ];
96
+ const TASK_LEDGER_MANAGED_FIELDS = [
97
+ "description",
98
+ "assignee",
99
+ "assignor",
100
+ "entries",
101
+ "currentStatus",
102
+ "details",
103
+ "status"
104
+ ];
105
+ const DECISION_INPUT_MANAGED_FIELDS = ["informedBy", "informedByIds", "inputRecords"];
106
+ const JOURNAL_ENTRY_MANAGED_FIELDS = ["kind", "body", "tag", "covers", "coveredBySummaryId"];
107
+ const JOURNAL_COMPACTION_THRESHOLD = 200;
108
+ const VERSIONED_TYPED_FIELDS = {
109
+ statements: ["statement", "source"],
110
+ expectations: ["statement", "successRecognition", "approvalState", "approvedBy", "approvedAt", "source"],
111
+ requirements: ["statement", "acceptanceCriteria", "priority", "status"],
112
+ estimates: ["lineItems", "rollup"],
113
+ benefits: ["benefitItems", "rollup"],
114
+ environments: ["name", "description"],
115
+ components: ["name", "environmentId", "kind", "locator", "identifiers", "secretPointers", "notes"]
116
+ };
117
+ const RESERVED_RELATIONSHIP_FIELDS = {
118
+ changes: ["requirementId"],
119
+ commitments: ["requirementIds", "expectationIds", "deferralId"],
120
+ deferrals: ["requirementIds", "expectationIds"],
121
+ estimates: ["requirementIds", "expectationIds"],
122
+ benefits: ["requirementIds", "expectationIds"],
123
+ expectations: ["statementId"],
124
+ requirements: ["expectationId"],
125
+ tasks: ["requirementId"]
126
+ };
127
+ const REMOVED_INITIATIVE_FIELD_RECORD_TYPES = [
128
+ "changes",
129
+ "estimates",
130
+ "benefits",
131
+ "expectations"
132
+ ];
133
+ export function assertCollectionName(value) {
134
+ if (COLLECTION_NAMES.includes(value)) {
135
+ return value;
136
+ }
137
+ throw new Error(`Unsupported record type "${value}".`);
138
+ }
139
+ export async function createRecord(db, recordType, input, actorId) {
140
+ assertNoReservedRelationshipFields(recordType, input.fields);
141
+ if (input.allowManagedFields) {
142
+ assertNoReviewNotesField(recordType, input.fields);
143
+ }
144
+ else {
145
+ assertNoManagedField(recordType, input.fields);
146
+ }
147
+ const now = new Date().toISOString();
148
+ const workspaceId = workspaceIdForCreate(recordType, input.workspaceId);
149
+ if (workspaceId) {
150
+ await assertWorkspaceExists(db, workspaceId);
151
+ }
152
+ const record = {
153
+ _id: input.id ?? randomUUID(),
154
+ recordType,
155
+ ...(workspaceId ? { workspaceId } : {}),
156
+ title: input.title,
157
+ summary: input.summary,
158
+ fields: input.fields ?? {},
159
+ links: [],
160
+ createdAt: now,
161
+ createdBy: actorId,
162
+ updatedAt: now,
163
+ updatedBy: actorId
164
+ };
165
+ if (recordTypeSupportsReadableId(recordType)) {
166
+ const session = db.client.startSession();
167
+ try {
168
+ await session.withTransaction(async () => {
169
+ record.readableId = await allocateReadableId(db, recordType, workspaceId, actorId, now, session);
170
+ await db.collection(recordType).insertOne(record, { session });
171
+ });
172
+ }
173
+ finally {
174
+ await session.endSession();
175
+ }
176
+ return record;
177
+ }
178
+ await db.collection(recordType).insertOne(record);
179
+ return record;
180
+ }
181
+ export async function listRecords(db, recordType, limit, options = {}) {
182
+ const filter = {};
183
+ if (recordTypeRequiresWorkspace(recordType)) {
184
+ filter.workspaceId = readRequiredWorkspaceId(options.workspaceId, recordType);
185
+ }
186
+ if (!options.includeArchived) {
187
+ filter.archivedAt = { $exists: false };
188
+ }
189
+ return db
190
+ .collection(recordType)
191
+ .find(filter)
192
+ .sort({ createdAt: -1 })
193
+ .limit(limit)
194
+ .toArray();
195
+ }
196
+ export async function getRecord(db, recordType, id, options = {}) {
197
+ const filter = recordIdentityFilter(recordType, id);
198
+ if (recordTypeRequiresWorkspace(recordType) &&
199
+ !options.allowAnyWorkspace &&
200
+ isCurrentCollection(recordType)) {
201
+ filter.workspaceId = readRequiredWorkspaceId(options.workspaceId, recordType);
202
+ }
203
+ return db.collection(recordType).findOne(filter);
204
+ }
205
+ export async function listLinkedRecords(db, input) {
206
+ const source = await getRecord(db, input.recordType, input.id, { workspaceId: input.workspaceId });
207
+ if (!source) {
208
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
209
+ }
210
+ const direction = input.direction ?? "both";
211
+ const result = {
212
+ source,
213
+ outbound: [],
214
+ inbound: []
215
+ };
216
+ if (direction === "outbound" || direction === "both") {
217
+ for (const link of source.links.filter((link) => linkMatches(link, input.relationship))) {
218
+ const target = await getRecord(db, link.toType, link.toId, {
219
+ workspaceId: source.workspaceId,
220
+ allowAnyWorkspace: !source.workspaceId
221
+ });
222
+ if (!target ||
223
+ (!input.includeArchived && target.archivedAt) ||
224
+ !recordBelongsToWorkspace(target, source.workspaceId)) {
225
+ continue;
226
+ }
227
+ result.outbound.push({
228
+ edge: {
229
+ fromType: source.recordType,
230
+ fromId: source._id,
231
+ ...link
232
+ },
233
+ record: target
234
+ });
235
+ }
236
+ }
237
+ if (direction === "inbound" || direction === "both") {
238
+ for (const collectionName of LINK_SCAN_COLLECTION_NAMES) {
239
+ const filter = {
240
+ links: {
241
+ $elemMatch: {
242
+ toType: input.recordType,
243
+ toId: source._id,
244
+ ...(input.relationship ? { relationship: input.relationship } : {})
245
+ }
246
+ }
247
+ };
248
+ if (source.workspaceId && recordTypeRequiresWorkspace(collectionName)) {
249
+ filter.workspaceId = source.workspaceId;
250
+ }
251
+ if (!input.includeArchived) {
252
+ filter.archivedAt = { $exists: false };
253
+ }
254
+ const records = await db.collection(collectionName).find(filter).toArray();
255
+ for (const record of records) {
256
+ for (const link of record.links.filter((link) => link.toType === input.recordType &&
257
+ link.toId === source._id &&
258
+ linkMatches(link, input.relationship))) {
259
+ result.inbound.push({
260
+ edge: {
261
+ fromType: record.recordType,
262
+ fromId: record._id,
263
+ ...link
264
+ },
265
+ record
266
+ });
267
+ }
268
+ }
269
+ }
270
+ }
271
+ return result;
272
+ }
273
+ export async function migrateLegacyIntakeItemsToDxcompleteTickets(db) {
274
+ const legacyCollection = db.collection(LEGACY_INTAKE_COLLECTION_NAME);
275
+ const ticketCollection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
276
+ const legacyRecords = await legacyCollection.find({}).toArray();
277
+ let copied = 0;
278
+ let skipped = 0;
279
+ for (const legacyRecord of legacyRecords) {
280
+ const existing = await ticketCollection.findOne({ _id: legacyRecord._id });
281
+ if (existing) {
282
+ skipped += 1;
283
+ continue;
284
+ }
285
+ const migratedRecord = {
286
+ ...legacyRecord,
287
+ recordType: DXCOMPLETE_TICKET_COLLECTION_NAME,
288
+ fields: {
289
+ ...legacyRecord.fields,
290
+ entries: normalizeTicketEntries(legacyRecord.fields.entries)
291
+ }
292
+ };
293
+ await ticketCollection.insertOne(migratedRecord);
294
+ copied += 1;
295
+ }
296
+ return { copied, skipped };
297
+ }
298
+ export async function createDxcompleteTicket(db, input, actor) {
299
+ const now = new Date().toISOString();
300
+ const entry = {
301
+ id: randomUUID(),
302
+ body: input.body,
303
+ createdAt: now,
304
+ createdBy: actor.actorId,
305
+ direction: "submitter_entry"
306
+ };
307
+ const record = {
308
+ _id: randomUUID(),
309
+ recordType: DXCOMPLETE_TICKET_COLLECTION_NAME,
310
+ title: input.title,
311
+ fields: {
312
+ ownerActorId: actor.actorId,
313
+ entries: [entry]
314
+ },
315
+ links: [],
316
+ createdAt: now,
317
+ createdBy: actor.actorId,
318
+ updatedAt: now,
319
+ updatedBy: actor.actorId
320
+ };
321
+ await db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME).insertOne(record);
322
+ return record;
323
+ }
324
+ export async function getDxcompleteTicket(db, id, actor) {
325
+ const record = await db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME).findOne(ticketOwnerFilter(id, actor));
326
+ if (!record) {
327
+ throw new Error(`DX Complete Ticket not found: ${id}`);
328
+ }
329
+ return record;
330
+ }
331
+ export async function listDxcompleteTickets(db, actor, limit, options = {}) {
332
+ const filter = {
333
+ "fields.ownerActorId": actor.actorId
334
+ };
335
+ if (!options.includeArchived) {
336
+ filter.archivedAt = { $exists: false };
337
+ }
338
+ return db
339
+ .collection(DXCOMPLETE_TICKET_COLLECTION_NAME)
340
+ .find(filter)
341
+ .sort({ updatedAt: -1 })
342
+ .limit(limit)
343
+ .toArray();
344
+ }
345
+ export async function appendDxcompleteTicket(db, input, actor) {
346
+ const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
347
+ const existing = await collection.findOne({
348
+ ...ticketOwnerFilter(input.id, actor),
349
+ archivedAt: { $exists: false }
350
+ });
351
+ if (!existing) {
352
+ throw new Error(`Active DX Complete Ticket not found: ${input.id}`);
353
+ }
354
+ const now = new Date().toISOString();
355
+ const entry = {
356
+ id: randomUUID(),
357
+ body: input.body,
358
+ createdAt: now,
359
+ createdBy: actor.actorId,
360
+ direction: "submitter_entry"
361
+ };
362
+ await collection.updateOne(ticketOwnerFilter(input.id, actor), {
363
+ $push: {
364
+ "fields.entries": entry
365
+ },
366
+ $set: {
367
+ updatedAt: now,
368
+ updatedBy: actor.actorId
369
+ }
370
+ });
371
+ return getDxcompleteTicket(db, input.id, actor);
372
+ }
373
+ export async function appendDxcompleteTicketReply(db, input, actorId = RUNTIME_ACTOR_ID) {
374
+ const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
375
+ const existing = await collection.findOne({
376
+ _id: input.id,
377
+ "fields.ownerActorId": input.addressedToActorId,
378
+ archivedAt: { $exists: false }
379
+ });
380
+ if (!existing) {
381
+ throw new Error(`Active DX Complete Ticket not found for addressed actor: ${input.id}`);
382
+ }
383
+ const now = new Date().toISOString();
384
+ const entry = {
385
+ id: randomUUID(),
386
+ body: input.body,
387
+ createdAt: now,
388
+ createdBy: actorId,
389
+ direction: "dxcomplete_reply",
390
+ addressedToActorId: input.addressedToActorId
391
+ };
392
+ await collection.updateOne({ _id: input.id }, {
393
+ $push: {
394
+ "fields.entries": entry
395
+ },
396
+ $set: {
397
+ updatedAt: now,
398
+ updatedBy: actorId
399
+ }
400
+ });
401
+ const record = await collection.findOne({ _id: input.id });
402
+ if (!record) {
403
+ throw new Error(`DX Complete Ticket not found after reply append: ${input.id}`);
404
+ }
405
+ return record;
406
+ }
407
+ export async function appendJournalNote(db, input, actorId) {
408
+ return createRecord(db, "journal_entries", {
409
+ workspaceId: input.workspaceId,
410
+ title: input.tag ? `Journal note: ${input.tag}` : "Journal note",
411
+ summary: input.body,
412
+ allowManagedFields: true,
413
+ fields: {
414
+ kind: "note",
415
+ body: input.body,
416
+ ...(input.tag ? { tag: input.tag } : {})
417
+ }
418
+ }, actorId);
419
+ }
420
+ export async function readJournal(db, input) {
421
+ const limit = clampJournalReadLimit(input.limit);
422
+ const filter = {
423
+ workspaceId: readRequiredWorkspaceId(input.workspaceId, "journal_entries")
424
+ };
425
+ if (!input.includeArchived) {
426
+ filter.archivedAt = { $exists: false };
427
+ filter["fields.kind"] = { $in: ["note", "summary"] };
428
+ }
429
+ const [entries, activeRawNoteCount] = await Promise.all([
430
+ db
431
+ .collection("journal_entries")
432
+ .find(filter)
433
+ .sort({ createdAt: 1 })
434
+ .limit(limit)
435
+ .toArray(),
436
+ db.collection("journal_entries").countDocuments({
437
+ workspaceId: input.workspaceId,
438
+ archivedAt: { $exists: false },
439
+ "fields.kind": "note"
440
+ })
441
+ ]);
442
+ return {
443
+ workspaceId: input.workspaceId,
444
+ readTier: input.includeArchived ? "cold" : "hot",
445
+ compaction: {
446
+ activeRawNoteCount,
447
+ threshold: JOURNAL_COMPACTION_THRESHOLD,
448
+ recommended: activeRawNoteCount >= JOURNAL_COMPACTION_THRESHOLD
449
+ },
450
+ entries
451
+ };
452
+ }
453
+ export async function getJournalEntry(db, input) {
454
+ const entry = await getRecord(db, "journal_entries", input.id, { workspaceId: input.workspaceId });
455
+ if (!entry) {
456
+ throw new Error(`Journal entry not found: journal_entries/${input.id}`);
457
+ }
458
+ return entry;
459
+ }
460
+ export async function appendJournalSummary(db, input, actorId) {
461
+ const coveredIds = [...new Set(input.covers.map((id) => id.trim()).filter(Boolean))];
462
+ if (coveredIds.length === 0) {
463
+ throw new Error("append_journal_summary requires at least one covered journal entry id.");
464
+ }
465
+ const coveredEntries = [];
466
+ for (const id of coveredIds) {
467
+ const entry = await getRecord(db, "journal_entries", id, { workspaceId: input.workspaceId });
468
+ if (!entry) {
469
+ throw new Error(`Covered journal entry not found: journal_entries/${id}`);
470
+ }
471
+ const kind = readJournalEntryKind(entry);
472
+ if (!kind) {
473
+ throw new Error(`Covered record is not a journal note or summary: journal_entries/${id}`);
474
+ }
475
+ coveredEntries.push(entry);
476
+ }
477
+ const summary = await createRecord(db, "journal_entries", {
478
+ workspaceId: input.workspaceId,
479
+ title: input.tag ? `Journal summary: ${input.tag}` : "Journal summary",
480
+ summary: input.body,
481
+ allowManagedFields: true,
482
+ fields: {
483
+ kind: "summary",
484
+ body: input.body,
485
+ covers: coveredEntries.map((entry) => entry._id),
486
+ ...(input.tag ? { tag: input.tag } : {})
487
+ }
488
+ }, actorId);
489
+ const now = new Date().toISOString();
490
+ await db.collection("journal_entries").updateMany({
491
+ workspaceId: input.workspaceId,
492
+ _id: { $in: coveredEntries.map((entry) => entry._id) },
493
+ archivedAt: { $exists: false }
494
+ }, {
495
+ $set: {
496
+ archivedAt: now,
497
+ archivedBy: actorId,
498
+ archiveReason: `Covered by journal summary ${summary._id}`,
499
+ "fields.coveredBySummaryId": summary._id,
500
+ updatedAt: now,
501
+ updatedBy: actorId
502
+ }
503
+ });
504
+ return summary;
505
+ }
506
+ function clampJournalReadLimit(limit) {
507
+ if (!limit) {
508
+ return 100;
509
+ }
510
+ return Math.min(Math.max(limit, 1), 500);
511
+ }
512
+ function readJournalEntryKind(record) {
513
+ if (record.fields.kind === "note" || record.fields.kind === "summary") {
514
+ return record.fields.kind;
515
+ }
516
+ return undefined;
517
+ }
518
+ export async function appendReviewNote(db, input, actorId) {
519
+ const collection = db.collection(input.recordType);
520
+ const filter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
521
+ const existing = await collection.findOne(filter);
522
+ if (!existing) {
523
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
524
+ }
525
+ const now = new Date().toISOString();
526
+ const note = {
527
+ id: randomUUID(),
528
+ body: input.body,
529
+ createdAt: now,
530
+ createdBy: actorId,
531
+ ...(input.important ? { important: true } : {})
532
+ };
533
+ await collection.updateOne(filter, {
534
+ $push: {
535
+ "fields.reviewNotes": note
536
+ },
537
+ $set: {
538
+ updatedAt: now,
539
+ updatedBy: actorId
540
+ }
541
+ });
542
+ const updated = await getRecord(db, input.recordType, input.id, { workspaceId: input.workspaceId });
543
+ if (!updated) {
544
+ throw new Error(`Record not found after review note append: ${input.recordType}/${input.id}`);
545
+ }
546
+ return updated;
547
+ }
548
+ export async function appendChangeEvent(db, input, actorId) {
549
+ const collection = db.collection("changes");
550
+ const filter = scopedRecordFilter("changes", input.changeId, input.workspaceId);
551
+ const existing = await collection.findOne(filter);
552
+ if (!existing) {
553
+ throw new Error(`Record not found: changes/${input.changeId}`);
554
+ }
555
+ const now = new Date().toISOString();
556
+ const event = {
557
+ ...input.event,
558
+ id: randomUUID(),
559
+ eventType: input.eventType,
560
+ createdAt: now,
561
+ createdBy: actorId
562
+ };
563
+ await collection.updateOne(filter, {
564
+ $push: {
565
+ "fields.events": event
566
+ },
567
+ $set: {
568
+ updatedAt: now,
569
+ updatedBy: actorId
570
+ }
571
+ });
572
+ const updated = await getRecord(db, "changes", input.changeId, { workspaceId: input.workspaceId });
573
+ if (!updated) {
574
+ throw new Error(`Record not found after change event append: changes/${input.changeId}`);
575
+ }
576
+ return updated;
577
+ }
578
+ export async function appendDeferralEvent(db, input, actorId) {
579
+ const collection = db.collection("deferrals");
580
+ const filter = scopedRecordFilter("deferrals", input.deferralId, input.workspaceId);
581
+ const existing = await collection.findOne(filter);
582
+ if (!existing) {
583
+ throw new Error(`Record not found: deferrals/${input.deferralId}`);
584
+ }
585
+ const now = new Date().toISOString();
586
+ const event = {
587
+ ...input.event,
588
+ id: randomUUID(),
589
+ eventType: input.eventType,
590
+ createdAt: now,
591
+ createdBy: actorId
592
+ };
593
+ const { conditions, status } = applyDeferralEventState(existing, event, actorId, now);
594
+ await collection.updateOne(filter, {
595
+ $push: {
596
+ "fields.conditionEvents": event
597
+ },
598
+ $set: {
599
+ "fields.conditions": conditions,
600
+ "fields.status": status,
601
+ updatedAt: now,
602
+ updatedBy: actorId
603
+ }
604
+ });
605
+ const updated = await getRecord(db, "deferrals", input.deferralId, { workspaceId: input.workspaceId });
606
+ if (!updated) {
607
+ throw new Error(`Record not found after deferral event append: deferrals/${input.deferralId}`);
608
+ }
609
+ return updated;
610
+ }
611
+ export async function appendDecisionEntry(db, input, actorId) {
612
+ const collection = db.collection("decisions");
613
+ const filter = scopedRecordFilter("decisions", input.decisionId, input.workspaceId);
614
+ const existing = await collection.findOne(filter);
615
+ if (!existing) {
616
+ throw new Error(`Record not found: decisions/${input.decisionId}`);
617
+ }
618
+ assertDecisionEntryInput(input);
619
+ const now = new Date().toISOString();
620
+ const entry = {
621
+ id: randomUUID(),
622
+ entryType: input.entryType,
623
+ body: input.body,
624
+ createdAt: now,
625
+ createdBy: actorId,
626
+ ...(input.decidedBy ? { decidedBy: input.decidedBy } : {}),
627
+ ...(input.rationale ? { rationale: input.rationale } : {})
628
+ };
629
+ const update = {
630
+ $push: {
631
+ "fields.entries": entry
632
+ },
633
+ $set: {
634
+ updatedAt: now,
635
+ updatedBy: actorId
636
+ }
637
+ };
638
+ if (entry.entryType === "decision") {
639
+ update.$set["fields.currentDecision"] = decisionEntryToCurrentDecision(entry);
640
+ }
641
+ await collection.updateOne(filter, update);
642
+ const updated = await getRecord(db, "decisions", input.decisionId, { workspaceId: input.workspaceId });
643
+ if (!updated) {
644
+ throw new Error(`Record not found after decision entry append: decisions/${input.decisionId}`);
645
+ }
646
+ return updated;
647
+ }
648
+ export async function appendTaskEntry(db, input, actorId) {
649
+ const collection = db.collection("tasks");
650
+ const filter = scopedRecordFilter("tasks", input.taskId, input.workspaceId);
651
+ const existing = await collection.findOne(filter);
652
+ if (!existing) {
653
+ throw new Error(`Record not found: tasks/${input.taskId}`);
654
+ }
655
+ assertTaskEntryInput(input);
656
+ const now = new Date().toISOString();
657
+ const entry = {
658
+ id: randomUUID(),
659
+ entryType: input.entryType,
660
+ body: input.body,
661
+ createdAt: now,
662
+ createdBy: actorId,
663
+ ...(input.status ? { status: input.status } : {})
664
+ };
665
+ const update = {
666
+ $push: {
667
+ "fields.entries": entry
668
+ },
669
+ $set: {
670
+ updatedAt: now,
671
+ updatedBy: actorId
672
+ }
673
+ };
674
+ if (entry.entryType === "status_change") {
675
+ update.$set["fields.currentStatus"] = taskEntryToCurrentStatus(entry);
676
+ }
677
+ await collection.updateOne(filter, update);
678
+ const updated = await getRecord(db, "tasks", input.taskId, { workspaceId: input.workspaceId });
679
+ if (!updated) {
680
+ throw new Error(`Record not found after task entry append: tasks/${input.taskId}`);
681
+ }
682
+ return updated;
683
+ }
684
+ export function decisionEntryToCurrentDecision(entry) {
685
+ return {
686
+ entryId: entry.id,
687
+ body: entry.body,
688
+ createdAt: entry.createdAt,
689
+ createdBy: entry.createdBy,
690
+ ...(entry.decidedBy ? { decidedBy: entry.decidedBy } : {}),
691
+ ...(entry.rationale ? { rationale: entry.rationale } : {})
692
+ };
693
+ }
694
+ export function taskEntryToCurrentStatus(entry) {
695
+ if (entry.entryType !== "status_change" || !entry.status) {
696
+ throw new Error("Task current status can only derive from a status_change entry.");
697
+ }
698
+ return {
699
+ entryId: entry.id,
700
+ status: entry.status,
701
+ body: entry.body,
702
+ createdAt: entry.createdAt,
703
+ createdBy: entry.createdBy
704
+ };
705
+ }
706
+ function assertDecisionEntryInput(input) {
707
+ if (input.entryType !== "decision" && (input.decidedBy || input.rationale)) {
708
+ throw new Error("decidedBy and rationale are only valid on decision entries.");
709
+ }
710
+ }
711
+ function assertTaskEntryInput(input) {
712
+ if (input.entryType === "status_change" && !input.status) {
713
+ throw new Error("status_change entries require status.");
714
+ }
715
+ if (input.entryType !== "status_change" && input.status) {
716
+ throw new Error("status is only valid on status_change entries.");
717
+ }
718
+ }
719
+ function applyDeferralEventState(existing, event, actorId, now) {
720
+ const conditions = normalizeDeferralConditions(existing.fields.conditions);
721
+ let status = typeof existing.fields.status === "string" ? existing.fields.status : "open";
722
+ switch (event.eventType) {
723
+ case "condition_addressed":
724
+ return {
725
+ conditions: updateDeferralConditionState(conditions, event, "addressed", actorId, now),
726
+ status
727
+ };
728
+ case "condition_reopened":
729
+ return {
730
+ conditions: updateDeferralConditionState(conditions, event, "open", actorId, now),
731
+ status
732
+ };
733
+ case "condition_note_added":
734
+ assertDeferralConditionExists(conditions, event);
735
+ return { conditions, status };
736
+ case "deferral_resolved":
737
+ status = "resolved";
738
+ return { conditions, status };
739
+ case "deferral_abandoned":
740
+ status = "abandoned";
741
+ return { conditions, status };
742
+ }
743
+ }
744
+ function normalizeDeferralConditions(value) {
745
+ if (!Array.isArray(value)) {
746
+ return [];
747
+ }
748
+ return value.filter(isDeferralCondition);
749
+ }
750
+ function isDeferralCondition(value) {
751
+ if (!value || typeof value !== "object") {
752
+ return false;
753
+ }
754
+ const condition = value;
755
+ return (typeof condition.id === "string" &&
756
+ typeof condition.statement === "string" &&
757
+ (condition.state === "open" || condition.state === "addressed") &&
758
+ typeof condition.createdAt === "string" &&
759
+ typeof condition.createdBy === "string" &&
760
+ typeof condition.updatedAt === "string" &&
761
+ typeof condition.updatedBy === "string");
762
+ }
763
+ function updateDeferralConditionState(conditions, event, state, actorId, now) {
764
+ const conditionId = readRequiredDeferralEventString(event, "conditionId");
765
+ let found = false;
766
+ const updated = conditions.map((condition) => {
767
+ if (condition.id !== conditionId) {
768
+ return condition;
769
+ }
770
+ found = true;
771
+ return {
772
+ ...condition,
773
+ state,
774
+ updatedAt: now,
775
+ updatedBy: actorId
776
+ };
777
+ });
778
+ if (!found) {
779
+ throw new Error(`Deferral condition not found: ${conditionId}`);
780
+ }
781
+ return updated;
782
+ }
783
+ function assertDeferralConditionExists(conditions, event) {
784
+ const conditionId = readRequiredDeferralEventString(event, "conditionId");
785
+ if (!conditions.some((condition) => condition.id === conditionId)) {
786
+ throw new Error(`Deferral condition not found: ${conditionId}`);
787
+ }
788
+ }
789
+ function readRequiredDeferralEventString(event, key) {
790
+ const value = event[key];
791
+ if (typeof value !== "string" || !value.trim()) {
792
+ throw new Error(`${event.eventType} requires ${key}.`);
793
+ }
794
+ return value;
795
+ }
796
+ export async function listUnreadDxcompleteTicketReplies(db, actor, limit) {
797
+ const records = await db
798
+ .collection(DXCOMPLETE_TICKET_COLLECTION_NAME)
799
+ .find({
800
+ "fields.ownerActorId": actor.actorId,
801
+ archivedAt: { $exists: false },
802
+ "fields.entries": {
803
+ $elemMatch: {
804
+ direction: "dxcomplete_reply",
805
+ addressedToActorId: actor.actorId,
806
+ readAt: { $exists: false }
807
+ }
808
+ }
809
+ })
810
+ .sort({ updatedAt: -1 })
811
+ .limit(limit)
812
+ .toArray();
813
+ return records.map((record) => {
814
+ const replies = normalizeTicketEntries(record.fields.entries).filter((entry) => entry.direction === "dxcomplete_reply" &&
815
+ entry.addressedToActorId === actor.actorId &&
816
+ !entry.readAt);
817
+ const replySummaries = replies.map((entry) => ({
818
+ id: entry.id,
819
+ createdAt: entry.createdAt,
820
+ createdBy: entry.createdBy,
821
+ direction: "dxcomplete_reply",
822
+ ...(entry.addressedToActorId ? { addressedToActorId: entry.addressedToActorId } : {})
823
+ }));
824
+ const newestReplyAt = replySummaries.reduce((current, entry) => (!current || entry.createdAt > current ? entry.createdAt : current), undefined);
825
+ return {
826
+ ticketId: record._id,
827
+ ...(record.title ? { title: record.title } : {}),
828
+ updatedAt: record.updatedAt,
829
+ unreadReplyCount: replySummaries.length,
830
+ ...(newestReplyAt ? { newestReplyAt } : {}),
831
+ replies: replySummaries
832
+ };
833
+ });
834
+ }
835
+ export async function readDxcompleteTicket(db, input, actor) {
836
+ const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
837
+ const existing = await collection.findOne(ticketOwnerFilter(input.id, actor));
838
+ if (!existing) {
839
+ throw new Error(`DX Complete Ticket not found: ${input.id}`);
840
+ }
841
+ const now = new Date().toISOString();
842
+ const entries = normalizeTicketEntries(existing.fields.entries);
843
+ let changed = false;
844
+ const nextEntries = entries.map((entry) => {
845
+ const shouldMark = entry.direction === "dxcomplete_reply" &&
846
+ entry.addressedToActorId === actor.actorId &&
847
+ !entry.readAt;
848
+ if (!shouldMark) {
849
+ return entry;
850
+ }
851
+ changed = true;
852
+ return {
853
+ ...entry,
854
+ readAt: now
855
+ };
856
+ });
857
+ if (!changed) {
858
+ return existing;
859
+ }
860
+ await collection.updateOne(ticketOwnerFilter(input.id, actor), {
861
+ $set: {
862
+ "fields.entries": nextEntries,
863
+ updatedAt: now,
864
+ updatedBy: actor.actorId
865
+ }
866
+ });
867
+ return getDxcompleteTicket(db, input.id, actor);
868
+ }
869
+ export async function archiveDxcompleteTicket(db, input, actor) {
870
+ const collection = db.collection(DXCOMPLETE_TICKET_COLLECTION_NAME);
871
+ const existing = await collection.findOne(ticketOwnerFilter(input.id, actor));
872
+ if (!existing) {
873
+ throw new Error(`DX Complete Ticket not found: ${input.id}`);
874
+ }
875
+ if (existing.archivedAt) {
876
+ return existing;
877
+ }
878
+ const now = new Date().toISOString();
879
+ await collection.updateOne(ticketOwnerFilter(input.id, actor), {
880
+ $set: {
881
+ archivedAt: now,
882
+ updatedAt: now,
883
+ updatedBy: actor.actorId
884
+ }
885
+ });
886
+ return getDxcompleteTicket(db, input.id, actor);
887
+ }
888
+ export async function updateRecord(db, input, actorId) {
889
+ const collection = db.collection(input.recordType);
890
+ const recordFilter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
891
+ const existing = await collection.findOne(recordFilter);
892
+ if (!existing) {
893
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
894
+ }
895
+ const now = new Date().toISOString();
896
+ const set = {
897
+ updatedAt: now,
898
+ updatedBy: actorId
899
+ };
900
+ const unset = {};
901
+ const versioned = recordTypeSupportsVersionHistory(input.recordType);
902
+ if (input.title !== undefined) {
903
+ set.title = input.title;
904
+ }
905
+ if (input.summary !== undefined) {
906
+ set.summary = input.summary;
907
+ }
908
+ for (const [key, value] of Object.entries(input.fields ?? {})) {
909
+ assertFieldName(key);
910
+ assertNotReservedRelationshipField(input.recordType, key);
911
+ if (input.allowManagedFields) {
912
+ assertNotReviewNotesField(input.recordType, key);
913
+ assertNotVersionHistoryField(input.recordType, key);
914
+ }
915
+ else {
916
+ assertNotManagedField(input.recordType, key);
917
+ assertNotVersionedTypedField(input.recordType, key);
918
+ }
919
+ set[`fields.${key}`] = value;
920
+ }
921
+ for (const key of input.unsetFields ?? []) {
922
+ assertFieldName(key);
923
+ if (input.allowManagedFields) {
924
+ assertNotReviewNotesField(input.recordType, key);
925
+ assertNotVersionHistoryField(input.recordType, key);
926
+ }
927
+ else {
928
+ assertNotManagedField(input.recordType, key);
929
+ assertNotVersionedTypedField(input.recordType, key);
930
+ }
931
+ unset[`fields.${key}`] = "";
932
+ }
933
+ if (versioned) {
934
+ const previousSnapshot = createRecordVersionSnapshot(existing);
935
+ const nextSnapshot = createRecordVersionSnapshot(applyRecordUpdate(existing, input));
936
+ const changedFields = listSnapshotChanges(previousSnapshot, nextSnapshot);
937
+ const existingVersionHistory = normalizeVersionHistory(existing.fields.versionHistory);
938
+ if (changedFields.length === 0) {
939
+ return existing;
940
+ }
941
+ set["fields.versionHistory"] = [
942
+ ...existingVersionHistory,
943
+ createVersionHistoryEntry({
944
+ existingVersionHistory,
945
+ previousSnapshot,
946
+ nextSnapshot,
947
+ changedFields,
948
+ actorId,
949
+ createdAt: now,
950
+ revisionNote: input.revisionNote
951
+ })
952
+ ];
953
+ }
954
+ const update = Object.keys(unset).length > 0 ? { $set: set, $unset: unset } : { $set: set };
955
+ await collection.updateOne(recordFilter, update);
956
+ const updated = await collection.findOne(recordFilter);
957
+ if (!updated) {
958
+ throw new Error(`Updated record not found: ${input.recordType}/${input.id}`);
959
+ }
960
+ return updated;
961
+ }
962
+ function applyRecordUpdate(record, input) {
963
+ const fields = { ...record.fields };
964
+ for (const [key, value] of Object.entries(input.fields ?? {})) {
965
+ fields[key] = value;
966
+ }
967
+ for (const key of input.unsetFields ?? []) {
968
+ delete fields[key];
969
+ }
970
+ return {
971
+ ...record,
972
+ ...(input.title !== undefined ? { title: input.title } : {}),
973
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
974
+ fields
975
+ };
976
+ }
977
+ function createRecordVersionSnapshot(record) {
978
+ return {
979
+ ...(record.title !== undefined ? { title: record.title } : {}),
980
+ ...(record.summary !== undefined ? { summary: record.summary } : {}),
981
+ fields: Object.fromEntries(Object.entries(record.fields)
982
+ .filter(([key]) => key !== VERSION_HISTORY_FIELD && key !== "reviewNotes")
983
+ .map(([key, value]) => [key, cloneSnapshotValue(value)]))
984
+ };
985
+ }
986
+ function listSnapshotChanges(previousSnapshot, nextSnapshot) {
987
+ const changedFields = [];
988
+ if (!valuesEqual(previousSnapshot.title, nextSnapshot.title)) {
989
+ changedFields.push("title");
990
+ }
991
+ if (!valuesEqual(previousSnapshot.summary, nextSnapshot.summary)) {
992
+ changedFields.push("summary");
993
+ }
994
+ const fieldNames = new Set([
995
+ ...Object.keys(previousSnapshot.fields),
996
+ ...Object.keys(nextSnapshot.fields)
997
+ ]);
998
+ for (const fieldName of [...fieldNames].sort()) {
999
+ if (!valuesEqual(previousSnapshot.fields[fieldName], nextSnapshot.fields[fieldName])) {
1000
+ changedFields.push(`fields.${fieldName}`);
1001
+ }
1002
+ }
1003
+ return changedFields;
1004
+ }
1005
+ function normalizeVersionHistory(value) {
1006
+ if (!Array.isArray(value)) {
1007
+ return [];
1008
+ }
1009
+ return value.filter(isVersionHistoryEntry);
1010
+ }
1011
+ function createVersionHistoryEntry(input) {
1012
+ const fromVersion = input.existingVersionHistory.reduce((currentVersion, entry) => Math.max(currentVersion, entry.toVersion), 1);
1013
+ return {
1014
+ id: randomUUID(),
1015
+ fromVersion,
1016
+ toVersion: fromVersion + 1,
1017
+ createdAt: input.createdAt,
1018
+ createdBy: input.actorId,
1019
+ changedFields: input.changedFields,
1020
+ previousSnapshot: input.previousSnapshot,
1021
+ nextSnapshot: input.nextSnapshot,
1022
+ ...(input.revisionNote ? { revisionNote: input.revisionNote } : {})
1023
+ };
1024
+ }
1025
+ function isVersionHistoryEntry(value) {
1026
+ if (!value || typeof value !== "object") {
1027
+ return false;
1028
+ }
1029
+ const candidate = value;
1030
+ return (typeof candidate.id === "string" &&
1031
+ typeof candidate.fromVersion === "number" &&
1032
+ typeof candidate.toVersion === "number" &&
1033
+ typeof candidate.createdAt === "string" &&
1034
+ typeof candidate.createdBy === "string" &&
1035
+ Array.isArray(candidate.changedFields) &&
1036
+ typeof candidate.previousSnapshot === "object" &&
1037
+ typeof candidate.nextSnapshot === "object");
1038
+ }
1039
+ function cloneSnapshotValue(value) {
1040
+ if (Array.isArray(value)) {
1041
+ return value.map((entry) => cloneSnapshotValue(entry));
1042
+ }
1043
+ if (value && typeof value === "object") {
1044
+ return Object.fromEntries(Object.entries(value)
1045
+ .sort(([left], [right]) => left.localeCompare(right))
1046
+ .map(([key, entry]) => [key, cloneSnapshotValue(entry)]));
1047
+ }
1048
+ return value;
1049
+ }
1050
+ function valuesEqual(left, right) {
1051
+ return stableStringify(left) === stableStringify(right);
1052
+ }
1053
+ function stableStringify(value) {
1054
+ return JSON.stringify(cloneSnapshotValue(value));
1055
+ }
1056
+ export async function archiveRecord(db, input, actorId) {
1057
+ const collection = db.collection(input.recordType);
1058
+ const recordFilter = scopedRecordFilter(input.recordType, input.id, input.workspaceId);
1059
+ const existing = await collection.findOne(recordFilter);
1060
+ if (!existing) {
1061
+ throw new Error(`Record not found: ${input.recordType}/${input.id}`);
1062
+ }
1063
+ if ((input.supersededByType && !input.supersededById) || (!input.supersededByType && input.supersededById)) {
1064
+ throw new Error("supersededByType and supersededById must be provided together.");
1065
+ }
1066
+ const supersedingRecord = input.supersededByType && input.supersededById
1067
+ ? await getRecord(db, input.supersededByType, input.supersededById, {
1068
+ workspaceId: existing.workspaceId
1069
+ })
1070
+ : null;
1071
+ if (input.supersededByType && input.supersededById && !supersedingRecord) {
1072
+ throw new Error(`Superseding record not found: ${input.supersededByType}/${input.supersededById}`);
1073
+ }
1074
+ const now = new Date().toISOString();
1075
+ const links = [...existing.links];
1076
+ if (input.supersededByType && input.supersededById) {
1077
+ links.push({
1078
+ toType: input.supersededByType,
1079
+ toId: supersedingRecord?._id ?? input.supersededById,
1080
+ relationship: "superseded_by",
1081
+ createdAt: now,
1082
+ createdBy: actorId
1083
+ });
1084
+ }
1085
+ await collection.updateOne(recordFilter, {
1086
+ $set: {
1087
+ links,
1088
+ archivedAt: now,
1089
+ archivedBy: actorId,
1090
+ archiveReason: input.reason ?? "Archived",
1091
+ updatedAt: now,
1092
+ updatedBy: actorId
1093
+ }
1094
+ });
1095
+ const updated = await collection.findOne(recordFilter);
1096
+ if (!updated) {
1097
+ throw new Error(`Archived record not found: ${input.recordType}/${input.id}`);
1098
+ }
1099
+ return updated;
1100
+ }
1101
+ export async function linkRecords(db, input, actorId) {
1102
+ const sourceCollection = db.collection(input.fromType);
1103
+ const source = await getRecord(db, input.fromType, input.fromId, {
1104
+ workspaceId: input.workspaceId
1105
+ });
1106
+ const target = await getRecord(db, input.toType, input.toId, {
1107
+ workspaceId: input.workspaceId
1108
+ });
1109
+ if (!source) {
1110
+ throw new Error(`Source record not found: ${input.fromType}/${input.fromId}`);
1111
+ }
1112
+ if (!target) {
1113
+ throw new Error(`Target record not found: ${input.toType}/${input.toId}`);
1114
+ }
1115
+ assertLinkWorkspaceBoundary(source, target);
1116
+ const now = new Date().toISOString();
1117
+ const link = {
1118
+ toType: input.toType,
1119
+ toId: target._id,
1120
+ relationship: input.relationship ?? "related_to",
1121
+ createdAt: now,
1122
+ createdBy: actorId
1123
+ };
1124
+ await sourceCollection.updateOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId), {
1125
+ $push: { links: link },
1126
+ $set: {
1127
+ updatedAt: now,
1128
+ updatedBy: actorId
1129
+ }
1130
+ });
1131
+ const updated = await sourceCollection.findOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId));
1132
+ if (!updated) {
1133
+ throw new Error(`Updated source record not found: ${input.fromType}/${input.fromId}`);
1134
+ }
1135
+ return updated;
1136
+ }
1137
+ export async function unlinkRecords(db, input, actorId) {
1138
+ const sourceCollection = db.collection(input.fromType);
1139
+ const source = await getRecord(db, input.fromType, input.fromId, {
1140
+ workspaceId: input.workspaceId
1141
+ });
1142
+ const target = await getRecord(db, input.toType, input.toId, {
1143
+ workspaceId: input.workspaceId
1144
+ });
1145
+ if (!source) {
1146
+ throw new Error(`Source record not found: ${input.fromType}/${input.fromId}`);
1147
+ }
1148
+ if (!target) {
1149
+ throw new Error(`Target record not found: ${input.toType}/${input.toId}`);
1150
+ }
1151
+ assertLinkWorkspaceBoundary(source, target);
1152
+ const relationship = input.relationship ?? "related_to";
1153
+ const remainingLinks = source.links.filter((link) => !(link.toType === input.toType &&
1154
+ link.toId === target._id &&
1155
+ link.relationship === relationship));
1156
+ if (remainingLinks.length === source.links.length) {
1157
+ return source;
1158
+ }
1159
+ const now = new Date().toISOString();
1160
+ await sourceCollection.updateOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId), {
1161
+ $set: {
1162
+ links: remainingLinks,
1163
+ updatedAt: now,
1164
+ updatedBy: actorId
1165
+ }
1166
+ });
1167
+ const updated = await sourceCollection.findOne(scopedRecordFilter(input.fromType, source._id, input.workspaceId));
1168
+ if (!updated) {
1169
+ throw new Error(`Updated source record not found: ${input.fromType}/${input.fromId}`);
1170
+ }
1171
+ return updated;
1172
+ }
1173
+ function assertFieldName(key) {
1174
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {
1175
+ throw new Error(`Invalid field name "${key}". Field updates only support top-level field names.`);
1176
+ }
1177
+ }
1178
+ function assertNoReservedRelationshipFields(recordType, fields) {
1179
+ for (const key of Object.keys(fields ?? {})) {
1180
+ assertNotReservedRelationshipField(recordType, key);
1181
+ }
1182
+ }
1183
+ function assertNoReviewNotesField(recordType, fields) {
1184
+ for (const key of Object.keys(fields ?? {})) {
1185
+ assertNotReviewNotesField(recordType, key);
1186
+ }
1187
+ }
1188
+ function assertNoManagedField(recordType, fields) {
1189
+ for (const key of Object.keys(fields ?? {})) {
1190
+ assertNotManagedField(recordType, key);
1191
+ }
1192
+ }
1193
+ function assertNotReservedRelationshipField(recordType, key) {
1194
+ if (key === "workspaceId" && recordTypeRequiresWorkspace(recordType)) {
1195
+ throw new Error(`fields.${key} is reserved for the workspace boundary on ${recordType}. Use the top-level ${key} argument instead.`);
1196
+ }
1197
+ if (key === "initiativeId" && REMOVED_INITIATIVE_FIELD_RECORD_TYPES.includes(recordType)) {
1198
+ throw new Error(`fields.${key} belongs to the removed Initiative layer on ${recordType}. Records are scoped directly to workspace now.`);
1199
+ }
1200
+ if ((RESERVED_RELATIONSHIP_FIELDS[recordType] ?? []).includes(key)) {
1201
+ throw new Error(`fields.${key} is reserved for relationships on ${recordType}. Use the typed relationship argument or link_records instead.`);
1202
+ }
1203
+ }
1204
+ function assertNotManagedField(recordType, key) {
1205
+ assertNotReviewNotesField(recordType, key);
1206
+ assertNotVersionHistoryField(recordType, key);
1207
+ assertNotChangeManagedField(recordType, key);
1208
+ assertNotCommitmentManagedField(recordType, key);
1209
+ assertNotDeferralManagedField(recordType, key);
1210
+ assertNotEstimateManagedField(recordType, key);
1211
+ assertNotBenefitsManagedField(recordType, key);
1212
+ assertNotEnvironmentManagedField(recordType, key);
1213
+ assertNotComponentManagedField(recordType, key);
1214
+ assertNotDecisionLedgerManagedField(recordType, key);
1215
+ assertNotTaskLedgerManagedField(recordType, key);
1216
+ assertNotDecisionInputManagedField(recordType, key);
1217
+ assertNotJournalEntryManagedField(recordType, key);
1218
+ }
1219
+ function assertNotVersionedTypedField(recordType, key) {
1220
+ if (!(VERSIONED_TYPED_FIELDS[recordType] ?? []).includes(key)) {
1221
+ return;
1222
+ }
1223
+ throw new Error(`fields.${key} is managed on ${recordType}. Use ${versionedUpdateToolName(recordType)} to change it.`);
1224
+ }
1225
+ function assertNotReviewNotesField(recordType, key) {
1226
+ if (key !== "reviewNotes" || !recordTypeSupportsReviewNotes(recordType)) {
1227
+ return;
1228
+ }
1229
+ throw new Error(`fields.reviewNotes is append-only on ${recordType}. Use append_review_note instead of setting or unsetting it directly.`);
1230
+ }
1231
+ function assertNotVersionHistoryField(recordType, key) {
1232
+ if (key !== VERSION_HISTORY_FIELD || !recordTypeSupportsVersionHistory(recordType)) {
1233
+ return;
1234
+ }
1235
+ throw new Error(`fields.versionHistory is append-only on ${recordType}. Current content changes record version history automatically.`);
1236
+ }
1237
+ function assertNotChangeManagedField(recordType, key) {
1238
+ if (recordType !== "changes" || !CHANGE_MANAGED_FIELDS.includes(key)) {
1239
+ return;
1240
+ }
1241
+ throw new Error(`fields.${key} is managed on changes. Use create_change for the baseline and append_change_event for event history or plan revisions.`);
1242
+ }
1243
+ function assertNotCommitmentManagedField(recordType, key) {
1244
+ if (recordType !== "commitments" || !COMMITMENT_MANAGED_FIELDS.includes(key)) {
1245
+ return;
1246
+ }
1247
+ throw new Error(`fields.${key} is managed on commitments. Use create_commitment instead of setting or unsetting it directly.`);
1248
+ }
1249
+ function assertNotDeferralManagedField(recordType, key) {
1250
+ if (recordType !== "deferrals" || !DEFERRAL_MANAGED_FIELDS.includes(key)) {
1251
+ return;
1252
+ }
1253
+ throw new Error(`fields.${key} is managed on deferrals. Use create_deferral for the baseline and append_deferral_event for condition history or resolution.`);
1254
+ }
1255
+ function assertNotEstimateManagedField(recordType, key) {
1256
+ if (recordType !== "estimates" || !ESTIMATE_MANAGED_FIELDS.includes(key)) {
1257
+ return;
1258
+ }
1259
+ throw new Error(`fields.${key} is managed on estimates. Use create_estimate or update_estimate instead of setting or unsetting it directly.`);
1260
+ }
1261
+ function assertNotBenefitsManagedField(recordType, key) {
1262
+ if (recordType !== "benefits" || !BENEFITS_MANAGED_FIELDS.includes(key)) {
1263
+ return;
1264
+ }
1265
+ throw new Error(`fields.${key} is managed on benefits. Use create_benefits or update_benefits instead of setting or unsetting it directly.`);
1266
+ }
1267
+ function assertNotEnvironmentManagedField(recordType, key) {
1268
+ if (recordType !== "environments" || !ENVIRONMENT_MANAGED_FIELDS.includes(key)) {
1269
+ return;
1270
+ }
1271
+ throw new Error(`fields.${key} is managed on environments. Use create_environment or update_environment instead of setting or unsetting it directly.`);
1272
+ }
1273
+ function assertNotComponentManagedField(recordType, key) {
1274
+ if (recordType !== "components" || !COMPONENT_MANAGED_FIELDS.includes(key)) {
1275
+ return;
1276
+ }
1277
+ throw new Error(`fields.${key} is managed on components. Use create_component or update_component instead of setting or unsetting it directly.`);
1278
+ }
1279
+ function assertNotDecisionLedgerManagedField(recordType, key) {
1280
+ if (recordType !== "decisions" || !DECISION_LEDGER_MANAGED_FIELDS.includes(key)) {
1281
+ return;
1282
+ }
1283
+ throw new Error(`fields.${key} is managed on decisions. Use create_decision or append_decision_entry instead of setting or unsetting it directly.`);
1284
+ }
1285
+ function assertNotTaskLedgerManagedField(recordType, key) {
1286
+ if (recordType !== "tasks" || !TASK_LEDGER_MANAGED_FIELDS.includes(key)) {
1287
+ return;
1288
+ }
1289
+ throw new Error(`fields.${key} is managed on tasks. Use create_task or append_task_entry instead of setting or unsetting it directly.`);
1290
+ }
1291
+ function assertNotDecisionInputManagedField(recordType, key) {
1292
+ if (recordType !== "decisions" || !DECISION_INPUT_MANAGED_FIELDS.includes(key)) {
1293
+ return;
1294
+ }
1295
+ throw new Error(`fields.${key} is managed on decisions. Use link_decision_input to record decision inputs.`);
1296
+ }
1297
+ function assertNotJournalEntryManagedField(recordType, key) {
1298
+ if (recordType !== "journal_entries" || !JOURNAL_ENTRY_MANAGED_FIELDS.includes(key)) {
1299
+ return;
1300
+ }
1301
+ throw new Error(`fields.${key} is managed on journal entries. Use append_journal_note or append_journal_summary instead of setting or unsetting it directly.`);
1302
+ }
1303
+ function linkMatches(link, relationship) {
1304
+ return !relationship || link.relationship === relationship;
1305
+ }
1306
+ function recordTypeSupportsReviewNotes(recordType) {
1307
+ return REVIEW_NOTE_RECORD_TYPES.includes(recordType);
1308
+ }
1309
+ function recordTypeSupportsVersionHistory(recordType) {
1310
+ return VERSIONED_RECORD_TYPES.includes(recordType);
1311
+ }
1312
+ function versionedUpdateToolName(recordType) {
1313
+ if (recordType === "environments") {
1314
+ return "update_environment";
1315
+ }
1316
+ if (recordType === "components") {
1317
+ return "update_component";
1318
+ }
1319
+ if (recordType === "estimates") {
1320
+ return "update_estimate";
1321
+ }
1322
+ if (recordType === "benefits") {
1323
+ return "update_benefits";
1324
+ }
1325
+ if (recordType === "statements") {
1326
+ return "update_statement";
1327
+ }
1328
+ return recordType === "expectations" ? "update_expectation" : "update_requirement";
1329
+ }
1330
+ function isCurrentCollection(recordType) {
1331
+ return COLLECTION_NAMES.includes(recordType);
1332
+ }
1333
+ function recordTypeRequiresWorkspace(recordType) {
1334
+ return recordType !== "workspaces" && recordType !== DXCOMPLETE_TICKET_COLLECTION_NAME;
1335
+ }
1336
+ function readRequiredWorkspaceId(workspaceId, recordType) {
1337
+ const trimmed = workspaceId?.trim();
1338
+ if (!trimmed) {
1339
+ throw new Error(`${recordType} records require workspaceId.`);
1340
+ }
1341
+ return trimmed;
1342
+ }
1343
+ function workspaceIdForCreate(recordType, workspaceId) {
1344
+ if (!recordTypeRequiresWorkspace(recordType)) {
1345
+ if (workspaceId?.trim()) {
1346
+ throw new Error("Workspace records do not accept workspaceId.");
1347
+ }
1348
+ return undefined;
1349
+ }
1350
+ return readRequiredWorkspaceId(workspaceId, recordType);
1351
+ }
1352
+ async function allocateReadableId(db, recordType, workspaceId, actorId, now, session) {
1353
+ const scopedWorkspaceId = readRequiredWorkspaceId(workspaceId, recordType);
1354
+ const sequenceId = `${scopedWorkspaceId}:${recordType}`;
1355
+ const sequence = await db.collection(READABLE_ID_SEQUENCES_COLLECTION).findOneAndUpdate({ _id: sequenceId }, {
1356
+ $inc: { nextNumber: 1 },
1357
+ $set: {
1358
+ updatedAt: now,
1359
+ updatedBy: actorId
1360
+ },
1361
+ $setOnInsert: {
1362
+ _id: sequenceId,
1363
+ workspaceId: scopedWorkspaceId,
1364
+ recordType,
1365
+ createdAt: now,
1366
+ createdBy: actorId
1367
+ }
1368
+ }, {
1369
+ upsert: true,
1370
+ returnDocument: "after",
1371
+ session
1372
+ });
1373
+ if (!sequence || !Number.isInteger(sequence.nextNumber) || sequence.nextNumber < 1) {
1374
+ throw new Error(`Readable ID sequence was not allocated for ${recordType}.`);
1375
+ }
1376
+ return `${READABLE_ID_TYPE_CODES[recordType]}-${String(sequence.nextNumber).padStart(4, "0")}`;
1377
+ }
1378
+ function recordTypeSupportsReadableId(recordType) {
1379
+ return Object.hasOwn(READABLE_ID_TYPE_CODES, recordType);
1380
+ }
1381
+ function normalizeReadableId(value) {
1382
+ return value.trim().toUpperCase();
1383
+ }
1384
+ function recordIdentityFilter(recordType, id) {
1385
+ if (!recordTypeSupportsReadableId(recordType)) {
1386
+ return { _id: id };
1387
+ }
1388
+ return {
1389
+ $or: [
1390
+ { _id: id },
1391
+ { readableId: normalizeReadableId(id) }
1392
+ ]
1393
+ };
1394
+ }
1395
+ function scopedRecordFilter(recordType, id, workspaceId) {
1396
+ const filter = recordIdentityFilter(recordType, id);
1397
+ if (recordTypeRequiresWorkspace(recordType)) {
1398
+ filter.workspaceId = readRequiredWorkspaceId(workspaceId, recordType);
1399
+ }
1400
+ return filter;
1401
+ }
1402
+ async function assertWorkspaceExists(db, workspaceId) {
1403
+ const workspace = await db.collection("workspaces").findOne({
1404
+ _id: workspaceId,
1405
+ archivedAt: { $exists: false }
1406
+ });
1407
+ if (!workspace) {
1408
+ throw new Error(`Workspace not found: workspaces/${workspaceId}`);
1409
+ }
1410
+ return workspace;
1411
+ }
1412
+ function recordBelongsToWorkspace(record, workspaceId) {
1413
+ return !workspaceId || record.recordType === "workspaces" || record.workspaceId === workspaceId;
1414
+ }
1415
+ function assertLinkWorkspaceBoundary(source, target) {
1416
+ if (!source.workspaceId || !target.workspaceId) {
1417
+ return;
1418
+ }
1419
+ if (source.workspaceId !== target.workspaceId) {
1420
+ throw new Error(`Cannot link records across workspaces: ${source.recordType}/${source._id} is in ${source.workspaceId}, while ${target.recordType}/${target._id} is in ${target.workspaceId}.`);
1421
+ }
1422
+ }
1423
+ function ticketOwnerFilter(id, actor) {
1424
+ return {
1425
+ _id: id,
1426
+ "fields.ownerActorId": actor.actorId
1427
+ };
1428
+ }
1429
+ function normalizeTicketEntries(value) {
1430
+ if (!Array.isArray(value)) {
1431
+ return [];
1432
+ }
1433
+ return value.flatMap((entry, index) => normalizeTicketEntry(entry, index));
1434
+ }
1435
+ function normalizeTicketEntry(entry, index) {
1436
+ if (!entry || typeof entry !== "object") {
1437
+ return [];
1438
+ }
1439
+ const candidate = entry;
1440
+ const body = typeof candidate.body === "string" ? candidate.body : "";
1441
+ if (!body) {
1442
+ return [];
1443
+ }
1444
+ const createdAt = typeof candidate.createdAt === "string" ? candidate.createdAt : new Date(0).toISOString();
1445
+ const createdBy = typeof candidate.createdBy === "string" ? candidate.createdBy : RUNTIME_ACTOR_ID;
1446
+ const direction = candidate.direction === "dxcomplete_reply" || candidate.direction === "submitter_entry"
1447
+ ? candidate.direction
1448
+ : "submitter_entry";
1449
+ const normalized = {
1450
+ id: typeof candidate.id === "string" && candidate.id ? candidate.id : `legacy-entry-${index + 1}`,
1451
+ body,
1452
+ createdAt,
1453
+ createdBy,
1454
+ direction
1455
+ };
1456
+ if (typeof candidate.addressedToActorId === "string" && candidate.addressedToActorId) {
1457
+ normalized.addressedToActorId = candidate.addressedToActorId;
1458
+ }
1459
+ if (typeof candidate.readAt === "string" && candidate.readAt) {
1460
+ normalized.readAt = candidate.readAt;
1461
+ }
1462
+ return [normalized];
1463
+ }