dxcomplete 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.env.example +0 -7
  2. package/README.md +18 -54
  3. package/dist/cli.js +0 -22
  4. package/dist/validate.js +10 -26
  5. package/docs/model.md +3 -3
  6. package/docs/taxonomy.md +1 -1
  7. package/package.json +23 -23
  8. package/templates/process/README.md +1 -1
  9. package/dist/http/service.d.ts +0 -7
  10. package/dist/http/service.js +0 -725
  11. package/dist/mcp/docs.d.ts +0 -114
  12. package/dist/mcp/docs.js +0 -626
  13. package/dist/mcp/server.d.ts +0 -20
  14. package/dist/mcp/server.js +0 -3059
  15. package/dist/runtime/auth.d.ts +0 -162
  16. package/dist/runtime/auth.js +0 -394
  17. package/dist/runtime/check.d.ts +0 -7
  18. package/dist/runtime/check.js +0 -16
  19. package/dist/runtime/config.d.ts +0 -17
  20. package/dist/runtime/config.js +0 -93
  21. package/dist/runtime/mongo.d.ts +0 -9
  22. package/dist/runtime/mongo.js +0 -56
  23. package/dist/runtime/records.d.ts +0 -427
  24. package/dist/runtime/records.js +0 -2092
  25. package/scripts/check-env-surface.mjs +0 -136
  26. package/scripts/check-public-copy.mjs +0 -263
  27. package/scripts/check-service-boundary.mjs +0 -63
  28. package/scripts/dogfood-work-order.mjs +0 -506
  29. package/scripts/smoke-mcp-http.mjs +0 -4026
  30. package/src/cli.ts +0 -268
  31. package/src/http/server.ts +0 -314
  32. package/src/http/service.ts +0 -934
  33. package/src/init.ts +0 -262
  34. package/src/install-manifest.ts +0 -144
  35. package/src/mcp/docs.ts +0 -777
  36. package/src/mcp/server.ts +0 -4580
  37. package/src/package-root.ts +0 -31
  38. package/src/runtime/actor.ts +0 -61
  39. package/src/runtime/auth.ts +0 -673
  40. package/src/runtime/check.ts +0 -18
  41. package/src/runtime/config.ts +0 -128
  42. package/src/runtime/mongo.ts +0 -89
  43. package/src/runtime/records.ts +0 -3205
  44. package/src/runtime/workspace.ts +0 -155
  45. package/src/upgrade.ts +0 -356
  46. package/src/validate.ts +0 -141
  47. package/src/version.ts +0 -16
