groundwork-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1524 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/core/collections.ts
8
+ var COLLECTION_KIND = {
9
+ insights: "insight",
10
+ hypotheses: "hypothesis",
11
+ experiments: "experiment",
12
+ findings: "finding",
13
+ requirements: "requirement",
14
+ activity: "activity"
15
+ };
16
+ var COLLECTION_KEYS = Object.keys(COLLECTION_KIND);
17
+ var emptyCollections = () => ({
18
+ insights: [],
19
+ hypotheses: [],
20
+ experiments: [],
21
+ findings: [],
22
+ requirements: [],
23
+ activity: []
24
+ });
25
+ function diffCollections(before, after) {
26
+ const upserts = [];
27
+ const deletes = [];
28
+ for (const key of COLLECTION_KEYS) {
29
+ const was = before[key];
30
+ const now = after[key];
31
+ if (was === now) continue;
32
+ const old = new Map(was.map((x) => [x.id, x]));
33
+ const kept = /* @__PURE__ */ new Set();
34
+ for (const item of now) {
35
+ kept.add(item.id);
36
+ if (old.get(item.id) !== item) {
37
+ const { id, ...data } = item;
38
+ upserts.push({ id, kind: COLLECTION_KIND[key], data });
39
+ }
40
+ }
41
+ for (const id of old.keys()) if (!kept.has(id)) deletes.push(id);
42
+ }
43
+ return { upserts, deletes };
44
+ }
45
+
46
+ // src/core/requirements.ts
47
+ function kindOf(r) {
48
+ return r.kind ?? "solution";
49
+ }
50
+ var isObsolete = (r) => r.status === "obsolete";
51
+ var canObsolete = (r) => r.status === "approved";
52
+ var canUpdateInPlace = (r) => r.status === "draft";
53
+ var canSendToDelivery = (r) => kindOf(r) === "solution" && r.status === "approved" && !r.delivery;
54
+
55
+ // src/core/verdict.ts
56
+ function metricPasses(m) {
57
+ if (m.actual === void 0 || m.actual === null || Number.isNaN(m.actual)) return void 0;
58
+ return m.direction === "decrease" ? m.actual <= m.target : m.actual >= m.target;
59
+ }
60
+ function computeVerdict(exp) {
61
+ const primary = metricPasses(exp.primaryMetric);
62
+ if (primary === void 0) {
63
+ return { verdict: "inconclusive", reason: "No result recorded for the primary metric yet." };
64
+ }
65
+ const failedGuardrails = exp.guardrails.filter((g) => metricPasses(g) === false);
66
+ if (!primary) {
67
+ return {
68
+ verdict: "invalidated",
69
+ reason: `${exp.primaryMetric.name} did not reach the target (${fmtMetric(exp.primaryMetric, exp.primaryMetric.actual)} vs target ${targetLabel(exp.primaryMetric)}).`
70
+ };
71
+ }
72
+ if (failedGuardrails.length > 0) {
73
+ return {
74
+ verdict: "invalidated",
75
+ reason: `Primary metric hit target, but guardrail breached: ${failedGuardrails.map((g) => g.name).join(", ")}.`
76
+ };
77
+ }
78
+ return {
79
+ verdict: "validated",
80
+ reason: `${exp.primaryMetric.name} hit target (${fmtMetric(exp.primaryMetric, exp.primaryMetric.actual)} vs target ${targetLabel(exp.primaryMetric)}) and all guardrails held.`
81
+ };
82
+ }
83
+ function fmtMetric(m, v) {
84
+ const n = Number.isInteger(v) ? v.toString() : v.toFixed(1);
85
+ return m.unit === "%" ? `${n}%` : `${n} ${m.unit}`;
86
+ }
87
+ function targetLabel(m) {
88
+ return `${m.direction === "decrease" ? "\u2264" : "\u2265"} ${fmtMetric(m, m.target)}`;
89
+ }
90
+
91
+ // src/core/ops.ts
92
+ var ops_exports = {};
93
+ __export(ops_exports, {
94
+ addExperiment: () => addExperiment,
95
+ addFindings: () => addFindings,
96
+ addHypotheses: () => addHypotheses,
97
+ addInsights: () => addInsights,
98
+ addRequirements: () => addRequirements,
99
+ applyRequirementChanges: () => applyRequirementChanges,
100
+ approveRequirement: () => approveRequirement,
101
+ createRequirement: () => createRequirement,
102
+ deleteExperiment: () => deleteExperiment,
103
+ deleteFinding: () => deleteFinding,
104
+ deleteHypothesis: () => deleteHypothesis,
105
+ deleteInsight: () => deleteInsight,
106
+ deleteRequirement: () => deleteRequirement,
107
+ dominantArea: () => dominantArea,
108
+ markSentToDelivery: () => markSentToDelivery,
109
+ obsoleteRequirement: () => obsoleteRequirement,
110
+ prioritizeMany: () => prioritizeMany,
111
+ recordResults: () => recordResults,
112
+ sendBackRequirement: () => sendBackRequirement,
113
+ startExperiment: () => startExperiment,
114
+ submitRequirement: () => submitRequirement,
115
+ updateDeliveryStates: () => updateDeliveryStates,
116
+ updateExperiment: () => updateExperiment,
117
+ updateFinding: () => updateFinding,
118
+ updateHypothesis: () => updateHypothesis,
119
+ updateInsight: () => updateInsight,
120
+ updateRequirement: () => updateRequirement
121
+ });
122
+ var nothing = (result) => ({ next: {}, result });
123
+ function log(c, kind, text, refId) {
124
+ return { id: c.newId(), at: c.now, actor: c.actor, text, kind, refId, ...c.via ? { via: c.via } : {} };
125
+ }
126
+ function dominantArea(items) {
127
+ const counts = /* @__PURE__ */ new Map();
128
+ items.forEach((x) => x.productArea && counts.set(x.productArea, (counts.get(x.productArea) ?? 0) + 1));
129
+ let best;
130
+ let n = 0;
131
+ counts.forEach((c, a) => {
132
+ if (c > n) [best, n] = [a, c];
133
+ });
134
+ return best;
135
+ }
136
+ function addInsights(s, c, items) {
137
+ const created = items.map((i) => ({ ...i, id: c.newId(), createdAt: c.now, createdBy: c.actor }));
138
+ return {
139
+ next: {
140
+ insights: [...created, ...s.insights],
141
+ activity: [
142
+ log(c, "insight", created.length === 1 ? `added insight "${created[0].title}"` : `added ${created.length} insights`, created[0]?.id),
143
+ ...s.activity
144
+ ]
145
+ },
146
+ result: created
147
+ };
148
+ }
149
+ function updateInsight(s, id, patch) {
150
+ return nothing0({ insights: s.insights.map((i) => i.id === id ? { ...i, ...patch } : i) });
151
+ }
152
+ function deleteInsight(s, id) {
153
+ return nothing0({
154
+ insights: s.insights.filter((i) => i.id !== id),
155
+ hypotheses: s.hypotheses.map((h) => ({ ...h, insightIds: h.insightIds.filter((x) => x !== id) })),
156
+ findings: s.findings.map((f) => ({ ...f, insightIds: f.insightIds.filter((x) => x !== id) })),
157
+ requirements: s.requirements.map((r) => r.insightIds ? { ...r, insightIds: r.insightIds.filter((x) => x !== id) } : r)
158
+ });
159
+ }
160
+ function nothing0(next) {
161
+ return { next, result: void 0 };
162
+ }
163
+ function addHypotheses(s, c, items) {
164
+ const created = items.map((h) => ({
165
+ ...h,
166
+ productArea: h.productArea ?? dominantArea(s.insights.filter((i) => h.insightIds.includes(i.id))),
167
+ id: c.newId(),
168
+ owner: c.actor,
169
+ createdAt: c.now,
170
+ updatedAt: c.now
171
+ }));
172
+ return {
173
+ next: {
174
+ hypotheses: [...created, ...s.hypotheses],
175
+ activity: [
176
+ log(c, "hypothesis", created.length === 1 ? `drafted "${created[0].title}"` : `drafted ${created.length} hypotheses`, created[0]?.id),
177
+ ...s.activity
178
+ ]
179
+ },
180
+ result: created
181
+ };
182
+ }
183
+ function updateHypothesis(s, c, id, patch) {
184
+ return nothing0({ hypotheses: s.hypotheses.map((h) => h.id === id ? { ...h, ...patch, updatedAt: c.now } : h) });
185
+ }
186
+ function prioritizeMany(s, c, ratings) {
187
+ if (!ratings.length) return nothing(void 0);
188
+ const byId = new Map(ratings.map((r) => [r.id, r.priority]));
189
+ return nothing0({
190
+ hypotheses: s.hypotheses.map((h) => byId.has(h.id) ? { ...h, priority: byId.get(h.id), updatedAt: c.now } : h),
191
+ activity: [
192
+ log(c, "hypothesis", `prioritized ${ratings.length} hypothes${ratings.length === 1 ? "is" : "es"} in a round`, ratings[0].id),
193
+ ...s.activity
194
+ ]
195
+ });
196
+ }
197
+ function deleteHypothesis(s, id) {
198
+ return nothing0({
199
+ hypotheses: s.hypotheses.filter((h) => h.id !== id),
200
+ experiments: s.experiments.filter((e) => e.hypothesisId !== id),
201
+ requirements: s.requirements.map((r) => r.hypothesisIds ? { ...r, hypothesisIds: r.hypothesisIds.filter((x) => x !== id) } : r)
202
+ });
203
+ }
204
+ function addExperiment(s, c, item) {
205
+ const exp = { ...item, id: c.newId(), owner: c.actor };
206
+ return {
207
+ next: { experiments: [exp, ...s.experiments], activity: [log(c, "experiment", `designed experiment "${exp.title}"`, exp.id), ...s.activity] },
208
+ result: exp
209
+ };
210
+ }
211
+ function updateExperiment(s, id, patch) {
212
+ return nothing0({ experiments: s.experiments.map((e) => e.id === id ? { ...e, ...patch } : e) });
213
+ }
214
+ function startExperiment(s, c, id) {
215
+ const exp = s.experiments.find((e) => e.id === id);
216
+ if (!exp) return nothing(void 0);
217
+ return nothing0({
218
+ experiments: s.experiments.map((e) => e.id === id ? { ...e, status: "running", startDate: c.now } : e),
219
+ hypotheses: s.hypotheses.map((h) => h.id === exp.hypothesisId && h.status === "draft" ? { ...h, status: "testing", updatedAt: c.now } : h),
220
+ activity: [log(c, "experiment", `started experiment "${exp.title}"`, id), ...s.activity]
221
+ });
222
+ }
223
+ function recordResults(s, c, id, primaryActual, guardrailActuals, notes) {
224
+ const exp = s.experiments.find((e) => e.id === id);
225
+ if (!exp) return nothing(void 0);
226
+ const withActuals = {
227
+ ...exp,
228
+ primaryMetric: { ...exp.primaryMetric, actual: primaryActual },
229
+ guardrails: exp.guardrails.map((g, i) => ({ ...g, actual: guardrailActuals[i] }))
230
+ };
231
+ const result = computeVerdict(withActuals);
232
+ const updated = { ...withActuals, status: "completed", endDate: c.now, resultNotes: notes, verdict: result.verdict };
233
+ const hyp = s.hypotheses.find((h) => h.id === exp.hypothesisId);
234
+ const newStatus = result.verdict === "validated" ? "validated" : result.verdict === "invalidated" ? "invalidated" : hyp?.status ?? "testing";
235
+ const newConfidence = result.verdict === "validated" ? 86 : result.verdict === "invalidated" ? 14 : hyp?.confidence ?? 50;
236
+ return {
237
+ next: {
238
+ experiments: s.experiments.map((e) => e.id === id ? updated : e),
239
+ hypotheses: s.hypotheses.map((h) => h.id === exp.hypothesisId ? { ...h, status: newStatus, confidence: newConfidence, updatedAt: c.now } : h),
240
+ activity: [log(c, "hypothesis", `${result.verdict} "${hyp?.title ?? "hypothesis"}" via experiment results`, exp.hypothesisId), ...s.activity]
241
+ },
242
+ result: { result, prevConfidence: hyp?.confidence ?? 50 }
243
+ };
244
+ }
245
+ function deleteExperiment(s, id) {
246
+ return nothing0({
247
+ experiments: s.experiments.filter((e) => e.id !== id),
248
+ findings: s.findings.map((f) => f.experimentIds.includes(id) ? { ...f, experimentIds: f.experimentIds.filter((x) => x !== id) } : f)
249
+ });
250
+ }
251
+ function addFindings(s, c, items) {
252
+ const created = items.map((f) => ({
253
+ ...f,
254
+ productArea: f.productArea ?? dominantArea(s.hypotheses.filter((h) => f.hypothesisIds.includes(h.id))) ?? dominantArea(s.insights.filter((i) => f.insightIds.includes(i.id))),
255
+ id: c.newId(),
256
+ createdAt: c.now
257
+ }));
258
+ return {
259
+ next: {
260
+ findings: [...created, ...s.findings],
261
+ activity: [
262
+ log(c, "finding", created.length === 1 ? `synthesized finding "${created[0].title}"` : `synthesized ${created.length} findings`, created[0]?.id),
263
+ ...s.activity
264
+ ]
265
+ },
266
+ result: created
267
+ };
268
+ }
269
+ function updateFinding(s, id, patch) {
270
+ return nothing0({ findings: s.findings.map((f) => f.id === id ? { ...f, ...patch } : f) });
271
+ }
272
+ function deleteFinding(s, id) {
273
+ return nothing0({
274
+ findings: s.findings.filter((f) => f.id !== id),
275
+ requirements: s.requirements.map((r) => ({ ...r, findingIds: r.findingIds.filter((x) => x !== id) }))
276
+ });
277
+ }
278
+ function addRequirements(s, c, items) {
279
+ const created = items.map((r) => ({
280
+ ...r,
281
+ productArea: r.productArea ?? dominantArea(s.findings.filter((f) => r.findingIds.includes(f.id))),
282
+ id: c.newId(),
283
+ createdAt: c.now,
284
+ status: "draft"
285
+ }));
286
+ return {
287
+ next: {
288
+ requirements: [...created, ...s.requirements],
289
+ activity: [
290
+ log(
291
+ c,
292
+ "requirement",
293
+ created.length === 1 ? `derived requirement "${created[0].title}"` : `derived ${created.length} requirements`,
294
+ created[0]?.id
295
+ ),
296
+ ...s.activity
297
+ ]
298
+ },
299
+ result: created
300
+ };
301
+ }
302
+ function createRequirement(s, c, item) {
303
+ const r = {
304
+ kind: "solution",
305
+ ...item,
306
+ findingIds: [],
307
+ productArea: item.productArea ?? dominantArea(s.insights.filter((i) => item.insightIds?.includes(i.id))),
308
+ id: c.newId(),
309
+ createdAt: c.now
310
+ };
311
+ return {
312
+ next: { requirements: [r, ...s.requirements], activity: [log(c, "requirement", `created requirement "${r.title}" directly`, r.id), ...s.activity] },
313
+ result: r
314
+ };
315
+ }
316
+ function updateRequirement(s, id, patch) {
317
+ return nothing0({ requirements: s.requirements.map((r) => r.id === id ? { ...r, ...patch } : r) });
318
+ }
319
+ function deleteRequirement(s, id) {
320
+ return nothing0({
321
+ requirements: s.requirements.filter((r) => r.id !== id).map((r) => r.stakeholderIds?.includes(id) ? { ...r, stakeholderIds: r.stakeholderIds.filter((x) => x !== id) } : r)
322
+ });
323
+ }
324
+ function submitRequirement(s, c, id, approver) {
325
+ const r = s.requirements.find((x) => x.id === id);
326
+ if (!r || r.status !== "draft") return nothing(false);
327
+ return {
328
+ next: {
329
+ requirements: s.requirements.map((x) => x.id === id ? { ...x, status: "awaiting-approval", approver } : x),
330
+ activity: [log(c, "requirement", `asked for approval of "${r.title}"`, id), ...s.activity]
331
+ },
332
+ result: true
333
+ };
334
+ }
335
+ function approveRequirement(s, c, id) {
336
+ const r = s.requirements.find((x) => x.id === id);
337
+ if (!r || r.status === "approved" || r.status === "in-delivery" || r.status === "obsolete") return nothing(false);
338
+ return {
339
+ next: {
340
+ requirements: s.requirements.map((x) => x.id === id ? { ...x, status: "approved", approvedBy: c.actor, approvedAt: c.now } : x),
341
+ activity: [log(c, "requirement", `approved "${r.title}"`, id), ...s.activity]
342
+ },
343
+ result: true
344
+ };
345
+ }
346
+ function sendBackRequirement(s, c, id) {
347
+ const r = s.requirements.find((x) => x.id === id);
348
+ if (!r || r.status !== "awaiting-approval") return nothing(false);
349
+ return {
350
+ next: {
351
+ requirements: s.requirements.map((x) => x.id === id ? { ...x, status: "draft" } : x),
352
+ activity: [log(c, "requirement", `sent "${r.title}" back for changes`, id), ...s.activity]
353
+ },
354
+ result: true
355
+ };
356
+ }
357
+ function obsoleteRequirement(s, c, id, by) {
358
+ const r = s.requirements.find((x) => x.id === id);
359
+ if (!r || !canObsolete(r)) return nothing(false);
360
+ return {
361
+ next: {
362
+ requirements: s.requirements.map(
363
+ (x) => x.id === id ? { ...x, status: "obsolete", obsoletedAt: c.now, obsoletedBy: by?.length ? by : x.obsoletedBy } : x
364
+ ),
365
+ activity: [log(c, "requirement", `made "${r.title}" obsolete`, id), ...s.activity]
366
+ },
367
+ result: true
368
+ };
369
+ }
370
+ function applyRequirementChanges(s, c, { create, update, obsolete }) {
371
+ const before = s.requirements;
372
+ const patches = /* @__PURE__ */ new Map();
373
+ update.forEach((u) => patches.set(u.id, { ...patches.get(u.id), ...u.patch }));
374
+ const supersede = /* @__PURE__ */ new Map();
375
+ obsolete.forEach((o) => {
376
+ const r = before.find((x) => x.id === o.id);
377
+ if (r && canObsolete(r)) supersede.set(o.id, [...supersede.get(o.id) ?? [], o.by]);
378
+ });
379
+ const updatedDrafts = update.filter((u) => u.patch.title).map((u) => u.id);
380
+ const stake = create.filter((r) => kindOf(r) === "stakeholder").length;
381
+ const sol = create.length - stake;
382
+ const parts = [stake && `${stake} stakeholder`, sol && `${sol} solution`].filter(Boolean);
383
+ const entries = [];
384
+ if (create.length) entries.push(log(c, "requirement", `derived ${parts.join(" and ")} requirement${create.length === 1 ? "" : "s"}`, create[0].id));
385
+ updatedDrafts.forEach((id) => entries.push(log(c, "requirement", `updated draft "${patches.get(id)?.title}" from a new finding`, id)));
386
+ supersede.forEach((_, id) => entries.push(log(c, "requirement", `made "${before.find((x) => x.id === id)?.title}" obsolete`, id)));
387
+ return nothing0({
388
+ requirements: [
389
+ ...create,
390
+ ...s.requirements.map((r) => {
391
+ let x = patches.has(r.id) ? { ...r, ...patches.get(r.id) } : r;
392
+ if (supersede.has(r.id)) x = { ...x, status: "obsolete", obsoletedAt: c.now, obsoletedBy: supersede.get(r.id) };
393
+ return x;
394
+ })
395
+ ],
396
+ activity: [...entries.reverse(), ...s.activity]
397
+ });
398
+ }
399
+ function markSentToDelivery(s, c, id, delivery) {
400
+ const r = s.requirements.find((x) => x.id === id);
401
+ if (!r || r.delivery) return nothing(false);
402
+ return {
403
+ next: {
404
+ requirements: s.requirements.map((x) => x.id === id ? { ...x, status: "in-delivery", delivery } : x),
405
+ activity: [log(c, "requirement", `sent "${r.title}" to Linear as ${delivery.identifier}`, id), ...s.activity]
406
+ },
407
+ result: true
408
+ };
409
+ }
410
+ function updateDeliveryStates(s, byRequirement) {
411
+ return nothing0({ requirements: s.requirements.map((r) => byRequirement[r.id] ? { ...r, delivery: byRequirement[r.id] } : r) });
412
+ }
413
+
414
+ // src/core/schemas.ts
415
+ import { z } from "zod";
416
+ var short = (max = 200) => z.string().trim().min(1).max(max);
417
+ var long = (max = 4e3) => z.string().trim().max(max);
418
+ var area = z.string().max(100).optional().describe("Product area: its label or id from get_workspace. Leave out to inherit it from linked evidence.");
419
+ var SOURCE = z.enum(["interview", "support", "survey", "analytics", "observation"]);
420
+ var SENTIMENT = z.enum(["negative", "neutral", "positive"]);
421
+ var HYPOTHESIS_STATUS = z.enum(["draft", "testing", "validated", "invalidated"]);
422
+ var METHOD = z.enum(["pilot", "ab-test", "prototype-test", "survey", "fake-door", "concierge"]);
423
+ var EXPERIMENT_STATUS = z.enum(["planned", "running", "completed"]);
424
+ var PRIORITY = z.enum(["must", "should", "could"]);
425
+ var REQUIREMENT_KIND = z.enum(["stakeholder", "solution"]);
426
+ var REQUIREMENT_ORIGIN = z.enum(["tender", "regulation", "contract", "customer-need"]);
427
+ var FINDING_CONFIDENCE = z.enum(["low", "medium", "high"]);
428
+ var KIND = z.enum(["insight", "hypothesis", "experiment", "finding", "requirement"]);
429
+ function makeSchemas(id) {
430
+ const ids = (what) => z.array(id).max(100).describe(`Ids of ${what} in this workspace (from search_items or get_item).`);
431
+ const insightInput3 = z.object({
432
+ title: short().describe("One line naming the pain or need, in plain words."),
433
+ quote: long(2e3).min(1).describe("What the person actually said or did, verbatim where possible. This is the evidence."),
434
+ source: SOURCE.describe("Where it came from."),
435
+ persona: short(100).describe('Who said it, as a role or segment, e.g. "Finance manager at a mid-size firm".'),
436
+ participant: z.string().trim().max(100).optional().describe("Optional participant reference, e.g. P07. Never a full name or contact details."),
437
+ tags: z.array(short(40)).max(10).default([]),
438
+ sentiment: SENTIMENT.default("neutral"),
439
+ productArea: area
440
+ });
441
+ const successMetric = z.object({
442
+ name: short(100),
443
+ unit: z.string().trim().max(20).describe('e.g. "%", "min", "tickets/week"'),
444
+ baseline: z.number(),
445
+ target: z.number(),
446
+ direction: z.enum(["increase", "decrease"]),
447
+ timeframe: z.string().trim().max(100).describe('e.g. "over a 4-week pilot"')
448
+ });
449
+ const hypothesisInput3 = z.object({
450
+ title: short(),
451
+ outcome: short(300).describe('"We believe we will [outcome]": the business result the team is after.'),
452
+ forWhom: short(300).describe('"\u2026if [forWhom]": the users.'),
453
+ benefit: short(300).describe('"\u2026[get] [benefit]": what the users gain, in their terms.'),
454
+ feature: short(300).describe('"\u2026with [feature]": the product idea.'),
455
+ successMetric: successMetric.optional().describe("One number with a baseline, target and timeframe. Strongly recommended."),
456
+ guardrail: z.string().trim().max(300).optional().describe("What must not get worse."),
457
+ knowWhen: z.string().trim().max(600).optional().describe("Plain-language success statement. Composed from successMetric and guardrail when those are set."),
458
+ alternatives: z.string().trim().max(600).optional().describe("What target users rely on today."),
459
+ edge: z.string().trim().max(600).optional().describe("Why this wins against those alternatives."),
460
+ riskiestAssumption: z.string().trim().max(600).optional(),
461
+ confidence: z.number().int().min(0).max(100).default(50).describe("0-100, how confident the team is before testing."),
462
+ insightIds: ids("the insights this hypothesis is built on").default([]),
463
+ productArea: area
464
+ });
465
+ const metric = z.object({
466
+ name: short(100),
467
+ unit: z.string().trim().max(20),
468
+ baseline: z.number(),
469
+ target: z.number().describe('Success means actual <= target for "decrease" and actual >= target for "increase".'),
470
+ direction: z.enum(["increase", "decrease"])
471
+ });
472
+ const experimentInput3 = z.object({
473
+ hypothesisId: id.describe("The hypothesis this experiment tests."),
474
+ title: short(),
475
+ method: METHOD,
476
+ description: long(4e3).min(1).describe("What will be done, with whom, and how results are measured."),
477
+ primaryMetric: metric,
478
+ guardrails: z.array(metric).max(5).default([]),
479
+ sampleSize: z.string().trim().max(100).default("").describe('e.g. "40 accounts"'),
480
+ durationWeeks: z.number().min(0).max(52).default(2),
481
+ checkBackDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe("For small bets: YYYY-MM-DD to check whether it made a difference.")
482
+ });
483
+ const findingInput3 = z.object({
484
+ title: short(),
485
+ summary: long(4e3).min(1).describe("What was learned and what it means for the product."),
486
+ experimentIds: ids("the experiments behind it").default([]),
487
+ hypothesisIds: ids("the hypotheses it speaks to").default([]),
488
+ insightIds: ids("supporting insights").default([]),
489
+ confidence: FINDING_CONFIDENCE.default("medium"),
490
+ productArea: area
491
+ });
492
+ const requirementInput3 = z.object({
493
+ kind: REQUIREMENT_KIND.default("solution").describe(
494
+ "stakeholder = what a group of stakeholders needs, in their terms. solution = what the product must do to meet stakeholder needs."
495
+ ),
496
+ title: short(),
497
+ story: long(2e3).min(1).describe("Stakeholder: the need statement. Solution: the user story (As a \u2026 I want \u2026 so that \u2026)."),
498
+ stakeholder: z.string().trim().max(100).optional().describe('Stakeholder requirements: who has the need, e.g. "Finance managers".'),
499
+ product: z.string().trim().max(100).optional().describe("Solution requirements: the product that delivers it (one from get_workspace)."),
500
+ stakeholderIds: ids("the stakeholder requirements this solution requirement helps meet").optional(),
501
+ acceptanceCriteria: z.array(short(500)).min(1).max(20),
502
+ priority: PRIORITY.default("should"),
503
+ findingIds: ids("the findings that justify it").default([]),
504
+ insightIds: ids("customer evidence linked directly").optional(),
505
+ hypothesisIds: ids("hypotheses it was committed from").optional(),
506
+ origin: REQUIREMENT_ORIGIN.optional().describe(
507
+ "Only for requirements decided outside the evidence loop (tender, regulation, contract, customer-need). Required when findingIds is empty."
508
+ ),
509
+ originNote: z.string().trim().max(300).optional().describe('Where the decision comes from, e.g. "Region North tender 2026, section 4.2".'),
510
+ productArea: area
511
+ });
512
+ const PATCHES2 = {
513
+ insight: insightInput3.partial().extend({ tags: z.array(short(40)).max(10).optional(), sentiment: SENTIMENT.optional() }),
514
+ hypothesis: hypothesisInput3.partial().extend({
515
+ status: HYPOTHESIS_STATUS.optional(),
516
+ confidence: z.number().int().min(0).max(100).optional(),
517
+ insightIds: z.array(id).max(100).optional()
518
+ }),
519
+ experiment: experimentInput3.omit({ hypothesisId: true }).partial().extend({
520
+ guardrails: z.array(metric).max(5).optional(),
521
+ sampleSize: z.string().trim().max(100).optional(),
522
+ durationWeeks: z.number().min(0).max(52).optional(),
523
+ resultNotes: z.string().trim().max(4e3).optional()
524
+ }),
525
+ finding: findingInput3.partial().extend({
526
+ experimentIds: z.array(id).max(100).optional(),
527
+ hypothesisIds: z.array(id).max(100).optional(),
528
+ insightIds: z.array(id).max(100).optional(),
529
+ confidence: FINDING_CONFIDENCE.optional()
530
+ }),
531
+ requirement: requirementInput3.partial().extend({
532
+ priority: PRIORITY.optional(),
533
+ findingIds: z.array(id).max(100).optional(),
534
+ kind: REQUIREMENT_KIND.optional()
535
+ })
536
+ };
537
+ return { id, insightInput: insightInput3, hypothesisInput: hypothesisInput3, experimentInput: experimentInput3, findingInput: findingInput3, requirementInput: requirementInput3, PATCHES: PATCHES2 };
538
+ }
539
+ var ID_PREFIX = { insight: "INS", hypothesis: "HYP", experiment: "EXP", finding: "FND", requirement: "REQ" };
540
+ var LOCAL_ID = /^(INS|HYP|EXP|FND|REQ)-\d{4,}$/;
541
+ var localId = z.string().regex(LOCAL_ID, "an id like INS-0007");
542
+ var localSchemas = makeSchemas(localId);
543
+
544
+ // src/core/hypothesis.ts
545
+ function hasSuccessMetric(m) {
546
+ return Boolean(m && m.name.trim());
547
+ }
548
+ function lowerFirst(s) {
549
+ return s.length > 1 && s[1] === s[1].toUpperCase() && /[A-Z]/.test(s[1]) ? s : s.charAt(0).toLowerCase() + s.slice(1);
550
+ }
551
+ function describeSuccess(m) {
552
+ const verb = m.direction === "decrease" ? "falls" : "rises";
553
+ const bound = m.direction === "decrease" ? "or less" : "or more";
554
+ const unit = m.unit ? ` ${m.unit}` : "";
555
+ const when = m.timeframe.trim() ? ` ${m.timeframe.trim()}` : "";
556
+ return `${lowerFirst(m.name.trim())} ${verb} from ${m.baseline} to ${m.target}${unit} ${bound}${when}`;
557
+ }
558
+ function composeKnowWhen(d) {
559
+ if (!hasSuccessMetric(d.successMetric)) return "";
560
+ const g = (d.guardrail ?? "").trim();
561
+ return describeSuccess(d.successMetric) + (g ? `, without ${g}` : "");
562
+ }
563
+ function composeStatement(h) {
564
+ return `We believe we will ${h.outcome.trim()} if ${h.forWhom.trim()} get ${h.benefit.trim()} with ${h.feature.trim()}.`;
565
+ }
566
+
567
+ // src/store/config.ts
568
+ import { execFileSync } from "child_process";
569
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
570
+ import { basename, dirname, join, resolve } from "path";
571
+ import YAML from "yaml";
572
+ import { z as z2 } from "zod";
573
+ var DIR = "groundwork";
574
+ var CONFIG_FILE = "config.yml";
575
+ var SCHEMA_VERSION = 1;
576
+ var slugId = z2.string().regex(/^[a-z0-9][a-z0-9-]{0,39}$/, "lowercase letters, digits and dashes");
577
+ var configSchema = z2.object({
578
+ schemaVersion: z2.number().int().positive().default(SCHEMA_VERSION),
579
+ name: z2.string().trim().min(1).max(100),
580
+ productAreas: z2.array(z2.object({ id: slugId, label: z2.string().trim().min(1).max(100) })).default([]),
581
+ products: z2.array(z2.string().trim().min(1).max(100)).default([]),
582
+ people: z2.array(
583
+ z2.object({
584
+ id: slugId,
585
+ name: z2.string().trim().min(1).max(100),
586
+ role: z2.enum(["owner", "editor", "viewer"]).default("editor"),
587
+ /** Optional: lets Groundwork recognise you from `git config user.email`. */
588
+ email: z2.string().trim().max(200).optional()
589
+ })
590
+ ).default([]),
591
+ /** Set when this folder was imported into the Groundwork web app. Local writes stop, so the two can't drift apart. */
592
+ migrated: z2.string().url().optional()
593
+ });
594
+ function findRoot(cwd = process.cwd()) {
595
+ if (process.env.GROUNDWORK_DIR) return resolve(process.env.GROUNDWORK_DIR);
596
+ let dir = resolve(cwd);
597
+ for (; ; ) {
598
+ if (existsSync(join(dir, DIR, CONFIG_FILE))) return dir;
599
+ const up = dirname(dir);
600
+ if (up === dir) return resolve(cwd);
601
+ dir = up;
602
+ }
603
+ }
604
+ var configPath = (root) => join(root, DIR, CONFIG_FILE);
605
+ var isInitialized = (root) => existsSync(configPath(root));
606
+ function defaultConfig(root) {
607
+ return configSchema.parse({ name: basename(resolve(root)) || "Product" });
608
+ }
609
+ var ConfigError = class extends Error {
610
+ };
611
+ function readConfig(root) {
612
+ const file = configPath(root);
613
+ if (!existsSync(file)) return defaultConfig(root);
614
+ let raw;
615
+ try {
616
+ raw = YAML.parse(readFileSync(file, "utf8")) ?? {};
617
+ } catch (e) {
618
+ throw new ConfigError(`${DIR}/${CONFIG_FILE} isn't valid YAML: ${e.message}`);
619
+ }
620
+ const parsed = configSchema.safeParse(raw);
621
+ if (!parsed.success) throw new ConfigError(`${DIR}/${CONFIG_FILE} is invalid: ${z2.prettifyError(parsed.error)}`);
622
+ if (parsed.data.schemaVersion > SCHEMA_VERSION) {
623
+ throw new ConfigError(`${DIR}/${CONFIG_FILE} uses schema version ${parsed.data.schemaVersion}; this Groundwork understands up to ${SCHEMA_VERSION}. Update groundwork-mcp.`);
624
+ }
625
+ return parsed.data;
626
+ }
627
+ var CONFIG_HEADER = `# Groundwork settings. See SPEC.md in the groundwork-mcp package for every field.
628
+ # productAreas: [{ id: onboarding, label: Onboarding }]
629
+ # products: [Acme app]
630
+ # people: [{ id: sam, name: Sam, role: owner }] # roles: owner, editor, viewer
631
+ `;
632
+ function writeConfig(root, config) {
633
+ mkdirSync(join(root, DIR), { recursive: true });
634
+ writeFileSync(configPath(root), CONFIG_HEADER + YAML.stringify(config, { lineWidth: 0 }));
635
+ }
636
+ function gitEmail(root) {
637
+ try {
638
+ return execFileSync("git", ["config", "user.email"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
639
+ } catch {
640
+ return void 0;
641
+ }
642
+ }
643
+ function resolveActor(root, config) {
644
+ const byId = (id) => config.people.find((p) => p.id === id);
645
+ const env = process.env.GROUNDWORK_USER?.trim();
646
+ if (env) return { id: env, person: byId(env) };
647
+ const email = gitEmail(root)?.toLowerCase();
648
+ const match = email && config.people.find((p) => p.email?.toLowerCase() === email);
649
+ if (match) return { id: match.id, person: match };
650
+ if (config.people.length === 1) return { id: config.people[0].id, person: config.people[0] };
651
+ return { id: "me" };
652
+ }
653
+
654
+ // src/store/files.ts
655
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
656
+ import { join as join2, relative } from "path";
657
+ import YAML2 from "yaml";
658
+ var COLLECTIONS = {
659
+ insight: "insights",
660
+ hypothesis: "hypotheses",
661
+ experiment: "experiments",
662
+ finding: "findings",
663
+ requirement: "requirements"
664
+ };
665
+ var KIND_OF = {
666
+ insights: "insight",
667
+ hypotheses: "hypothesis",
668
+ experiments: "experiment",
669
+ findings: "finding",
670
+ requirements: "requirement"
671
+ };
672
+ var ITEM_COLLECTIONS = COLLECTION_KEYS.filter((k) => k !== "activity");
673
+ function slug(title) {
674
+ return title.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "") || "item";
675
+ }
676
+ function newPath(kind, id, title) {
677
+ return `${DIR}/${COLLECTIONS[kind]}/${id}-${slug(title)}.md`;
678
+ }
679
+ var FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
680
+ function parseItem(text) {
681
+ const m = FRONTMATTER.exec(text);
682
+ if (!m) throw new Error("no YAML frontmatter (the file must start with a line of three dashes)");
683
+ const data = YAML2.parse(m[1]);
684
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("the frontmatter isn't a set of fields");
685
+ return { data, notes: m[2].replace(/^\r?\n/, "").trimEnd() };
686
+ }
687
+ function clean(v) {
688
+ if (Array.isArray(v)) return v.map(clean);
689
+ if (v && typeof v === "object") {
690
+ return Object.fromEntries(Object.entries(v).flatMap(([k, x]) => x === void 0 ? [] : [[k, clean(x)]]));
691
+ }
692
+ return v;
693
+ }
694
+ function renderItem(item) {
695
+ const { id, title, notes, ...rest } = item;
696
+ const fm = YAML2.stringify(clean({ id, title, ...rest }), { lineWidth: 0 });
697
+ const body = typeof notes === "string" && notes.trim() ? `
698
+ ${notes.trim()}
699
+ ` : "";
700
+ return `---
701
+ ${fm}---
702
+ ${body}`;
703
+ }
704
+ function load(root) {
705
+ const items = emptyCollections();
706
+ const paths = /* @__PURE__ */ new Map();
707
+ const problems = [];
708
+ for (const key of ITEM_COLLECTIONS) {
709
+ const dir = join2(root, DIR, key);
710
+ if (!existsSync2(dir)) continue;
711
+ const prefix = ID_PREFIX[KIND_OF[key]];
712
+ for (const name of readdirSync(dir).sort()) {
713
+ if (!name.endsWith(".md")) continue;
714
+ const file = relative(root, join2(dir, name));
715
+ try {
716
+ const { data, notes } = parseItem(readFileSync2(join2(dir, name), "utf8"));
717
+ const id = data.id;
718
+ if (typeof id !== "string" || !LOCAL_ID.test(id)) throw new Error(`id must look like ${prefix}-0001, not ${JSON.stringify(id)}`);
719
+ if (!id.startsWith(`${prefix}-`)) throw new Error(`${id} is in ${key}/, but ${key} ids start with ${prefix}-`);
720
+ if (paths.has(id)) {
721
+ problems.push({ file, message: `duplicate id ${id}, also used by ${paths.get(id)}. Give one of them a new id.` });
722
+ continue;
723
+ }
724
+ paths.set(id, file);
725
+ items[key].push(notes ? { ...data, notes } : data);
726
+ } catch (e) {
727
+ problems.push({ file, message: e.message });
728
+ }
729
+ }
730
+ }
731
+ return { items, paths, problems };
732
+ }
733
+ function idAllocator(items) {
734
+ const next = /* @__PURE__ */ new Map();
735
+ for (const key of ITEM_COLLECTIONS) {
736
+ let max = 0;
737
+ for (const x of items[key]) {
738
+ const n = Number(x.id.split("-")[1]);
739
+ if (Number.isFinite(n) && n > max) max = n;
740
+ }
741
+ next.set(KIND_OF[key], max + 1);
742
+ }
743
+ return (kind) => {
744
+ const n = next.get(kind);
745
+ next.set(kind, n + 1);
746
+ return `${ID_PREFIX[kind]}-${String(n).padStart(4, "0")}`;
747
+ };
748
+ }
749
+ var LINK_FIELDS = ["insightIds", "hypothesisIds", "experimentIds", "findingIds", "stakeholderIds", "obsoletedBy"];
750
+ function assignIds(before, after) {
751
+ const known = new Set(ITEM_COLLECTIONS.flatMap((k) => before[k].map((x) => x.id)));
752
+ const alloc = idAllocator(before);
753
+ const renamed = /* @__PURE__ */ new Map();
754
+ for (const key of ITEM_COLLECTIONS) {
755
+ for (const x of after[key]) if (!known.has(x.id) && !LOCAL_ID.test(x.id)) renamed.set(x.id, alloc(KIND_OF[key]));
756
+ }
757
+ if (!renamed.size) return { items: after, renamed };
758
+ const map = (id) => renamed.get(id) ?? id;
759
+ const items = { ...after };
760
+ for (const key of ITEM_COLLECTIONS) {
761
+ items[key] = after[key].map((x) => {
762
+ let y = x;
763
+ const touch = () => y === x ? y = { ...x } : y;
764
+ if (renamed.has(x.id)) touch().id = map(x.id);
765
+ if (typeof x.hypothesisId === "string" && renamed.has(x.hypothesisId)) touch().hypothesisId = map(x.hypothesisId);
766
+ for (const f of LINK_FIELDS) {
767
+ const list = x[f];
768
+ if (Array.isArray(list) && list.some((v) => renamed.has(v))) touch()[f] = list.map(map);
769
+ }
770
+ return y;
771
+ });
772
+ }
773
+ return { items, renamed };
774
+ }
775
+ function sameJSON(a, b) {
776
+ const norm = (v) => Array.isArray(v) ? v.map(norm) : v && typeof v === "object" ? Object.fromEntries(
777
+ Object.keys(v).filter((k) => v[k] !== void 0).sort().map((k) => [k, norm(v[k])])
778
+ ) : v;
779
+ return JSON.stringify(norm(a)) === JSON.stringify(norm(b));
780
+ }
781
+ function writeAtomic(file, text) {
782
+ const tmp = `${file}.tmp-${process.pid}`;
783
+ writeFileSync2(tmp, text);
784
+ renameSync(tmp, file);
785
+ }
786
+ function save(root, loaded, after) {
787
+ const { upserts, deletes } = diffCollections(loaded.items, after);
788
+ const before = new Map(ITEM_COLLECTIONS.flatMap((k) => loaded.items[k].map((x) => [x.id, x])));
789
+ const touched = [];
790
+ for (const u of upserts) {
791
+ if (u.kind === "activity") continue;
792
+ const old = before.get(u.id);
793
+ if (old && sameJSON(old, { id: u.id, ...u.data })) continue;
794
+ const kind = u.kind;
795
+ const rel = loaded.paths.get(u.id) ?? newPath(kind, u.id, String(u.data.title ?? ""));
796
+ mkdirSync2(join2(root, DIR, COLLECTIONS[kind]), { recursive: true });
797
+ writeAtomic(join2(root, rel), renderItem({ id: u.id, ...u.data }));
798
+ loaded.paths.set(u.id, rel);
799
+ touched.push(rel);
800
+ }
801
+ for (const id of deletes) {
802
+ const rel = loaded.paths.get(id);
803
+ if (!rel) continue;
804
+ if (existsSync2(join2(root, rel))) unlinkSync(join2(root, rel));
805
+ loaded.paths.delete(id);
806
+ touched.push(rel);
807
+ }
808
+ loaded.items = after;
809
+ return touched;
810
+ }
811
+
812
+ // src/store/validate.ts
813
+ import { z as z3 } from "zod";
814
+ var REQUIREMENT_STATUS = z3.enum(["draft", "awaiting-approval", "approved", "in-delivery", "obsolete"]);
815
+ var { insightInput, hypothesisInput, experimentInput, findingInput, requirementInput } = localSchemas;
816
+ var STORED = {
817
+ insight: insightInput.extend({ createdAt: z3.string() }).loose(),
818
+ hypothesis: hypothesisInput.extend({ status: HYPOTHESIS_STATUS, knowWhen: z3.string().optional() }).loose(),
819
+ experiment: experimentInput.extend({ status: EXPERIMENT_STATUS }).loose(),
820
+ finding: findingInput.loose(),
821
+ requirement: requirementInput.extend({ status: REQUIREMENT_STATUS, acceptanceCriteria: z3.array(z3.string()).default([]) }).loose()
822
+ };
823
+ function validate(loaded, config) {
824
+ const out = loaded.problems.map((p) => ({ level: "error", ...p }));
825
+ const s = loaded.items;
826
+ const kindById = /* @__PURE__ */ new Map();
827
+ for (const kind of Object.keys(COLLECTIONS)) for (const x of s[COLLECTIONS[kind]]) kindById.set(x.id, kind);
828
+ const areaIds = new Set(config.productAreas.map((a) => a.id));
829
+ const people = new Set(config.people.map((p) => p.id));
830
+ for (const kind of Object.keys(COLLECTIONS)) {
831
+ for (const item of s[COLLECTIONS[kind]]) {
832
+ const file = loaded.paths.get(item.id) ?? item.id;
833
+ const err = (message) => out.push({ level: "error", file, message });
834
+ const warn = (message) => out.push({ level: "warning", file, message });
835
+ const parsed = STORED[kind].safeParse(item);
836
+ if (!parsed.success) err(z3.prettifyError(parsed.error).replace(/\n/g, "; "));
837
+ const link = (field, want, ids) => {
838
+ for (const id of Array.isArray(ids) ? ids : ids === void 0 ? [] : [ids]) {
839
+ const got = kindById.get(id);
840
+ if (!got) err(`${field}: ${id} doesn't exist`);
841
+ else if (got !== want) err(`${field}: ${id} is a ${got}, not a ${want}`);
842
+ else if (id === item.id) err(`${field}: an item can't link to itself`);
843
+ }
844
+ };
845
+ const area2 = item.productArea;
846
+ if (area2 && !areaIds.has(area2)) warn(`productArea "${area2}" isn't in config.yml productAreas`);
847
+ switch (kind) {
848
+ case "hypothesis":
849
+ link("insightIds", "insight", item.insightIds);
850
+ if (!item.insightIds?.length) warn("no insights linked: what evidence is this built on?");
851
+ break;
852
+ case "experiment":
853
+ link("hypothesisId", "hypothesis", item.hypothesisId);
854
+ break;
855
+ case "finding":
856
+ link("experimentIds", "experiment", item.experimentIds);
857
+ link("hypothesisIds", "hypothesis", item.hypothesisIds);
858
+ link("insightIds", "insight", item.insightIds);
859
+ if (![item.experimentIds, item.hypothesisIds, item.insightIds].some((l) => l?.length)) {
860
+ warn("no evidence linked: link the experiments, hypotheses or insights behind it");
861
+ }
862
+ break;
863
+ case "requirement": {
864
+ const r = item;
865
+ link("findingIds", "finding", r.findingIds);
866
+ link("insightIds", "insight", r.insightIds);
867
+ link("hypothesisIds", "hypothesis", r.hypothesisIds);
868
+ link("stakeholderIds", "requirement", r.stakeholderIds);
869
+ link("obsoletedBy", "requirement", r.obsoletedBy);
870
+ for (const id of r.stakeholderIds ?? []) {
871
+ const t = s.requirements.find((x) => x.id === id);
872
+ if (t && kindOf(t) !== "stakeholder") err(`stakeholderIds: ${id} is a solution requirement, not a stakeholder requirement`);
873
+ }
874
+ if (r.stakeholderIds?.length && kindOf(r) === "stakeholder") err("stakeholderIds is only for solution requirements");
875
+ if (!r.findingIds?.length && !r.origin) err("needs findingIds, or an origin (tender, regulation, contract, customer-need) if it was decided elsewhere");
876
+ if (r.product && config.products.length && !config.products.includes(r.product)) warn(`product "${r.product}" isn't in config.yml products`);
877
+ if (r.approver && !people.has(r.approver)) warn(`approver "${r.approver}" isn't in config.yml people`);
878
+ break;
879
+ }
880
+ }
881
+ }
882
+ }
883
+ return out;
884
+ }
885
+
886
+ // src/mcp/server.ts
887
+ import { randomUUID } from "crypto";
888
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
889
+ import { z as z4 } from "zod";
890
+ var VERSION = true ? "0.2.0" : "0.0.0-dev";
891
+ var { insightInput: insightInput2, hypothesisInput: hypothesisInput2, experimentInput: experimentInput2, findingInput: findingInput2, requirementInput: requirementInput2, PATCHES } = localSchemas;
892
+ var INSTRUCTIONS = `Groundwork keeps this product's evidence and decisions as linked Markdown files in the groundwork/ folder, as a chain:
893
+ insight -> hypothesis -> experiment -> finding -> requirement.
894
+
895
+ - Insight: evidence from a real person: what they said or did (quote), where it came from (source) and who they are (persona). Not opinions or ideas. Never store full names or contact details; use a role and an optional participant ref like P07.
896
+ - Hypothesis: "We believe we will [outcome] if [forWhom] get [benefit] with [feature]", built on insights (insightIds), ideally with a successMetric (baseline, target, timeframe).
897
+ - Experiment: tests exactly one hypothesis (hypothesisId) with one primary metric and optional guardrails. Lifecycle: planned -> start_experiment -> record_experiment_results (Groundwork computes the verdict and updates the hypothesis).
898
+ - Finding: what was learned, linked to the experiments, hypotheses and insights behind it.
899
+ - Requirement: "stakeholder" (a need, in the stakeholder's words) or "solution" (what the product must do). Justified by findingIds, or, when decided elsewhere, by an origin (tender, regulation, contract, customer-need).
900
+
901
+ How to work:
902
+ 1. Call get_workspace first: it gives product areas, products and people (for approvers).
903
+ 2. Before creating anything, search_items for duplicates and for evidence to link. Prefer linking to existing items over creating near-duplicates.
904
+ 3. Always link evidence: hypotheses to insights, experiments to a hypothesis, findings to experiments/hypotheses/insights, requirements to findings.
905
+ 4. Ask the user before deleting items or approving requirements, unless they already told you to.
906
+ 5. Use these tools rather than editing the files directly: they keep ids unique and links valid. Each result includes the item's file: mention it so the user can open it.
907
+ 6. The Markdown body under an item's frontmatter is the user's own notes. Read it, but don't overwrite it.`;
908
+ var UserError = class extends Error {
909
+ };
910
+ var an = (kind) => `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind}`;
911
+ var ok = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
912
+ var fail = (message) => ({ content: [{ type: "text", text: message }], isError: true });
913
+ function find(s, id) {
914
+ for (const kind of KIND.options) {
915
+ const item = s[COLLECTIONS[kind]].find((x) => x.id === id);
916
+ if (item) return { kind, item };
917
+ }
918
+ return void 0;
919
+ }
920
+ function outgoing(kind, item) {
921
+ switch (kind) {
922
+ case "hypothesis":
923
+ return item.insightIds ?? [];
924
+ case "experiment":
925
+ return [item.hypothesisId];
926
+ case "finding": {
927
+ const f = item;
928
+ return [...f.experimentIds ?? [], ...f.hypothesisIds ?? [], ...f.insightIds ?? []];
929
+ }
930
+ case "requirement": {
931
+ const r = item;
932
+ return [...r.findingIds ?? [], ...r.insightIds ?? [], ...r.hypothesisIds ?? [], ...r.stakeholderIds ?? [], ...r.obsoletedBy ?? []];
933
+ }
934
+ default:
935
+ return [];
936
+ }
937
+ }
938
+ var statusOf = (kind, item) => kind === "hypothesis" || kind === "experiment" || kind === "requirement" ? item.status : void 0;
939
+ function textOf(kind, item) {
940
+ const notes = item.notes ?? "";
941
+ switch (kind) {
942
+ case "insight": {
943
+ const i = item;
944
+ return [i.title, i.quote, i.persona, (i.tags ?? []).join(" "), notes].join(" ");
945
+ }
946
+ case "hypothesis": {
947
+ const h = item;
948
+ return [h.title, h.outcome, h.forWhom, h.benefit, h.feature, h.knowWhen, notes].join(" ");
949
+ }
950
+ case "experiment": {
951
+ const e = item;
952
+ return [e.title, e.description, e.primaryMetric?.name, e.resultNotes ?? "", notes].join(" ");
953
+ }
954
+ case "finding": {
955
+ const f = item;
956
+ return [f.title, f.summary, notes].join(" ");
957
+ }
958
+ case "requirement": {
959
+ const r = item;
960
+ return [r.title, r.story, r.stakeholder ?? "", r.product ?? "", (r.acceptanceCriteria ?? []).join(" "), notes].join(" ");
961
+ }
962
+ }
963
+ }
964
+ var Session = class {
965
+ constructor(root) {
966
+ this.root = root;
967
+ this.config = readConfig(root);
968
+ this.loaded = load(root);
969
+ this.actor = resolveActor(root, this.config);
970
+ }
971
+ root;
972
+ config;
973
+ loaded;
974
+ actor;
975
+ file(kind, item) {
976
+ return this.loaded.paths.get(item.id) ?? newPath(kind, item.id, item.title);
977
+ }
978
+ areaLabel = (id) => this.config.productAreas.find((a) => a.id === id)?.label ?? "";
979
+ /** Accept an area's id or label; undefined stays undefined. */
980
+ area(value) {
981
+ if (!value) return void 0;
982
+ const a = this.config.productAreas.find((x) => x.id === value || x.label.toLowerCase() === value.trim().toLowerCase());
983
+ if (!a) {
984
+ const known = this.config.productAreas.map((x) => x.label).join(", ") || "none defined";
985
+ throw new UserError(`Unknown product area "${value}". Areas in groundwork/config.yml: ${known}. Add it there first, or leave it out.`);
986
+ }
987
+ return a.id;
988
+ }
989
+ /** Every id must be an item of this kind. */
990
+ check(s, kind, ids, field) {
991
+ for (const id of ids ?? []) {
992
+ const hit = find(s, id);
993
+ if (!hit) throw new UserError(`${field}: no item with id ${id}.`);
994
+ if (hit.kind !== kind) throw new UserError(`${field}: ${id} is ${an(hit.kind)}, not ${an(kind)}.`);
995
+ }
996
+ }
997
+ checkStakeholders(s, ids) {
998
+ this.check(s, "requirement", ids, "stakeholderIds");
999
+ for (const id of ids ?? []) {
1000
+ const r = s.requirements.find((x) => x.id === id);
1001
+ if (kindOf(r) !== "stakeholder") throw new UserError(`stakeholderIds: "${r.title}" is a solution requirement, not a stakeholder requirement.`);
1002
+ }
1003
+ }
1004
+ summary(kind, item) {
1005
+ const area2 = this.areaLabel(item.productArea) || void 0;
1006
+ return {
1007
+ kind,
1008
+ id: item.id,
1009
+ title: item.title,
1010
+ ...statusOf(kind, item) ? { status: statusOf(kind, item) } : {},
1011
+ ...kind === "requirement" ? { requirementKind: kindOf(item) } : {},
1012
+ ...area2 ? { area: area2 } : {},
1013
+ file: this.file(kind, item)
1014
+ };
1015
+ }
1016
+ full(kind, item) {
1017
+ const area2 = this.areaLabel(item.productArea) || void 0;
1018
+ return { kind, ...item, ...area2 ? { areaLabel: area2 } : {}, file: this.file(kind, item) };
1019
+ }
1020
+ ctx() {
1021
+ return { actor: this.actor.id, now: (/* @__PURE__ */ new Date()).toISOString(), newId: () => `new-${randomUUID()}` };
1022
+ }
1023
+ canEdit() {
1024
+ return !this.actor.person || this.actor.person.role !== "viewer";
1025
+ }
1026
+ };
1027
+ function buildServer({ root }) {
1028
+ const server = new McpServer({ name: "groundwork", version: VERSION }, { instructions: INSTRUCTIONS });
1029
+ const open = () => new Session(root);
1030
+ const read = (fn) => async (args) => {
1031
+ try {
1032
+ return ok(await fn(open(), args));
1033
+ } catch (e) {
1034
+ return fail(e instanceof UserError ? e.message : `Groundwork couldn't read the project: ${e.message}`);
1035
+ }
1036
+ };
1037
+ const write = (fn) => async (args) => {
1038
+ try {
1039
+ const s = open();
1040
+ if (s.config.migrated) {
1041
+ return fail(
1042
+ `This folder was imported into the Groundwork web app (${s.config.migrated}), which is now where changes go. Connect its MCP server instead (Groundwork \u2192 Settings \u2192 Connect an agent). These files are kept as a read-only record.`
1043
+ );
1044
+ }
1045
+ if (!s.canEdit()) return fail(`${s.actor.person?.name ?? s.actor.id} is a viewer in groundwork/config.yml, so this agent can't change anything.`);
1046
+ if (!isInitialized(root)) writeConfig(root, s.config);
1047
+ const { state, result } = fn(s, s.loaded.items, s.ctx(), args);
1048
+ const { items, renamed } = assignIds(s.loaded.items, state);
1049
+ const files = save(root, s.loaded, items);
1050
+ let text = JSON.stringify({ ...result, filesChanged: files }, null, 2);
1051
+ renamed.forEach((to, from) => text = text.split(from).join(to));
1052
+ return { content: [{ type: "text", text }] };
1053
+ } catch (e) {
1054
+ if (e instanceof UserError) return fail(e.message);
1055
+ return fail(`Groundwork couldn't save that: ${e.message}`);
1056
+ }
1057
+ };
1058
+ const apply = (state, change) => [{ ...state, ...change.next }, change.result];
1059
+ const itemId = localId.describe("An item id, e.g. INS-0007.");
1060
+ server.registerTool(
1061
+ "get_workspace",
1062
+ {
1063
+ title: "Get workspace",
1064
+ description: "The project's name, product areas, products, people, item counts and any file problems. Call this first.",
1065
+ inputSchema: {},
1066
+ annotations: { readOnlyHint: true }
1067
+ },
1068
+ read((s) => {
1069
+ const items = s.loaded.items;
1070
+ const problems = validate(s.loaded, s.config);
1071
+ return {
1072
+ workspace: s.config.name,
1073
+ folder: `${s.root}/groundwork`,
1074
+ initialized: isInitialized(root),
1075
+ ...s.config.migrated ? { migratedTo: s.config.migrated, readOnly: true } : {},
1076
+ you: { id: s.actor.id, name: s.actor.person?.name, role: s.actor.person?.role ?? "editor" },
1077
+ productAreas: s.config.productAreas,
1078
+ products: s.config.products,
1079
+ members: s.config.people.map(({ id, name, role }) => ({ id, name, role })),
1080
+ counts: Object.fromEntries(KIND.options.map((k) => [k, items[COLLECTIONS[k]].length])),
1081
+ problems: {
1082
+ errors: problems.filter((p) => p.level === "error").length,
1083
+ warnings: problems.filter((p) => p.level === "warning").length,
1084
+ first: problems.slice(0, 10)
1085
+ }
1086
+ };
1087
+ })
1088
+ );
1089
+ server.registerTool(
1090
+ "search_items",
1091
+ {
1092
+ title: "Search items",
1093
+ description: "Find insights, hypotheses, experiments, findings or requirements. Matches every word of `query` against titles, main text and notes. Returns short summaries; use get_item for the full item and its links.",
1094
+ inputSchema: {
1095
+ kind: KIND.optional().describe("Only this kind."),
1096
+ query: z4.string().max(200).optional().describe("Words to match, any order."),
1097
+ status: z4.string().max(40).optional().describe("Only items with this status, e.g. draft, testing, running, awaiting-approval."),
1098
+ area: z4.string().max(100).optional().describe("Only items in this product area (label or id)."),
1099
+ limit: z4.number().int().min(1).max(100).default(20)
1100
+ },
1101
+ annotations: { readOnlyHint: true }
1102
+ },
1103
+ read((s, { kind, query, status, area: area2, limit }) => {
1104
+ const areaId = s.area(area2);
1105
+ const words = (query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
1106
+ const out = [];
1107
+ let total = 0;
1108
+ for (const k of kind ? [kind] : KIND.options) {
1109
+ for (const item of s.loaded.items[COLLECTIONS[k]]) {
1110
+ if (status && statusOf(k, item) !== status) continue;
1111
+ if (areaId && item.productArea !== areaId) continue;
1112
+ if (words.length) {
1113
+ const text = textOf(k, item).toLowerCase();
1114
+ if (!words.every((w) => text.includes(w))) continue;
1115
+ }
1116
+ total++;
1117
+ if (out.length < limit) out.push(s.summary(k, item));
1118
+ }
1119
+ }
1120
+ return { total, shown: out.length, items: out };
1121
+ })
1122
+ );
1123
+ server.registerTool(
1124
+ "get_item",
1125
+ {
1126
+ title: "Get item",
1127
+ description: "One item in full, with its notes, the items it links to and the items that link to it.",
1128
+ inputSchema: { id: itemId },
1129
+ annotations: { readOnlyHint: true }
1130
+ },
1131
+ read((s, { id }) => {
1132
+ const items = s.loaded.items;
1133
+ const hit = find(items, id);
1134
+ if (!hit) throw new UserError(`No item with id ${id}.`);
1135
+ const linksTo = outgoing(hit.kind, hit.item).map((x) => find(items, x)).filter((x) => Boolean(x)).map((x) => s.summary(x.kind, x.item));
1136
+ const linkedFrom = [];
1137
+ for (const k of KIND.options) {
1138
+ for (const item of items[COLLECTIONS[k]]) if (outgoing(k, item).includes(id)) linkedFrom.push(s.summary(k, item));
1139
+ }
1140
+ return { item: s.full(hit.kind, hit.item), linksTo, linkedFrom };
1141
+ })
1142
+ );
1143
+ server.registerTool(
1144
+ "add_insights",
1145
+ {
1146
+ title: "Add insights",
1147
+ description: "Log customer evidence: one insight per distinct pain, need or behaviour, each with the quote that shows it.",
1148
+ inputSchema: { insights: z4.array(insightInput2).min(1).max(50) }
1149
+ },
1150
+ write((s, state, c, { insights }) => {
1151
+ const items = insights.map((i) => ({ ...i, productArea: s.area(i.productArea) }));
1152
+ const [next, created] = apply(state, addInsights(state, c, items));
1153
+ return { state: next, result: { created: created.map((x) => s.summary("insight", x)) } };
1154
+ })
1155
+ );
1156
+ server.registerTool(
1157
+ "add_hypotheses",
1158
+ {
1159
+ title: "Add hypotheses",
1160
+ description: 'Draft hypotheses in the form "We believe we will [outcome] if [forWhom] get [benefit] with [feature]", linked to the insights behind them.',
1161
+ inputSchema: { hypotheses: z4.array(hypothesisInput2).min(1).max(20) }
1162
+ },
1163
+ write((s, state, c, { hypotheses }) => {
1164
+ const items = hypotheses.map((h) => {
1165
+ s.check(state, "insight", h.insightIds, "insightIds");
1166
+ return {
1167
+ ...h,
1168
+ knowWhen: composeKnowWhen({ successMetric: h.successMetric, guardrail: h.guardrail }) || h.knowWhen || "",
1169
+ productArea: s.area(h.productArea),
1170
+ status: "draft",
1171
+ aiGenerated: true
1172
+ };
1173
+ });
1174
+ const [next, created] = apply(state, addHypotheses(state, c, items));
1175
+ return { state: next, result: { created: created.map((x) => s.summary("hypothesis", x)) } };
1176
+ })
1177
+ );
1178
+ server.registerTool(
1179
+ "add_experiment",
1180
+ {
1181
+ title: "Add experiment",
1182
+ description: "Design an experiment for one hypothesis. It starts as planned; call start_experiment when it begins.",
1183
+ inputSchema: { experiment: experimentInput2 }
1184
+ },
1185
+ write((s, state, c, { experiment }) => {
1186
+ s.check(state, "hypothesis", [experiment.hypothesisId], "hypothesisId");
1187
+ const [next, created] = apply(state, addExperiment(state, c, { ...experiment, status: "planned", aiGenerated: true }));
1188
+ return { state: next, result: { created: s.summary("experiment", created) } };
1189
+ })
1190
+ );
1191
+ server.registerTool(
1192
+ "add_findings",
1193
+ {
1194
+ title: "Add findings",
1195
+ description: "Record what was learned, linked to the experiments, hypotheses and insights behind it.",
1196
+ inputSchema: { findings: z4.array(findingInput2).min(1).max(20) }
1197
+ },
1198
+ write((s, state, c, { findings }) => {
1199
+ const items = findings.map((f) => {
1200
+ s.check(state, "experiment", f.experimentIds, "experimentIds");
1201
+ s.check(state, "hypothesis", f.hypothesisIds, "hypothesisIds");
1202
+ s.check(state, "insight", f.insightIds, "insightIds");
1203
+ return { ...f, productArea: s.area(f.productArea), aiGenerated: true };
1204
+ });
1205
+ const [next, created] = apply(state, addFindings(state, c, items));
1206
+ return { state: next, result: { created: created.map((x) => s.summary("finding", x)) } };
1207
+ })
1208
+ );
1209
+ server.registerTool(
1210
+ "add_requirements",
1211
+ {
1212
+ title: "Add requirements",
1213
+ description: "Add stakeholder or solution requirements as drafts. Link findingIds when they come from evidence; otherwise give an origin (tender, regulation, contract, customer-need). To ask for sign-off afterwards, use submit_requirement_for_approval.",
1214
+ inputSchema: { requirements: z4.array(requirementInput2).min(1).max(30) }
1215
+ },
1216
+ write((s, state, c, { requirements }) => {
1217
+ let next = state;
1218
+ const created = [];
1219
+ const derived = [];
1220
+ for (const r of requirements) {
1221
+ s.check(state, "finding", r.findingIds, "findingIds");
1222
+ s.check(state, "insight", r.insightIds, "insightIds");
1223
+ s.check(state, "hypothesis", r.hypothesisIds, "hypothesisIds");
1224
+ s.checkStakeholders(state, r.stakeholderIds);
1225
+ if (r.product && s.config.products.length && !s.config.products.includes(r.product)) {
1226
+ throw new UserError(`Unknown product "${r.product}". Products in groundwork/config.yml: ${s.config.products.join(", ")}.`);
1227
+ }
1228
+ const base = { ...r, productArea: s.area(r.productArea), aiGenerated: true };
1229
+ if (r.findingIds.length) {
1230
+ derived.push(base);
1231
+ } else {
1232
+ if (!r.origin) throw new UserError(`"${r.title}": link findingIds, or give an origin for a requirement decided elsewhere.`);
1233
+ const { findingIds: _unused, ...direct } = base;
1234
+ void _unused;
1235
+ const [after, one] = apply(next, createRequirement(next, c, { ...direct, status: "draft" }));
1236
+ next = after;
1237
+ created.push(one);
1238
+ }
1239
+ }
1240
+ if (derived.length) {
1241
+ const [after, many] = apply(next, addRequirements(next, c, derived));
1242
+ next = after;
1243
+ created.push(...many);
1244
+ }
1245
+ return { state: next, result: { created: created.map((x) => s.summary("requirement", x)) } };
1246
+ })
1247
+ );
1248
+ server.registerTool(
1249
+ "update_item",
1250
+ {
1251
+ title: "Update item",
1252
+ description: "Change fields of an existing item. `patch` takes the same fields as the add_ tool for that kind (only the ones to change; arrays replace the old value). Requirement status changes have their own tools.",
1253
+ inputSchema: { id: itemId, patch: z4.record(z4.string(), z4.unknown()) }
1254
+ },
1255
+ write((s, state, c, { id, patch }) => {
1256
+ const hit = find(state, id);
1257
+ if (!hit) throw new UserError(`No item with id ${id}.`);
1258
+ const parsed = PATCHES[hit.kind].strict().safeParse(patch);
1259
+ if (!parsed.success) throw new UserError(`Invalid patch for ${an(hit.kind)}: ${z4.prettifyError(parsed.error)}`);
1260
+ const p = parsed.data;
1261
+ if (!Object.keys(p).length) throw new UserError("The patch has no fields to change.");
1262
+ if ("productArea" in p) p.productArea = s.area(p.productArea);
1263
+ let change;
1264
+ switch (hit.kind) {
1265
+ case "insight":
1266
+ change = updateInsight(state, id, p);
1267
+ break;
1268
+ case "hypothesis": {
1269
+ s.check(state, "insight", p.insightIds, "insightIds");
1270
+ const merged = { ...hit.item, ...p };
1271
+ if ("successMetric" in p || "guardrail" in p) {
1272
+ const composed = composeKnowWhen({ successMetric: merged.successMetric, guardrail: merged.guardrail });
1273
+ if (composed) p.knowWhen = composed;
1274
+ }
1275
+ change = updateHypothesis(state, c, id, p);
1276
+ break;
1277
+ }
1278
+ case "experiment":
1279
+ change = updateExperiment(state, id, p);
1280
+ break;
1281
+ case "finding":
1282
+ s.check(state, "experiment", p.experimentIds, "experimentIds");
1283
+ s.check(state, "hypothesis", p.hypothesisIds, "hypothesisIds");
1284
+ s.check(state, "insight", p.insightIds, "insightIds");
1285
+ change = updateFinding(state, id, p);
1286
+ break;
1287
+ case "requirement": {
1288
+ const r = hit.item;
1289
+ if (r.status === "obsolete" || r.status === "in-delivery") {
1290
+ throw new UserError(`"${r.title}" is ${r.status}, so it can't be edited. Create a new requirement instead.`);
1291
+ }
1292
+ s.check(state, "finding", p.findingIds, "findingIds");
1293
+ s.check(state, "insight", p.insightIds, "insightIds");
1294
+ s.check(state, "hypothesis", p.hypothesisIds, "hypothesisIds");
1295
+ s.checkStakeholders(state, p.stakeholderIds);
1296
+ change = updateRequirement(state, id, { ...p, updatedAt: c.now });
1297
+ break;
1298
+ }
1299
+ }
1300
+ const [next] = apply(state, change);
1301
+ const updated = find(next, id);
1302
+ return { state: next, result: { updated: s.full(updated.kind, updated.item) } };
1303
+ })
1304
+ );
1305
+ server.registerTool(
1306
+ "link_items",
1307
+ {
1308
+ title: "Link items",
1309
+ description: "Add evidence links without replacing existing ones. `id` is the item to link from; `linkTo` are the items it builds on. Supported: hypothesis -> insights; finding -> experiments, hypotheses, insights; requirement -> findings, insights, hypotheses, stakeholder requirements (for a solution requirement); experiment -> one hypothesis (replaces it).",
1310
+ inputSchema: { id: itemId, linkTo: z4.array(localId).min(1).max(50) }
1311
+ },
1312
+ write((s, state, _c, { id, linkTo }) => {
1313
+ const hit = find(state, id);
1314
+ if (!hit) throw new UserError(`No item with id ${id}.`);
1315
+ const add = (list, x) => list?.includes(x) ? list : [...list ?? [], x];
1316
+ let item = { ...hit.item };
1317
+ for (const target of linkTo) {
1318
+ const t = find(state, target);
1319
+ if (!t) throw new UserError(`No item with id ${target}.`);
1320
+ if (target === id) throw new UserError("An item can't link to itself.");
1321
+ const field = hit.kind === "hypothesis" && t.kind === "insight" ? "insightIds" : hit.kind === "experiment" && t.kind === "hypothesis" ? "hypothesisId" : hit.kind === "finding" && (t.kind === "experiment" || t.kind === "hypothesis" || t.kind === "insight") ? `${t.kind}Ids` : hit.kind === "requirement" && t.kind === "finding" ? "findingIds" : hit.kind === "requirement" && t.kind === "insight" ? "insightIds" : hit.kind === "requirement" && t.kind === "hypothesis" ? "hypothesisIds" : hit.kind === "requirement" && t.kind === "requirement" && kindOf(hit.item) === "solution" && kindOf(t.item) === "stakeholder" ? "stakeholderIds" : null;
1322
+ if (!field) {
1323
+ const what = t.kind === "requirement" ? `a ${kindOf(t.item)} requirement` : an(t.kind);
1324
+ throw new UserError(`${an(hit.kind).replace(/^a/, "A")} can't link to ${what}.`);
1325
+ }
1326
+ item = field === "hypothesisId" ? { ...item, hypothesisId: target } : { ...item, [field]: add(item[field], target) };
1327
+ }
1328
+ const key = COLLECTIONS[hit.kind];
1329
+ const next = { ...state, [key]: state[key].map((x) => x.id === id ? item : x) };
1330
+ return { state: next, result: { updated: s.full(hit.kind, item) } };
1331
+ })
1332
+ );
1333
+ server.registerTool(
1334
+ "start_experiment",
1335
+ {
1336
+ title: "Start experiment",
1337
+ description: "Mark a planned experiment as running. A draft hypothesis it tests moves to testing.",
1338
+ inputSchema: { id: itemId }
1339
+ },
1340
+ write((s, state, c, { id }) => {
1341
+ const e = state.experiments.find((x) => x.id === id);
1342
+ if (!e) throw new UserError(`No experiment with id ${id}.`);
1343
+ if (e.status !== "planned") throw new UserError(`"${e.title}" is already ${e.status}.`);
1344
+ const [next] = apply(state, startExperiment(state, c, id));
1345
+ return { state: next, result: { started: s.summary("experiment", next.experiments.find((x) => x.id === id)) } };
1346
+ })
1347
+ );
1348
+ server.registerTool(
1349
+ "record_experiment_results",
1350
+ {
1351
+ title: "Record experiment results",
1352
+ description: "Record the measured values and complete the experiment. Groundwork computes the verdict (validated, invalidated or inconclusive) from the targets and moves the hypothesis accordingly.",
1353
+ inputSchema: {
1354
+ id: itemId,
1355
+ primaryActual: z4.number().describe("Measured value of the primary metric."),
1356
+ guardrailActuals: z4.array(z4.number()).max(5).default([]).describe("Measured value of each guardrail, in the experiment's order."),
1357
+ notes: z4.string().trim().max(4e3).default("").describe("What happened, in a few sentences.")
1358
+ }
1359
+ },
1360
+ write((s, state, c, a) => {
1361
+ const e = state.experiments.find((x) => x.id === a.id);
1362
+ if (!e) throw new UserError(`No experiment with id ${a.id}.`);
1363
+ if (e.status === "completed") throw new UserError(`"${e.title}" already has results (${e.verdict}).`);
1364
+ const guardrails = e.guardrails ?? [];
1365
+ if (a.guardrailActuals.length !== guardrails.length) {
1366
+ throw new UserError(`"${e.title}" has ${guardrails.length} guardrail(s): ${guardrails.map((g) => g.name).join(", ") || "none"}. Give one value for each.`);
1367
+ }
1368
+ const [next, out] = apply(state, recordResults(state, c, a.id, a.primaryActual, a.guardrailActuals, a.notes));
1369
+ const h = next.hypotheses.find((x) => x.id === e.hypothesisId);
1370
+ return {
1371
+ state: next,
1372
+ result: { verdict: out.result.verdict, reason: out.result.reason, experiment: s.summary("experiment", e), hypothesis: h && s.summary("hypothesis", h) }
1373
+ };
1374
+ })
1375
+ );
1376
+ const requirementOf = (state, id) => {
1377
+ const r = state.requirements.find((x) => x.id === id);
1378
+ if (!r) throw new UserError(`No requirement with id ${id}.`);
1379
+ return r;
1380
+ };
1381
+ server.registerTool(
1382
+ "submit_requirement_for_approval",
1383
+ {
1384
+ title: "Submit requirement for approval",
1385
+ description: "Ask a person (by id from get_workspace members) to sign off a draft requirement.",
1386
+ inputSchema: { id: itemId, approverId: z4.string().max(40) }
1387
+ },
1388
+ write((s, state, c, { id, approverId }) => {
1389
+ const r = requirementOf(state, id);
1390
+ const approver = s.config.people.find((m) => m.id === approverId);
1391
+ if (!approver) throw new UserError(`${approverId} isn't in groundwork/config.yml people. Add them there first.`);
1392
+ if (approver.role === "viewer") throw new UserError(`${approver.name} is a viewer, so they can't approve.`);
1393
+ if (r.status !== "draft") throw new UserError(`"${r.title}" is ${r.status}; only drafts can be submitted.`);
1394
+ const [next] = apply(state, submitRequirement(state, c, id, approverId));
1395
+ return { state: next, result: { submitted: s.summary("requirement", requirementOf(next, id)), approver: approver.name } };
1396
+ })
1397
+ );
1398
+ server.registerTool(
1399
+ "approve_requirement",
1400
+ {
1401
+ title: "Approve requirement",
1402
+ description: "Sign off a requirement that is awaiting your approval. Only the named approver can approve.",
1403
+ inputSchema: { id: itemId },
1404
+ annotations: { destructiveHint: false }
1405
+ },
1406
+ write((s, state, c, { id }) => {
1407
+ const r = requirementOf(state, id);
1408
+ if (r.status !== "awaiting-approval") throw new UserError(`"${r.title}" is ${r.status}, not awaiting approval.`);
1409
+ if (r.approver !== s.actor.id) {
1410
+ const name = s.config.people.find((m) => m.id === r.approver)?.name ?? r.approver ?? "someone else";
1411
+ throw new UserError(`"${r.title}" is waiting for ${name}, not you (${s.actor.id}). Set GROUNDWORK_USER or your email in config.yml people if that's wrong.`);
1412
+ }
1413
+ const [next] = apply(state, approveRequirement(state, c, id));
1414
+ return { state: next, result: { approved: s.summary("requirement", requirementOf(next, id)) } };
1415
+ })
1416
+ );
1417
+ server.registerTool(
1418
+ "send_back_requirement",
1419
+ {
1420
+ title: "Send requirement back",
1421
+ description: "Return a requirement awaiting your approval to draft, for changes. Only the named approver can do this.",
1422
+ inputSchema: { id: itemId }
1423
+ },
1424
+ write((s, state, c, { id }) => {
1425
+ const r = requirementOf(state, id);
1426
+ if (r.status !== "awaiting-approval") throw new UserError(`"${r.title}" is ${r.status}, not awaiting approval.`);
1427
+ if (r.approver !== s.actor.id) throw new UserError(`Only the approver can send "${r.title}" back.`);
1428
+ const [next] = apply(state, sendBackRequirement(state, c, id));
1429
+ return { state: next, result: { sentBack: s.summary("requirement", requirementOf(next, id)) } };
1430
+ })
1431
+ );
1432
+ server.registerTool(
1433
+ "obsolete_requirement",
1434
+ {
1435
+ title: "Make requirement obsolete",
1436
+ description: "Retire an approved requirement, e.g. when newer evidence supersedes it, optionally naming the requirements that replace it.",
1437
+ inputSchema: { id: itemId, replacedBy: z4.array(localId).max(20).optional() }
1438
+ },
1439
+ write((s, state, c, { id, replacedBy }) => {
1440
+ const r = requirementOf(state, id);
1441
+ if (r.status !== "approved") throw new UserError(`Only approved requirements can be made obsolete; "${r.title}" is ${r.status}.`);
1442
+ s.check(state, "requirement", replacedBy, "replacedBy");
1443
+ const [next] = apply(state, obsoleteRequirement(state, c, id, replacedBy));
1444
+ return { state: next, result: { obsolete: s.summary("requirement", requirementOf(next, id)) } };
1445
+ })
1446
+ );
1447
+ server.registerTool(
1448
+ "delete_item",
1449
+ {
1450
+ title: "Delete item",
1451
+ description: "Delete an item's file. Links to it are removed from other items; deleting a hypothesis also deletes its experiments. Confirm with the user first.",
1452
+ inputSchema: { id: itemId },
1453
+ annotations: { destructiveHint: true }
1454
+ },
1455
+ write((_s, state, _c, { id }) => {
1456
+ const hit = find(state, id);
1457
+ if (!hit) throw new UserError(`No item with id ${id}.`);
1458
+ const change = hit.kind === "insight" ? deleteInsight(state, id) : hit.kind === "hypothesis" ? deleteHypothesis(state, id) : hit.kind === "experiment" ? deleteExperiment(state, id) : hit.kind === "finding" ? deleteFinding(state, id) : deleteRequirement(state, id);
1459
+ const [next] = apply(state, change);
1460
+ const alsoDeleted = hit.kind === "hypothesis" ? state.experiments.filter((e) => e.hypothesisId === id).map((e) => e.id) : [];
1461
+ return { state: next, result: { deleted: { kind: hit.kind, id, title: hit.item.title }, ...alsoDeleted.length ? { alsoDeletedExperiments: alsoDeleted } : {} } };
1462
+ })
1463
+ );
1464
+ return server;
1465
+ }
1466
+
1467
+ export {
1468
+ COLLECTION_KIND,
1469
+ COLLECTION_KEYS,
1470
+ emptyCollections,
1471
+ diffCollections,
1472
+ kindOf,
1473
+ isObsolete,
1474
+ canObsolete,
1475
+ canUpdateInPlace,
1476
+ canSendToDelivery,
1477
+ metricPasses,
1478
+ computeVerdict,
1479
+ fmtMetric,
1480
+ targetLabel,
1481
+ ops_exports,
1482
+ SOURCE,
1483
+ SENTIMENT,
1484
+ HYPOTHESIS_STATUS,
1485
+ METHOD,
1486
+ EXPERIMENT_STATUS,
1487
+ PRIORITY,
1488
+ REQUIREMENT_KIND,
1489
+ REQUIREMENT_ORIGIN,
1490
+ FINDING_CONFIDENCE,
1491
+ KIND,
1492
+ makeSchemas,
1493
+ ID_PREFIX,
1494
+ LOCAL_ID,
1495
+ localId,
1496
+ localSchemas,
1497
+ hasSuccessMetric,
1498
+ describeSuccess,
1499
+ composeKnowWhen,
1500
+ composeStatement,
1501
+ DIR,
1502
+ CONFIG_FILE,
1503
+ SCHEMA_VERSION,
1504
+ configSchema,
1505
+ findRoot,
1506
+ configPath,
1507
+ isInitialized,
1508
+ defaultConfig,
1509
+ ConfigError,
1510
+ readConfig,
1511
+ writeConfig,
1512
+ resolveActor,
1513
+ COLLECTIONS,
1514
+ parseItem,
1515
+ renderItem,
1516
+ load,
1517
+ assignIds,
1518
+ save,
1519
+ validate,
1520
+ INSTRUCTIONS,
1521
+ outgoing,
1522
+ buildServer
1523
+ };
1524
+ //# sourceMappingURL=chunk-5LIKTHEE.js.map