package/src/mcp/server.ts DELETED
@@ -1,4580 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import * as z from "zod/v4";
4
- import { DOC_PAGE_IDS, DOC_REFERENCE, getDocReference } from "./docs.js";
5
- import { createLocalActorContext, type ActorContext } from "../runtime/actor.js";
6
- import type { WorkspaceRole } from "../runtime/auth.js";
7
- import type { DxRuntime } from "../runtime/mongo.js";
8
- import {
9
- DXCOMPLETE_PACKAGE_VERSION,
10
- MCP_SURFACE_ID,
11
- WORKSPACE_COMPATIBILITY_VERSION
12
- } from "../version.js";
13
- import {
14
- COLLECTION_NAMES,
15
- RUNTIME_ACTOR_ID,
16
- appendChangeEvent,
17
- appendDecisionEntry,
18
- appendDeferralEvent,
19
- appendIncidentEntry,
20
- appendJournalNote,
21
- appendJournalSummary,
22
- appendProblemEntry,
23
- appendReviewNote,
24
- appendRiskEntry,
25
- appendSupportRequestEntry,
26
- appendTaskEntry,
27
- archiveRecord,
28
- appendDxcompleteTicket,
29
- archiveDxcompleteTicket,
30
- type CollectionName,
31
- type DecisionEntry,
32
- decisionEntryToCurrentDecision,
33
- createDxcompleteTicket,
34
- createRecord,
35
- getJournalEntry,
36
- getRecord,
37
- type IncidentEntry,
38
- incidentEntryToCurrentSeverity,
39
- incidentEntryToCurrentStatus,
40
- linkRecords,
41
- listDxcompleteTickets,
42
- listLinkedRecords,
43
- listUnreadDxcompleteTicketReplies,
44
- listRecords,
45
- readJournal,
46
- readDxcompleteTicket,
47
- type ProblemEntry,
48
- problemEntryToCurrentRootCause,
49
- problemEntryToCurrentStatus,
50
- type RiskEntry,
51
- riskEntryToCurrentAssessment,
52
- riskEntryToCurrentStatus,
53
- riskEntryToCurrentTreatment,
54
- type SupportRequestEntry,
55
- supportRequestEntryToCurrentStatus,
56
- type TaskEntry,
57
- taskEntryToCurrentStatus,
58
- unlinkRecords,
59
- updateRecord
60
- } from "../runtime/records.js";
61
-
62
- const collectionSchema = z.enum(COLLECTION_NAMES);
63
- type WorkspaceScopedCollectionName = Exclude<CollectionName, "workspaces">;
64
- const workspaceScopedCollectionNames = COLLECTION_NAMES.filter(
65
- (name): name is WorkspaceScopedCollectionName => name !== "workspaces"
66
- ) as [WorkspaceScopedCollectionName, ...WorkspaceScopedCollectionName[]];
67
- const hostedCollectionSchema = z.enum(workspaceScopedCollectionNames);
68
- const amountSchema = z.number().finite().optional();
69
- const requiredAmountSchema = z.number().finite().nonnegative();
70
- const currencySchema = z.string().min(3).max(12).optional();
71
- const requiredCurrencySchema = z.string().min(3).max(12);
72
- const workspaceIdSchema = z.string().min(1);
73
- const workspaceModeSchema = z.enum(["transformation", "greenfield", "limited-disclosure"]);
74
- const expectationApprovalStateSchema = z.enum(["draft", "approved", "not_approved", "superseded"]);
75
- const requirementStatusSchema = z.enum(["draft", "ready", "approved", "superseded"]);
76
- const taskStatusSchema = z.enum(["open", "in_progress", "blocked", "done"]);
77
- const decisionEntryTypeSchema = z.enum(["argument", "decision", "note"]);
78
- const taskEntryTypeSchema = z.enum(["comment", "status_change", "note"]);
79
- const riskEntryTypeSchema = z.enum(["identified", "assessment", "treatment", "monitor_note", "closed", "reopened"]);
80
- const riskLevelSchema = z.enum(["low", "medium", "high"]);
81
- const riskTreatmentSchema = z.enum(["accept", "mitigate", "transfer", "avoid"]);
82
- const incidentEntryTypeSchema = z.enum(["detected", "update", "severity", "resolved", "reopened", "note"]);
83
- const incidentSeveritySchema = z.enum(["low", "medium", "high", "critical"]);
84
- const problemEntryTypeSchema = z.enum([
85
- "identified",
86
- "investigation",
87
- "root_cause",
88
- "known_error",
89
- "resolved",
90
- "reopened",
91
- "note"
92
- ]);
93
- const supportRequestEntryTypeSchema = z.enum(["raised", "triage", "update", "escalated", "resolved", "reopened", "note"]);
94
- const maintenanceCadenceSchema = z.object({
95
- count: z.number().int().min(1),
96
- unit: z.enum(["day", "week", "month", "quarter", "year"])
97
- }).strict();
98
- type MaintenanceCadenceInput = z.infer<typeof maintenanceCadenceSchema>;
99
- const valueMetricMeasurementSchema = z.object({
100
- value: z.number().finite(),
101
- measuredAt: z.string().min(1)
102
- }).strict();
103
- const valueMetricSchema = z.object({
104
- id: z.string().min(1).optional(),
105
- name: z.string().min(1),
106
- unit: z.string().min(1),
107
- direction: z.enum(["lower_is_better", "higher_is_better"]),
108
- baseline: valueMetricMeasurementSchema,
109
- actual: valueMetricMeasurementSchema.optional()
110
- }).strict();
111
- type ValueMetricInput = z.infer<typeof valueMetricSchema>;
112
- const reviewableRecordTypeSchema = z.enum(["expectations", "requirements"]);
113
- const decisionInputRecordTypes = [
114
- "expectations",
115
- "requirements",
116
- "commitments",
117
- "deferrals",
118
- "journal_entries",
119
- "environments",
120
- "components",
121
- "estimates",
122
- "benefits",
123
- "maintenance_schedules",
124
- "support_requests",
125
- "value_realizations",
126
- "risks",
127
- "changes",
128
- "incidents",
129
- "problems",
130
- "decisions"
131
- ] as const;
132
- const decisionInputRecordTypeSchema = z.enum(decisionInputRecordTypes);
133
- type DecisionInputRecordType = (typeof decisionInputRecordTypes)[number];
134
- const changeEventTypeSchema = z.enum([
135
- "notice_given",
136
- "veto_recorded",
137
- "decision_recorded",
138
- "result_reported",
139
- "recovery_recorded",
140
- "plan_revised",
141
- "note_added"
142
- ]);
143
- const changeTypeSchema = z.enum(["standard", "normal", "emergency"]);
144
- const changeImpactGradeSchema = z.enum(["minor", "significant", "major"]);
145
- const changeVetoRoleSchema = z.enum(["Owner", "Engineer"]);
146
- const changeDecisionSchema = z.enum(["proceed", "defer", "cancel"]);
147
- const changeResultSchema = z.enum(["completed", "failed", "rolled_back"]);
148
- const gitCommitReferenceSchema = z.object({
149
- commit: z.string().min(1),
150
- repository: z.string().min(1).optional(),
151
- url: z.string().min(1).optional()
152
- });
153
- const deferralEventTypeSchema = z.enum([
154
- "condition_addressed",
155
- "condition_reopened",
156
- "condition_note_added",
157
- "deferral_resolved",
158
- "deferral_abandoned"
159
- ]);
160
- const journalTagSchema = z.string().min(1).max(80);
161
- const recordFieldsSchema = z.record(z.string(), z.unknown()).optional();
162
- const amountInputSchema = z.union([
163
- z.object({
164
- kind: z.literal("single"),
165
- value: requiredAmountSchema
166
- }),
167
- z.object({
168
- kind: z.literal("range"),
169
- min: requiredAmountSchema,
170
- expected: requiredAmountSchema,
171
- max: requiredAmountSchema
172
- })
173
- ]);
174
- const timingSchema = z.enum(["one_time", "recurring"]);
175
- const estimateLineItemSchema = z.object({
176
- id: z.string().min(1).optional(),
177
- label: z.string().min(1),
178
- timing: timingSchema,
179
- period: z.string().min(1).optional(),
180
- currency: requiredCurrencySchema,
181
- amount: amountInputSchema
182
- }).strict();
183
- type EstimateLineItemInput = z.infer<typeof estimateLineItemSchema>;
184
- const benefitItemSchema = z.object({
185
- id: z.string().min(1).optional(),
186
- label: z.string().min(1),
187
- timing: timingSchema.optional(),
188
- period: z.string().min(1).optional(),
189
- currency: requiredCurrencySchema.optional(),
190
- amount: amountInputSchema.optional()
191
- }).strict();
192
- type BenefitItemInput = z.infer<typeof benefitItemSchema>;
193
- const componentLocatorSchema = z.record(z.string().min(1), z.unknown()).refine(
194
- (value) => Object.keys(value).length > 0,
195
- "locator must be a non-empty structured object."
196
- );
197
- const componentIdentifiersSchema = z.record(z.string().min(1), z.unknown()).optional();
198
- const secretPointerSchema = z.object({
199
- store: z.string().min(1),
200
- key: z.string().min(1),
201
- location: z.string().min(1).optional(),
202
- url: z.string().min(1).optional(),
203
- note: z.string().min(1).optional()
204
- }).strict();
205
- type ComponentLocatorInput = z.infer<typeof componentLocatorSchema>;
206
- type ComponentIdentifiersInput = z.infer<typeof componentIdentifiersSchema>;
207
- type SecretPointerInput = z.infer<typeof secretPointerSchema>;
208
- const decisionInitialEntrySchema = z.object({
209
- entryType: decisionEntryTypeSchema,
210
- body: z.string().min(1),
211
- decidedBy: z.string().min(1).optional(),
212
- rationale: z.string().min(1).optional()
213
- }).strict();
214
- type DecisionInitialEntryInput = z.infer<typeof decisionInitialEntrySchema>;
215
- const initialDecisionSchema = z.object({
216
- body: z.string().min(1),
217
- decidedBy: z.string().min(1).optional(),
218
- rationale: z.string().min(1).optional()
219
- }).strict();
220
- type InitialDecisionInput = z.infer<typeof initialDecisionSchema>;
221
- const fieldNameSchema = z
222
- .string()
223
- .regex(/^[A-Za-z_][A-Za-z0-9_-]*$/, "Only top-level field names are supported.");
224
- const SERVER_STARTED_AT = new Date().toISOString();
225
- const STATEMENT_TYPED_FIELDS = ["statement", "source"];
226
- const EXPECTATION_TYPED_FIELDS = [
227
- "statement",
228
- "successRecognition",
229
- "approvalState",
230
- "approvedBy",
231
- "approvedAt",
232
- "source"
233
- ];
234
- const REQUIREMENT_TYPED_FIELDS = [
235
- "statement",
236
- "acceptanceCriteria",
237
- "priority",
238
- "status"
239
- ];
240
- const CHANGE_TYPED_FIELDS = [
241
- "changePlan",
242
- "executionSteps",
243
- "rollbackPlan",
244
- "riskImpact",
245
- "changeType",
246
- "impactGrade",
247
- "emergencyImportance",
248
- "emergencyImmediacy",
249
- "emergencyRationaleGaps",
250
- "plannedFor",
251
- "events"
252
- ];
253
- const COMMITMENT_TYPED_FIELDS = ["commitmentStatement", "reservations"];
254
- const DEFERRAL_TYPED_FIELDS = ["reason", "status", "conditions", "conditionEvents"];
255
- const ESTIMATE_TYPED_FIELDS = ["lineItems", "rollup", "versionHistory"];
256
- const BENEFITS_TYPED_FIELDS = ["benefitItems", "rollup", "versionHistory"];
257
- const ENVIRONMENT_TYPED_FIELDS = ["name", "description", "versionHistory"];
258
- const COMPONENT_TYPED_FIELDS = [
259
- "name",
260
- "environmentId",
261
- "kind",
262
- "locator",
263
- "identifiers",
264
- "secretPointers",
265
- "notes",
266
- "versionHistory"
267
- ];
268
- const MAINTENANCE_SCHEDULE_TYPED_FIELDS = [
269
- "name",
270
- "kind",
271
- "cadence",
272
- "startDate",
273
- "rationale",
274
- "notes",
275
- "versionHistory"
276
- ];
277
- const SUPPORT_REQUEST_TYPED_FIELDS = [
278
- "workspaceId",
279
- "reporter",
280
- "kind",
281
- "reportedExperience",
282
- "entries",
283
- "currentStatus",
284
- "status"
285
- ];
286
- const VALUE_REALIZATION_TYPED_FIELDS = ["metrics", "versionHistory"];
287
- const OBSOLETE_EXPECTATION_FIELDS = ["confirmationState", "ratifiedBy", "ratifiedAt"];
288
- const DECISION_INPUT_FIELDS = ["informedBy", "informedByIds", "inputRecords"];
289
- const DECISION_TYPED_FIELDS = [
290
- "workspaceId",
291
- "matter",
292
- "entries",
293
- "currentDecision",
294
- "question",
295
- "decision",
296
- "decidedBy",
297
- "rationale",
298
- "argumentsConsidered",
299
- "concerns",
300
- "status"
301
- ];
302
- const TASK_TYPED_FIELDS = ["workspaceId", "description", "assignee", "assignor", "entries", "currentStatus", "details", "status"];
303
- const RISK_TYPED_FIELDS = [
304
- "workspaceId",
305
- "topic",
306
- "entries",
307
- "currentStatus",
308
- "currentAssessment",
309
- "currentTreatment",
310
- "likelihood",
311
- "impact",
312
- "mitigation"
313
- ];
314
- const INCIDENT_TYPED_FIELDS = ["workspaceId", "description", "entries", "currentStatus", "currentSeverity", "status", "severity"];
315
- const PROBLEM_TYPED_FIELDS = ["workspaceId", "description", "entries", "currentStatus", "currentRootCause", "status", "rootCause"];
316
- const PROCESS_GUIDE = {
317
- name: "DX Complete process guide",
318
- status:
319
- "Current operating guidance for working inside DX Complete. It is a lean guide for MCP clients; it is not the full reference, not a final model, and not a validation rule.",
320
- currentFlow: ["Statement", "Expectation", "Requirement", "Commitment"],
321
- phaseGuidance: [
322
- "These phases describe a typical first-pass order and each has a target end-state, but they are non-terminal and re-enterable: at any point the most useful next activity may belong to any phase, including returning to an earlier one, and no phase is ever closed or locked behind you."
323
- ],
324
- crossCuttingRecords: [
325
- {
326
- record: "Journal",
327
- use: "Shared workspace context that does not yet belong in a dedicated record; use dedicated records first and Journal only as the fallback."
328
- },
329
- {
330
- record: "Task",
331
- use: "Execution work that can be created whenever a phase needs concrete action; Task is not part of the Statement, Expectation, Requirement, Commitment sequence."
332
- },
333
- {
334
- record: "Decision",
335
- use: "A recorded choice that can appear in any phase when a meaningful decision needs to remain legible."
336
- },
337
- {
338
- record: "Support Request",
339
- use: "Shared user-facing support follow-up for a reported experience, question, request, or issue."
340
- }
341
- ],
342
- recordRoutingGuidance: {
343
- principle:
344
- "Use the dedicated record first. Journal is the fallback for relevant workspace context only when no dedicated record fits.",
345
- sharpTest:
346
- "Will anything reference or depend on this? If yes, prefer a dedicated record that can carry the relationship.",
347
- routingOrder: [
348
- {
349
- when: "The information is desired truth, success criteria, or a buildable commitment.",
350
- use: "Use Statement, Expectation, or Requirement."
351
- },
352
- {
353
- when: "The information is a choice weighed between alternatives.",
354
- use: "Use Decision."
355
- },
356
- {
357
- when: "The information is an action someone needs to do.",
358
- use: "Use Task."
359
- },
360
- {
361
- when: "The information is a discrete alteration to the running service.",
362
- use: "Use Change."
363
- },
364
- {
365
- when: "The information is a specific service-impacting occurrence that needs response.",
366
- use: "Use Incident."
367
- },
368
- {
369
- when: "The information is an underlying or recurring cause behind one or more incidents.",
370
- use: "Use Problem."
371
- },
372
- {
373
- when: "The information is uncertainty or exposure.",
374
- use: "Use Risk."
375
- },
376
- {
377
- when: "The information is operational infrastructure state.",
378
- use: "Use Environment and Component records in the Operational Registry; do not use Journal as the long-term home."
379
- },
380
- {
381
- when: "The information is recurring operational hygiene, such as a scheduled review, rotation, backup check, or maintenance duty.",
382
- use: "Use Maintenance Schedule."
383
- },
384
- {
385
- when: "The information is a user-facing question, request, or issue that needs shared support follow-up.",
386
- use: "Use Support Request."
387
- },
388
- {
389
- when: "The information is measured before/after value for an approved outcome or commitment.",
390
- use: "Use Value Realization."
391
- },
392
- {
393
- when: "The information is a private question, report, request, correction, or follow-up with DX Complete.",
394
- use: "Use DX Complete Ticket."
395
- },
396
- {
397
- when: "The information is relevant context with no better home.",
398
- use: "Use Journal."
399
- }
400
- ],
401
- promotion:
402
- "If Journal content becomes load-bearing, promote it to the appropriate dedicated record and link back where useful."
403
- },
404
- roleOperatingGuidance: [
405
- {
406
- role: "Owner",
407
- guidance:
408
- "Use Statement, Expectation, Benefits, Commitment, Deferral, Decision, Value Realization, and Risk records for direction, expected value, measured value, commitment, deferral, formal risk acceptance, and authority decisions."
409
- },
410
- {
411
- role: "Engineer",
412
- guidance:
413
- "Default to Requirement -> Task for implementation work. Use Decision for meaningful choices, Risk for uncertainty, Journal for relevant context with no better home, and Change only when the work becomes a run-side alteration."
414
- },
415
- {
416
- role: "Codex assistance",
417
- guidance:
418
- "Codex is a coding-capable tool used by the Engineer, not a DX Complete role. A fresh Codex instance should orient from get_process_guide, get_doc({ page: \"operating_guide\" }), and the installed Codex guidance before choosing records."
419
- },
420
- {
421
- role: "Tester",
422
- guidance:
423
- "Use Task entries, review notes, Risk, Decision, or Journal to keep verification evidence visible. Do not create Change records merely because testing is happening."
424
- },
425
- {
426
- role: "Operator",
427
- guidance:
428
- "Use Change for discrete run-side alterations, Incident for specific service-impacting occurrences, Problem for underlying or recurring causes, Environment and Component for operational inventory, Maintenance Schedule for recurring operational hygiene, and Risk or Decision where operations need accountability. Administration duties such as users, permissions, settings, provisioning, and run-side security live here."
429
- },
430
- {
431
- role: "Support Agent",
432
- guidance:
433
- "Use Support Request for shared user-facing support follow-up. Use DX Complete Ticket only for private questions, reports, requests, corrections, and follow-ups with DX Complete itself. Promote to Statement, Requirement, Task, Incident, Problem, Risk, Decision, Change, or Journal only when the signal has that meaning."
434
- },
435
- {
436
- role: "End User",
437
- guidance:
438
- "End User is not a DX Complete operator and does not approve records. Their input is captured by another role as Statement, report, request, correction, feedback signal, or ticket."
439
- }
440
- ],
441
- itsmGuidance: [
442
- "Change is the current first-class run-side control record.",
443
- "Incident is the current first-class record for a specific service-impacting or potentially service-impacting occurrence.",
444
- "Problem is the current first-class record for an underlying or recurring cause evidenced by one or more incidents.",
445
- "Do not create ITSM-style records merely because work is happening; use Change, Incident, Problem, and Risk only when the record meaning fits."
446
- ],
447
- phases: [
448
- {
449
- id: "orient",
450
- name: "Orient",
451
- purpose:
452
- "Capture the desired outcome in plain terms, restate expectations, and confirm how success will be recognized where possible.",
453
- commonRecords: ["Workspace", "Statement", "Expectation", "DX Complete Ticket"],
454
- processConcepts: [],
455
- handoff:
456
- "Expectations describe the desired outcome clearly enough to elicit requirements, or any missing approval is visible as open risk.",
457
- operatingGuidance: {
458
- clientRole: "Help the user express the desired outcome in their terms, confirm captured wording before recording, and prepare expectations for approval where needed.",
459
- conductRules: [
460
- "Elicit the person's Statement; do not invent it.",
461
- "When the client articulates Statement or Expectation wording on a user's behalf, confirm that wording before recording it.",
462
- "Do not store same-person capture-confirmation as record state.",
463
- "Stay in plain outcome language.",
464
- "Do not move into technical solution design during Orient.",
465
- "Treat missing separate authority approval as visible open risk, not as a process block."
466
- ],
467
- questionsToAsk: [
468
- "What problem, need, or outcome should DX Complete help clarify?",
469
- "What would make this successful from the user's point of view?",
470
- "How will people recognize that the expected outcome has been met?",
471
- "Is this wording accurate enough to record and use as the basis for requirements?"
472
- ],
473
- expectedOutput: [
474
- "Statement record in the person's language.",
475
- "Restated Expectations with success recognition.",
476
- "Owner approval where available, or visible open risk where approval is missing."
477
- ],
478
- exitCheck:
479
- "Move to Elicit when expectations are clear enough to translate into requirements, or when proceeding without separate authority approval is visible as open risk.",
480
- checkpointNotes: [
481
- "Owner approval reduces wrong-outcome risk.",
482
- "Unapproved expectations can move forward only when the risk is explicit."
483
- ]
484
- }
485
- },
486
- {
487
- id: "elicit",
488
- name: "Elicit",
489
- purpose: "Translate expectations into requirements, dependencies, assumptions, unknowns, and risk.",
490
- commonRecords: ["Statement", "Expectation", "Requirement", "Risk", "Decision", "DX Complete Ticket"],
491
- processConcepts: ["Requirement"],
492
- handoff: "The requirement set is clear enough to estimate cost, value, risk, and confidence, or the open risk is visible.",
493
- operatingGuidance: {
494
- clientRole: "Translate approved or visibly unapproved expectations into requirements and related delivery facts.",
495
- conductRules: [
496
- "Keep each requirement tied to the expectation it is meant to satisfy.",
497
- "Separate requirements from implementation tasks.",
498
- "Surface dependencies, assumptions, unknowns, and risks before estimating.",
499
- "Use review notes for Engineer input on expectations or requirements; do not treat review notes as approval, objection state, or blockers.",
500
- "Do not treat uncertain details as settled requirements."
501
- ],
502
- questionsToAsk: [
503
- "What must be true for each expectation to be satisfied?",
504
- "What dependencies, constraints, or unknowns could affect the work?",
505
- "What assumptions are being made because information is incomplete?",
506
- "Which risks should be visible before the Owner weighs the work?"
507
- ],
508
- expectedOutput: [
509
- "A requirement set.",
510
- "Review notes where Engineer input should stay visible.",
511
- "Known dependencies, assumptions, unknowns, and risks.",
512
- "Open questions, visible risks, or follow-ups where clarity is incomplete."
513
- ],
514
- exitCheck:
515
- "Move to Weigh when the requirement set is clear enough to support cost, value, risk, and confidence discussion.",
516
- checkpointNotes: [
517
- "Requirement clarity reduces estimate risk.",
518
- "Open unknowns can move forward when they are recorded as visible risk or follow-up."
519
- ]
520
- }
521
- },
522
- {
523
- id: "weigh",
524
- name: "Weigh",
525
- purpose:
526
- "Compare expected cost, expected value, risks, and confidence before recording a Commitment or Deferral.",
527
- commonRecords: [
528
- "Estimate",
529
- "Benefits",
530
- "Commitment",
531
- "Deferral",
532
- "Decision",
533
- "Risk"
534
- ],
535
- handoff:
536
- "The Owner records a Commitment that can move into Build, or a Deferral that makes unmet conditions visible.",
537
- operatingGuidance: {
538
- clientRole: "Help the decision authority compare the requirement set against cost, value, risk, and confidence.",
539
- conductRules: [
540
- "Make current-state cost context visible where relevant, but do not require complete baseline data.",
541
- "Generate or review a scope-linked Engineer cost Estimate by default from the elicited requirement set.",
542
- "Record Owner-authored Benefits separately from Engineer cost Estimates.",
543
- "Consider important review notes, but do not require the Owner to acknowledge or answer them.",
544
- "Keep the phase outcome-neutral; do not force a Commitment.",
545
- "If budget or benefit basis was considered, link the Estimate, Benefits, or Decision rationale to the Commitment; if not, do not fabricate a waiver.",
546
- "Use Commitment when the Owner is moving forward, with any reservations recorded.",
547
- "Use Deferral when the Owner is not moving forward yet and wants the unmet conditions made explicit.",
548
- "Record uncertainty and confidence rather than hiding it.",
549
- "Do not compute a verdict; DX Complete preserves the basis for the Owner's judgment."
550
- ],
551
- questionsToAsk: [
552
- "What is known about current cost, proposed cost, and expected benefit?",
553
- "How confident is the cost estimate?",
554
- "Which Benefits, Estimate, or Decision rationale, if any, should inform the Commitment?",
555
- "What risks or missing information affect whether the Owner can commit?",
556
- "Is the Owner committing now, or deferring until named conditions are addressed?",
557
- "If committing, what reservations should be kept visible?",
558
- "If deferring, what conditions would make a future Commitment possible?"
559
- ],
560
- expectedOutput: [
561
- "Decision basis for the Owner's judgment.",
562
- "Scope-linked Engineer cost Estimate where available.",
563
- "Owner-authored Benefits where available, including qualitative benefits when they cannot be quantified.",
564
- "Important review notes considered as input where they exist.",
565
- "Commitment with linked requirements or expectations, or Deferral with explicit conditions.",
566
- "Decision with linked inputs where a separate rationale record is useful.",
567
- "Visible risks."
568
- ],
569
- exitCheck:
570
- "Move to Build only after a Commitment; otherwise keep the Deferral conditions visible or return to Elicit as recorded.",
571
- checkpointNotes: [
572
- "Incomplete cost or benefit data does not block the decision.",
573
- "Proceeding with low confidence should leave the open risk visible.",
574
- "A Deferral is not failure; it is the recorded path to a possible future Commitment."
575
- ]
576
- }
577
- },
578
- {
579
- id: "build",
580
- name: "Build",
581
- purpose: "Turn committed requirements into working changes.",
582
- commonRecords: ["Commitment", "Requirement", "Task", "Decision", "Risk"],
583
- handoff: "The change is ready for release preparation and readiness checks.",
584
- operatingGuidance: {
585
- clientRole: "Help the team break committed requirements into tasks and track implementation evidence.",
586
- conductRules: [
587
- "Create tasks from requirements covered by a Commitment.",
588
- "Keep implementation detail connected to the requirement it supports.",
589
- "Use decisions for meaningful design or tradeoff choices.",
590
- "Surface blockers and delivery risk early."
591
- ],
592
- questionsToAsk: [
593
- "Which requirement does this task implement?",
594
- "What working change will satisfy the requirement?",
595
- "What decision, risk, or blocker affects the build?",
596
- "What evidence will show that the task is complete?"
597
- ],
598
- expectedOutput: [
599
- "Tasks linked to requirements.",
600
- "Working changes or implementation evidence.",
601
- "Recorded decisions and risks where needed."
602
- ],
603
- exitCheck: "Move to Go Live when the committed change is built and ready for release preparation.",
604
- checkpointNotes: [
605
- "Task completion does not replace requirement verification.",
606
- "Known build risk should remain visible through release preparation."
607
- ]
608
- }
609
- },
610
- {
611
- id: "go_live",
612
- name: "Go Live",
613
- purpose: "Prepare the change, confirm readiness, and put it into use.",
614
- commonRecords: ["Change", "Task", "Decision", "Risk"],
615
- handoff: "The change is completed, deferred, cancelled, rolled back, or left with its event history visible.",
616
- operatingGuidance: {
617
- clientRole: "Help the Operator record the intended service change, readiness basis, execution path, rollback path, and resulting events.",
618
- conductRules: [
619
- "Use Change for a discrete alteration to the running service; reserve Operations Plan for a future standing operating model.",
620
- "Record the original change plan, execution steps, rollback plan, and risk, impact, and downstream impact as the baseline.",
621
- "Classify the Change as standard, normal, or emergency, then use append-only Change events for notice, veto, decision, result, recovery, notes, and plan revisions.",
622
- "When result or recovery events have Git commits behind them, record optional Git commit references for that execution attempt or rollback.",
623
- "Check readiness before putting the change into use.",
624
- "Make release, rollback, notice, veto, change type, and communication risks visible.",
625
- "Do not treat vetoes or readiness checks as mechanical blockers; DX Complete records accountability and does not perform or enforce the operation.",
626
- "Record open readiness risk when a readiness concern remains open."
627
- ],
628
- questionsToAsk: [
629
- "What is changing, why, and when is it planned?",
630
- "What steps will carry out the change?",
631
- "What rollback or recovery path exists if something goes wrong?",
632
- "What else may be affected, and what depends on what is changing?",
633
- "Who needs to know about the change?",
634
- "Has anyone recorded a veto or concern?",
635
- "What readiness concerns are still open?"
636
- ],
637
- expectedOutput: [
638
- "Change record with change plan, execution steps, rollback plan, and risk, impact, and downstream-impact notes.",
639
- "Append-only Change events for notice, veto, decision, result, recovery, notes, or revisions where they occur.",
640
- "Optional Git commit references on result or recovery events where they help trace the execution attempt.",
641
- "Readiness basis.",
642
- "Release or service-change decision context.",
643
- "Visible open risks and any Owner risk-acceptance decisions."
644
- ],
645
- exitCheck: "Move to Operate when the change event history shows the change is completed, deferred, cancelled, rolled back, or ready to be monitored.",
646
- checkpointNotes: [
647
- "Readiness checks reduce launch risk.",
648
- "A veto by Owner or Engineer is a serious recorded event, not a mechanical stop.",
649
- "Emergency changes should record both importance and immediacy where available; missing rationale remains visible but does not block the record.",
650
- "Open readiness concerns can move forward only when the risk remains visible or is formally accepted by the Owner."
651
- ]
652
- }
653
- },
654
- {
655
- id: "operate",
656
- name: "Operate",
657
- purpose: "Run the service, help users, and respond when something goes wrong.",
658
- commonRecords: ["Incident", "Problem", "Support Request", "Change", "Environment", "Component", "Maintenance Schedule", "DX Complete Ticket", "Risk", "Decision", "Task"],
659
- handoff: "Operational signals are handled or sent into measurement, improvement, or new work.",
660
- operatingGuidance: {
661
- clientRole: "Help keep the service legible while it is running and route operational signals to the right follow-up.",
662
- conductRules: [
663
- "Separate immediate user-facing help from deeper improvement work.",
664
- "Record Incident for a specific service-impacting occurrence, Problem for an underlying or recurring cause, and Risk, Decision, or Task when those meanings fit.",
665
- "Use Support Request for shared user-facing support follow-up.",
666
- "Use Change when the follow-up is a discrete alteration to the running service.",
667
- "Use Maintenance Schedule for recurring operational hygiene and link completed Changes or Tasks to it when the work is performed.",
668
- "Do not assume the service is finished just because there is no active build.",
669
- "Surface recurring signals for later improvement or measurement."
670
- ],
671
- questionsToAsk: [
672
- "Is the service running as intended?",
673
- "What user-facing issue, operational issue, or risk needs attention?",
674
- "Does this signal need immediate response, a task, a decision, or later improvement?",
675
- "Is this a shared support request, an incident, a problem, or recurring maintenance?",
676
- "What operational follow-up remains open?"
677
- ],
678
- expectedOutput: [
679
- "Handled operational signal or routed follow-up.",
680
- "Visible support requests, incidents, problems, maintenance schedules, risks, decisions, or tasks where needed.",
681
- "Ongoing operating state."
682
- ],
683
- exitCheck:
684
- "Move to Measure when cost, benefit, reliability, or other operating data is available for comparison or learning.",
685
- checkpointNotes: [
686
- "Operational work is part of the lifecycle, not an exception.",
687
- "Unresolved operating signals should remain visible until handled or accepted."
688
- ]
689
- }
690
- },
691
- {
692
- id: "measure",
693
- name: "Measure",
694
- purpose: "Compare expected and actual cost or benefit when data is available.",
695
- commonRecords: ["Value Realization", "Estimate", "Benefits", "Decision", "Risk"],
696
- handoff: "Learning from actuals is available for future estimates and decisions.",
697
- operatingGuidance: {
698
- clientRole: "Help compare estimates to actuals where data exists and feed learning into future decisions.",
699
- conductRules: [
700
- "Capture actual cost or benefit observations when available.",
701
- "Use Value Realization for before/after metrics tied to expectations, requirements, or commitments.",
702
- "Do not block closure or continued operation because actuals are unavailable.",
703
- "Compare measured results to earlier estimates where possible.",
704
- "Turn meaningful differences into learning, risk, decision context, or future work."
705
- ],
706
- questionsToAsk: [
707
- "What actual cost or benefit data is available?",
708
- "How does it compare with the estimate?",
709
- "Which value metric has a baseline, an actual measurement, or an open measurement gap?",
710
- "What should future estimates or decisions learn from this?",
711
- "Is new work, risk, or a decision needed because of the measurement?"
712
- ],
713
- expectedOutput: [
714
- "Actual cost or benefit observations where available.",
715
- "Value Realization records for measured or still-open value metrics where useful.",
716
- "Comparison to estimates where possible.",
717
- "Learning for future estimates and decisions."
718
- ],
719
- exitCheck:
720
- "Keep operating, refine estimates, or start new Orient/Elicit work when measurement reveals a new need.",
721
- checkpointNotes: [
722
- "Actuals improve future estimates but do not block project closure.",
723
- "Missing measurement data should be visible without being treated as failure."
724
- ]
725
- }
726
- }
727
- ],
728
- processConcepts: [
729
- {
730
- name: "Statement",
731
- status: "runtime_record",
732
- currentRuntimeRecordType: "statements",
733
- use: "The user's own words before DX Complete interprets or translates them.",
734
- handling: "Track as a workspace-scoped record. Expectations can derive from Statement records through the derives_from relationship."
735
- },
736
- {
737
- name: "Expectation",
738
- status: "runtime_record",
739
- currentRuntimeRecordType: "expectations",
740
- use: "The expected result and how success will be recognized, captured in user-facing language.",
741
- handling: "Track as a workspace-scoped record that can link to statements, requirements, risks, and decisions. Separate authority approval is tracked as risk-reducing state; same-person capture-confirmation is client conduct."
742
- },
743
- {
744
- name: "Requirement detail",
745
- status: "requirement_detail",
746
- currentRuntimeRecordType: "requirements",
747
- use: "Optional implementation or verification detail kept with the requirement when needed.",
748
- handling: "Do not treat Specification as a current first-class runtime record."
749
- }
750
- ],
751
- checkpointGuidance: [
752
- "Approval and other checkpoints reduce risk; they do not block progress by themselves.",
753
- "A checkpoint can be approved or mitigated, formally accepted as risk by the Owner, or proceeded past with open risk still visible.",
754
- "Formal risk acceptance is an Owner-level decision; domain actors may proceed, but proceeding does not close or accept the risk.",
755
- "Use Risk and Decision records to capture Owner risk acceptance or proceeding past an open checkpoint until dedicated checkpoint fields or tools are proven necessary.",
756
- "Use Decision input links to preserve which records informed important choices.",
757
- "Use Change records for run-side service changes where change type, notice, veto, execution, rollback, result, and optional Git commit references need an ordered audit trail."
758
- ],
759
- nextStepGuidance: {
760
- responsibility:
761
- "The MCP client derives the next step from the current records, phase handoffs, operating guidance, open risks, and unanswered questions. DX Complete does not compute or prescribe a single server-side next step.",
762
- conductRules: [
763
- "Use the current phase, record state, links, open questions, risks, and decisions to reason about what should happen next.",
764
- "When the next step is uncertain, name the missing information or checkpoint rather than inventing certainty.",
765
- "Treat the next-step answer as guidance for the user, not as a hidden server decision."
766
- ]
767
- },
768
- runtimeRecordTypes: COLLECTION_NAMES,
769
- deploymentModel: {
770
- default: "one_mcp_endpoint_per_workspace",
771
- workspaceBinding:
772
- "Hosted MCP endpoints get workspace scope from installed repo config, then proxy to the central DX Complete service. Shared record access is scoped by authenticated actor and authorized workspace context. Workspace scope is not an environment variable.",
773
- databaseModel:
774
- "Workspace MCP servers do not hold database credentials. The central service owns database access, OAuth exchange, membership checks, readable ID allocation, and MCP tool execution.",
775
- authorizationModel:
776
- "Workspace servers authenticate to the central service with a workspace service client. The central service verifies the human actor and derives allowed tool access from stored workspace roles."
777
- },
778
- recordGuidance: [
779
- {
780
- record: "Workspace",
781
- use: "The boundary for one service scope, including its name, summary, and mode when useful."
782
- },
783
- {
784
- record: "Statement",
785
- use: "A user's own words before interpretation, kept as the traceable root for expectations and downstream work."
786
- },
787
- {
788
- record: "Journal",
789
- use: "Shared, append-only workspace notes for relevant background, preferences, observations, and context that has no dedicated record home. Journal notes are visible to workspace members and compacted through summary entries when the hot context grows."
790
- },
791
- {
792
- record: "DX Complete Ticket",
793
- use: "Private, appendable communication between the current actor and DX Complete before anyone decides whether shared follow-up is needed."
794
- },
795
- {
796
- record: "Expectation",
797
- use: "A user-facing condition of satisfaction that can be approved by separate authority, left not approved with open risk visible, linked to requirements, reviewed with non-blocking notes, and revised with version history."
798
- },
799
- {
800
- record: "Requirement",
801
- use: "A team-owned commitment that translates expectations into something buildable and verifiable, with optional non-blocking review notes and version history."
802
- },
803
- {
804
- record: "Commitment",
805
- use: "An Owner point-in-time authority record that commits requirements or expectations into Build, with optional reservations kept visible."
806
- },
807
- {
808
- record: "Deferral",
809
- use: "An Owner record for not committing yet, with explicit conditions and append-only condition history that can resolve into a Commitment."
810
- },
811
- {
812
- record: "Task",
813
- use: "Execution work with an append-only entry log; current status comes from the latest status_change entry."
814
- },
815
- {
816
- record: "Change",
817
- use: "A discrete service change record with baseline change type, plan sections, and append-only events for notice, veto, decision, result, recovery, notes, and revisions."
818
- },
819
- {
820
- record: "Incident",
821
- use: "A specific service-impacting or potentially service-impacting occurrence with an append-only entry log; current status and severity come from the latest relevant entries."
822
- },
823
- {
824
- record: "Problem",
825
- use: "An underlying or recurring cause evidenced by one or more Incidents, with an append-only entry log and current root cause derived from entries."
826
- },
827
- {
828
- record: "Environment",
829
- use: "A named operating context such as local, staging, or production, with version history for operational-state changes."
830
- },
831
- {
832
- record: "Component",
833
- use: "One environment-specific operational component with kind, structured locator, identifiers, secret pointers, notes, and version history."
834
- },
835
- {
836
- record: "Maintenance Schedule",
837
- use: "A recurring operational hygiene record with cadence, start date, rationale, version history, and due state derived from linked completed Changes or Tasks."
838
- },
839
- {
840
- record: "Estimate",
841
- use: "An Engineer cost input for Weigh, with itemized line items, scope links, cost-only roll-up totals, and version history."
842
- },
843
- {
844
- record: "Benefits",
845
- use: "An Owner-authored benefit input for Weigh, with qualitative or quantified benefit items, scope links, quantified roll-up totals where amounts exist, and version history."
846
- },
847
- {
848
- record: "Value Realization",
849
- use: "A measured-value record for before/after metrics tied to expectations, requirements, or commitments, with comparisons derived from baseline and actual values."
850
- },
851
- {
852
- record: "Support Request",
853
- use: "A shared support ledger for a user-facing reported experience, question, request, or issue; current status comes from ordered entries."
854
- },
855
- {
856
- record: "Decision",
857
- use: "A revisitable choice record with an append-only entry log; current decision comes from the latest decision entry while earlier arguments and decisions remain visible."
858
- }
859
- ],
860
- clientGuidance: [
861
- "Use get_process_guide when you need the current DX Complete phase language.",
862
- "Use get_doc for the fuller reference on outcomes, flow, records, roles, operating guide, and glossary terms.",
863
- "Use get_doc({ page: \"operating_guide\" }) when a fresh client or agent needs role-by-role record routing.",
864
- "Use DX Complete Ticket tools for private questions, reports, requests, corrections, or follow-ups.",
865
- "Use Journal tools only after checking whether the information belongs in Statement, Expectation, Requirement, Decision, Task, Change, Incident, Problem, Support Request, Risk, Environment, Component, Maintenance Schedule, Value Realization, or another dedicated record.",
866
- "Use workspace-scoped records for shared process work.",
867
- "Use readableId values such as REQ-0001 as human-facing references when a tool accepts an existing record id; UUID remains the primary key and link target.",
868
- "Hosted MCP access derives workspace scope from installed repo config and actor scope from OAuth.",
869
- "Use update_expectation and update_requirement for current content changes so prior versions are preserved.",
870
- "Use append_decision_entry and append_task_entry for Decision and Task history; do not rewrite their current decision or status directly.",
871
- "Use link_decision_input when a record informed a Decision; use list_linked_records with relationship informed_by to review the decision inputs.",
872
- "Use Benefits for Owner-authored benefit lists; use Estimate for Engineer cost estimates.",
873
- "Use Value Realization for measured before/after value, not for expected benefits.",
874
- "Use Support Request for shared user-facing support follow-up; use DX Complete Ticket for private communication with DX Complete.",
875
- "Use link_records and unlink_records for other relationships between records."
876
- ]
877
- };
878
-
879
- type ToolSchema = Record<string, z.ZodType>;
880
- type ToolHandler = (...args: any[]) => unknown;
881
- type ToolManifestEntry = {
882
- name: string;
883
- description: string;
884
- inputFields: string[];
885
- inputSchemaFingerprint: string;
886
- };
887
- type ToolManifest = {
888
- toolCount: number;
889
- tools: ToolManifestEntry[];
890
- };
891
- type McpSurface = ToolManifest & {
892
- version: string;
893
- fingerprint: string;
894
- workspaceCompatibility: number;
895
- };
896
- export type McpServerOptions = {
897
- actor?: ActorContext;
898
- recordActorId?: string;
899
- hostedWorkspace?: {
900
- workspaceId: string;
901
- name?: string;
902
- };
903
- workspaceRoles?: WorkspaceRole[];
904
- hostedHttp?: {
905
- canonicalMcpPath: string;
906
- canonicalMcpUrl: string;
907
- protectedResourceMetadataUrl: string;
908
- googleCallbackUrl: string;
909
- };
910
- };
911
-
912
- export function createMcpServer(runtime: DxRuntime, options: McpServerOptions = {}): McpServer {
913
- const server = new McpServer({
914
- name: "dxcomplete",
915
- version: DXCOMPLETE_PACKAGE_VERSION
916
- });
917
- const actor = options.actor ?? createLocalActorContext();
918
- const recordActorId = options.recordActorId ?? (options.actor ? actor.actorId : RUNTIME_ACTOR_ID);
919
- const hostedWorkspace = options.hostedWorkspace;
920
- const hostedHttp = options.hostedHttp;
921
- const activeCollectionSchema = hostedWorkspace ? hostedCollectionSchema : collectionSchema;
922
- const toolManifestEntries: ToolManifestEntry[] = [];
923
-
924
- function registerDxcTool<TInputSchema extends ToolSchema>(
925
- name: string,
926
- config: {
927
- description: string;
928
- inputSchema: TInputSchema;
929
- },
930
- handler: ToolHandler
931
- ): void {
932
- if (hostedWorkspace && name === "create_workspace") {
933
- return;
934
- }
935
-
936
- const inputSchema = hostedWorkspace ? omitWorkspaceId(config.inputSchema) : config.inputSchema;
937
-
938
- toolManifestEntries.push({
939
- name,
940
- description: config.description,
941
- inputFields: Object.keys(inputSchema).sort(),
942
- inputSchemaFingerprint: getInputSchemaFingerprint(inputSchema)
943
- });
944
- server.registerTool(
945
- name,
946
- {
947
- ...config,
948
- inputSchema
949
- },
950
- (async (input: Record<string, unknown>) => {
951
- const handlerInput = hostedWorkspace
952
- ? injectHostedWorkspace(input, config.inputSchema, hostedWorkspace.workspaceId)
953
- : input;
954
- assertHostedWorkspaceAccess(name, handlerInput, hostedWorkspace?.workspaceId);
955
- assertToolRoleAccess(name, options.workspaceRoles, handlerInput);
956
- return handler(handlerInput);
957
- }) as any
958
- );
959
- }
960
-
961
- function getToolManifest(): ToolManifest {
962
- const tools = [...toolManifestEntries].sort((left, right) => left.name.localeCompare(right.name));
963
-
964
- return {
965
- toolCount: tools.length,
966
- tools
967
- };
968
- }
969
-
970
- function getMcpSurface(): McpSurface {
971
- const toolManifest = getToolManifest();
972
- const fingerprint = createHash("sha256")
973
- .update(
974
- stableStringify({
975
- surfaceId: MCP_SURFACE_ID,
976
- workspaceCompatibility: WORKSPACE_COMPATIBILITY_VERSION,
977
- tools: toolManifest.tools,
978
- processGuide: PROCESS_GUIDE,
979
- docReferences: DOC_REFERENCE
980
- })
981
- )
982
- .digest("hex")
983
- .slice(0, 16);
984
-
985
- return {
986
- version: MCP_SURFACE_ID,
987
- fingerprint,
988
- workspaceCompatibility: WORKSPACE_COMPATIBILITY_VERSION,
989
- ...toolManifest
990
- };
991
- }
992
-
993
- registerDxcTool(
994
- "runtime_status",
995
- {
996
- description: "Check the DX Complete runtime connection and configured record collections.",
997
- inputSchema: {}
998
- },
999
- async () => {
1000
- const surface = getMcpSurface();
1001
-
1002
- return jsonResult({
1003
- ok: true,
1004
- databaseName: runtime.config.databaseName,
1005
- actorId: recordActorId,
1006
- actor,
1007
- ...(hostedWorkspace
1008
- ? {
1009
- workspace: {
1010
- workspaceId: hostedWorkspace.workspaceId,
1011
- ...(hostedWorkspace.name ? { name: hostedWorkspace.name } : {}),
1012
- source: "central_service_membership",
1013
- ...(options.workspaceRoles ? { roles: options.workspaceRoles } : {})
1014
- }
1015
- }
1016
- : {}),
1017
- collections: COLLECTION_NAMES,
1018
- server: {
1019
- pid: process.pid,
1020
- version: DXCOMPLETE_PACKAGE_VERSION,
1021
- packageVersion: DXCOMPLETE_PACKAGE_VERSION,
1022
- workspaceCompatibility: surface.workspaceCompatibility,
1023
- startedAt: SERVER_STARTED_AT,
1024
- surfaceVersion: surface.version,
1025
- surfaceFingerprint: surface.fingerprint,
1026
- surfaceIncludes: ["tools", "toolSchemas", "processGuide", "docReferences"],
1027
- ...(hostedHttp
1028
- ? {
1029
- http: hostedHttp
1030
- }
1031
- : {}),
1032
- toolCount: surface.toolCount,
1033
- tools: surface.tools.map((tool) => tool.name),
1034
- toolManifest: surface.tools
1035
- }
1036
- });
1037
- }
1038
- );
1039
-
1040
- registerDxcTool(
1041
- "get_process_guide",
1042
- {
1043
- description: "Get the current DX Complete process guide, including phases, common records, and handoff guidance.",
1044
- inputSchema: {}
1045
- },
1046
- async () => {
1047
- const surface = getMcpSurface();
1048
-
1049
- return jsonResult({
1050
- surfaceVersion: surface.version,
1051
- surfaceFingerprint: surface.fingerprint,
1052
- workspaceCompatibility: surface.workspaceCompatibility,
1053
- ...PROCESS_GUIDE
1054
- });
1055
- }
1056
- );
1057
-
1058
- registerDxcTool(
1059
- "get_doc",
1060
- {
1061
- description:
1062
- "Get an on-demand DX Complete reference page for MCP clients. Use this for fuller outcomes, flow, records, roles, operating guide, and glossary content without loading all documentation into the process guide.",
1063
- inputSchema: {
1064
- page: z.enum(DOC_PAGE_IDS),
1065
- term: z.string().min(1).optional()
1066
- }
1067
- },
1068
- async ({ page, term }) => {
1069
- const surface = getMcpSurface();
1070
- const doc = getDocReference(page, term);
1071
-
1072
- return jsonResult({
1073
- surfaceVersion: surface.version,
1074
- surfaceFingerprint: surface.fingerprint,
1075
- workspaceCompatibility: surface.workspaceCompatibility,
1076
- ...doc
1077
- });
1078
- }
1079
- );
1080
-
1081
- registerDxcTool(
1082
- "create_workspace",
1083
- {
1084
- description: "Create a workspace, the shared-runtime boundary for one service scope.",
1085
- inputSchema: {
1086
- id: workspaceIdSchema.optional(),
1087
- name: z.string().min(1),
1088
- summary: z.string().min(1).optional(),
1089
- mode: workspaceModeSchema.optional(),
1090
- fields: recordFieldsSchema
1091
- }
1092
- },
1093
- async ({ id, name, summary, mode, fields }) => {
1094
- const existing = id
1095
- ? await getRecord(runtime.db, "workspaces", id, { allowAnyWorkspace: true })
1096
- : null;
1097
-
1098
- if (existing) {
1099
- return jsonResult(existing);
1100
- }
1101
-
1102
- return jsonResult(
1103
- await createRecord(
1104
- runtime.db,
1105
- "workspaces",
1106
- {
1107
- ...(id ? { id } : {}),
1108
- title: name,
1109
- summary,
1110
- fields: {
1111
- name,
1112
- ...(mode ? { mode } : {}),
1113
- ...(fields ?? {})
1114
- }
1115
- },
1116
- recordActorId
1117
- )
1118
- );
1119
- }
1120
- );
1121
-
1122
- registerDxcTool(
1123
- "create_record",
1124
- {
1125
- description: "Create a record in one of the DX Complete collections.",
1126
- inputSchema: {
1127
- recordType: activeCollectionSchema,
1128
- workspaceId: workspaceIdSchema.optional(),
1129
- title: z.string().min(1).optional(),
1130
- summary: z.string().min(1).optional(),
1131
- fields: recordFieldsSchema
1132
- }
1133
- },
1134
- async ({ recordType, workspaceId, title, summary, fields }) =>
1135
- jsonResult(await createRecord(runtime.db, recordType, { workspaceId, title, summary, fields }, recordActorId))
1136
- );
1137
-
1138
- registerDxcTool(
1139
- "get_record",
1140
- {
1141
- description: "Get one DX Complete record by type and id.",
1142
- inputSchema: {
1143
- recordType: activeCollectionSchema,
1144
- workspaceId: workspaceIdSchema.optional(),
1145
- id: z.string().min(1)
1146
- }
1147
- },
1148
- async ({ recordType, workspaceId, id }) => {
1149
- const record = await getRecord(runtime.db, recordType, id, { workspaceId });
1150
-
1151
- if (!record) {
1152
- throw new Error(`Record not found: ${recordType}/${id}`);
1153
- }
1154
-
1155
- return jsonResult(record);
1156
- }
1157
- );
1158
-
1159
- registerDxcTool(
1160
- "create_dxcomplete_ticket",
1161
- {
1162
- description:
1163
- "Create a private DX Complete Ticket for a question, report, request, correction, or follow-up from the current actor. The body is stored as the first entry; summary is optional and is not generated automatically.",
1164
- inputSchema: {
1165
- title: z.string().min(1),
1166
- body: z.string().min(1)
1167
- }
1168
- },
1169
- async (input) => jsonResult(await createDxcompleteTicket(runtime.db, input, actor))
1170
- );
1171
-
1172
- registerDxcTool(
1173
- "append_dxcomplete_ticket",
1174
- {
1175
- description:
1176
- "Append a follow-up entry to one of the current actor's DX Complete Tickets while preserving earlier entries.",
1177
- inputSchema: {
1178
- id: z.string().min(1),
1179
- body: z.string().min(1)
1180
- }
1181
- },
1182
- async (input) => jsonResult(await appendDxcompleteTicket(runtime.db, input, actor))
1183
- );
1184
-
1185
- registerDxcTool(
1186
- "list_dxcomplete_tickets",
1187
- {
1188
- description:
1189
- "List the current actor's own DX Complete Tickets. Archived tickets are hidden unless includeArchived is true.",
1190
- inputSchema: {
1191
- limit: z.number().int().min(1).max(100).optional(),
1192
- includeArchived: z.boolean().optional()
1193
- }
1194
- },
1195
- async ({ limit, includeArchived }) =>
1196
- jsonResult(await listDxcompleteTickets(runtime.db, actor, limit ?? 20, { includeArchived }))
1197
- );
1198
-
1199
- registerDxcTool(
1200
- "list_unread_dxcomplete_ticket_replies",
1201
- {
1202
- description:
1203
- "List tickets with unread DX Complete replies addressed to the current actor. This returns reply identifiers and timestamps only; use read_dxcomplete_ticket to read the ticket and mark replies read.",
1204
- inputSchema: {
1205
- limit: z.number().int().min(1).max(100).optional()
1206
- }
1207
- },
1208
- async ({ limit }) => jsonResult(await listUnreadDxcompleteTicketReplies(runtime.db, actor, limit ?? 20))
1209
- );
1210
-
1211
- registerDxcTool(
1212
- "read_dxcomplete_ticket",
1213
- {
1214
- description: "Read one DX Complete Ticket owned by the current actor. Reading the ticket marks its unread DX Complete replies as read.",
1215
- inputSchema: {
1216
- id: z.string().min(1)
1217
- }
1218
- },
1219
- async (input) => jsonResult(await readDxcompleteTicket(runtime.db, input, actor))
1220
- );
1221
-
1222
- registerDxcTool(
1223
- "archive_dxcomplete_ticket",
1224
- {
1225
- description: "Hide one DX Complete Ticket from the current actor's active ticket list. This is personal cleanup.",
1226
- inputSchema: {
1227
- id: z.string().min(1)
1228
- }
1229
- },
1230
- async ({ id }) => jsonResult(await archiveDxcompleteTicket(runtime.db, { id }, actor))
1231
- );
1232
-
1233
- registerDxcTool(
1234
- "append_journal_note",
1235
- {
1236
- description:
1237
- "Append a shared workspace Journal note only after checking that the information has no better dedicated record home. Any workspace member may append; author and timestamp are captured automatically.",
1238
- inputSchema: {
1239
- workspaceId: workspaceIdSchema,
1240
- body: z.string().min(1),
1241
- tag: journalTagSchema.optional()
1242
- }
1243
- },
1244
- async (input) => jsonResult(await appendJournalNote(runtime.db, input, recordActorId))
1245
- );
1246
-
1247
- registerDxcTool(
1248
- "read_journal",
1249
- {
1250
- description:
1251
- "Read the workspace Journal fallback context. By default this returns the hot tier: active summaries plus active raw notes, not the full archive.",
1252
- inputSchema: {
1253
- workspaceId: workspaceIdSchema,
1254
- limit: z.number().int().min(1).max(500).optional(),
1255
- includeArchived: z.boolean().optional()
1256
- }
1257
- },
1258
- async (input) => jsonResult(await readJournal(runtime.db, input))
1259
- );
1260
-
1261
- registerDxcTool(
1262
- "get_journal_entry",
1263
- {
1264
- description:
1265
- "Fetch one Journal entry by UUID or readable ID, including fallback context entries that have aged out of the hot Journal read.",
1266
- inputSchema: {
1267
- workspaceId: workspaceIdSchema,
1268
- id: z.string().min(1)
1269
- }
1270
- },
1271
- async (input) => jsonResult(await getJournalEntry(runtime.db, input))
1272
- );
1273
-
1274
- registerDxcTool(
1275
- "append_journal_summary",
1276
- {
1277
- description:
1278
- "Append a Journal summary for fallback context that covers existing Journal entries by UUID or readable ID, then archives the covered entries out of the hot read without deleting them.",
1279
- inputSchema: {
1280
- workspaceId: workspaceIdSchema,
1281
- body: z.string().min(1),
1282
- covers: z.array(z.string().min(1)).min(1),
1283
- tag: journalTagSchema.optional()
1284
- }
1285
- },
1286
- async (input) => jsonResult(await appendJournalSummary(runtime.db, input, recordActorId))
1287
- );
1288
-
1289
- registerDxcTool(
1290
- "create_statement",
1291
- {
1292
- description: "Create a Statement record that preserves a person's own words before interpretation.",
1293
- inputSchema: {
1294
- workspaceId: workspaceIdSchema,
1295
- title: z.string().min(1),
1296
- statement: z.string().min(1),
1297
- source: z.string().min(1).optional(),
1298
- fields: recordFieldsSchema
1299
- }
1300
- },
1301
- async (input) => jsonResult(await createStatement(runtime, input, recordActorId))
1302
- );
1303
-
1304
- registerDxcTool(
1305
- "update_statement",
1306
- {
1307
- description: "Update a Statement record while preserving prior versions.",
1308
- inputSchema: {
1309
- workspaceId: workspaceIdSchema,
1310
- id: z.string().min(1),
1311
- title: z.string().min(1).optional(),
1312
- statement: z.string().min(1).optional(),
1313
- source: z.string().min(1).optional(),
1314
- fields: recordFieldsSchema,
1315
- unsetFields: z.array(fieldNameSchema).optional(),
1316
- revisionNote: z.string().min(1).optional()
1317
- }
1318
- },
1319
- async (input) => jsonResult(await updateStatement(runtime, input, recordActorId))
1320
- );
1321
-
1322
- registerDxcTool(
1323
- "list_environments",
1324
- {
1325
- description: "List Operational Registry Environment records for the workspace.",
1326
- inputSchema: {
1327
- workspaceId: workspaceIdSchema,
1328
- limit: z.number().int().min(1).max(100).optional(),
1329
- includeArchived: z.boolean().optional()
1330
- }
1331
- },
1332
- async ({ workspaceId, limit, includeArchived }) =>
1333
- jsonResult(await listRecords(runtime.db, "environments", limit ?? 20, { workspaceId, includeArchived }))
1334
- );
1335
-
1336
- registerDxcTool(
1337
- "create_environment",
1338
- {
1339
- description: "Create an Operational Registry Environment, such as local, staging, or production.",
1340
- inputSchema: {
1341
- workspaceId: workspaceIdSchema,
1342
- name: z.string().min(1),
1343
- summary: z.string().min(1).optional(),
1344
- description: z.string().min(1).optional(),
1345
- fields: recordFieldsSchema
1346
- }
1347
- },
1348
- async (input) => jsonResult(await createEnvironment(runtime, input, recordActorId))
1349
- );
1350
-
1351
- registerDxcTool(
1352
- "update_environment",
1353
- {
1354
- description: "Update an Operational Registry Environment while preserving prior versions.",
1355
- inputSchema: {
1356
- workspaceId: workspaceIdSchema,
1357
- id: z.string().min(1),
1358
- name: z.string().min(1).optional(),
1359
- summary: z.string().min(1).optional(),
1360
- description: z.string().min(1).optional(),
1361
- fields: recordFieldsSchema,
1362
- unsetFields: z.array(fieldNameSchema).optional(),
1363
- revisionNote: z.string().min(1).optional()
1364
- }
1365
- },
1366
- async (input) => jsonResult(await updateEnvironment(runtime, input, recordActorId))
1367
- );
1368
-
1369
- registerDxcTool(
1370
- "list_components",
1371
- {
1372
- description: "List Operational Registry Components that belong to one Environment.",
1373
- inputSchema: {
1374
- workspaceId: workspaceIdSchema,
1375
- environmentId: z.string().min(1),
1376
- limit: z.number().int().min(1).max(100).optional(),
1377
- includeArchived: z.boolean().optional()
1378
- }
1379
- },
1380
- async (input) => jsonResult(await listComponents(runtime, input))
1381
- );
1382
-
1383
- registerDxcTool(
1384
- "create_component",
1385
- {
1386
- description:
1387
- "Create an Operational Registry Component for one Environment. Secret pointers are pointers only; do not paste credentials or secret values.",
1388
- inputSchema: {
1389
- workspaceId: workspaceIdSchema,
1390
- name: z.string().min(1),
1391
- environmentId: z.string().min(1),
1392
- kind: z.string().min(1),
1393
- locator: componentLocatorSchema,
1394
- summary: z.string().min(1).optional(),
1395
- identifiers: componentIdentifiersSchema,
1396
- secretPointers: z.array(secretPointerSchema).optional(),
1397
- notes: z.string().min(1).optional(),
1398
- fields: recordFieldsSchema
1399
- }
1400
- },
1401
- async (input) => jsonResult(await createComponent(runtime, input, recordActorId))
1402
- );
1403
-
1404
- registerDxcTool(
1405
- "update_component",
1406
- {
1407
- description:
1408
- "Update an Operational Registry Component while preserving prior versions. Secret pointers are pointers only; do not paste credentials or secret values.",
1409
- inputSchema: {
1410
- workspaceId: workspaceIdSchema,
1411
- id: z.string().min(1),
1412
- name: z.string().min(1).optional(),
1413
- kind: z.string().min(1).optional(),
1414
- locator: componentLocatorSchema.optional(),
1415
- summary: z.string().min(1).optional(),
1416
- identifiers: componentIdentifiersSchema,
1417
- secretPointers: z.array(secretPointerSchema).optional(),
1418
- notes: z.string().min(1).optional(),
1419
- fields: recordFieldsSchema,
1420
- unsetFields: z.array(fieldNameSchema).optional(),
1421
- revisionNote: z.string().min(1).optional()
1422
- }
1423
- },
1424
- async (input) => jsonResult(await updateComponent(runtime, input, recordActorId))
1425
- );
1426
-
1427
- registerDxcTool(
1428
- "create_maintenance_schedule",
1429
- {
1430
- description:
1431
- "Create a Maintenance Schedule for recurring operational hygiene. Due state is derived from cadence and linked completed Changes or Tasks.",
1432
- inputSchema: {
1433
- workspaceId: workspaceIdSchema,
1434
- name: z.string().min(1),
1435
- kind: z.string().min(1),
1436
- cadence: maintenanceCadenceSchema,
1437
- startDate: z.string().min(1),
1438
- summary: z.string().min(1).optional(),
1439
- rationale: z.string().min(1).optional(),
1440
- notes: z.string().min(1).optional(),
1441
- fields: recordFieldsSchema
1442
- }
1443
- },
1444
- async (input) => jsonResult(await createMaintenanceSchedule(runtime, input, recordActorId))
1445
- );
1446
-
1447
- registerDxcTool(
1448
- "update_maintenance_schedule",
1449
- {
1450
- description: "Update a Maintenance Schedule while preserving prior versions.",
1451
- inputSchema: {
1452
- workspaceId: workspaceIdSchema,
1453
- id: z.string().min(1),
1454
- name: z.string().min(1).optional(),
1455
- kind: z.string().min(1).optional(),
1456
- cadence: maintenanceCadenceSchema.optional(),
1457
- startDate: z.string().min(1).optional(),
1458
- summary: z.string().min(1).optional(),
1459
- rationale: z.string().min(1).optional(),
1460
- notes: z.string().min(1).optional(),
1461
- fields: recordFieldsSchema,
1462
- unsetFields: z.array(fieldNameSchema).optional(),
1463
- revisionNote: z.string().min(1).optional()
1464
- }
1465
- },
1466
- async (input) => jsonResult(await updateMaintenanceSchedule(runtime, input, recordActorId))
1467
- );
1468
-
1469
- registerDxcTool(
1470
- "create_estimate",
1471
- {
1472
- description: "Create an itemized Engineer cost estimate for Weigh.",
1473
- inputSchema: {
1474
- workspaceId: workspaceIdSchema,
1475
- title: z.string().min(1),
1476
- summary: z.string().min(1).optional(),
1477
- lineItems: z.array(estimateLineItemSchema).min(1),
1478
- requirementIds: z.array(z.string().min(1)).optional(),
1479
- expectationIds: z.array(z.string().min(1)).optional(),
1480
- fields: recordFieldsSchema
1481
- }
1482
- },
1483
- async (input) => jsonResult(await createEstimate(runtime, input, recordActorId))
1484
- );
1485
-
1486
- registerDxcTool(
1487
- "update_estimate",
1488
- {
1489
- description: "Update an itemized Engineer cost estimate while preserving prior versions.",
1490
- inputSchema: {
1491
- workspaceId: workspaceIdSchema,
1492
- id: z.string().min(1),
1493
- title: z.string().min(1).optional(),
1494
- summary: z.string().min(1).optional(),
1495
- lineItems: z.array(estimateLineItemSchema).min(1).optional(),
1496
- fields: recordFieldsSchema,
1497
- unsetFields: z.array(fieldNameSchema).optional(),
1498
- revisionNote: z.string().min(1).optional()
1499
- }
1500
- },
1501
- async (input) => jsonResult(await updateEstimate(runtime, input, recordActorId))
1502
- );
1503
-
1504
- registerDxcTool(
1505
- "create_benefits",
1506
- {
1507
- description: "Create an Owner-authored Benefits record for Weigh.",
1508
- inputSchema: {
1509
- workspaceId: workspaceIdSchema,
1510
- title: z.string().min(1),
1511
- summary: z.string().min(1).optional(),
1512
- benefitItems: z.array(benefitItemSchema).min(1),
1513
- requirementIds: z.array(z.string().min(1)).optional(),
1514
- expectationIds: z.array(z.string().min(1)).optional(),
1515
- fields: recordFieldsSchema
1516
- }
1517
- },
1518
- async (input) => jsonResult(await createBenefits(runtime, input, recordActorId))
1519
- );
1520
-
1521
- registerDxcTool(
1522
- "update_benefits",
1523
- {
1524
- description: "Update an Owner-authored Benefits record while preserving prior versions.",
1525
- inputSchema: {
1526
- workspaceId: workspaceIdSchema,
1527
- id: z.string().min(1),
1528
- title: z.string().min(1).optional(),
1529
- summary: z.string().min(1).optional(),
1530
- benefitItems: z.array(benefitItemSchema).min(1).optional(),
1531
- fields: recordFieldsSchema,
1532
- unsetFields: z.array(fieldNameSchema).optional(),
1533
- revisionNote: z.string().min(1).optional()
1534
- }
1535
- },
1536
- async (input) => jsonResult(await updateBenefits(runtime, input, recordActorId))
1537
- );
1538
-
1539
- registerDxcTool(
1540
- "create_value_realization",
1541
- {
1542
- description:
1543
- "Create a Value Realization record for measured before/after value. Comparisons are derived from baseline and actual metric values.",
1544
- inputSchema: {
1545
- workspaceId: workspaceIdSchema,
1546
- title: z.string().min(1),
1547
- summary: z.string().min(1).optional(),
1548
- metrics: z.array(valueMetricSchema).min(1),
1549
- requirementIds: z.array(z.string().min(1)).optional(),
1550
- expectationIds: z.array(z.string().min(1)).optional(),
1551
- commitmentIds: z.array(z.string().min(1)).optional(),
1552
- fields: recordFieldsSchema
1553
- }
1554
- },
1555
- async (input) => jsonResult(await createValueRealization(runtime, input, recordActorId))
1556
- );
1557
-
1558
- registerDxcTool(
1559
- "update_value_realization",
1560
- {
1561
- description: "Update a Value Realization record while preserving prior metric versions.",
1562
- inputSchema: {
1563
- workspaceId: workspaceIdSchema,
1564
- id: z.string().min(1),
1565
- title: z.string().min(1).optional(),
1566
- summary: z.string().min(1).optional(),
1567
- metrics: z.array(valueMetricSchema).min(1).optional(),
1568
- fields: recordFieldsSchema,
1569
- unsetFields: z.array(fieldNameSchema).optional(),
1570
- revisionNote: z.string().min(1).optional()
1571
- }
1572
- },
1573
- async (input) => jsonResult(await updateValueRealization(runtime, input, recordActorId))
1574
- );
1575
-
1576
- registerDxcTool(
1577
- "create_expectation",
1578
- {
1579
- description: "Create an expectation record.",
1580
- inputSchema: {
1581
- workspaceId: workspaceIdSchema,
1582
- title: z.string().min(1),
1583
- statement: z.string().min(1),
1584
- successRecognition: z.string().min(1).optional(),
1585
- approvalState: expectationApprovalStateSchema.optional(),
1586
- approvedBy: z.string().min(1).optional(),
1587
- approvedAt: z.string().min(1).optional(),
1588
- source: z.string().min(1).optional(),
1589
- statementId: z.string().min(1).optional(),
1590
- fields: recordFieldsSchema
1591
- }
1592
- },
1593
- async ({
1594
- workspaceId,
1595
- title,
1596
- statement,
1597
- successRecognition,
1598
- approvalState,
1599
- approvedBy,
1600
- approvedAt,
1601
- source,
1602
- statementId,
1603
- fields
1604
- }) =>
1605
- jsonResult(
1606
- await createExpectation(
1607
- runtime,
1608
- {
1609
- workspaceId,
1610
- title,
1611
- statement,
1612
- successRecognition,
1613
- approvalState,
1614
- approvedBy,
1615
- approvedAt,
1616
- source,
1617
- statementId,
1618
- fields
1619
- },
1620
- recordActorId
1621
- )
1622
- )
1623
- );
1624
-
1625
- registerDxcTool(
1626
- "create_requirement",
1627
- {
1628
- description: "Create a requirement record.",
1629
- inputSchema: {
1630
- workspaceId: workspaceIdSchema,
1631
- title: z.string().min(1),
1632
- expectationId: z.string().min(1).optional(),
1633
- statement: z.string().min(1),
1634
- acceptanceCriteria: z.array(z.string().min(1)).optional(),
1635
- priority: z.enum(["low", "medium", "high"]).optional(),
1636
- status: requirementStatusSchema.optional(),
1637
- fields: recordFieldsSchema
1638
- }
1639
- },
1640
- async ({ workspaceId, title, expectationId, statement, acceptanceCriteria, priority, status, fields }) =>
1641
- jsonResult(
1642
- await createRequirement(
1643
- runtime,
1644
- { workspaceId, title, expectationId, statement, acceptanceCriteria, priority, status, fields },
1645
- recordActorId
1646
- )
1647
- )
1648
- );
1649
-
1650
- registerDxcTool(
1651
- "create_task",
1652
- {
1653
- description:
1654
- "Create an execution task ledger. Current status is derived from the latest status_change entry.",
1655
- inputSchema: {
1656
- workspaceId: workspaceIdSchema,
1657
- title: z.string().min(1),
1658
- description: z.string().min(1),
1659
- assignee: z.string().min(1).optional(),
1660
- assignor: z.string().min(1).optional(),
1661
- requirementId: z.string().min(1).optional(),
1662
- initialStatus: taskStatusSchema.optional(),
1663
- fields: recordFieldsSchema
1664
- }
1665
- },
1666
- async (input) => jsonResult(await createTask(runtime, input, recordActorId))
1667
- );
1668
-
1669
- registerDxcTool(
1670
- "append_task_entry",
1671
- {
1672
- description:
1673
- "Append an immutable entry to a Task. Use status_change entries to change the derived current status.",
1674
- inputSchema: {
1675
- workspaceId: workspaceIdSchema,
1676
- taskId: z.string().min(1),
1677
- entryType: taskEntryTypeSchema,
1678
- body: z.string().min(1),
1679
- status: taskStatusSchema.optional()
1680
- }
1681
- },
1682
- async (input) => jsonResult(await appendTaskEntry(runtime.db, input, recordActorId))
1683
- );
1684
-
1685
- registerDxcTool(
1686
- "create_commitment",
1687
- {
1688
- description: "Create an Owner commitment record that moves requirements or expectations toward Build.",
1689
- inputSchema: {
1690
- workspaceId: workspaceIdSchema,
1691
- title: z.string().min(1),
1692
- summary: z.string().min(1).optional(),
1693
- commitmentStatement: z.string().min(1),
1694
- requirementIds: z.array(z.string().min(1)).optional(),
1695
- expectationIds: z.array(z.string().min(1)).optional(),
1696
- reservationNotes: z.array(z.string().min(1)).optional(),
1697
- deferralId: z.string().min(1).optional(),
1698
- fields: recordFieldsSchema
1699
- }
1700
- },
1701
- async (input) => jsonResult(await createCommitment(runtime, input, recordActorId))
1702
- );
1703
-
1704
- registerDxcTool(
1705
- "create_deferral",
1706
- {
1707
- description: "Create an Owner deferral record with explicit conditions required for a future Commitment.",
1708
- inputSchema: {
1709
- workspaceId: workspaceIdSchema,
1710
- title: z.string().min(1),
1711
- summary: z.string().min(1).optional(),
1712
- reason: z.string().min(1),
1713
- conditions: z.array(z.string().min(1)).min(1),
1714
- requirementIds: z.array(z.string().min(1)).optional(),
1715
- expectationIds: z.array(z.string().min(1)).optional(),
1716
- fields: recordFieldsSchema
1717
- }
1718
- },
1719
- async (input) => jsonResult(await createDeferral(runtime, input, recordActorId))
1720
- );
1721
-
1722
- registerDxcTool(
1723
- "append_deferral_event",
1724
- {
1725
- description:
1726
- "Append an immutable event to a Deferral record. Use this for condition updates, notes, resolution into Commitment, or abandonment.",
1727
- inputSchema: {
1728
- workspaceId: workspaceIdSchema,
1729
- deferralId: z.string().min(1),
1730
- eventType: deferralEventTypeSchema,
1731
- conditionId: z.string().min(1).optional(),
1732
- note: z.string().min(1).optional(),
1733
- summary: z.string().min(1).optional(),
1734
- reason: z.string().min(1).optional(),
1735
- commitmentId: z.string().min(1).optional()
1736
- }
1737
- },
1738
- async (input) => jsonResult(await appendDeferralEventForTool(runtime, input, recordActorId))
1739
- );
1740
-
1741
- registerDxcTool(
1742
- "create_change",
1743
- {
1744
- description:
1745
- "Create a service change record with baseline type, plan, execution, rollback, and risk/impact sections. Use riskImpact to include downstream impact or blast radius when known.",
1746
- inputSchema: {
1747
- workspaceId: workspaceIdSchema,
1748
- title: z.string().min(1),
1749
- summary: z.string().min(1).optional(),
1750
- changeType: changeTypeSchema.optional(),
1751
- impactGrade: changeImpactGradeSchema.optional(),
1752
- emergencyImportance: z.string().min(1).optional(),
1753
- emergencyImmediacy: z.string().min(1).optional(),
1754
- changePlan: z.string().min(1),
1755
- executionSteps: z.array(z.string().min(1)).min(1),
1756
- rollbackPlan: z.string().min(1),
1757
- riskImpact: z
1758
- .string()
1759
- .min(1)
1760
- .describe(
1761
- "Risk, impact, open concerns, and downstream impact for this Change. Include what else may be affected, what depends on what is changing, and the blast-radius conclusion identified by the Engineer or their tool when available. This is documentary and absence of analysis is visible; it is not a separate blocker."
1762
- ),
1763
- plannedFor: z.string().min(1).optional(),
1764
- requirementId: z.string().min(1).optional(),
1765
- fields: recordFieldsSchema
1766
- }
1767
- },
1768
- async (input) => jsonResult(await createChange(runtime, input, recordActorId))
1769
- );
1770
-
1771
- registerDxcTool(
1772
- "append_change_event",
1773
- {
1774
- description:
1775
- "Append an immutable event to a Change record. Use this for notice, veto, decision, result, recovery, plan revisions, and notes. Result and recovery events may include optional Git commit references as documentary traceability.",
1776
- inputSchema: {
1777
- workspaceId: workspaceIdSchema,
1778
- changeId: z.string().min(1),
1779
- eventType: changeEventTypeSchema,
1780
- notice: z.string().min(1).optional(),
1781
- noticeTo: z.array(z.string().min(1)).optional(),
1782
- effectiveAt: z.string().min(1).optional(),
1783
- vetoByRole: changeVetoRoleSchema.optional(),
1784
- reason: z.string().min(1).optional(),
1785
- decision: changeDecisionSchema.optional(),
1786
- result: changeResultSchema.optional(),
1787
- gitCommitReferences: z
1788
- .array(gitCommitReferenceSchema)
1789
- .min(1)
1790
- .optional()
1791
- .describe(
1792
- "Optional Git commit references for result or recovery events. Each reference stores a commit identifier plus optional repository and URL. DX Complete records these as provided and does not validate or inspect Git."
1793
- ),
1794
- summary: z.string().min(1).optional(),
1795
- note: z.string().min(1).optional(),
1796
- revisedChangeType: changeTypeSchema.optional(),
1797
- revisedImpactGrade: changeImpactGradeSchema.optional(),
1798
- revisedEmergencyImportance: z.string().min(1).optional(),
1799
- revisedEmergencyImmediacy: z.string().min(1).optional(),
1800
- revisedChangePlan: z.string().min(1).optional(),
1801
- revisedExecutionSteps: z.array(z.string().min(1)).optional(),
1802
- revisedRollbackPlan: z.string().min(1).optional(),
1803
- revisedRiskImpact: z.string().min(1).optional(),
1804
- revisedPlannedFor: z.string().min(1).optional()
1805
- }
1806
- },
1807
- async (input) =>
1808
- jsonResult(
1809
- await appendChangeEvent(
1810
- runtime.db,
1811
- {
1812
- workspaceId: input.workspaceId,
1813
- changeId: input.changeId,
1814
- eventType: input.eventType,
1815
- event: buildChangeEventContent(input)
1816
- },
1817
- recordActorId
1818
- )
1819
- )
1820
- );
1821
-
1822
- registerDxcTool(
1823
- "create_decision",
1824
- {
1825
- description:
1826
- "Create a revisitable decision ledger. Current decision is derived from the latest decision entry.",
1827
- inputSchema: {
1828
- workspaceId: workspaceIdSchema,
1829
- title: z.string().min(1),
1830
- matter: z.string().min(1),
1831
- initialEntries: z.array(decisionInitialEntrySchema).optional(),
1832
- initialDecision: initialDecisionSchema.optional(),
1833
- fields: recordFieldsSchema
1834
- }
1835
- },
1836
- async ({ workspaceId, title, matter, initialEntries, initialDecision, fields }) => {
1837
- assertNoTypedFields(fields, "create_decision", DECISION_TYPED_FIELDS);
1838
- assertNoDecisionInputFields(fields);
1839
-
1840
- return jsonResult(await createDecision(runtime, { workspaceId, title, matter, initialEntries, initialDecision, fields }, recordActorId));
1841
- }
1842
- );
1843
-
1844
- registerDxcTool(
1845
- "append_decision_entry",
1846
- {
1847
- description:
1848
- "Append an immutable entry to a Decision. Use decision entries to change the derived current decision.",
1849
- inputSchema: {
1850
- workspaceId: workspaceIdSchema,
1851
- decisionId: z.string().min(1),
1852
- entryType: decisionEntryTypeSchema,
1853
- body: z.string().min(1),
1854
- decidedBy: z.string().min(1).optional(),
1855
- rationale: z.string().min(1).optional()
1856
- }
1857
- },
1858
- async (input) => jsonResult(await appendDecisionEntry(runtime.db, input, recordActorId))
1859
- );
1860
-
1861
- registerDxcTool(
1862
- "create_risk",
1863
- {
1864
- description: "Create a Risk ledger for uncertainty or exposure. Current status, assessment, and treatment derive from entries.",
1865
- inputSchema: {
1866
- workspaceId: workspaceIdSchema,
1867
- title: z.string().min(1),
1868
- topic: z.string().min(1),
1869
- summary: z.string().min(1).optional(),
1870
- body: z.string().min(1).optional(),
1871
- likelihood: riskLevelSchema.optional(),
1872
- impact: riskLevelSchema.optional(),
1873
- treatment: riskTreatmentSchema.optional(),
1874
- treatmentRationale: z.string().min(1).optional(),
1875
- fields: recordFieldsSchema
1876
- }
1877
- },
1878
- async (input) => jsonResult(await createRisk(runtime, input, recordActorId, options.workspaceRoles))
1879
- );
1880
-
1881
- registerDxcTool(
1882
- "append_risk_entry",
1883
- {
1884
- description:
1885
- "Append an immutable entry to a Risk. Use assessment entries for likelihood/impact and treatment entries for accept, mitigate, transfer, or avoid.",
1886
- inputSchema: {
1887
- workspaceId: workspaceIdSchema,
1888
- riskId: z.string().min(1),
1889
- entryType: riskEntryTypeSchema,
1890
- body: z.string().min(1),
1891
- likelihood: riskLevelSchema.optional(),
1892
- impact: riskLevelSchema.optional(),
1893
- treatment: riskTreatmentSchema.optional(),
1894
- treatmentRationale: z.string().min(1).optional()
1895
- }
1896
- },
1897
- async (input) => {
1898
- assertRiskAcceptanceAccess(input.treatment, options.workspaceRoles);
1899
- return jsonResult(await appendRiskEntry(runtime.db, input, recordActorId));
1900
- }
1901
- );
1902
-
1903
- registerDxcTool(
1904
- "create_incident",
1905
- {
1906
- description:
1907
- "Create an Incident ledger for a specific service-impacting or potentially service-impacting occurrence.",
1908
- inputSchema: {
1909
- workspaceId: workspaceIdSchema,
1910
- title: z.string().min(1),
1911
- description: z.string().min(1),
1912
- summary: z.string().min(1).optional(),
1913
- severity: incidentSeveritySchema.optional(),
1914
- componentIds: z.array(z.string().min(1)).optional(),
1915
- fields: recordFieldsSchema
1916
- }
1917
- },
1918
- async (input) => jsonResult(await createIncident(runtime, input, recordActorId))
1919
- );
1920
-
1921
- registerDxcTool(
1922
- "append_incident_entry",
1923
- {
1924
- description:
1925
- "Append an immutable entry to an Incident. Current status and severity derive from the latest relevant entries.",
1926
- inputSchema: {
1927
- workspaceId: workspaceIdSchema,
1928
- incidentId: z.string().min(1),
1929
- entryType: incidentEntryTypeSchema,
1930
- body: z.string().min(1),
1931
- severity: incidentSeveritySchema.optional()
1932
- }
1933
- },
1934
- async (input) => jsonResult(await appendIncidentEntry(runtime.db, input, recordActorId))
1935
- );
1936
-
1937
- registerDxcTool(
1938
- "create_support_request",
1939
- {
1940
- description:
1941
- "Create a shared Support Request ledger for a reported user experience, question, request, or issue. This is distinct from a private DX Complete Ticket.",
1942
- inputSchema: {
1943
- workspaceId: workspaceIdSchema,
1944
- title: z.string().min(1),
1945
- reporter: z.string().min(1),
1946
- kind: z.string().min(1),
1947
- reportedExperience: z.string().min(1),
1948
- summary: z.string().min(1).optional(),
1949
- fields: recordFieldsSchema
1950
- }
1951
- },
1952
- async (input) => jsonResult(await createSupportRequest(runtime, input, recordActorId))
1953
- );
1954
-
1955
- registerDxcTool(
1956
- "append_support_request_entry",
1957
- {
1958
- description:
1959
- "Append an immutable entry to a Support Request. Escalated entries require an Incident link; current status derives from the latest status-bearing entry.",
1960
- inputSchema: {
1961
- workspaceId: workspaceIdSchema,
1962
- supportRequestId: z.string().min(1),
1963
- entryType: supportRequestEntryTypeSchema,
1964
- body: z.string().min(1),
1965
- incidentId: z.string().min(1).optional()
1966
- }
1967
- },
1968
- async (input) => jsonResult(await appendSupportRequestEntryForTool(runtime, input, recordActorId))
1969
- );
1970
-
1971
- registerDxcTool(
1972
- "create_problem",
1973
- {
1974
- description:
1975
- "Create a Problem ledger for an underlying or recurring cause evidenced by one or more Incidents.",
1976
- inputSchema: {
1977
- workspaceId: workspaceIdSchema,
1978
- title: z.string().min(1),
1979
- description: z.string().min(1),
1980
- summary: z.string().min(1).optional(),
1981
- incidentIds: z.array(z.string().min(1)).min(1),
1982
- componentIds: z.array(z.string().min(1)).optional(),
1983
- fields: recordFieldsSchema
1984
- }
1985
- },
1986
- async (input) => jsonResult(await createProblem(runtime, input, recordActorId))
1987
- );
1988
-
1989
- registerDxcTool(
1990
- "append_problem_entry",
1991
- {
1992
- description:
1993
- "Append an immutable entry to a Problem. Current status and root cause derive from the latest relevant entries.",
1994
- inputSchema: {
1995
- workspaceId: workspaceIdSchema,
1996
- problemId: z.string().min(1),
1997
- entryType: problemEntryTypeSchema,
1998
- body: z.string().min(1),
1999
- rootCause: z.string().min(1).optional()
2000
- }
2001
- },
2002
- async (input) => jsonResult(await appendProblemEntry(runtime.db, input, recordActorId))
2003
- );
2004
-
2005
- registerDxcTool(
2006
- "list_records",
2007
- {
2008
- description: "List records from a DX Complete collection.",
2009
- inputSchema: {
2010
- recordType: activeCollectionSchema,
2011
- workspaceId: workspaceIdSchema.optional(),
2012
- limit: z.number().int().min(1).max(100).optional(),
2013
- includeArchived: z.boolean().optional()
2014
- }
2015
- },
2016
- async ({ recordType, workspaceId, limit, includeArchived }) =>
2017
- jsonResult(await listRecords(runtime.db, recordType, limit ?? 20, { workspaceId, includeArchived }))
2018
- );
2019
-
2020
- registerDxcTool(
2021
- "list_linked_records",
2022
- {
2023
- description: "List records linked to or from a DX Complete record.",
2024
- inputSchema: {
2025
- recordType: activeCollectionSchema,
2026
- workspaceId: workspaceIdSchema.optional(),
2027
- id: z.string().min(1),
2028
- direction: z.enum(["outbound", "inbound", "both"]).optional(),
2029
- relationship: z.string().min(1).optional(),
2030
- includeArchived: z.boolean().optional()
2031
- }
2032
- },
2033
- async (input) => jsonResult(await listLinkedRecords(runtime.db, input))
2034
- );
2035
-
2036
- registerDxcTool(
2037
- "link_decision_input",
2038
- {
2039
- description: "Link a Decision to one record that informed it using the informed_by relationship.",
2040
- inputSchema: {
2041
- workspaceId: workspaceIdSchema,
2042
- decisionId: z.string().min(1),
2043
- inputRecordType: decisionInputRecordTypeSchema,
2044
- inputId: z.string().min(1)
2045
- }
2046
- },
2047
- async (input) => jsonResult(await linkDecisionInput(runtime, input, recordActorId))
2048
- );
2049
-
2050
- registerDxcTool(
2051
- "update_record",
2052
- {
2053
- description: "Update a DX Complete record and optionally clear top-level fields.",
2054
- inputSchema: {
2055
- recordType: activeCollectionSchema,
2056
- workspaceId: workspaceIdSchema.optional(),
2057
- id: z.string().min(1),
2058
- title: z.string().min(1).optional(),
2059
- summary: z.string().min(1).optional(),
2060
- fields: recordFieldsSchema,
2061
- unsetFields: z.array(fieldNameSchema).optional()
2062
- }
2063
- },
2064
- async (input) => jsonResult(await updateRecord(runtime.db, input, recordActorId))
2065
- );
2066
-
2067
- registerDxcTool(
2068
- "update_expectation",
2069
- {
2070
- description: "Update an expectation record with typed expectation fields.",
2071
- inputSchema: {
2072
- workspaceId: workspaceIdSchema,
2073
- id: z.string().min(1),
2074
- title: z.string().min(1).optional(),
2075
- statement: z.string().min(1).optional(),
2076
- successRecognition: z.string().min(1).optional(),
2077
- approvalState: expectationApprovalStateSchema.optional(),
2078
- approvedBy: z.string().min(1).optional(),
2079
- approvedAt: z.string().min(1).optional(),
2080
- source: z.string().min(1).optional(),
2081
- revisionNote: z.string().min(1).optional(),
2082
- fields: recordFieldsSchema,
2083
- unsetFields: z.array(fieldNameSchema).optional()
2084
- }
2085
- },
2086
- async (input) => jsonResult(await updateExpectation(runtime, input, recordActorId))
2087
- );
2088
-
2089
- registerDxcTool(
2090
- "update_requirement",
2091
- {
2092
- description: "Update a requirement record with typed requirement fields.",
2093
- inputSchema: {
2094
- workspaceId: workspaceIdSchema,
2095
- id: z.string().min(1),
2096
- title: z.string().min(1).optional(),
2097
- statement: z.string().min(1).optional(),
2098
- acceptanceCriteria: z.array(z.string().min(1)).optional(),
2099
- priority: z.enum(["low", "medium", "high"]).optional(),
2100
- status: requirementStatusSchema.optional(),
2101
- revisionNote: z.string().min(1).optional(),
2102
- fields: recordFieldsSchema,
2103
- unsetFields: z.array(fieldNameSchema).optional()
2104
- }
2105
- },
2106
- async (input) => jsonResult(await updateRequirement(runtime, input, recordActorId))
2107
- );
2108
-
2109
- registerDxcTool(
2110
- "append_review_note",
2111
- {
2112
- description:
2113
- "Append a non-blocking review note to an expectation or requirement. The optional important flag only surfaces the note; it does not create an approval duty or workflow block.",
2114
- inputSchema: {
2115
- workspaceId: workspaceIdSchema,
2116
- recordType: reviewableRecordTypeSchema,
2117
- id: z.string().min(1),
2118
- body: z.string().min(1),
2119
- important: z.boolean().optional()
2120
- }
2121
- },
2122
- async (input) => jsonResult(await appendReviewNote(runtime.db, input, recordActorId))
2123
- );
2124
-
2125
- registerDxcTool(
2126
- "archive_record",
2127
- {
2128
- description: "Archive a DX Complete record without deleting it.",
2129
- inputSchema: {
2130
- recordType: activeCollectionSchema,
2131
- workspaceId: workspaceIdSchema.optional(),
2132
- id: z.string().min(1),
2133
- reason: z.string().min(1).optional(),
2134
- supersededByType: activeCollectionSchema.optional(),
2135
- supersededById: z.string().min(1).optional()
2136
- }
2137
- },
2138
- async (input) => jsonResult(await archiveRecord(runtime.db, input, recordActorId))
2139
- );
2140
-
2141
- registerDxcTool(
2142
- "link_records",
2143
- {
2144
- description: "Link one DX Complete record to another.",
2145
- inputSchema: {
2146
- workspaceId: workspaceIdSchema,
2147
- fromType: activeCollectionSchema,
2148
- fromId: z.string().min(1),
2149
- toType: activeCollectionSchema,
2150
- toId: z.string().min(1),
2151
- relationship: z.string().min(1).optional()
2152
- }
2153
- },
2154
- async (input) => jsonResult(await linkRecords(runtime.db, input, recordActorId))
2155
- );
2156
-
2157
- registerDxcTool(
2158
- "unlink_records",
2159
- {
2160
- description: "Remove one relationship link from a DX Complete record to another record.",
2161
- inputSchema: {
2162
- workspaceId: workspaceIdSchema,
2163
- fromType: activeCollectionSchema,
2164
- fromId: z.string().min(1),
2165
- toType: activeCollectionSchema,
2166
- toId: z.string().min(1),
2167
- relationship: z.string().min(1).optional()
2168
- }
2169
- },
2170
- async (input) => jsonResult(await unlinkRecords(runtime.db, input, recordActorId))
2171
- );
2172
-
2173
- return server;
2174
- }
2175
-
2176
- function omitWorkspaceId(schema: ToolSchema): ToolSchema {
2177
- const result: ToolSchema = {};
2178
-
2179
- for (const [key, value] of Object.entries(schema)) {
2180
- if (key !== "workspaceId") {
2181
- result[key] = value;
2182
- }
2183
- }
2184
-
2185
- return result;
2186
- }
2187
-
2188
- function injectHostedWorkspace(
2189
- input: Record<string, unknown>,
2190
- originalSchema: ToolSchema,
2191
- workspaceId: string
2192
- ): Record<string, unknown> {
2193
- if (!Object.hasOwn(originalSchema, "workspaceId")) {
2194
- return input;
2195
- }
2196
-
2197
- return {
2198
- ...input,
2199
- workspaceId
2200
- };
2201
- }
2202
-
2203
- function assertHostedWorkspaceAccess(
2204
- toolName: string,
2205
- input: Record<string, unknown>,
2206
- workspaceId: string | undefined
2207
- ): void {
2208
- if (!workspaceId) {
2209
- return;
2210
- }
2211
-
2212
- for (const key of ["recordType", "fromType", "toType", "supersededByType"]) {
2213
- if (input[key] === "workspaces") {
2214
- throw new Error(
2215
- `${toolName} cannot operate on workspace records through a hosted workspace MCP endpoint.`
2216
- );
2217
- }
2218
- }
2219
-
2220
- if (typeof input.workspaceId === "string" && input.workspaceId !== workspaceId) {
2221
- throw new Error("Hosted MCP workspace scope mismatch.");
2222
- }
2223
- }
2224
-
2225
- function assertToolRoleAccess(toolName: string, roles: WorkspaceRole[] | undefined, input: Record<string, unknown>): void {
2226
- if (!roles) {
2227
- return;
2228
- }
2229
-
2230
- if (roles.includes("owner") || memberAllowedTools.has(toolName)) {
2231
- return;
2232
- }
2233
-
2234
- if (roles.includes("engineer") && engineerAllowedTools.has(toolName)) {
2235
- return;
2236
- }
2237
-
2238
- if (roles.includes("tester") && testerAllowedTools.has(toolName)) {
2239
- return;
2240
- }
2241
-
2242
- if (roles.includes("operator") && operatorAllowedTools.has(toolName)) {
2243
- return;
2244
- }
2245
-
2246
- if (roles.includes("support_agent") && supportAgentAllowedTools.has(toolName)) {
2247
- return;
2248
- }
2249
-
2250
- if (
2251
- roles.includes("operator") &&
2252
- toolName === "archive_record" &&
2253
- (input.recordType === "environments" || input.recordType === "components" || input.recordType === "maintenance_schedules")
2254
- ) {
2255
- return;
2256
- }
2257
-
2258
- throw new Error(`Workspace role access denied for ${toolName}.`);
2259
- }
2260
-
2261
- const memberAllowedTools = new Set([
2262
- "runtime_status",
2263
- "get_process_guide",
2264
- "get_doc",
2265
- "get_record",
2266
- "list_records",
2267
- "list_linked_records",
2268
- "list_environments",
2269
- "list_components",
2270
- "create_dxcomplete_ticket",
2271
- "append_dxcomplete_ticket",
2272
- "list_dxcomplete_tickets",
2273
- "list_unread_dxcomplete_ticket_replies",
2274
- "read_dxcomplete_ticket",
2275
- "archive_dxcomplete_ticket",
2276
- "append_journal_note",
2277
- "read_journal",
2278
- "get_journal_entry",
2279
- "append_journal_summary"
2280
- ]);
2281
-
2282
- const engineerAllowedTools = new Set([
2283
- "create_estimate",
2284
- "update_estimate",
2285
- "create_task",
2286
- "append_task_entry",
2287
- "create_risk",
2288
- "append_risk_entry",
2289
- "append_review_note"
2290
- ]);
2291
-
2292
- const testerAllowedTools = new Set([
2293
- "create_risk",
2294
- "append_risk_entry",
2295
- "append_review_note"
2296
- ]);
2297
-
2298
- const operatorAllowedTools = new Set([
2299
- "create_change",
2300
- "append_change_event",
2301
- "create_risk",
2302
- "append_risk_entry",
2303
- "create_incident",
2304
- "append_incident_entry",
2305
- "create_problem",
2306
- "append_problem_entry",
2307
- "create_environment",
2308
- "update_environment",
2309
- "create_component",
2310
- "update_component",
2311
- "create_maintenance_schedule",
2312
- "update_maintenance_schedule"
2313
- ]);
2314
-
2315
- const supportAgentAllowedTools = new Set([
2316
- "create_incident",
2317
- "append_incident_entry",
2318
- "create_support_request",
2319
- "append_support_request_entry"
2320
- ]);
2321
-
2322
- function jsonResult(value: unknown) {
2323
- return {
2324
- content: [
2325
- {
2326
- type: "text" as const,
2327
- text: JSON.stringify(value, null, 2)
2328
- }
2329
- ]
2330
- };
2331
- }
2332
-
2333
- function getInputSchemaFingerprint(inputSchema: ToolSchema): string {
2334
- return createHash("sha256")
2335
- .update(stableStringify(z.toJSONSchema(z.object(inputSchema))))
2336
- .digest("hex")
2337
- .slice(0, 16);
2338
- }
2339
-
2340
- function stableStringify(value: unknown): string {
2341
- return JSON.stringify(sortJsonValue(value));
2342
- }
2343
-
2344
- function sortJsonValue(value: unknown): unknown {
2345
- if (Array.isArray(value)) {
2346
- return value.map(sortJsonValue);
2347
- }
2348
-
2349
- if (value && typeof value === "object") {
2350
- const input = value as Record<string, unknown>;
2351
- const output: Record<string, unknown> = {};
2352
-
2353
- for (const key of Object.keys(input).sort()) {
2354
- output[key] = sortJsonValue(input[key]);
2355
- }
2356
-
2357
- return output;
2358
- }
2359
-
2360
- return value;
2361
- }
2362
-
2363
-
2364
- async function createStatement(
2365
- runtime: DxRuntime,
2366
- input: {
2367
- workspaceId: string;
2368
- title: string;
2369
- statement: string;
2370
- source?: string;
2371
- fields?: Record<string, unknown>;
2372
- },
2373
- actorId: string
2374
- ) {
2375
- assertNoTypedFields(input.fields, "create_statement", STATEMENT_TYPED_FIELDS);
2376
-
2377
- return createRecord(
2378
- runtime.db,
2379
- "statements",
2380
- {
2381
- workspaceId: input.workspaceId,
2382
- title: input.title,
2383
- summary: input.statement,
2384
- fields: {
2385
- ...(input.fields ?? {}),
2386
- statement: input.statement,
2387
- ...(input.source !== undefined ? { source: input.source } : {})
2388
- }
2389
- },
2390
- actorId
2391
- );
2392
- }
2393
-
2394
- async function updateStatement(
2395
- runtime: DxRuntime,
2396
- input: {
2397
- workspaceId: string;
2398
- id: string;
2399
- title?: string;
2400
- statement?: string;
2401
- source?: string;
2402
- fields?: Record<string, unknown>;
2403
- unsetFields?: string[];
2404
- revisionNote?: string;
2405
- },
2406
- actorId: string
2407
- ) {
2408
- assertNoTypedFields(input.fields, "update_statement", STATEMENT_TYPED_FIELDS);
2409
-
2410
- return updateRecord(
2411
- runtime.db,
2412
- {
2413
- recordType: "statements",
2414
- workspaceId: input.workspaceId,
2415
- id: input.id,
2416
- title: input.title,
2417
- summary: input.statement,
2418
- fields: {
2419
- ...(input.fields ?? {}),
2420
- ...(input.statement !== undefined ? { statement: input.statement } : {}),
2421
- ...(input.source !== undefined ? { source: input.source } : {})
2422
- },
2423
- unsetFields: input.unsetFields,
2424
- allowManagedFields: true,
2425
- revisionNote: input.revisionNote
2426
- },
2427
- actorId
2428
- );
2429
- }
2430
-
2431
- async function createEnvironment(
2432
- runtime: DxRuntime,
2433
- input: {
2434
- workspaceId: string;
2435
- name: string;
2436
- summary?: string;
2437
- description?: string;
2438
- fields?: Record<string, unknown>;
2439
- },
2440
- actorId: string
2441
- ) {
2442
- assertNoTypedFields(input.fields, "create_environment", ENVIRONMENT_TYPED_FIELDS);
2443
-
2444
- return createRecord(
2445
- runtime.db,
2446
- "environments",
2447
- {
2448
- workspaceId: input.workspaceId,
2449
- title: input.name,
2450
- summary: input.summary,
2451
- allowManagedFields: true,
2452
- fields: {
2453
- ...(input.fields ?? {}),
2454
- name: input.name,
2455
- ...(input.description !== undefined ? { description: input.description } : {})
2456
- }
2457
- },
2458
- actorId
2459
- );
2460
- }
2461
-
2462
- async function updateEnvironment(
2463
- runtime: DxRuntime,
2464
- input: {
2465
- workspaceId: string;
2466
- id: string;
2467
- name?: string;
2468
- summary?: string;
2469
- description?: string;
2470
- fields?: Record<string, unknown>;
2471
- unsetFields?: string[];
2472
- revisionNote?: string;
2473
- },
2474
- actorId: string
2475
- ) {
2476
- assertNoTypedFields(input.fields, "update_environment", ENVIRONMENT_TYPED_FIELDS);
2477
- assertNoTypedUnsetFields(input.unsetFields, "update_environment", ENVIRONMENT_TYPED_FIELDS);
2478
-
2479
- return updateRecord(
2480
- runtime.db,
2481
- {
2482
- recordType: "environments",
2483
- workspaceId: input.workspaceId,
2484
- id: input.id,
2485
- title: input.name,
2486
- summary: input.summary,
2487
- fields: {
2488
- ...(input.fields ?? {}),
2489
- ...(input.name !== undefined ? { name: input.name } : {}),
2490
- ...(input.description !== undefined ? { description: input.description } : {})
2491
- },
2492
- unsetFields: input.unsetFields,
2493
- allowManagedFields: true,
2494
- revisionNote: input.revisionNote
2495
- },
2496
- actorId
2497
- );
2498
- }
2499
-
2500
- async function listComponents(
2501
- runtime: DxRuntime,
2502
- input: {
2503
- workspaceId: string;
2504
- environmentId: string;
2505
- limit?: number;
2506
- includeArchived?: boolean;
2507
- }
2508
- ) {
2509
- const environment = await getRecord(runtime.db, "environments", input.environmentId, {
2510
- workspaceId: input.workspaceId
2511
- });
2512
- if (!environment) {
2513
- throw new Error(`Environment not found: environments/${input.environmentId}`);
2514
- }
2515
-
2516
- const filter: Record<string, unknown> = {
2517
- workspaceId: input.workspaceId,
2518
- "fields.environmentId": environment._id
2519
- };
2520
-
2521
- if (!input.includeArchived) {
2522
- filter.archivedAt = { $exists: false };
2523
- }
2524
-
2525
- return runtime.db
2526
- .collection("components")
2527
- .find(filter)
2528
- .sort({ createdAt: 1, _id: 1 })
2529
- .limit(input.limit ?? 20)
2530
- .toArray();
2531
- }
2532
-
2533
- async function createComponent(
2534
- runtime: DxRuntime,
2535
- input: {
2536
- workspaceId: string;
2537
- name: string;
2538
- environmentId: string;
2539
- kind: string;
2540
- locator: ComponentLocatorInput;
2541
- summary?: string;
2542
- identifiers?: ComponentIdentifiersInput;
2543
- secretPointers?: SecretPointerInput[];
2544
- notes?: string;
2545
- fields?: Record<string, unknown>;
2546
- },
2547
- actorId: string
2548
- ) {
2549
- assertNoReservedFields(input.fields, ["workspaceId", "environmentId"]);
2550
- assertNoTypedFields(input.fields, "create_component", COMPONENT_TYPED_FIELDS);
2551
-
2552
- const environment = await getRecord(runtime.db, "environments", input.environmentId, {
2553
- workspaceId: input.workspaceId
2554
- });
2555
- if (!environment) {
2556
- throw new Error(`Environment not found: environments/${input.environmentId}`);
2557
- }
2558
-
2559
- const component = await createRecord(
2560
- runtime.db,
2561
- "components",
2562
- {
2563
- workspaceId: input.workspaceId,
2564
- title: input.name,
2565
- summary: input.summary,
2566
- allowManagedFields: true,
2567
- fields: {
2568
- ...(input.fields ?? {}),
2569
- name: input.name,
2570
- environmentId: environment._id,
2571
- kind: input.kind,
2572
- locator: input.locator,
2573
- ...(input.identifiers !== undefined ? { identifiers: input.identifiers } : {}),
2574
- ...(input.secretPointers !== undefined ? { secretPointers: input.secretPointers } : {}),
2575
- ...(input.notes !== undefined ? { notes: input.notes } : {})
2576
- }
2577
- },
2578
- actorId
2579
- );
2580
-
2581
- return ensureLinkRecords(
2582
- runtime,
2583
- {
2584
- workspaceId: input.workspaceId,
2585
- fromType: "components",
2586
- fromId: component._id,
2587
- toType: "environments",
2588
- toId: environment._id,
2589
- relationship: "belongs_to_environment"
2590
- },
2591
- actorId
2592
- );
2593
- }
2594
-
2595
- async function updateComponent(
2596
- runtime: DxRuntime,
2597
- input: {
2598
- workspaceId: string;
2599
- id: string;
2600
- name?: string;
2601
- kind?: string;
2602
- locator?: ComponentLocatorInput;
2603
- summary?: string;
2604
- identifiers?: ComponentIdentifiersInput;
2605
- secretPointers?: SecretPointerInput[];
2606
- notes?: string;
2607
- fields?: Record<string, unknown>;
2608
- unsetFields?: string[];
2609
- revisionNote?: string;
2610
- },
2611
- actorId: string
2612
- ) {
2613
- assertNoTypedFields(input.fields, "update_component", COMPONENT_TYPED_FIELDS);
2614
- assertNoTypedUnsetFields(input.unsetFields, "update_component", COMPONENT_TYPED_FIELDS);
2615
-
2616
- return updateRecord(
2617
- runtime.db,
2618
- {
2619
- recordType: "components",
2620
- workspaceId: input.workspaceId,
2621
- id: input.id,
2622
- title: input.name,
2623
- summary: input.summary,
2624
- fields: {
2625
- ...(input.fields ?? {}),
2626
- ...(input.name !== undefined ? { name: input.name } : {}),
2627
- ...(input.kind !== undefined ? { kind: input.kind } : {}),
2628
- ...(input.locator !== undefined ? { locator: input.locator } : {}),
2629
- ...(input.identifiers !== undefined ? { identifiers: input.identifiers } : {}),
2630
- ...(input.secretPointers !== undefined ? { secretPointers: input.secretPointers } : {}),
2631
- ...(input.notes !== undefined ? { notes: input.notes } : {})
2632
- },
2633
- unsetFields: input.unsetFields,
2634
- allowManagedFields: true,
2635
- revisionNote: input.revisionNote
2636
- },
2637
- actorId
2638
- );
2639
- }
2640
-
2641
- async function createMaintenanceSchedule(
2642
- runtime: DxRuntime,
2643
- input: {
2644
- workspaceId: string;
2645
- name: string;
2646
- kind: string;
2647
- cadence: MaintenanceCadenceInput;
2648
- startDate: string;
2649
- summary?: string;
2650
- rationale?: string;
2651
- notes?: string;
2652
- fields?: Record<string, unknown>;
2653
- },
2654
- actorId: string
2655
- ) {
2656
- assertNoTypedFields(input.fields, "create_maintenance_schedule", MAINTENANCE_SCHEDULE_TYPED_FIELDS);
2657
-
2658
- return createRecord(
2659
- runtime.db,
2660
- "maintenance_schedules",
2661
- {
2662
- workspaceId: input.workspaceId,
2663
- title: input.name,
2664
- summary: input.summary ?? input.rationale,
2665
- allowManagedFields: true,
2666
- fields: {
2667
- ...(input.fields ?? {}),
2668
- name: input.name,
2669
- kind: input.kind,
2670
- cadence: input.cadence,
2671
- startDate: input.startDate,
2672
- ...(input.rationale !== undefined ? { rationale: input.rationale } : {}),
2673
- ...(input.notes !== undefined ? { notes: input.notes } : {})
2674
- }
2675
- },
2676
- actorId
2677
- );
2678
- }
2679
-
2680
- async function updateMaintenanceSchedule(
2681
- runtime: DxRuntime,
2682
- input: {
2683
- workspaceId: string;
2684
- id: string;
2685
- name?: string;
2686
- kind?: string;
2687
- cadence?: MaintenanceCadenceInput;
2688
- startDate?: string;
2689
- summary?: string;
2690
- rationale?: string;
2691
- notes?: string;
2692
- fields?: Record<string, unknown>;
2693
- unsetFields?: string[];
2694
- revisionNote?: string;
2695
- },
2696
- actorId: string
2697
- ) {
2698
- assertNoTypedFields(input.fields, "update_maintenance_schedule", MAINTENANCE_SCHEDULE_TYPED_FIELDS);
2699
- assertNoTypedUnsetFields(input.unsetFields, "update_maintenance_schedule", MAINTENANCE_SCHEDULE_TYPED_FIELDS);
2700
-
2701
- return updateRecord(
2702
- runtime.db,
2703
- {
2704
- recordType: "maintenance_schedules",
2705
- workspaceId: input.workspaceId,
2706
- id: input.id,
2707
- title: input.name,
2708
- summary: input.summary,
2709
- fields: {
2710
- ...(input.fields ?? {}),
2711
- ...(input.name !== undefined ? { name: input.name } : {}),
2712
- ...(input.kind !== undefined ? { kind: input.kind } : {}),
2713
- ...(input.cadence !== undefined ? { cadence: input.cadence } : {}),
2714
- ...(input.startDate !== undefined ? { startDate: input.startDate } : {}),
2715
- ...(input.rationale !== undefined ? { rationale: input.rationale } : {}),
2716
- ...(input.notes !== undefined ? { notes: input.notes } : {})
2717
- },
2718
- unsetFields: input.unsetFields,
2719
- allowManagedFields: true,
2720
- revisionNote: input.revisionNote
2721
- },
2722
- actorId
2723
- );
2724
- }
2725
-
2726
- async function createExpectation(
2727
- runtime: DxRuntime,
2728
- input: {
2729
- workspaceId: string;
2730
- title: string;
2731
- statement: string;
2732
- successRecognition?: string;
2733
- approvalState?: "draft" | "approved" | "not_approved" | "superseded";
2734
- approvedBy?: string;
2735
- approvedAt?: string;
2736
- source?: string;
2737
- statementId?: string;
2738
- fields?: Record<string, unknown>;
2739
- },
2740
- actorId: string
2741
- ) {
2742
- assertNoTypedFields(input.fields, "create_expectation", EXPECTATION_TYPED_FIELDS);
2743
- assertNoObsoleteExpectationFields(input.fields, "create_expectation");
2744
-
2745
- if (input.statementId) {
2746
- const statement = await getRecord(runtime.db, "statements", input.statementId, {
2747
- workspaceId: input.workspaceId
2748
- });
2749
- if (!statement) {
2750
- throw new Error(`Statement not found: statements/${input.statementId}`);
2751
- }
2752
- }
2753
-
2754
- const expectation = await createRecord(
2755
- runtime.db,
2756
- "expectations",
2757
- {
2758
- workspaceId: input.workspaceId,
2759
- title: input.title,
2760
- summary: input.statement,
2761
- fields: {
2762
- ...(input.fields ?? {}),
2763
- statement: input.statement,
2764
- ...(input.successRecognition !== undefined ? { successRecognition: input.successRecognition } : {}),
2765
- approvalState: input.approvalState ?? "draft",
2766
- ...(input.approvedBy !== undefined ? { approvedBy: input.approvedBy } : {}),
2767
- ...(input.approvedAt !== undefined ? { approvedAt: input.approvedAt } : {}),
2768
- ...(input.source !== undefined ? { source: input.source } : {})
2769
- }
2770
- },
2771
- actorId
2772
- );
2773
-
2774
- if (!input.statementId) {
2775
- return expectation;
2776
- }
2777
-
2778
- return linkRecords(
2779
- runtime.db,
2780
- {
2781
- workspaceId: input.workspaceId,
2782
- fromType: "expectations",
2783
- fromId: expectation._id,
2784
- toType: "statements",
2785
- toId: input.statementId,
2786
- relationship: "derives_from"
2787
- },
2788
- actorId
2789
- );
2790
- }
2791
-
2792
- type EstimateLineItem = {
2793
- id: string;
2794
- label: string;
2795
- timing: "one_time" | "recurring";
2796
- period?: string;
2797
- currency: string;
2798
- amount:
2799
- | {
2800
- kind: "single";
2801
- value: number;
2802
- }
2803
- | {
2804
- kind: "range";
2805
- min: number;
2806
- expected: number;
2807
- max: number;
2808
- };
2809
- };
2810
-
2811
- type BenefitItem = {
2812
- id: string;
2813
- label: string;
2814
- timing?: "one_time" | "recurring";
2815
- period?: string;
2816
- currency?: string;
2817
- amount?: EstimateLineItem["amount"];
2818
- };
2819
-
2820
- type RollupAmount = {
2821
- min: number;
2822
- expected: number;
2823
- max: number;
2824
- };
2825
-
2826
- type QuantifiedRollupItem = {
2827
- timing: "one_time" | "recurring";
2828
- period?: string;
2829
- currency: string;
2830
- amount: EstimateLineItem["amount"];
2831
- };
2832
-
2833
- async function createEstimate(
2834
- runtime: DxRuntime,
2835
- input: {
2836
- workspaceId: string;
2837
- title: string;
2838
- summary?: string;
2839
- lineItems: EstimateLineItemInput[];
2840
- requirementIds?: string[];
2841
- expectationIds?: string[];
2842
- fields?: Record<string, unknown>;
2843
- },
2844
- actorId: string
2845
- ) {
2846
- assertNoReservedFields(input.fields, ["workspaceId", "initiativeId", "requirementIds", "expectationIds"]);
2847
- assertNoTypedFields(input.fields, "create_estimate", ESTIMATE_TYPED_FIELDS);
2848
- assertAtLeastOneEstimateTarget(input.requirementIds, input.expectationIds);
2849
- await assertRecordsExist(runtime, "requirements", input.requirementIds ?? [], input.workspaceId);
2850
- await assertRecordsExist(runtime, "expectations", input.expectationIds ?? [], input.workspaceId);
2851
-
2852
- const lineItems = normalizeEstimateLineItems(input.lineItems);
2853
- let estimate = await createRecord(
2854
- runtime.db,
2855
- "estimates",
2856
- {
2857
- workspaceId: input.workspaceId,
2858
- title: input.title,
2859
- summary: input.summary,
2860
- allowManagedFields: true,
2861
- fields: {
2862
- ...(input.fields ?? {}),
2863
- lineItems,
2864
- rollup: computeQuantifiedRollup(lineItems)
2865
- }
2866
- },
2867
- actorId
2868
- );
2869
-
2870
- estimate = await linkManyRecords(runtime, estimate, "requirements", input.requirementIds ?? [], "estimates", actorId);
2871
- estimate = await linkManyRecords(runtime, estimate, "expectations", input.expectationIds ?? [], "estimates", actorId);
2872
-
2873
- return estimate;
2874
- }
2875
-
2876
- async function updateEstimate(
2877
- runtime: DxRuntime,
2878
- input: {
2879
- workspaceId: string;
2880
- id: string;
2881
- title?: string;
2882
- summary?: string;
2883
- lineItems?: EstimateLineItemInput[];
2884
- fields?: Record<string, unknown>;
2885
- unsetFields?: string[];
2886
- revisionNote?: string;
2887
- },
2888
- actorId: string
2889
- ) {
2890
- assertNoTypedFields(input.fields, "update_estimate", ESTIMATE_TYPED_FIELDS);
2891
- assertNoTypedUnsetFields(input.unsetFields, "update_estimate", ESTIMATE_TYPED_FIELDS);
2892
-
2893
- const lineItems = input.lineItems ? normalizeEstimateLineItems(input.lineItems) : undefined;
2894
-
2895
- return updateRecord(
2896
- runtime.db,
2897
- {
2898
- recordType: "estimates",
2899
- workspaceId: input.workspaceId,
2900
- id: input.id,
2901
- title: input.title,
2902
- summary: input.summary,
2903
- fields: {
2904
- ...(input.fields ?? {}),
2905
- ...(lineItems ? { lineItems, rollup: computeQuantifiedRollup(lineItems) } : {})
2906
- },
2907
- unsetFields: input.unsetFields,
2908
- allowManagedFields: true,
2909
- revisionNote: input.revisionNote
2910
- },
2911
- actorId
2912
- );
2913
- }
2914
-
2915
- function normalizeEstimateLineItems(lineItems: EstimateLineItemInput[]): EstimateLineItem[] {
2916
- const seenIds = new Set<string>();
2917
- return lineItems.map((item, index) => {
2918
- const id = item.id ?? randomUUID();
2919
- if (seenIds.has(id)) {
2920
- throw new Error(`Estimate line item id must be unique: ${id}.`);
2921
- }
2922
- seenIds.add(id);
2923
-
2924
- if (item.timing === "recurring" && !item.period) {
2925
- throw new Error(`Estimate line item ${index + 1} is recurring and requires period.`);
2926
- }
2927
- if (item.timing === "one_time" && item.period) {
2928
- throw new Error(`Estimate line item ${index + 1} is one_time and must omit period.`);
2929
- }
2930
- if (item.amount.kind === "range" && !(item.amount.min <= item.amount.expected && item.amount.expected <= item.amount.max)) {
2931
- throw new Error(`Estimate line item ${index + 1} range must satisfy min <= expected <= max.`);
2932
- }
2933
-
2934
- return {
2935
- id,
2936
- label: item.label,
2937
- timing: item.timing,
2938
- ...(item.period ? { period: item.period } : {}),
2939
- currency: item.currency,
2940
- amount: item.amount
2941
- };
2942
- });
2943
- }
2944
-
2945
- async function createBenefits(
2946
- runtime: DxRuntime,
2947
- input: {
2948
- workspaceId: string;
2949
- title: string;
2950
- summary?: string;
2951
- benefitItems: BenefitItemInput[];
2952
- requirementIds?: string[];
2953
- expectationIds?: string[];
2954
- fields?: Record<string, unknown>;
2955
- },
2956
- actorId: string
2957
- ) {
2958
- assertNoReservedFields(input.fields, ["workspaceId", "initiativeId", "requirementIds", "expectationIds"]);
2959
- assertNoTypedFields(input.fields, "create_benefits", BENEFITS_TYPED_FIELDS);
2960
- assertAtLeastOneBenefitsTarget(input.requirementIds, input.expectationIds);
2961
- await assertRecordsExist(runtime, "requirements", input.requirementIds ?? [], input.workspaceId);
2962
- await assertRecordsExist(runtime, "expectations", input.expectationIds ?? [], input.workspaceId);
2963
-
2964
- const benefitItems = normalizeBenefitItems(input.benefitItems);
2965
- let benefits = await createRecord(
2966
- runtime.db,
2967
- "benefits",
2968
- {
2969
- workspaceId: input.workspaceId,
2970
- title: input.title,
2971
- summary: input.summary,
2972
- allowManagedFields: true,
2973
- fields: {
2974
- ...(input.fields ?? {}),
2975
- benefitItems,
2976
- rollup: computeQuantifiedRollup(benefitItems.filter(isQuantifiedBenefitItem))
2977
- }
2978
- },
2979
- actorId
2980
- );
2981
-
2982
- benefits = await linkManyRecords(runtime, benefits, "requirements", input.requirementIds ?? [], "benefits", actorId);
2983
- benefits = await linkManyRecords(runtime, benefits, "expectations", input.expectationIds ?? [], "benefits", actorId);
2984
-
2985
- return benefits;
2986
- }
2987
-
2988
- async function updateBenefits(
2989
- runtime: DxRuntime,
2990
- input: {
2991
- workspaceId: string;
2992
- id: string;
2993
- title?: string;
2994
- summary?: string;
2995
- benefitItems?: BenefitItemInput[];
2996
- fields?: Record<string, unknown>;
2997
- unsetFields?: string[];
2998
- revisionNote?: string;
2999
- },
3000
- actorId: string
3001
- ) {
3002
- assertNoTypedFields(input.fields, "update_benefits", BENEFITS_TYPED_FIELDS);
3003
- assertNoTypedUnsetFields(input.unsetFields, "update_benefits", BENEFITS_TYPED_FIELDS);
3004
-
3005
- const benefitItems = input.benefitItems ? normalizeBenefitItems(input.benefitItems) : undefined;
3006
-
3007
- return updateRecord(
3008
- runtime.db,
3009
- {
3010
- recordType: "benefits",
3011
- workspaceId: input.workspaceId,
3012
- id: input.id,
3013
- title: input.title,
3014
- summary: input.summary,
3015
- fields: {
3016
- ...(input.fields ?? {}),
3017
- ...(benefitItems ? { benefitItems, rollup: computeQuantifiedRollup(benefitItems.filter(isQuantifiedBenefitItem)) } : {})
3018
- },
3019
- unsetFields: input.unsetFields,
3020
- allowManagedFields: true,
3021
- revisionNote: input.revisionNote
3022
- },
3023
- actorId
3024
- );
3025
- }
3026
-
3027
- async function createValueRealization(
3028
- runtime: DxRuntime,
3029
- input: {
3030
- workspaceId: string;
3031
- title: string;
3032
- summary?: string;
3033
- metrics: ValueMetricInput[];
3034
- requirementIds?: string[];
3035
- expectationIds?: string[];
3036
- commitmentIds?: string[];
3037
- fields?: Record<string, unknown>;
3038
- },
3039
- actorId: string
3040
- ) {
3041
- assertNoReservedFields(input.fields, ["workspaceId", "requirementIds", "expectationIds", "commitmentIds"]);
3042
- assertNoTypedFields(input.fields, "create_value_realization", VALUE_REALIZATION_TYPED_FIELDS);
3043
- assertAtLeastOneValueRealizationTarget(input.requirementIds, input.expectationIds, input.commitmentIds);
3044
- await assertRuntimeRecordsExist(runtime, input.workspaceId, "requirements", uniqueIds(input.requirementIds ?? []));
3045
- await assertRuntimeRecordsExist(runtime, input.workspaceId, "expectations", uniqueIds(input.expectationIds ?? []));
3046
- await assertRuntimeRecordsExist(runtime, input.workspaceId, "commitments", uniqueIds(input.commitmentIds ?? []));
3047
-
3048
- let valueRealization = await createRecord(
3049
- runtime.db,
3050
- "value_realizations",
3051
- {
3052
- workspaceId: input.workspaceId,
3053
- title: input.title,
3054
- summary: input.summary,
3055
- allowManagedFields: true,
3056
- fields: {
3057
- ...(input.fields ?? {}),
3058
- metrics: normalizeValueMetrics(input.metrics)
3059
- }
3060
- },
3061
- actorId
3062
- );
3063
-
3064
- valueRealization = await linkManyRecords(runtime, valueRealization, "requirements", input.requirementIds ?? [], "realizes_value_for", actorId);
3065
- valueRealization = await linkManyRecords(runtime, valueRealization, "expectations", input.expectationIds ?? [], "realizes_value_for", actorId);
3066
- valueRealization = await linkManyRecords(runtime, valueRealization, "commitments", input.commitmentIds ?? [], "realizes_value_for", actorId);
3067
-
3068
- return valueRealization;
3069
- }
3070
-
3071
- async function updateValueRealization(
3072
- runtime: DxRuntime,
3073
- input: {
3074
- workspaceId: string;
3075
- id: string;
3076
- title?: string;
3077
- summary?: string;
3078
- metrics?: ValueMetricInput[];
3079
- fields?: Record<string, unknown>;
3080
- unsetFields?: string[];
3081
- revisionNote?: string;
3082
- },
3083
- actorId: string
3084
- ) {
3085
- assertNoTypedFields(input.fields, "update_value_realization", VALUE_REALIZATION_TYPED_FIELDS);
3086
- assertNoTypedUnsetFields(input.unsetFields, "update_value_realization", VALUE_REALIZATION_TYPED_FIELDS);
3087
-
3088
- return updateRecord(
3089
- runtime.db,
3090
- {
3091
- recordType: "value_realizations",
3092
- workspaceId: input.workspaceId,
3093
- id: input.id,
3094
- title: input.title,
3095
- summary: input.summary,
3096
- fields: {
3097
- ...(input.fields ?? {}),
3098
- ...(input.metrics ? { metrics: normalizeValueMetrics(input.metrics) } : {})
3099
- },
3100
- unsetFields: input.unsetFields,
3101
- allowManagedFields: true,
3102
- revisionNote: input.revisionNote
3103
- },
3104
- actorId
3105
- );
3106
- }
3107
-
3108
- function normalizeValueMetrics(metrics: ValueMetricInput[]): ValueMetricInput[] {
3109
- const seenIds = new Set<string>();
3110
- return metrics.map((metric, index) => {
3111
- const id = metric.id ?? randomUUID();
3112
- if (seenIds.has(id)) {
3113
- throw new Error(`Value metric id must be unique: ${id}.`);
3114
- }
3115
- seenIds.add(id);
3116
- assertMeasuredAtDate(metric.baseline.measuredAt, `Value metric ${index + 1} baseline`);
3117
- if (metric.actual) {
3118
- assertMeasuredAtDate(metric.actual.measuredAt, `Value metric ${index + 1} actual`);
3119
- }
3120
-
3121
- return {
3122
- ...metric,
3123
- id
3124
- };
3125
- });
3126
- }
3127
-
3128
- function assertMeasuredAtDate(value: string, label: string): void {
3129
- if (Number.isNaN(new Date(value).getTime())) {
3130
- throw new Error(`${label} measuredAt must be a valid date string.`);
3131
- }
3132
- }
3133
-
3134
- function normalizeBenefitItems(benefitItems: BenefitItemInput[]): BenefitItem[] {
3135
- const seenIds = new Set<string>();
3136
- return benefitItems.map((item, index) => {
3137
- const id = item.id ?? randomUUID();
3138
- if (seenIds.has(id)) {
3139
- throw new Error(`Benefit item id must be unique: ${id}.`);
3140
- }
3141
- seenIds.add(id);
3142
-
3143
- if (!item.amount) {
3144
- if (item.timing || item.period || item.currency) {
3145
- throw new Error(`Benefit item ${index + 1} is qualitative and must omit timing, period, and currency.`);
3146
- }
3147
- return {
3148
- id,
3149
- label: item.label
3150
- };
3151
- }
3152
-
3153
- if (!item.timing) {
3154
- throw new Error(`Benefit item ${index + 1} has amount and requires timing.`);
3155
- }
3156
- if (!item.currency) {
3157
- throw new Error(`Benefit item ${index + 1} has amount and requires currency.`);
3158
- }
3159
- if (item.timing === "recurring" && !item.period) {
3160
- throw new Error(`Benefit item ${index + 1} is recurring and requires period.`);
3161
- }
3162
- if (item.timing === "one_time" && item.period) {
3163
- throw new Error(`Benefit item ${index + 1} is one_time and must omit period.`);
3164
- }
3165
- if (item.amount.kind === "range" && !(item.amount.min <= item.amount.expected && item.amount.expected <= item.amount.max)) {
3166
- throw new Error(`Benefit item ${index + 1} range must satisfy min <= expected <= max.`);
3167
- }
3168
-
3169
- return {
3170
- id,
3171
- label: item.label,
3172
- timing: item.timing,
3173
- ...(item.period ? { period: item.period } : {}),
3174
- currency: item.currency,
3175
- amount: item.amount
3176
- };
3177
- });
3178
- }
3179
-
3180
- function isQuantifiedBenefitItem(item: BenefitItem): item is BenefitItem & QuantifiedRollupItem {
3181
- return !!item.amount && !!item.timing && !!item.currency;
3182
- }
3183
-
3184
- function computeQuantifiedRollup(lineItems: QuantifiedRollupItem[]): Record<string, unknown> {
3185
- const currencies: Record<string, Record<string, unknown>> = {};
3186
-
3187
- for (const item of lineItems) {
3188
- const currency = (currencies[item.currency] ??= createEmptyRollupTimingGroup());
3189
- const amount = normalizeRollupAmount(item.amount);
3190
-
3191
- if (item.timing === "one_time") {
3192
- currency.one_time = addRollupAmounts(currency.one_time as RollupAmount | undefined, amount);
3193
- continue;
3194
- }
3195
-
3196
- const recurring = currency.recurring as Record<string, RollupAmount>;
3197
- recurring[item.period ?? ""] = addRollupAmounts(recurring[item.period ?? ""], amount);
3198
- }
3199
-
3200
- return { currencies };
3201
- }
3202
-
3203
- function createEmptyRollupTimingGroup(): Record<string, unknown> {
3204
- return {
3205
- one_time: createZeroRollupAmount(),
3206
- recurring: {}
3207
- };
3208
- }
3209
-
3210
- function createZeroRollupAmount(): RollupAmount {
3211
- return { min: 0, expected: 0, max: 0 };
3212
- }
3213
-
3214
- function normalizeRollupAmount(amount: EstimateLineItem["amount"]): RollupAmount {
3215
- if (amount.kind === "single") {
3216
- return { min: amount.value, expected: amount.value, max: amount.value };
3217
- }
3218
-
3219
- return { min: amount.min, expected: amount.expected, max: amount.max };
3220
- }
3221
-
3222
- function addRollupAmounts(
3223
- left: RollupAmount | undefined,
3224
- right: RollupAmount
3225
- ): RollupAmount {
3226
- const base = left ?? createZeroRollupAmount();
3227
- return {
3228
- min: base.min + right.min,
3229
- expected: base.expected + right.expected,
3230
- max: base.max + right.max
3231
- };
3232
- }
3233
-
3234
- async function createRequirement(
3235
- runtime: DxRuntime,
3236
- input: {
3237
- workspaceId: string;
3238
- title: string;
3239
- expectationId?: string;
3240
- statement: string;
3241
- acceptanceCriteria?: string[];
3242
- priority?: "low" | "medium" | "high";
3243
- status?: "draft" | "ready" | "approved" | "superseded";
3244
- fields?: Record<string, unknown>;
3245
- },
3246
- actorId: string
3247
- ) {
3248
- assertNoReservedFields(input.fields, ["workspaceId", "expectationId"]);
3249
- assertNoTypedFields(input.fields, "create_requirement", REQUIREMENT_TYPED_FIELDS);
3250
-
3251
- if (input.expectationId) {
3252
- const expectation = await getRecord(runtime.db, "expectations", input.expectationId, {
3253
- workspaceId: input.workspaceId
3254
- });
3255
- if (!expectation) {
3256
- throw new Error(`Expectation not found: expectations/${input.expectationId}`);
3257
- }
3258
- }
3259
-
3260
- const requirement = await createRecord(
3261
- runtime.db,
3262
- "requirements",
3263
- {
3264
- workspaceId: input.workspaceId,
3265
- title: input.title,
3266
- summary: input.statement,
3267
- fields: {
3268
- ...(input.fields ?? {}),
3269
- statement: input.statement,
3270
- ...(input.acceptanceCriteria ? { acceptanceCriteria: input.acceptanceCriteria } : {}),
3271
- ...(input.priority ? { priority: input.priority } : {}),
3272
- status: input.status ?? "draft"
3273
- }
3274
- },
3275
- actorId
3276
- );
3277
-
3278
- if (!input.expectationId) {
3279
- return requirement;
3280
- }
3281
-
3282
- return linkRecords(
3283
- runtime.db,
3284
- {
3285
- workspaceId: input.workspaceId,
3286
- fromType: "requirements",
3287
- fromId: requirement._id,
3288
- toType: "expectations",
3289
- toId: input.expectationId,
3290
- relationship: "satisfies"
3291
- },
3292
- actorId
3293
- );
3294
- }
3295
-
3296
- async function createTask(
3297
- runtime: DxRuntime,
3298
- input: {
3299
- workspaceId: string;
3300
- title: string;
3301
- description: string;
3302
- assignee?: string;
3303
- assignor?: string;
3304
- requirementId?: string;
3305
- initialStatus?: "open" | "in_progress" | "blocked" | "done";
3306
- fields?: Record<string, unknown>;
3307
- },
3308
- actorId: string
3309
- ) {
3310
- assertNoReservedFields(input.fields, ["workspaceId", "requirementId"]);
3311
- assertNoTypedFields(input.fields, "create_task", TASK_TYPED_FIELDS);
3312
-
3313
- if (input.requirementId) {
3314
- const requirement = await getRecord(runtime.db, "requirements", input.requirementId, {
3315
- workspaceId: input.workspaceId
3316
- });
3317
- if (!requirement) {
3318
- throw new Error(`Requirement not found: requirements/${input.requirementId}`);
3319
- }
3320
- }
3321
-
3322
- const now = new Date().toISOString();
3323
- const initialStatus = input.initialStatus ?? "open";
3324
- const initialStatusEntry: TaskEntry = {
3325
- id: randomUUID(),
3326
- entryType: "status_change",
3327
- body: `Initial status: ${initialStatus}.`,
3328
- status: initialStatus,
3329
- createdAt: now,
3330
- createdBy: actorId
3331
- };
3332
-
3333
- const task = await createRecord(
3334
- runtime.db,
3335
- "tasks",
3336
- {
3337
- workspaceId: input.workspaceId,
3338
- title: input.title,
3339
- summary: input.description,
3340
- allowManagedFields: true,
3341
- fields: {
3342
- ...(input.fields ?? {}),
3343
- description: input.description,
3344
- ...(input.assignee !== undefined ? { assignee: input.assignee } : {}),
3345
- ...(input.assignor !== undefined ? { assignor: input.assignor } : {}),
3346
- entries: [initialStatusEntry],
3347
- currentStatus: taskEntryToCurrentStatus(initialStatusEntry)
3348
- }
3349
- },
3350
- actorId
3351
- );
3352
-
3353
- if (!input.requirementId) {
3354
- return task;
3355
- }
3356
-
3357
- return linkRecords(
3358
- runtime.db,
3359
- {
3360
- workspaceId: input.workspaceId,
3361
- fromType: "tasks",
3362
- fromId: task._id,
3363
- toType: "requirements",
3364
- toId: input.requirementId,
3365
- relationship: "implements"
3366
- },
3367
- actorId
3368
- );
3369
- }
3370
-
3371
- async function createDecision(
3372
- runtime: DxRuntime,
3373
- input: {
3374
- workspaceId: string;
3375
- title: string;
3376
- matter: string;
3377
- initialEntries?: DecisionInitialEntryInput[];
3378
- initialDecision?: InitialDecisionInput;
3379
- fields?: Record<string, unknown>;
3380
- },
3381
- actorId: string
3382
- ) {
3383
- assertNoTypedFields(input.fields, "create_decision", DECISION_TYPED_FIELDS);
3384
- assertNoDecisionInputFields(input.fields);
3385
-
3386
- const now = new Date().toISOString();
3387
- const entries = buildInitialDecisionEntries(input.initialEntries, input.initialDecision, actorId, now);
3388
- const latestDecisionEntry = [...entries].reverse().find((entry) => entry.entryType === "decision");
3389
-
3390
- return createRecord(
3391
- runtime.db,
3392
- "decisions",
3393
- {
3394
- workspaceId: input.workspaceId,
3395
- title: input.title,
3396
- summary: latestDecisionEntry?.body ?? input.matter,
3397
- allowManagedFields: true,
3398
- fields: {
3399
- ...(input.fields ?? {}),
3400
- matter: input.matter,
3401
- entries,
3402
- ...(latestDecisionEntry ? { currentDecision: decisionEntryToCurrentDecision(latestDecisionEntry) } : {})
3403
- }
3404
- },
3405
- actorId
3406
- );
3407
- }
3408
-
3409
- function buildInitialDecisionEntries(
3410
- initialEntries: DecisionInitialEntryInput[] | undefined,
3411
- initialDecision: InitialDecisionInput | undefined,
3412
- actorId: string,
3413
- createdAt: string
3414
- ): DecisionEntry[] {
3415
- const entries = (initialEntries ?? []).map((entry) =>
3416
- buildDecisionEntry(
3417
- {
3418
- entryType: entry.entryType,
3419
- body: entry.body,
3420
- decidedBy: entry.decidedBy,
3421
- rationale: entry.rationale
3422
- },
3423
- actorId,
3424
- createdAt
3425
- )
3426
- );
3427
-
3428
- if (initialDecision) {
3429
- entries.push(
3430
- buildDecisionEntry(
3431
- {
3432
- entryType: "decision",
3433
- body: initialDecision.body,
3434
- decidedBy: initialDecision.decidedBy,
3435
- rationale: initialDecision.rationale
3436
- },
3437
- actorId,
3438
- createdAt
3439
- )
3440
- );
3441
- }
3442
-
3443
- return entries;
3444
- }
3445
-
3446
- function buildDecisionEntry(
3447
- input: {
3448
- entryType: "argument" | "decision" | "note";
3449
- body: string;
3450
- decidedBy?: string;
3451
- rationale?: string;
3452
- },
3453
- actorId: string,
3454
- createdAt: string
3455
- ): DecisionEntry {
3456
- if (input.entryType !== "decision" && (input.decidedBy || input.rationale)) {
3457
- throw new Error("decidedBy and rationale are only valid on decision entries.");
3458
- }
3459
-
3460
- return {
3461
- id: randomUUID(),
3462
- entryType: input.entryType,
3463
- body: input.body,
3464
- createdAt,
3465
- createdBy: actorId,
3466
- ...(input.decidedBy ? { decidedBy: input.decidedBy } : {}),
3467
- ...(input.rationale ? { rationale: input.rationale } : {})
3468
- };
3469
- }
3470
-
3471
- async function createCommitment(
3472
- runtime: DxRuntime,
3473
- input: {
3474
- workspaceId: string;
3475
- title: string;
3476
- summary?: string;
3477
- commitmentStatement: string;
3478
- requirementIds?: string[];
3479
- expectationIds?: string[];
3480
- reservationNotes?: string[];
3481
- deferralId?: string;
3482
- fields?: Record<string, unknown>;
3483
- },
3484
- actorId: string
3485
- ) {
3486
- assertNoReservedFields(input.fields, ["workspaceId", "requirementIds", "expectationIds", "deferralId"]);
3487
- assertNoTypedFields(input.fields, "create_commitment", COMMITMENT_TYPED_FIELDS);
3488
- assertAtLeastOneCommitmentTarget(input.requirementIds, input.expectationIds);
3489
- await assertRecordsExist(runtime, "requirements", input.requirementIds ?? [], input.workspaceId);
3490
- await assertRecordsExist(runtime, "expectations", input.expectationIds ?? [], input.workspaceId);
3491
-
3492
- if (input.deferralId) {
3493
- const deferral = await getRecord(runtime.db, "deferrals", input.deferralId, {
3494
- workspaceId: input.workspaceId
3495
- });
3496
- if (!deferral) {
3497
- throw new Error(`Deferral not found: deferrals/${input.deferralId}`);
3498
- }
3499
- }
3500
-
3501
- const now = new Date().toISOString();
3502
- let commitment = await createRecord(
3503
- runtime.db,
3504
- "commitments",
3505
- {
3506
- workspaceId: input.workspaceId,
3507
- title: input.title,
3508
- summary: input.summary ?? input.commitmentStatement,
3509
- allowManagedFields: true,
3510
- fields: {
3511
- ...(input.fields ?? {}),
3512
- commitmentStatement: input.commitmentStatement,
3513
- reservations: (input.reservationNotes ?? []).map((note) => ({
3514
- id: randomUUID(),
3515
- note,
3516
- createdAt: now,
3517
- createdBy: actorId
3518
- }))
3519
- }
3520
- },
3521
- actorId
3522
- );
3523
-
3524
- commitment = await linkManyRecords(runtime, commitment, "requirements", input.requirementIds ?? [], "commits", actorId);
3525
- commitment = await linkManyRecords(runtime, commitment, "expectations", input.expectationIds ?? [], "commits", actorId);
3526
-
3527
- if (input.deferralId) {
3528
- commitment = await ensureLinkRecords(
3529
- runtime,
3530
- {
3531
- workspaceId: input.workspaceId,
3532
- fromType: "commitments",
3533
- fromId: commitment._id,
3534
- toType: "deferrals",
3535
- toId: input.deferralId,
3536
- relationship: "resolves_deferral"
3537
- },
3538
- actorId
3539
- );
3540
- }
3541
-
3542
- return commitment;
3543
- }
3544
-
3545
- async function createDeferral(
3546
- runtime: DxRuntime,
3547
- input: {
3548
- workspaceId: string;
3549
- title: string;
3550
- summary?: string;
3551
- reason: string;
3552
- conditions: string[];
3553
- requirementIds?: string[];
3554
- expectationIds?: string[];
3555
- fields?: Record<string, unknown>;
3556
- },
3557
- actorId: string
3558
- ) {
3559
- assertNoReservedFields(input.fields, ["workspaceId", "requirementIds", "expectationIds"]);
3560
- assertNoTypedFields(input.fields, "create_deferral", DEFERRAL_TYPED_FIELDS);
3561
- await assertRecordsExist(runtime, "requirements", input.requirementIds ?? [], input.workspaceId);
3562
- await assertRecordsExist(runtime, "expectations", input.expectationIds ?? [], input.workspaceId);
3563
-
3564
- const now = new Date().toISOString();
3565
- let deferral = await createRecord(
3566
- runtime.db,
3567
- "deferrals",
3568
- {
3569
- workspaceId: input.workspaceId,
3570
- title: input.title,
3571
- summary: input.summary ?? input.reason,
3572
- allowManagedFields: true,
3573
- fields: {
3574
- ...(input.fields ?? {}),
3575
- reason: input.reason,
3576
- status: "open",
3577
- conditions: input.conditions.map((statement) => ({
3578
- id: randomUUID(),
3579
- statement,
3580
- state: "open",
3581
- createdAt: now,
3582
- createdBy: actorId,
3583
- updatedAt: now,
3584
- updatedBy: actorId
3585
- })),
3586
- conditionEvents: []
3587
- }
3588
- },
3589
- actorId
3590
- );
3591
-
3592
- deferral = await linkManyRecords(runtime, deferral, "requirements", input.requirementIds ?? [], "defers", actorId);
3593
- deferral = await linkManyRecords(runtime, deferral, "expectations", input.expectationIds ?? [], "defers", actorId);
3594
-
3595
- return deferral;
3596
- }
3597
-
3598
- async function appendDeferralEventForTool(
3599
- runtime: DxRuntime,
3600
- input: {
3601
- workspaceId: string;
3602
- deferralId: string;
3603
- eventType: "condition_addressed" | "condition_reopened" | "condition_note_added" | "deferral_resolved" | "deferral_abandoned";
3604
- conditionId?: string;
3605
- note?: string;
3606
- summary?: string;
3607
- reason?: string;
3608
- commitmentId?: string;
3609
- },
3610
- actorId: string
3611
- ) {
3612
- const event = buildDeferralEventContent(input);
3613
-
3614
- if (input.eventType === "deferral_resolved") {
3615
- const commitment = await getRecord(runtime.db, "commitments", event.commitmentId as string, {
3616
- workspaceId: input.workspaceId
3617
- });
3618
- if (!commitment) {
3619
- throw new Error(`Commitment not found: commitments/${event.commitmentId}`);
3620
- }
3621
- }
3622
-
3623
- const deferral = await appendDeferralEvent(
3624
- runtime.db,
3625
- {
3626
- workspaceId: input.workspaceId,
3627
- deferralId: input.deferralId,
3628
- eventType: input.eventType,
3629
- event
3630
- },
3631
- actorId
3632
- );
3633
-
3634
- if (input.eventType !== "deferral_resolved") {
3635
- return deferral;
3636
- }
3637
-
3638
- await ensureLinkRecords(
3639
- runtime,
3640
- {
3641
- workspaceId: input.workspaceId,
3642
- fromType: "commitments",
3643
- fromId: event.commitmentId as string,
3644
- toType: "deferrals",
3645
- toId: deferral._id,
3646
- relationship: "resolves_deferral"
3647
- },
3648
- actorId
3649
- );
3650
-
3651
- const updated = await getRecord(runtime.db, "deferrals", input.deferralId, { workspaceId: input.workspaceId });
3652
- if (!updated) {
3653
- throw new Error(`Deferral not found after resolution link: deferrals/${input.deferralId}`);
3654
- }
3655
-
3656
- return updated;
3657
- }
3658
-
3659
- function buildDeferralEventContent(input: {
3660
- eventType: "condition_addressed" | "condition_reopened" | "condition_note_added" | "deferral_resolved" | "deferral_abandoned";
3661
- conditionId?: string;
3662
- note?: string;
3663
- summary?: string;
3664
- reason?: string;
3665
- commitmentId?: string;
3666
- }): Record<string, unknown> {
3667
- switch (input.eventType) {
3668
- case "condition_addressed":
3669
- case "condition_reopened":
3670
- return compactObject({
3671
- conditionId: requireDeferralEventField(input.conditionId, input.eventType, "conditionId"),
3672
- summary: input.summary
3673
- });
3674
- case "condition_note_added":
3675
- return compactObject({
3676
- conditionId: requireDeferralEventField(input.conditionId, input.eventType, "conditionId"),
3677
- note: requireDeferralEventField(input.note, input.eventType, "note")
3678
- });
3679
- case "deferral_resolved":
3680
- return compactObject({
3681
- commitmentId: requireDeferralEventField(input.commitmentId, input.eventType, "commitmentId"),
3682
- summary: input.summary
3683
- });
3684
- case "deferral_abandoned":
3685
- return compactObject({
3686
- reason: requireDeferralEventField(input.reason, input.eventType, "reason"),
3687
- summary: input.summary
3688
- });
3689
- }
3690
- }
3691
-
3692
- function requireDeferralEventField<T>(value: T | undefined, eventType: string, fieldName: string): T {
3693
- if (value === undefined) {
3694
- throw new Error(`${eventType} requires ${fieldName}.`);
3695
- }
3696
-
3697
- return value;
3698
- }
3699
-
3700
- function assertAtLeastOneCommitmentTarget(requirementIds: string[] | undefined, expectationIds: string[] | undefined): void {
3701
- if ((requirementIds?.length ?? 0) > 0 || (expectationIds?.length ?? 0) > 0) {
3702
- return;
3703
- }
3704
-
3705
- throw new Error("create_commitment requires at least one requirementId or expectationId.");
3706
- }
3707
-
3708
- function assertAtLeastOneEstimateTarget(requirementIds: string[] | undefined, expectationIds: string[] | undefined): void {
3709
- if ((requirementIds?.length ?? 0) > 0 || (expectationIds?.length ?? 0) > 0) {
3710
- return;
3711
- }
3712
-
3713
- throw new Error("create_estimate requires at least one requirementId or expectationId.");
3714
- }
3715
-
3716
- function assertAtLeastOneBenefitsTarget(requirementIds: string[] | undefined, expectationIds: string[] | undefined): void {
3717
- if ((requirementIds?.length ?? 0) > 0 || (expectationIds?.length ?? 0) > 0) {
3718
- return;
3719
- }
3720
-
3721
- throw new Error("create_benefits requires at least one requirementId or expectationId.");
3722
- }
3723
-
3724
- function assertAtLeastOneValueRealizationTarget(
3725
- requirementIds: string[] | undefined,
3726
- expectationIds: string[] | undefined,
3727
- commitmentIds: string[] | undefined
3728
- ): void {
3729
- if ((requirementIds?.length ?? 0) > 0 || (expectationIds?.length ?? 0) > 0 || (commitmentIds?.length ?? 0) > 0) {
3730
- return;
3731
- }
3732
-
3733
- throw new Error("create_value_realization requires at least one requirementId, expectationId, or commitmentId.");
3734
- }
3735
-
3736
- async function assertRecordsExist(
3737
- runtime: DxRuntime,
3738
- recordType: "requirements" | "expectations",
3739
- ids: string[],
3740
- workspaceId: string
3741
- ): Promise<void> {
3742
- for (const id of new Set(ids)) {
3743
- const record = await getRecord(runtime.db, recordType, id, { workspaceId });
3744
- if (!record) {
3745
- throw new Error(`Record not found: ${recordType}/${id}`);
3746
- }
3747
- }
3748
- }
3749
-
3750
- async function linkManyRecords(
3751
- runtime: DxRuntime,
3752
- source: Awaited<ReturnType<typeof getRecord>>,
3753
- toType: "requirements" | "expectations" | "commitments",
3754
- toIds: string[],
3755
- relationship: string,
3756
- actorId: string
3757
- ) {
3758
- if (!source) {
3759
- throw new Error("Source record not found.");
3760
- }
3761
-
3762
- let current = source;
3763
- for (const toId of new Set(toIds)) {
3764
- current = await ensureLinkRecords(
3765
- runtime,
3766
- {
3767
- workspaceId: current.workspaceId ?? "",
3768
- fromType: current.recordType as CollectionName,
3769
- fromId: current._id,
3770
- toType,
3771
- toId,
3772
- relationship
3773
- },
3774
- actorId
3775
- );
3776
- }
3777
-
3778
- return current;
3779
- }
3780
-
3781
- async function ensureLinkRecords(
3782
- runtime: DxRuntime,
3783
- input: {
3784
- workspaceId: string;
3785
- fromType: CollectionName;
3786
- fromId: string;
3787
- toType: CollectionName;
3788
- toId: string;
3789
- relationship: string;
3790
- },
3791
- actorId: string
3792
- ) {
3793
- const source = await getRecord(runtime.db, input.fromType, input.fromId, {
3794
- workspaceId: input.workspaceId
3795
- });
3796
- if (!source) {
3797
- throw new Error(`Source record not found: ${input.fromType}/${input.fromId}`);
3798
- }
3799
- const target = await getRecord(runtime.db, input.toType, input.toId, {
3800
- workspaceId: input.workspaceId
3801
- });
3802
- if (!target) {
3803
- throw new Error(`Target record not found: ${input.toType}/${input.toId}`);
3804
- }
3805
-
3806
- if (
3807
- source.links.some(
3808
- (link) =>
3809
- link.toType === input.toType &&
3810
- link.toId === target._id &&
3811
- link.relationship === input.relationship
3812
- )
3813
- ) {
3814
- return source;
3815
- }
3816
-
3817
- return linkRecords(runtime.db, input, actorId);
3818
- }
3819
-
3820
- async function createRisk(
3821
- runtime: DxRuntime,
3822
- input: {
3823
- workspaceId: string;
3824
- title: string;
3825
- topic: string;
3826
- summary?: string;
3827
- body?: string;
3828
- likelihood?: "low" | "medium" | "high";
3829
- impact?: "low" | "medium" | "high";
3830
- treatment?: "accept" | "mitigate" | "transfer" | "avoid";
3831
- treatmentRationale?: string;
3832
- fields?: Record<string, unknown>;
3833
- },
3834
- actorId: string,
3835
- roles?: WorkspaceRole[]
3836
- ) {
3837
- assertNoReservedFields(input.fields, ["workspaceId"]);
3838
- assertNoTypedFields(input.fields, "create_risk", RISK_TYPED_FIELDS);
3839
- assertRiskAcceptanceAccess(input.treatment, roles);
3840
- if ((input.likelihood && !input.impact) || (!input.likelihood && input.impact)) {
3841
- throw new Error("create_risk requires both likelihood and impact when creating an initial assessment.");
3842
- }
3843
-
3844
- const now = new Date().toISOString();
3845
- const identifiedEntry: RiskEntry = {
3846
- id: randomUUID(),
3847
- entryType: "identified",
3848
- body: input.body ?? input.topic,
3849
- createdAt: now,
3850
- createdBy: actorId
3851
- };
3852
- const entries: RiskEntry[] = [identifiedEntry];
3853
- const fields: Record<string, unknown> = {
3854
- ...(input.fields ?? {}),
3855
- topic: input.topic,
3856
- entries,
3857
- currentStatus: riskEntryToCurrentStatus(identifiedEntry, "open")
3858
- };
3859
-
3860
- if (input.likelihood && input.impact) {
3861
- const assessmentEntry: RiskEntry = {
3862
- id: randomUUID(),
3863
- entryType: "assessment",
3864
- body: "Initial risk assessment.",
3865
- likelihood: input.likelihood,
3866
- impact: input.impact,
3867
- createdAt: now,
3868
- createdBy: actorId
3869
- };
3870
- entries.push(assessmentEntry);
3871
- fields.currentAssessment = riskEntryToCurrentAssessment(assessmentEntry);
3872
- }
3873
-
3874
- if (input.treatment) {
3875
- const treatmentEntry: RiskEntry = {
3876
- id: randomUUID(),
3877
- entryType: "treatment",
3878
- body: input.treatmentRationale ?? `Initial risk treatment: ${input.treatment}.`,
3879
- treatment: input.treatment,
3880
- ...(input.treatmentRationale ? { treatmentRationale: input.treatmentRationale } : {}),
3881
- createdAt: now,
3882
- createdBy: actorId
3883
- };
3884
- entries.push(treatmentEntry);
3885
- fields.currentTreatment = riskEntryToCurrentTreatment(treatmentEntry);
3886
- }
3887
-
3888
- return createRecord(
3889
- runtime.db,
3890
- "risks",
3891
- {
3892
- workspaceId: input.workspaceId,
3893
- title: input.title,
3894
- summary: input.summary ?? input.topic,
3895
- allowManagedFields: true,
3896
- fields
3897
- },
3898
- actorId
3899
- );
3900
- }
3901
-
3902
- async function createIncident(
3903
- runtime: DxRuntime,
3904
- input: {
3905
- workspaceId: string;
3906
- title: string;
3907
- description: string;
3908
- summary?: string;
3909
- severity?: "low" | "medium" | "high" | "critical";
3910
- componentIds?: string[];
3911
- fields?: Record<string, unknown>;
3912
- },
3913
- actorId: string
3914
- ) {
3915
- assertNoReservedFields(input.fields, ["workspaceId", "componentIds"]);
3916
- assertNoTypedFields(input.fields, "create_incident", INCIDENT_TYPED_FIELDS);
3917
-
3918
- const componentIds = uniqueIds(input.componentIds ?? []);
3919
- await assertRuntimeRecordsExist(runtime, input.workspaceId, "components", componentIds);
3920
-
3921
- const now = new Date().toISOString();
3922
- const detectedEntry: IncidentEntry = {
3923
- id: randomUUID(),
3924
- entryType: "detected",
3925
- body: input.description,
3926
- createdAt: now,
3927
- createdBy: actorId
3928
- };
3929
- const entries: IncidentEntry[] = [detectedEntry];
3930
- const fields: Record<string, unknown> = {
3931
- ...(input.fields ?? {}),
3932
- description: input.description,
3933
- entries,
3934
- currentStatus: incidentEntryToCurrentStatus(detectedEntry, "open")
3935
- };
3936
-
3937
- if (input.severity) {
3938
- const severityEntry: IncidentEntry = {
3939
- id: randomUUID(),
3940
- entryType: "severity",
3941
- body: `Initial severity: ${input.severity}.`,
3942
- severity: input.severity,
3943
- createdAt: now,
3944
- createdBy: actorId
3945
- };
3946
- entries.push(severityEntry);
3947
- fields.currentSeverity = incidentEntryToCurrentSeverity(severityEntry);
3948
- }
3949
-
3950
- let incident = await createRecord(
3951
- runtime.db,
3952
- "incidents",
3953
- {
3954
- workspaceId: input.workspaceId,
3955
- title: input.title,
3956
- summary: input.summary ?? input.description,
3957
- allowManagedFields: true,
3958
- fields
3959
- },
3960
- actorId
3961
- );
3962
-
3963
- for (const componentId of componentIds) {
3964
- incident = await ensureLinkRecords(
3965
- runtime,
3966
- {
3967
- workspaceId: input.workspaceId,
3968
- fromType: "incidents",
3969
- fromId: incident._id,
3970
- toType: "components",
3971
- toId: componentId,
3972
- relationship: "affects"
3973
- },
3974
- actorId
3975
- );
3976
- }
3977
-
3978
- return incident;
3979
- }
3980
-
3981
- async function createSupportRequest(
3982
- runtime: DxRuntime,
3983
- input: {
3984
- workspaceId: string;
3985
- title: string;
3986
- reporter: string;
3987
- kind: string;
3988
- reportedExperience: string;
3989
- summary?: string;
3990
- fields?: Record<string, unknown>;
3991
- },
3992
- actorId: string
3993
- ) {
3994
- assertNoReservedFields(input.fields, ["workspaceId"]);
3995
- assertNoTypedFields(input.fields, "create_support_request", SUPPORT_REQUEST_TYPED_FIELDS);
3996
-
3997
- const now = new Date().toISOString();
3998
- const raisedEntry: SupportRequestEntry = {
3999
- id: randomUUID(),
4000
- entryType: "raised",
4001
- body: input.reportedExperience,
4002
- createdAt: now,
4003
- createdBy: actorId
4004
- };
4005
-
4006
- return createRecord(
4007
- runtime.db,
4008
- "support_requests",
4009
- {
4010
- workspaceId: input.workspaceId,
4011
- title: input.title,
4012
- summary: input.summary ?? input.reportedExperience,
4013
- allowManagedFields: true,
4014
- fields: {
4015
- ...(input.fields ?? {}),
4016
- reporter: input.reporter,
4017
- kind: input.kind,
4018
- reportedExperience: input.reportedExperience,
4019
- entries: [raisedEntry],
4020
- currentStatus: supportRequestEntryToCurrentStatus(raisedEntry)
4021
- }
4022
- },
4023
- actorId
4024
- );
4025
- }
4026
-
4027
- async function appendSupportRequestEntryForTool(
4028
- runtime: DxRuntime,
4029
- input: {
4030
- workspaceId: string;
4031
- supportRequestId: string;
4032
- entryType: "raised" | "triage" | "update" | "escalated" | "resolved" | "reopened" | "note";
4033
- body: string;
4034
- incidentId?: string;
4035
- },
4036
- actorId: string
4037
- ) {
4038
- if (input.incidentId) {
4039
- const incident = await getRecord(runtime.db, "incidents", input.incidentId, {
4040
- workspaceId: input.workspaceId
4041
- });
4042
- if (!incident) {
4043
- throw new Error(`Incident not found: incidents/${input.incidentId}`);
4044
- }
4045
- }
4046
-
4047
- const supportRequest = await appendSupportRequestEntry(runtime.db, input, actorId);
4048
-
4049
- if (!input.incidentId) {
4050
- return supportRequest;
4051
- }
4052
-
4053
- return ensureLinkRecords(
4054
- runtime,
4055
- {
4056
- workspaceId: input.workspaceId,
4057
- fromType: "support_requests",
4058
- fromId: supportRequest._id,
4059
- toType: "incidents",
4060
- toId: input.incidentId,
4061
- relationship: "spawned_incident"
4062
- },
4063
- actorId
4064
- );
4065
- }
4066
-
4067
- async function createProblem(
4068
- runtime: DxRuntime,
4069
- input: {
4070
- workspaceId: string;
4071
- title: string;
4072
- description: string;
4073
- summary?: string;
4074
- incidentIds: string[];
4075
- componentIds?: string[];
4076
- fields?: Record<string, unknown>;
4077
- },
4078
- actorId: string
4079
- ) {
4080
- assertNoReservedFields(input.fields, ["workspaceId", "incidentIds", "componentIds"]);
4081
- assertNoTypedFields(input.fields, "create_problem", PROBLEM_TYPED_FIELDS);
4082
-
4083
- const incidentIds = uniqueIds(input.incidentIds);
4084
- const componentIds = uniqueIds(input.componentIds ?? []);
4085
- if (incidentIds.length === 0) {
4086
- throw new Error("create_problem requires at least one incidentId.");
4087
- }
4088
- await assertRuntimeRecordsExist(runtime, input.workspaceId, "incidents", incidentIds);
4089
- await assertRuntimeRecordsExist(runtime, input.workspaceId, "components", componentIds);
4090
-
4091
- const now = new Date().toISOString();
4092
- const identifiedEntry: ProblemEntry = {
4093
- id: randomUUID(),
4094
- entryType: "identified",
4095
- body: input.description,
4096
- createdAt: now,
4097
- createdBy: actorId
4098
- };
4099
- let problem = await createRecord(
4100
- runtime.db,
4101
- "problems",
4102
- {
4103
- workspaceId: input.workspaceId,
4104
- title: input.title,
4105
- summary: input.summary ?? input.description,
4106
- allowManagedFields: true,
4107
- fields: {
4108
- ...(input.fields ?? {}),
4109
- description: input.description,
4110
- entries: [identifiedEntry],
4111
- currentStatus: problemEntryToCurrentStatus(identifiedEntry, "open")
4112
- }
4113
- },
4114
- actorId
4115
- );
4116
-
4117
- for (const incidentId of incidentIds) {
4118
- problem = await ensureLinkRecords(
4119
- runtime,
4120
- {
4121
- workspaceId: input.workspaceId,
4122
- fromType: "problems",
4123
- fromId: problem._id,
4124
- toType: "incidents",
4125
- toId: incidentId,
4126
- relationship: "evidenced_by"
4127
- },
4128
- actorId
4129
- );
4130
- }
4131
-
4132
- for (const componentId of componentIds) {
4133
- problem = await ensureLinkRecords(
4134
- runtime,
4135
- {
4136
- workspaceId: input.workspaceId,
4137
- fromType: "problems",
4138
- fromId: problem._id,
4139
- toType: "components",
4140
- toId: componentId,
4141
- relationship: "affects"
4142
- },
4143
- actorId
4144
- );
4145
- }
4146
-
4147
- return problem;
4148
- }
4149
-
4150
- function uniqueIds(ids: string[]): string[] {
4151
- return [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
4152
- }
4153
-
4154
- async function assertRuntimeRecordsExist(
4155
- runtime: DxRuntime,
4156
- workspaceId: string,
4157
- recordType: CollectionName,
4158
- ids: string[]
4159
- ): Promise<void> {
4160
- for (const id of ids) {
4161
- const record = await getRecord(runtime.db, recordType, id, { workspaceId });
4162
- if (!record) {
4163
- throw new Error(`Record not found: ${recordType}/${id}`);
4164
- }
4165
- }
4166
- }
4167
-
4168
- async function createChange(
4169
- runtime: DxRuntime,
4170
- input: {
4171
- workspaceId: string;
4172
- title: string;
4173
- summary?: string;
4174
- changeType?: "standard" | "normal" | "emergency";
4175
- impactGrade?: "minor" | "significant" | "major";
4176
- emergencyImportance?: string;
4177
- emergencyImmediacy?: string;
4178
- changePlan: string;
4179
- executionSteps: string[];
4180
- rollbackPlan: string;
4181
- riskImpact: string;
4182
- plannedFor?: string;
4183
- requirementId?: string;
4184
- fields?: Record<string, unknown>;
4185
- },
4186
- actorId: string
4187
- ) {
4188
- assertNoReservedFields(input.fields, ["workspaceId", "initiativeId", "requirementId"]);
4189
- assertNoTypedFields(input.fields, "create_change", CHANGE_TYPED_FIELDS);
4190
- assertChangeTypeInput(input);
4191
-
4192
- if (input.requirementId) {
4193
- const requirement = await getRecord(runtime.db, "requirements", input.requirementId, {
4194
- workspaceId: input.workspaceId
4195
- });
4196
- if (!requirement) {
4197
- throw new Error(`Requirement not found: requirements/${input.requirementId}`);
4198
- }
4199
- }
4200
-
4201
- let change = await createRecord(
4202
- runtime.db,
4203
- "changes",
4204
- {
4205
- workspaceId: input.workspaceId,
4206
- title: input.title,
4207
- summary: input.summary ?? input.changePlan,
4208
- allowManagedFields: true,
4209
- fields: {
4210
- ...(input.fields ?? {}),
4211
- changeType: input.changeType ?? "normal",
4212
- ...(input.impactGrade !== undefined ? { impactGrade: input.impactGrade } : {}),
4213
- ...(input.emergencyImportance !== undefined ? { emergencyImportance: input.emergencyImportance } : {}),
4214
- ...(input.emergencyImmediacy !== undefined ? { emergencyImmediacy: input.emergencyImmediacy } : {}),
4215
- ...emergencyRationaleGapFields(input),
4216
- changePlan: input.changePlan,
4217
- executionSteps: input.executionSteps,
4218
- rollbackPlan: input.rollbackPlan,
4219
- riskImpact: input.riskImpact,
4220
- ...(input.plannedFor !== undefined ? { plannedFor: input.plannedFor } : {})
4221
- }
4222
- },
4223
- actorId
4224
- );
4225
-
4226
- if (input.requirementId) {
4227
- change = await linkRecords(
4228
- runtime.db,
4229
- {
4230
- workspaceId: input.workspaceId,
4231
- fromType: "changes",
4232
- fromId: change._id,
4233
- toType: "requirements",
4234
- toId: input.requirementId,
4235
- relationship: "for_requirement"
4236
- },
4237
- actorId
4238
- );
4239
- }
4240
-
4241
- return change;
4242
- }
4243
-
4244
- function buildChangeEventContent(input: {
4245
- eventType:
4246
- | "notice_given"
4247
- | "veto_recorded"
4248
- | "decision_recorded"
4249
- | "result_reported"
4250
- | "recovery_recorded"
4251
- | "plan_revised"
4252
- | "note_added";
4253
- notice?: string;
4254
- noticeTo?: string[];
4255
- effectiveAt?: string;
4256
- vetoByRole?: "Owner" | "Engineer";
4257
- reason?: string;
4258
- decision?: "proceed" | "defer" | "cancel";
4259
- result?: "completed" | "failed" | "rolled_back";
4260
- gitCommitReferences?: Array<{
4261
- commit: string;
4262
- repository?: string;
4263
- url?: string;
4264
- }>;
4265
- summary?: string;
4266
- note?: string;
4267
- revisedChangeType?: "standard" | "normal" | "emergency";
4268
- revisedImpactGrade?: "minor" | "significant" | "major";
4269
- revisedEmergencyImportance?: string;
4270
- revisedEmergencyImmediacy?: string;
4271
- revisedChangePlan?: string;
4272
- revisedExecutionSteps?: string[];
4273
- revisedRollbackPlan?: string;
4274
- revisedRiskImpact?: string;
4275
- revisedPlannedFor?: string;
4276
- }): Record<string, unknown> {
4277
- if (input.gitCommitReferences && input.eventType !== "result_reported" && input.eventType !== "recovery_recorded") {
4278
- throw new Error("gitCommitReferences are only valid on result_reported or recovery_recorded Change events.");
4279
- }
4280
-
4281
- switch (input.eventType) {
4282
- case "notice_given":
4283
- return compactObject({
4284
- notice: requireChangeEventField(input.notice, input.eventType, "notice"),
4285
- noticeTo: input.noticeTo,
4286
- effectiveAt: input.effectiveAt
4287
- });
4288
- case "veto_recorded":
4289
- return compactObject({
4290
- vetoByRole: requireChangeEventField(input.vetoByRole, input.eventType, "vetoByRole"),
4291
- reason: input.reason,
4292
- summary: input.summary
4293
- });
4294
- case "decision_recorded":
4295
- return compactObject({
4296
- decision: requireChangeEventField(input.decision, input.eventType, "decision"),
4297
- reason: input.reason,
4298
- summary: input.summary
4299
- });
4300
- case "result_reported":
4301
- return compactObject({
4302
- result: requireChangeEventField(input.result, input.eventType, "result"),
4303
- gitCommitReferences: input.gitCommitReferences,
4304
- summary: input.summary
4305
- });
4306
- case "recovery_recorded":
4307
- return compactObject({
4308
- summary: requireChangeEventField(input.summary, input.eventType, "summary"),
4309
- gitCommitReferences: input.gitCommitReferences
4310
- });
4311
- case "plan_revised": {
4312
- const event = compactObject({
4313
- summary: input.summary,
4314
- revisedChangeType: input.revisedChangeType,
4315
- revisedImpactGrade: input.revisedImpactGrade,
4316
- revisedEmergencyImportance: input.revisedEmergencyImportance,
4317
- revisedEmergencyImmediacy: input.revisedEmergencyImmediacy,
4318
- revisedChangePlan: input.revisedChangePlan,
4319
- revisedExecutionSteps: input.revisedExecutionSteps,
4320
- revisedRollbackPlan: input.revisedRollbackPlan,
4321
- revisedRiskImpact: input.revisedRiskImpact,
4322
- revisedPlannedFor: input.revisedPlannedFor
4323
- });
4324
- if (Object.keys(event).length === 0) {
4325
- throw new Error("plan_revised requires summary or at least one revised plan field.");
4326
- }
4327
- return event;
4328
- }
4329
- case "note_added":
4330
- return compactObject({
4331
- note: requireChangeEventField(input.note, input.eventType, "note")
4332
- });
4333
- }
4334
- }
4335
-
4336
- function requireChangeEventField<T>(value: T | undefined, eventType: string, fieldName: string): T {
4337
- if (value === undefined) {
4338
- throw new Error(`${eventType} requires ${fieldName}.`);
4339
- }
4340
-
4341
- return value;
4342
- }
4343
-
4344
- function assertRiskAcceptanceAccess(treatment: "accept" | "mitigate" | "transfer" | "avoid" | undefined, roles: WorkspaceRole[] | undefined): void {
4345
- if (treatment !== "accept" || !roles || roles.includes("owner")) {
4346
- return;
4347
- }
4348
-
4349
- throw new Error("Formal risk acceptance requires the Owner role. Other roles may record non-acceptance treatment or proceed with visible open risk.");
4350
- }
4351
-
4352
- function assertChangeTypeInput(input: {
4353
- changeType?: "standard" | "normal" | "emergency";
4354
- impactGrade?: "minor" | "significant" | "major";
4355
- emergencyImportance?: string;
4356
- emergencyImmediacy?: string;
4357
- }): void {
4358
- const changeType = input.changeType ?? "normal";
4359
-
4360
- if (input.impactGrade && changeType !== "normal") {
4361
- throw new Error("impactGrade is only valid for normal changes.");
4362
- }
4363
-
4364
- if ((input.emergencyImportance || input.emergencyImmediacy) && changeType !== "emergency") {
4365
- throw new Error("emergencyImportance and emergencyImmediacy are only valid for emergency changes.");
4366
- }
4367
- }
4368
-
4369
- function emergencyRationaleGapFields(input: {
4370
- changeType?: "standard" | "normal" | "emergency";
4371
- emergencyImportance?: string;
4372
- emergencyImmediacy?: string;
4373
- }): Record<string, unknown> {
4374
- if ((input.changeType ?? "normal") !== "emergency") {
4375
- return {};
4376
- }
4377
-
4378
- const missing = [
4379
- ...(input.emergencyImportance ? [] : ["emergencyImportance"]),
4380
- ...(input.emergencyImmediacy ? [] : ["emergencyImmediacy"])
4381
- ];
4382
-
4383
- return missing.length > 0 ? { emergencyRationaleGaps: missing } : {};
4384
- }
4385
-
4386
- function compactObject(input: Record<string, unknown>): Record<string, unknown> {
4387
- return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
4388
- }
4389
-
4390
- async function updateExpectation(
4391
- runtime: DxRuntime,
4392
- input: {
4393
- workspaceId: string;
4394
- id: string;
4395
- title?: string;
4396
- statement?: string;
4397
- successRecognition?: string;
4398
- approvalState?: "draft" | "approved" | "not_approved" | "superseded";
4399
- approvedBy?: string;
4400
- approvedAt?: string;
4401
- source?: string;
4402
- revisionNote?: string;
4403
- fields?: Record<string, unknown>;
4404
- unsetFields?: string[];
4405
- },
4406
- actorId: string
4407
- ) {
4408
- assertNoTypedFields(input.fields, "update_expectation", EXPECTATION_TYPED_FIELDS);
4409
- assertNoObsoleteExpectationFields(input.fields, "update_expectation");
4410
-
4411
- return updateRecord(
4412
- runtime.db,
4413
- {
4414
- recordType: "expectations",
4415
- workspaceId: input.workspaceId,
4416
- id: input.id,
4417
- title: input.title,
4418
- summary: input.statement,
4419
- fields: {
4420
- ...(input.fields ?? {}),
4421
- ...(input.statement !== undefined ? { statement: input.statement } : {}),
4422
- ...(input.successRecognition !== undefined ? { successRecognition: input.successRecognition } : {}),
4423
- ...(input.approvalState !== undefined ? { approvalState: input.approvalState } : {}),
4424
- ...(input.approvedBy !== undefined ? { approvedBy: input.approvedBy } : {}),
4425
- ...(input.approvedAt !== undefined ? { approvedAt: input.approvedAt } : {}),
4426
- ...(input.source !== undefined ? { source: input.source } : {})
4427
- },
4428
- unsetFields: input.unsetFields,
4429
- allowManagedFields: true,
4430
- revisionNote: input.revisionNote
4431
- },
4432
- actorId
4433
- );
4434
- }
4435
-
4436
- async function updateRequirement(
4437
- runtime: DxRuntime,
4438
- input: {
4439
- workspaceId: string;
4440
- id: string;
4441
- title?: string;
4442
- statement?: string;
4443
- acceptanceCriteria?: string[];
4444
- priority?: "low" | "medium" | "high";
4445
- status?: "draft" | "ready" | "approved" | "superseded";
4446
- revisionNote?: string;
4447
- fields?: Record<string, unknown>;
4448
- unsetFields?: string[];
4449
- },
4450
- actorId: string
4451
- ) {
4452
- assertNoTypedFields(input.fields, "update_requirement", REQUIREMENT_TYPED_FIELDS);
4453
-
4454
- return updateRecord(
4455
- runtime.db,
4456
- {
4457
- recordType: "requirements",
4458
- workspaceId: input.workspaceId,
4459
- id: input.id,
4460
- title: input.title,
4461
- summary: input.statement,
4462
- fields: {
4463
- ...(input.fields ?? {}),
4464
- ...(input.statement !== undefined ? { statement: input.statement } : {}),
4465
- ...(input.acceptanceCriteria !== undefined ? { acceptanceCriteria: input.acceptanceCriteria } : {}),
4466
- ...(input.priority !== undefined ? { priority: input.priority } : {}),
4467
- ...(input.status !== undefined ? { status: input.status } : {})
4468
- },
4469
- unsetFields: input.unsetFields,
4470
- allowManagedFields: true,
4471
- revisionNote: input.revisionNote
4472
- },
4473
- actorId
4474
- );
4475
- }
4476
-
4477
- async function linkDecisionInput(
4478
- runtime: DxRuntime,
4479
- input: {
4480
- workspaceId: string;
4481
- decisionId: string;
4482
- inputRecordType: DecisionInputRecordType;
4483
- inputId: string;
4484
- },
4485
- actorId: string
4486
- ) {
4487
- if (input.inputRecordType === "decisions" && input.inputId === input.decisionId) {
4488
- throw new Error("A Decision cannot be linked to itself as a decision input.");
4489
- }
4490
-
4491
- const decision = await getRecord(runtime.db, "decisions", input.decisionId, {
4492
- workspaceId: input.workspaceId
4493
- });
4494
- if (!decision) {
4495
- throw new Error(`Decision not found: decisions/${input.decisionId}`);
4496
- }
4497
-
4498
- const inputRecord = await getRecord(runtime.db, input.inputRecordType, input.inputId, {
4499
- workspaceId: input.workspaceId
4500
- });
4501
- if (!inputRecord) {
4502
- throw new Error(`Decision input not found: ${input.inputRecordType}/${input.inputId}`);
4503
- }
4504
-
4505
- if (
4506
- decision.links.some(
4507
- (link) =>
4508
- link.toType === input.inputRecordType &&
4509
- link.toId === inputRecord._id &&
4510
- link.relationship === "informed_by"
4511
- )
4512
- ) {
4513
- return decision;
4514
- }
4515
-
4516
- return linkRecords(
4517
- runtime.db,
4518
- {
4519
- workspaceId: input.workspaceId,
4520
- fromType: "decisions",
4521
- fromId: decision._id,
4522
- toType: input.inputRecordType,
4523
- toId: inputRecord._id,
4524
- relationship: "informed_by"
4525
- },
4526
- actorId
4527
- );
4528
- }
4529
-
4530
- function assertNoReservedFields(fields: Record<string, unknown> | undefined, reservedFields: string[]): void {
4531
- for (const reservedField of reservedFields) {
4532
- if (fields && Object.hasOwn(fields, reservedField)) {
4533
- throw new Error(
4534
- `${reservedField} is a relationship input on this tool. Use the top-level ${reservedField} argument instead of fields.${reservedField}.`
4535
- );
4536
- }
4537
- }
4538
- }
4539
-
4540
- function assertNoTypedFields(
4541
- fields: Record<string, unknown> | undefined,
4542
- toolName: string,
4543
- typedFields: string[]
4544
- ): void {
4545
- for (const typedField of typedFields) {
4546
- if (fields && Object.hasOwn(fields, typedField)) {
4547
- throw new Error(
4548
- `${typedField} is a typed input on ${toolName}. Use the top-level ${typedField} argument instead of fields.${typedField}.`
4549
- );
4550
- }
4551
- }
4552
- }
4553
-
4554
- function assertNoTypedUnsetFields(unsetFields: string[] | undefined, toolName: string, typedFields: string[]): void {
4555
- for (const unsetField of unsetFields ?? []) {
4556
- if (typedFields.includes(unsetField)) {
4557
- throw new Error(`${unsetField} is managed on ${toolName}. Use the typed inputs instead of unsetFields.${unsetField}.`);
4558
- }
4559
- }
4560
- }
4561
-
4562
- function assertNoDecisionInputFields(fields: Record<string, unknown> | undefined): void {
4563
- for (const fieldName of DECISION_INPUT_FIELDS) {
4564
- if (fields && Object.hasOwn(fields, fieldName)) {
4565
- throw new Error(
4566
- `${fieldName} is managed on decisions. Use link_decision_input to record decision inputs.`
4567
- );
4568
- }
4569
- }
4570
- }
4571
-
4572
- function assertNoObsoleteExpectationFields(fields: Record<string, unknown> | undefined, toolName: string): void {
4573
- for (const obsoleteField of OBSOLETE_EXPECTATION_FIELDS) {
4574
- if (fields && Object.hasOwn(fields, obsoleteField)) {
4575
- throw new Error(
4576
- `${obsoleteField} is not part of the current Expectation model on ${toolName}. Use approvalState, approvedBy, or approvedAt where approval tracking is needed.`
4577
- );
4578
- }
4579
- }
4580
- }