groundwork-mcp 0.1.0 → 0.3.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.
package/dist/index.d.ts CHANGED
@@ -1053,6 +1053,17 @@ declare class ConfigError extends Error {
1053
1053
  }
1054
1054
  declare function readConfig(root: string): Config;
1055
1055
  declare function writeConfig(root: string, config: Config): void;
1056
+ /**
1057
+ * Append product areas and products to an existing config.yml, editing the YAML in place so the user's comments,
1058
+ * unknown keys and formatting are kept.
1059
+ */
1060
+ declare function appendToConfig(root: string, add: {
1061
+ productAreas?: {
1062
+ id: string;
1063
+ label: string;
1064
+ }[];
1065
+ products?: string[];
1066
+ }): void;
1056
1067
  /**
1057
1068
  * Who is acting: $GROUNDWORK_USER (a person id), else the person whose email matches git's, else the only person
1058
1069
  * listed. Unknown people act as "me", which is fine for a one-person folder.
@@ -1103,11 +1114,11 @@ interface Problem {
1103
1114
  /** Every problem in a project: unreadable files, invalid fields, broken or wrong-kind links, unknown areas. */
1104
1115
  declare function validate(loaded: Loaded, config: Config): Problem[];
1105
1116
 
1106
- declare const INSTRUCTIONS = "Groundwork keeps this product's evidence and decisions as linked Markdown files in the groundwork/ folder, as a chain:\ninsight -> hypothesis -> experiment -> finding -> requirement.\n\n- 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.\n- Hypothesis: \"We believe we will [outcome] if [forWhom] get [benefit] with [feature]\", built on insights (insightIds), ideally with a successMetric (baseline, target, timeframe).\n- 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).\n- Finding: what was learned, linked to the experiments, hypotheses and insights behind it.\n- 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).\n\nHow to work:\n1. Call get_workspace first: it gives product areas, products and people (for approvers).\n2. Before creating anything, search_items for duplicates and for evidence to link. Prefer linking to existing items over creating near-duplicates.\n3. Always link evidence: hypotheses to insights, experiments to a hypothesis, findings to experiments/hypotheses/insights, requirements to findings.\n4. Ask the user before deleting items or approving requirements, unless they already told you to.\n5. 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.\n6. The Markdown body under an item's frontmatter is the user's own notes. Read it, but don't overwrite it.";
1117
+ declare const INSTRUCTIONS = "Groundwork keeps this product's evidence and decisions as linked Markdown files in the groundwork/ folder, as a chain:\ninsight -> hypothesis -> experiment -> finding -> requirement.\n\n- 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.\n- Hypothesis: \"We believe we will [outcome] if [forWhom] get [benefit] with [feature]\", built on insights (insightIds), ideally with a successMetric (baseline, target, timeframe).\n- 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).\n- Finding: what was learned, linked to the experiments, hypotheses and insights behind it.\n- 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).\n\nHow to work:\n1. Call get_workspace first: it gives product areas, products and people (for approvers). If an area or product you need is missing, add it with add_product_areas or add_products, after checking for an existing match.\n2. Before creating anything, search_items for duplicates and for evidence to link. Prefer linking to existing items over creating near-duplicates.\n3. Always link evidence: hypotheses to insights, experiments to a hypothesis, findings to experiments/hypotheses/insights, requirements to findings.\n4. Ask the user before deleting items or approving requirements, unless they already told you to.\n5. 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.\n6. The Markdown body under an item's frontmatter is the user's own notes. Read it, but don't overwrite it.";
1107
1118
  interface ServerOptions {
1108
1119
  /** The project folder (the one that holds groundwork/). */
1109
1120
  root: string;
1110
1121
  }
1111
1122
  declare function buildServer({ root }: ServerOptions): McpServer;
1112
1123
 
1113
- export { type Activity, COLLECTIONS, COLLECTION_KEYS, COLLECTION_KIND, CONFIG_FILE, type Collections, type Config, ConfigError, DIR, type Delivery, type DeliverySettings, type DeliveryStateType, EXPERIMENT_STATUS, type Experiment, type ExperimentMethod, type ExperimentStatus, FINDING_CONFIDENCE, type Finding, type Graph, HYPOTHESIS_STATUS, type Hypothesis, type HypothesisStatus, type ID, ID_PREFIX, INSTRUCTIONS, type Insight, KIND, type Kind, LOCAL_ID, type Loaded, METHOD, type Metric, PRIORITY, type Person, type Prioritization, type Priority, type Problem, type ProductArea, REQUIREMENT_KIND, REQUIREMENT_ORIGIN, type Requirement, type RequirementChanges, type RequirementKind, type RequirementOrigin, type RequirementStatus, SCHEMA_VERSION, SENTIMENT, SOURCE, type Schemas, type Score, type Sentiment, type SourceType, type SuccessMetric, type Trail, type Upsert, type Verdict, type VerdictResult, assignIds, buildServer, canObsolete, canSendToDelivery, canUpdateInPlace, composeKnowWhen, composeStatement, computeVerdict, configPath, configSchema, connectedIds, defaultConfig, describeSuccess, diffCollections, emptyCollections, evidenceStrength, findRoot, fmtMetric, hasSuccessMetric, isInitialized, isObsolete, kindOf, load, localId, localSchemas, makeSchemas, metricPasses, ops, parseItem, readConfig, renderItem, resolveActor, save, targetLabel, trailForRequirement, validate, writeConfig };
1124
+ export { type Activity, COLLECTIONS, COLLECTION_KEYS, COLLECTION_KIND, CONFIG_FILE, type Collections, type Config, ConfigError, DIR, type Delivery, type DeliverySettings, type DeliveryStateType, EXPERIMENT_STATUS, type Experiment, type ExperimentMethod, type ExperimentStatus, FINDING_CONFIDENCE, type Finding, type Graph, HYPOTHESIS_STATUS, type Hypothesis, type HypothesisStatus, type ID, ID_PREFIX, INSTRUCTIONS, type Insight, KIND, type Kind, LOCAL_ID, type Loaded, METHOD, type Metric, PRIORITY, type Person, type Prioritization, type Priority, type Problem, type ProductArea, REQUIREMENT_KIND, REQUIREMENT_ORIGIN, type Requirement, type RequirementChanges, type RequirementKind, type RequirementOrigin, type RequirementStatus, SCHEMA_VERSION, SENTIMENT, SOURCE, type Schemas, type Score, type Sentiment, type SourceType, type SuccessMetric, type Trail, type Upsert, type Verdict, type VerdictResult, appendToConfig, assignIds, buildServer, canObsolete, canSendToDelivery, canUpdateInPlace, composeKnowWhen, composeStatement, computeVerdict, configPath, configSchema, connectedIds, defaultConfig, describeSuccess, diffCollections, emptyCollections, evidenceStrength, findRoot, fmtMetric, hasSuccessMetric, isInitialized, isObsolete, kindOf, load, localId, localSchemas, makeSchemas, metricPasses, ops, parseItem, readConfig, renderItem, resolveActor, save, targetLabel, trailForRequirement, validate, writeConfig };
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  SCHEMA_VERSION,
20
20
  SENTIMENT,
21
21
  SOURCE,
22
+ appendToConfig,
22
23
  assignIds,
23
24
  buildServer,
24
25
  canObsolete,
@@ -53,7 +54,7 @@ import {
53
54
  targetLabel,
54
55
  validate,
55
56
  writeConfig
56
- } from "./chunk-3W4X6WV2.js";
57
+ } from "./chunk-3YZLRKZH.js";
57
58
 
58
59
  // src/core/trace.ts
59
60
  function trailForRequirement(r, g) {
@@ -140,6 +141,7 @@ export {
140
141
  SCHEMA_VERSION,
141
142
  SENTIMENT,
142
143
  SOURCE,
144
+ appendToConfig,
143
145
  assignIds,
144
146
  buildServer,
145
147
  canObsolete,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/trace.ts"],"sourcesContent":["import type { Experiment, Finding, Hypothesis, Insight, Requirement } from \"./types\";\n\nexport interface Graph {\n insights: Insight[];\n hypotheses: Hypothesis[];\n experiments: Experiment[];\n findings: Finding[];\n requirements: Requirement[];\n}\n\nexport interface Trail {\n /** Solution requirements: the stakeholder requirements they help meet. */\n stakeholderRequirements: Requirement[];\n findings: Finding[];\n experiments: Experiment[];\n hypotheses: Hypothesis[];\n insights: Insight[];\n}\n\n/** Walk a requirement back to every piece of evidence behind it. */\nexport function trailForRequirement(r: Requirement, g: Graph): Trail {\n const stakeholderRequirements = g.requirements.filter((x) => r.stakeholderIds?.includes(x.id));\n const findings = g.findings.filter((f) => r.findingIds.includes(f.id));\n const experiments = g.experiments.filter((e) => findings.some((f) => f.experimentIds.includes(e.id)));\n const hypIds = new Set([\n ...findings.flatMap((f) => f.hypothesisIds),\n ...experiments.map((e) => e.hypothesisId),\n ...(r.hypothesisIds ?? []),\n ]);\n const hypotheses = g.hypotheses.filter((h) => hypIds.has(h.id));\n const insIds = new Set([\n ...findings.flatMap((f) => f.insightIds),\n ...hypotheses.flatMap((h) => h.insightIds),\n ...(r.insightIds ?? []),\n ]);\n const insights = g.insights.filter((i) => insIds.has(i.id));\n return { stakeholderRequirements, findings, experiments, hypotheses, insights };\n}\n\n/** All node ids connected (upstream and downstream) to a given node. */\nexport function connectedIds(id: string, g: Graph): Set<string> {\n const edges: [string, string][] = [];\n g.hypotheses.forEach((h) => h.insightIds.forEach((i) => edges.push([i, h.id])));\n g.experiments.forEach((e) => edges.push([e.hypothesisId, e.id]));\n g.findings.forEach((f) => {\n f.experimentIds.forEach((e) => edges.push([e, f.id]));\n if (!f.experimentIds.length) f.hypothesisIds.forEach((h) => edges.push([h, f.id]));\n });\n g.requirements.forEach((r) => {\n r.findingIds.forEach((f) => edges.push([f, r.id]));\n // Directly created requirements link straight to their evidence and source hypotheses.\n r.insightIds?.forEach((i) => edges.push([i, r.id]));\n r.hypothesisIds?.forEach((h) => edges.push([h, r.id]));\n // Solution requirements meet stakeholder requirements.\n r.stakeholderIds?.forEach((s) => edges.push([s, r.id]));\n });\n\n const result = new Set<string>([id]);\n // upstream\n const up = [id];\n while (up.length) {\n const cur = up.pop()!;\n edges.forEach(([a, b]) => {\n if (b === cur && !result.has(a)) {\n result.add(a);\n up.push(a);\n }\n });\n }\n // downstream\n const down = [id];\n const seenDown = new Set([id]);\n while (down.length) {\n const cur = down.pop()!;\n edges.forEach(([a, b]) => {\n if (a === cur && !seenDown.has(b)) {\n seenDown.add(b);\n result.add(b);\n down.push(b);\n }\n });\n }\n return result;\n}\n\nexport function evidenceStrength(t: Trail): { score: number; label: \"Strong\" | \"Moderate\" | \"Weak\" } {\n const validated = t.experiments.filter((e) => e.verdict === \"validated\").length;\n const invalidated = t.experiments.filter((e) => e.verdict === \"invalidated\").length;\n const score = Math.min(100, t.insights.length * 8 + validated * 35 + invalidated * 20 + t.findings.length * 10);\n return { score, label: score >= 70 ? \"Strong\" : score >= 40 ? \"Moderate\" : \"Weak\" };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,SAAS,oBAAoB,GAAgB,GAAiB;AACnE,QAAM,0BAA0B,EAAE,aAAa,OAAO,CAAC,MAAM,EAAE,gBAAgB,SAAS,EAAE,EAAE,CAAC;AAC7F,QAAM,WAAW,EAAE,SAAS,OAAO,CAAC,MAAM,EAAE,WAAW,SAAS,EAAE,EAAE,CAAC;AACrE,QAAM,cAAc,EAAE,YAAY,OAAO,CAAC,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,cAAc,SAAS,EAAE,EAAE,CAAC,CAAC;AACpG,QAAM,SAAS,oBAAI,IAAI;AAAA,IACrB,GAAG,SAAS,QAAQ,CAAC,MAAM,EAAE,aAAa;AAAA,IAC1C,GAAG,YAAY,IAAI,CAAC,MAAM,EAAE,YAAY;AAAA,IACxC,GAAI,EAAE,iBAAiB,CAAC;AAAA,EAC1B,CAAC;AACD,QAAM,aAAa,EAAE,WAAW,OAAO,CAAC,MAAM,OAAO,IAAI,EAAE,EAAE,CAAC;AAC9D,QAAM,SAAS,oBAAI,IAAI;AAAA,IACrB,GAAG,SAAS,QAAQ,CAAC,MAAM,EAAE,UAAU;AAAA,IACvC,GAAG,WAAW,QAAQ,CAAC,MAAM,EAAE,UAAU;AAAA,IACzC,GAAI,EAAE,cAAc,CAAC;AA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Q,CAAC,CAAC,GAAG,CAAC,MAAM;AACxB,UAAI,MAAM,OAAO,CAAC,OAAO,IAAI,CAAC,GAAG;AAC/B,eAAO,IAAI,CAAC;AACZ,WAAG,KAAK,CAAC;AAAA,MACX;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,OAAO,CAAC,EAAE;AAChB,QAAM,WAAW,oBAAI,IAAI,CAAC,EAAE,CAAC;AAC7B,SAAO,KAAK,QAAQ;AAClB,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM;AACxB,UAAI,MAAM,OAAO,CAAC,SAAS,IAAI,CAAC,GAAG;AACjC,iBAAS,IAAI,CAAC;AACd,eAAO,IAAI,CAAC;AACZ,aAAK,KAAK,CAAC;AAAA,MACb;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,GAAoE;AACnG,QAAM,YAAY,EAAE,YAAY,OAAO,CAAC,MAAM,EAAE,YAAY,WAAW,EAAE;AACzE,QAAM,cAAc,EAAE,YAAY,OAAO,CAAC,MAAM,EAAE,YAAY,aAAa,EAAE;AAC7E,QAAM,QAAQ,KAAK,IAAI,KAAK,EAAE,SAAS,SAAS,IAAI,YAAY,KAAK,cAAc,KAAK,EAAE,SAAS,SAAS,EAAE;AAC9G,SAAO,EAAE,OAAO,OAAO,SAAS,KAAK,WAAW,SAAS,KAAK,aAAa,OAAO;AACpF;","names":[]}
1
+ {"version":3,"sources":["../src/core/trace.ts"],"sourcesContent":["import type { Experiment, Finding, Hypothesis, Insight, Requirement } from \"./types\";\n\nexport interface Graph {\n insights: Insight[];\n hypotheses: Hypothesis[];\n experiments: Experiment[];\n findings: Finding[];\n requirements: Requirement[];\n}\n\nexport interface Trail {\n /** Solution requirements: the stakeholder requirements they help meet. */\n stakeholderRequirements: Requirement[];\n findings: Finding[];\n experiments: Experiment[];\n hypotheses: Hypothesis[];\n insights: Insight[];\n}\n\n/** Walk a requirement back to every piece of evidence behind it. */\nexport function trailForRequirement(r: Requirement, g: Graph): Trail {\n const stakeholderRequirements = g.requirements.filter((x) => r.stakeholderIds?.includes(x.id));\n const findings = g.findings.filter((f) => r.findingIds.includes(f.id));\n const experiments = g.experiments.filter((e) => findings.some((f) => f.experimentIds.includes(e.id)));\n const hypIds = new Set([\n ...findings.flatMap((f) => f.hypothesisIds),\n ...experiments.map((e) => e.hypothesisId),\n ...(r.hypothesisIds ?? []),\n ]);\n const hypotheses = g.hypotheses.filter((h) => hypIds.has(h.id));\n const insIds = new Set([\n ...findings.flatMap((f) => f.insightIds),\n ...hypotheses.flatMap((h) => h.insightIds),\n ...(r.insightIds ?? []),\n ]);\n const insights = g.insights.filter((i) => insIds.has(i.id));\n return { stakeholderRequirements, findings, experiments, hypotheses, insights };\n}\n\n/** All node ids connected (upstream and downstream) to a given node. */\nexport function connectedIds(id: string, g: Graph): Set<string> {\n const edges: [string, string][] = [];\n g.hypotheses.forEach((h) => h.insightIds.forEach((i) => edges.push([i, h.id])));\n g.experiments.forEach((e) => edges.push([e.hypothesisId, e.id]));\n g.findings.forEach((f) => {\n f.experimentIds.forEach((e) => edges.push([e, f.id]));\n if (!f.experimentIds.length) f.hypothesisIds.forEach((h) => edges.push([h, f.id]));\n });\n g.requirements.forEach((r) => {\n r.findingIds.forEach((f) => edges.push([f, r.id]));\n // Directly created requirements link straight to their evidence and source hypotheses.\n r.insightIds?.forEach((i) => edges.push([i, r.id]));\n r.hypothesisIds?.forEach((h) => edges.push([h, r.id]));\n // Solution requirements meet stakeholder requirements.\n r.stakeholderIds?.forEach((s) => edges.push([s, r.id]));\n });\n\n const result = new Set<string>([id]);\n // upstream\n const up = [id];\n while (up.length) {\n const cur = up.pop()!;\n edges.forEach(([a, b]) => {\n if (b === cur && !result.has(a)) {\n result.add(a);\n up.push(a);\n }\n });\n }\n // downstream\n const down = [id];\n const seenDown = new Set([id]);\n while (down.length) {\n const cur = down.pop()!;\n edges.forEach(([a, b]) => {\n if (a === cur && !seenDown.has(b)) {\n seenDown.add(b);\n result.add(b);\n down.push(b);\n }\n });\n }\n return result;\n}\n\nexport function evidenceStrength(t: Trail): { score: number; label: \"Strong\" | \"Moderate\" | \"Weak\" } {\n const validated = t.experiments.filter((e) => e.verdict === \"validated\").length;\n const invalidated = t.experiments.filter((e) => e.verdict === \"invalidated\").length;\n const score = Math.min(100, t.insights.length * 8 + validated * 35 + invalidated * 20 + t.findings.length * 10);\n return { score, label: score >= 70 ? \"Strong\" : score >= 40 ? \"Moderate\" : \"Weak\" };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,SAAS,oBAAoB,GAAgB,GAAiB;AACnE,QAAM,0BAA0B,EAAE,aAAa,OAAO,CAAC,MAAM,EAAE,gBAAgB,SAAS,EAAE,EAAE,CAAC;AAC7F,QAAM,WAAW,EAAE,SAAS,OAAO,CAAC,MAAM,EAAE,WAAW,SAAS,EAAE,EAAE,CAAC;AACrE,QAAM,cAAc,EAAE,YAAY,OAAO,CAAC,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,cAAc,SAAS,EAAE,EAAE,CAAC,CAAC;AACpG,QAAM,SAAS,oBAAI,IAAI;AAAA,IACrB,GAAG,SAAS,QAAQ,CAAC,MAAM,EAAE,aAAa;AAAA,IAC1C,GAAG,YAAY,IAAI,CAAC,MAAM,EAAE,YAAY;AAAA,IACxC,GAAI,EAAE,iBAAiB,CAAC;AAAA,EAC1B,CAAC;AACD,QAAM,aAAa,EAAE,WAAW,OAAO,CAAC,MAAM,OAAO,IAAI,EAAE,EAAE,CAAC;AAC9D,QAAM,SAAS,oBAAI,IAAI;AAAA,IACrB,GAAG,SAAS,QAAQ,CAAC,MAAM,EAAE,UAAU;AAAA,IACvC,GAAG,WAAW,QAAQ,CAAC,MAAM,EAAE,UAAU;AAAA,IACzC,GAAI,EAAE,cAAc,CAAC;AAAA,EACvB,CAAC;AACD,QAA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AC,MAAM;AACxB,UAAI,MAAM,OAAO,CAAC,OAAO,IAAI,CAAC,GAAG;AAC/B,eAAO,IAAI,CAAC;AACZ,WAAG,KAAK,CAAC;AAAA,MACX;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,OAAO,CAAC,EAAE;AAChB,QAAM,WAAW,oBAAI,IAAI,CAAC,EAAE,CAAC;AAC7B,SAAO,KAAK,QAAQ;AAClB,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM;AACxB,UAAI,MAAM,OAAO,CAAC,SAAS,IAAI,CAAC,GAAG;AACjC,iBAAS,IAAI,CAAC;AACd,eAAO,IAAI,CAAC;AACZ,aAAK,KAAK,CAAC;AAAA,MACb;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,GAAoE;AACnG,QAAM,YAAY,EAAE,YAAY,OAAO,CAAC,MAAM,EAAE,YAAY,WAAW,EAAE;AACzE,QAAM,cAAc,EAAE,YAAY,OAAO,CAAC,MAAM,EAAE,YAAY,aAAa,EAAE;AAC7E,QAAM,QAAQ,KAAK,IAAI,KAAK,EAAE,SAAS,SAAS,IAAI,YAAY,KAAK,cAAc,KAAK,EAAE,SAAS,SAAS,EAAE;AAC9G,SAAO,EAAE,OAAO,OAAO,SAAS,KAAK,WAAW,SAAS,KAAK,aAAa,OAAO;AACpF;","names":[]}
package/dist/mcp.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runMcp
4
- } from "./chunk-NRKF6WRA.js";
5
- import "./chunk-3W4X6WV2.js";
4
+ } from "./chunk-DU4P7DDY.js";
5
+ import "./chunk-3YZLRKZH.js";
6
6
 
7
7
  // src/mcp/main.ts
8
8
  runMcp().catch((e) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "groundwork-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Keep product evidence (insights, hypotheses, experiments, findings, requirements) as linked Markdown files in your repo, written by your own coding agent over MCP.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -35,10 +35,10 @@
35
35
  ],
36
36
  "repository": {
37
37
  "type": "git",
38
- "url": "git+https://github.com/ganjilive/groundwork.git"
38
+ "url": "git+https://github.com/IdeatorlabsAB/groundwork.git"
39
39
  },
40
- "homepage": "https://github.com/ganjilive/groundwork#readme",
41
- "bugs": "https://github.com/ganjilive/groundwork/issues",
40
+ "homepage": "https://github.com/IdeatorlabsAB/groundwork#readme",
41
+ "bugs": "https://github.com/IdeatorlabsAB/groundwork/issues",
42
42
  "scripts": {
43
43
  "build": "tsup",
44
44
  "dev": "tsup --watch",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/collections.ts","../src/core/requirements.ts","../src/core/verdict.ts","../src/core/ops.ts","../src/core/schemas.ts","../src/core/hypothesis.ts","../src/store/config.ts","../src/store/files.ts","../src/store/validate.ts","../src/mcp/server.ts"],"sourcesContent":["import type { Activity, Experiment, Finding, Hypothesis, Insight, Requirement } from \"./types\";\n\n/** A workspace's items, by collection. Shared by the local file store and the hosted app. */\nexport interface Collections {\n insights: Insight[];\n hypotheses: Hypothesis[];\n experiments: Experiment[];\n findings: Finding[];\n requirements: Requirement[];\n activity: Activity[];\n}\n\nexport const COLLECTION_KIND = {\n insights: \"insight\",\n hypotheses: \"hypothesis\",\n experiments: \"experiment\",\n findings: \"finding\",\n requirements: \"requirement\",\n activity: \"activity\",\n} as const satisfies Record<keyof Collections, string>;\n\nexport const COLLECTION_KEYS = Object.keys(COLLECTION_KIND) as (keyof Collections)[];\n\nexport const emptyCollections = (): Collections => ({\n insights: [],\n hypotheses: [],\n experiments: [],\n findings: [],\n requirements: [],\n activity: [],\n});\n\nexport interface Upsert {\n id: string;\n kind: string;\n data: Record<string, unknown>;\n}\n\n/**\n * The new, changed and removed items between two snapshots. Items are compared by object identity, which is\n * cheap and right because every change makes a new object.\n */\nexport function diffCollections(before: Collections, after: Collections): { upserts: Upsert[]; deletes: string[] } {\n const upserts: Upsert[] = [];\n const deletes: string[] = [];\n for (const key of COLLECTION_KEYS) {\n const was = before[key] as { id: string }[];\n const now = after[key] as { id: string }[];\n if (was === now) continue;\n const old = new Map(was.map((x) => [x.id, x]));\n const kept = new Set<string>();\n for (const item of now) {\n kept.add(item.id);\n if (old.get(item.id) !== item) {\n const { id, ...data } = item as { id: string } & Record<string, unknown>;\n upserts.push({ id, kind: COLLECTION_KIND[key], data });\n }\n }\n for (const id of old.keys()) if (!kept.has(id)) deletes.push(id);\n }\n return { upserts, deletes };\n}\n","import type { ID, Requirement, RequirementKind } from \"./types\";\n\n/** Requirements saved before the stakeholder / solution split are solution requirements. */\nexport function kindOf(r: Pick<Requirement, \"kind\">): RequirementKind {\n return r.kind ?? \"solution\";\n}\n\nexport const isObsolete = (r: Pick<Requirement, \"status\">) => r.status === \"obsolete\";\n\n/** Only approved requirements can be made obsolete. Drafts are updated in place instead. */\nexport const canObsolete = (r: Pick<Requirement, \"status\">) => r.status === \"approved\";\nexport const canUpdateInPlace = (r: Pick<Requirement, \"status\">) => r.status === \"draft\";\n\n/** Only approved solution requirements go to a delivery tool, and only once. */\nexport const canSendToDelivery = (r: Pick<Requirement, \"kind\" | \"status\" | \"delivery\">) =>\n kindOf(r) === \"solution\" && r.status === \"approved\" && !r.delivery;\n\n/** New requirements, rewritten drafts and approved requirements made obsolete, decided together. */\nexport interface RequirementChanges {\n create: Requirement[];\n update: { id: ID; patch: Partial<Requirement> }[];\n obsolete: { id: ID; by: ID }[];\n}\n","import type { Experiment, Metric, Verdict } from \"./types\";\n\nexport function metricPasses(m: Metric): boolean | undefined {\n if (m.actual === undefined || m.actual === null || Number.isNaN(m.actual)) return undefined;\n return m.direction === \"decrease\" ? m.actual <= m.target : m.actual >= m.target;\n}\n\nexport interface VerdictResult {\n verdict: Verdict;\n reason: string;\n}\n\n/** The heart of the experiment loop: compare results against the success criteria. */\nexport function computeVerdict(exp: Experiment): VerdictResult {\n const primary = metricPasses(exp.primaryMetric);\n if (primary === undefined) {\n return { verdict: \"inconclusive\", reason: \"No result recorded for the primary metric yet.\" };\n }\n const failedGuardrails = exp.guardrails.filter((g) => metricPasses(g) === false);\n if (!primary) {\n return {\n verdict: \"invalidated\",\n reason: `${exp.primaryMetric.name} did not reach the target (${fmtMetric(exp.primaryMetric, exp.primaryMetric.actual!)} vs target ${targetLabel(exp.primaryMetric)}).`,\n };\n }\n if (failedGuardrails.length > 0) {\n return {\n verdict: \"invalidated\",\n reason: `Primary metric hit target, but guardrail breached: ${failedGuardrails.map((g) => g.name).join(\", \")}.`,\n };\n }\n return {\n verdict: \"validated\",\n reason: `${exp.primaryMetric.name} hit target (${fmtMetric(exp.primaryMetric, exp.primaryMetric.actual!)} vs target ${targetLabel(exp.primaryMetric)}) and all guardrails held.`,\n };\n}\n\nexport function fmtMetric(m: Metric, v: number) {\n const n = Number.isInteger(v) ? v.toString() : v.toFixed(1);\n return m.unit === \"%\" ? `${n}%` : `${n} ${m.unit}`;\n}\n\nexport function targetLabel(m: Metric) {\n return `${m.direction === \"decrease\" ? \"≤\" : \"≥\"} ${fmtMetric(m, m.target)}`;\n}\n","import { canObsolete, kindOf, type RequirementChanges } from \"./requirements\";\nimport type {\n Activity,\n Delivery,\n Experiment,\n Finding,\n Hypothesis,\n Insight,\n Metric,\n Prioritization,\n ProductArea,\n Requirement,\n} from \"./types\";\nimport { computeVerdict, type VerdictResult } from \"./verdict\";\nimport type { Collections } from \"./collections\";\n\n/**\n * Every change to workspace items, as pure functions: a snapshot and a context in, the changed collections out.\n * Groundwork's local MCP server and the hosted app both run these, so the rules (defaults, cascades, verdicts,\n * status changes, activity entries) live in one place.\n */\n\nexport interface Ctx {\n /** User id of the person acting. */\n actor: string;\n /** One timestamp for the whole change. */\n now: string;\n newId: () => string;\n /** Set when an agent made the change: the name of the token it used, e.g. \"Claude Code\". */\n via?: string;\n}\n\nexport interface Change<R = void> {\n next: Partial<Collections>;\n result: R;\n}\n\nconst nothing = <R>(result: R): Change<R> => ({ next: {}, result });\n\nfunction log(c: Ctx, kind: Activity[\"kind\"], text: string, refId?: string): Activity {\n return { id: c.newId(), at: c.now, actor: c.actor, text, kind, refId, ...(c.via ? { via: c.via } : {}) };\n}\n\n/** The most common area among linked items, so new items inherit one from their evidence. */\nexport function dominantArea(items: { productArea?: ProductArea }[]): ProductArea | undefined {\n const counts = new Map<ProductArea, number>();\n items.forEach((x) => x.productArea && counts.set(x.productArea, (counts.get(x.productArea) ?? 0) + 1));\n let best: ProductArea | undefined;\n let n = 0;\n counts.forEach((c, a) => {\n if (c > n) [best, n] = [a, c];\n });\n return best;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Insights\n// ---------------------------------------------------------------------------------------------\n\nexport type NewInsight = Omit<Insight, \"id\" | \"createdAt\" | \"createdBy\">;\n\nexport function addInsights(s: Collections, c: Ctx, items: NewInsight[]): Change<Insight[]> {\n const created = items.map((i) => ({ ...i, id: c.newId(), createdAt: c.now, createdBy: c.actor }));\n return {\n next: {\n insights: [...created, ...s.insights],\n activity: [\n log(c, \"insight\", created.length === 1 ? `added insight \"${created[0].title}\"` : `added ${created.length} insights`, created[0]?.id),\n ...s.activity,\n ],\n },\n result: created,\n };\n}\n\nexport function updateInsight(s: Collections, id: string, patch: Partial<Insight>): Change {\n return nothing0({ insights: s.insights.map((i) => (i.id === id ? { ...i, ...patch } : i)) });\n}\n\nexport function deleteInsight(s: Collections, id: string): Change {\n return nothing0({\n insights: s.insights.filter((i) => i.id !== id),\n hypotheses: s.hypotheses.map((h) => ({ ...h, insightIds: h.insightIds.filter((x) => x !== id) })),\n findings: s.findings.map((f) => ({ ...f, insightIds: f.insightIds.filter((x) => x !== id) })),\n requirements: s.requirements.map((r) => (r.insightIds ? { ...r, insightIds: r.insightIds.filter((x) => x !== id) } : r)),\n });\n}\n\nfunction nothing0(next: Partial<Collections>): Change {\n return { next, result: undefined };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Hypotheses\n// ---------------------------------------------------------------------------------------------\n\nexport type NewHypothesis = Omit<Hypothesis, \"id\" | \"createdAt\" | \"updatedAt\" | \"owner\">;\n\nexport function addHypotheses(s: Collections, c: Ctx, items: NewHypothesis[]): Change<Hypothesis[]> {\n const created = items.map((h) => ({\n ...h,\n productArea: h.productArea ?? dominantArea(s.insights.filter((i) => h.insightIds.includes(i.id))),\n id: c.newId(),\n owner: c.actor,\n createdAt: c.now,\n updatedAt: c.now,\n }));\n return {\n next: {\n hypotheses: [...created, ...s.hypotheses],\n activity: [\n log(c, \"hypothesis\", created.length === 1 ? `drafted \"${created[0].title}\"` : `drafted ${created.length} hypotheses`, created[0]?.id),\n ...s.activity,\n ],\n },\n result: created,\n };\n}\n\nexport function updateHypothesis(s: Collections, c: Ctx, id: string, patch: Partial<Hypothesis>): Change {\n return nothing0({ hypotheses: s.hypotheses.map((h) => (h.id === id ? { ...h, ...patch, updatedAt: c.now } : h)) });\n}\n\nexport function prioritizeMany(s: Collections, c: Ctx, ratings: { id: string; priority: Prioritization }[]): Change {\n if (!ratings.length) return nothing(undefined);\n const byId = new Map(ratings.map((r) => [r.id, r.priority]));\n return nothing0({\n hypotheses: s.hypotheses.map((h) => (byId.has(h.id) ? { ...h, priority: byId.get(h.id), updatedAt: c.now } : h)),\n activity: [\n log(c, \"hypothesis\", `prioritized ${ratings.length} hypothes${ratings.length === 1 ? \"is\" : \"es\"} in a round`, ratings[0].id),\n ...s.activity,\n ],\n });\n}\n\n/** Deleting a hypothesis deletes its experiments too. */\nexport function deleteHypothesis(s: Collections, id: string): Change {\n return nothing0({\n hypotheses: s.hypotheses.filter((h) => h.id !== id),\n experiments: s.experiments.filter((e) => e.hypothesisId !== id),\n requirements: s.requirements.map((r) => (r.hypothesisIds ? { ...r, hypothesisIds: r.hypothesisIds.filter((x) => x !== id) } : r)),\n });\n}\n\n// ---------------------------------------------------------------------------------------------\n// Experiments\n// ---------------------------------------------------------------------------------------------\n\nexport type NewExperiment = Omit<Experiment, \"id\" | \"owner\">;\n\nexport function addExperiment(s: Collections, c: Ctx, item: NewExperiment): Change<Experiment> {\n const exp: Experiment = { ...item, id: c.newId(), owner: c.actor };\n return {\n next: { experiments: [exp, ...s.experiments], activity: [log(c, \"experiment\", `designed experiment \"${exp.title}\"`, exp.id), ...s.activity] },\n result: exp,\n };\n}\n\nexport function updateExperiment(s: Collections, id: string, patch: Partial<Experiment>): Change {\n return nothing0({ experiments: s.experiments.map((e) => (e.id === id ? { ...e, ...patch } : e)) });\n}\n\n/** Starting an experiment moves a draft hypothesis to \"testing\". */\nexport function startExperiment(s: Collections, c: Ctx, id: string): Change {\n const exp = s.experiments.find((e) => e.id === id);\n if (!exp) return nothing(undefined);\n return nothing0({\n experiments: s.experiments.map((e) => (e.id === id ? { ...e, status: \"running\", startDate: c.now } : e)),\n hypotheses: s.hypotheses.map((h) => (h.id === exp.hypothesisId && h.status === \"draft\" ? { ...h, status: \"testing\", updatedAt: c.now } : h)),\n activity: [log(c, \"experiment\", `started experiment \"${exp.title}\"`, id), ...s.activity],\n });\n}\n\nexport interface RecordedResult {\n result: VerdictResult;\n prevConfidence: number;\n}\n\n/** Record results, compute the verdict and move the hypothesis to validated or invalidated. */\nexport function recordResults(\n s: Collections,\n c: Ctx,\n id: string,\n primaryActual: number,\n guardrailActuals: number[],\n notes: string,\n): Change<RecordedResult | undefined> {\n const exp = s.experiments.find((e) => e.id === id);\n if (!exp) return nothing(undefined);\n const withActuals: Experiment = {\n ...exp,\n primaryMetric: { ...exp.primaryMetric, actual: primaryActual },\n guardrails: exp.guardrails.map((g, i): Metric => ({ ...g, actual: guardrailActuals[i] })),\n };\n const result = computeVerdict(withActuals);\n const updated: Experiment = { ...withActuals, status: \"completed\", endDate: c.now, resultNotes: notes, verdict: result.verdict };\n const hyp = s.hypotheses.find((h) => h.id === exp.hypothesisId);\n const newStatus = result.verdict === \"validated\" ? \"validated\" : result.verdict === \"invalidated\" ? \"invalidated\" : hyp?.status ?? \"testing\";\n const newConfidence = result.verdict === \"validated\" ? 86 : result.verdict === \"invalidated\" ? 14 : hyp?.confidence ?? 50;\n return {\n next: {\n experiments: s.experiments.map((e) => (e.id === id ? updated : e)),\n hypotheses: s.hypotheses.map((h) => (h.id === exp.hypothesisId ? { ...h, status: newStatus, confidence: newConfidence, updatedAt: c.now } : h)),\n activity: [log(c, \"hypothesis\", `${result.verdict} \"${hyp?.title ?? \"hypothesis\"}\" via experiment results`, exp.hypothesisId), ...s.activity],\n },\n result: { result, prevConfidence: hyp?.confidence ?? 50 },\n };\n}\n\nexport function deleteExperiment(s: Collections, id: string): Change {\n return nothing0({\n experiments: s.experiments.filter((e) => e.id !== id),\n findings: s.findings.map((f) => (f.experimentIds.includes(id) ? { ...f, experimentIds: f.experimentIds.filter((x) => x !== id) } : f)),\n });\n}\n\n// ---------------------------------------------------------------------------------------------\n// Findings\n// ---------------------------------------------------------------------------------------------\n\nexport type NewFinding = Omit<Finding, \"id\" | \"createdAt\">;\n\nexport function addFindings(s: Collections, c: Ctx, items: NewFinding[]): Change<Finding[]> {\n const created = items.map((f) => ({\n ...f,\n productArea:\n f.productArea ??\n dominantArea(s.hypotheses.filter((h) => f.hypothesisIds.includes(h.id))) ??\n dominantArea(s.insights.filter((i) => f.insightIds.includes(i.id))),\n id: c.newId(),\n createdAt: c.now,\n }));\n return {\n next: {\n findings: [...created, ...s.findings],\n activity: [\n log(c, \"finding\", created.length === 1 ? `synthesized finding \"${created[0].title}\"` : `synthesized ${created.length} findings`, created[0]?.id),\n ...s.activity,\n ],\n },\n result: created,\n };\n}\n\nexport function updateFinding(s: Collections, id: string, patch: Partial<Finding>): Change {\n return nothing0({ findings: s.findings.map((f) => (f.id === id ? { ...f, ...patch } : f)) });\n}\n\nexport function deleteFinding(s: Collections, id: string): Change {\n return nothing0({\n findings: s.findings.filter((f) => f.id !== id),\n requirements: s.requirements.map((r) => ({ ...r, findingIds: r.findingIds.filter((x) => x !== id) })),\n });\n}\n\n// ---------------------------------------------------------------------------------------------\n// Requirements\n// ---------------------------------------------------------------------------------------------\n\nexport type DerivedRequirement = Omit<Requirement, \"id\" | \"createdAt\" | \"status\">;\nexport type DirectRequirement = Omit<Requirement, \"id\" | \"createdAt\" | \"findingIds\">;\n\n/** Requirements derived from findings. They start as drafts. */\nexport function addRequirements(s: Collections, c: Ctx, items: DerivedRequirement[]): Change<Requirement[]> {\n const created = items.map((r) => ({\n ...r,\n productArea: r.productArea ?? dominantArea(s.findings.filter((f) => r.findingIds.includes(f.id))),\n id: c.newId(),\n createdAt: c.now,\n status: \"draft\" as const,\n }));\n return {\n next: {\n requirements: [...created, ...s.requirements],\n activity: [\n log(\n c,\n \"requirement\",\n created.length === 1 ? `derived requirement \"${created[0].title}\"` : `derived ${created.length} requirements`,\n created[0]?.id,\n ),\n ...s.activity,\n ],\n },\n result: created,\n };\n}\n\n/** A requirement created directly, bypassing hypotheses and experiments: the decision is already made. */\nexport function createRequirement(s: Collections, c: Ctx, item: DirectRequirement): Change<Requirement> {\n const r: Requirement = {\n kind: \"solution\",\n ...item,\n findingIds: [],\n productArea: item.productArea ?? dominantArea(s.insights.filter((i) => item.insightIds?.includes(i.id))),\n id: c.newId(),\n createdAt: c.now,\n };\n return {\n next: { requirements: [r, ...s.requirements], activity: [log(c, \"requirement\", `created requirement \"${r.title}\" directly`, r.id), ...s.activity] },\n result: r,\n };\n}\n\nexport function updateRequirement(s: Collections, id: string, patch: Partial<Requirement>): Change {\n return nothing0({ requirements: s.requirements.map((r) => (r.id === id ? { ...r, ...patch } : r)) });\n}\n\nexport function deleteRequirement(s: Collections, id: string): Change {\n return nothing0({\n requirements: s.requirements\n .filter((r) => r.id !== id)\n .map((r) => (r.stakeholderIds?.includes(id) ? { ...r, stakeholderIds: r.stakeholderIds.filter((x) => x !== id) } : r)),\n });\n}\n\n/** Ask someone to sign off a draft. */\nexport function submitRequirement(s: Collections, c: Ctx, id: string, approver: string): Change<boolean> {\n const r = s.requirements.find((x) => x.id === id);\n if (!r || r.status !== \"draft\") return nothing(false);\n return {\n next: {\n requirements: s.requirements.map((x) => (x.id === id ? { ...x, status: \"awaiting-approval\", approver } : x)),\n activity: [log(c, \"requirement\", `asked for approval of \"${r.title}\"`, id), ...s.activity],\n },\n result: true,\n };\n}\n\nexport function approveRequirement(s: Collections, c: Ctx, id: string): Change<boolean> {\n const r = s.requirements.find((x) => x.id === id);\n if (!r || r.status === \"approved\" || r.status === \"in-delivery\" || r.status === \"obsolete\") return nothing(false);\n return {\n next: {\n requirements: s.requirements.map((x) => (x.id === id ? { ...x, status: \"approved\", approvedBy: c.actor, approvedAt: c.now } : x)),\n activity: [log(c, \"requirement\", `approved \"${r.title}\"`, id), ...s.activity],\n },\n result: true,\n };\n}\n\nexport function sendBackRequirement(s: Collections, c: Ctx, id: string): Change<boolean> {\n const r = s.requirements.find((x) => x.id === id);\n if (!r || r.status !== \"awaiting-approval\") return nothing(false);\n return {\n next: {\n requirements: s.requirements.map((x) => (x.id === id ? { ...x, status: \"draft\" } : x)),\n activity: [log(c, \"requirement\", `sent \"${r.title}\" back for changes`, id), ...s.activity],\n },\n result: true,\n };\n}\n\nexport function obsoleteRequirement(s: Collections, c: Ctx, id: string, by?: string[]): Change<boolean> {\n const r = s.requirements.find((x) => x.id === id);\n if (!r || !canObsolete(r)) return nothing(false);\n return {\n next: {\n requirements: s.requirements.map((x) =>\n x.id === id ? { ...x, status: \"obsolete\", obsoletedAt: c.now, obsoletedBy: by?.length ? by : x.obsoletedBy } : x,\n ),\n activity: [log(c, \"requirement\", `made \"${r.title}\" obsolete`, id), ...s.activity],\n },\n result: true,\n };\n}\n\n/** Save the outcome of deriving requirements: new ones, updated drafts, and approved ones made obsolete. */\nexport function applyRequirementChanges(s: Collections, c: Ctx, { create, update, obsolete }: RequirementChanges): Change {\n const before = s.requirements;\n const patches = new Map<string, Partial<Requirement>>();\n update.forEach((u) => patches.set(u.id, { ...patches.get(u.id), ...u.patch }));\n const supersede = new Map<string, string[]>();\n obsolete.forEach((o) => {\n const r = before.find((x) => x.id === o.id);\n if (r && canObsolete(r)) supersede.set(o.id, [...(supersede.get(o.id) ?? []), o.by]);\n });\n const updatedDrafts = update.filter((u) => u.patch.title).map((u) => u.id);\n const stake = create.filter((r) => kindOf(r) === \"stakeholder\").length;\n const sol = create.length - stake;\n const parts = [stake && `${stake} stakeholder`, sol && `${sol} solution`].filter(Boolean);\n const entries: Activity[] = [];\n if (create.length) entries.push(log(c, \"requirement\", `derived ${parts.join(\" and \")} requirement${create.length === 1 ? \"\" : \"s\"}`, create[0].id));\n updatedDrafts.forEach((id) => entries.push(log(c, \"requirement\", `updated draft \"${patches.get(id)?.title}\" from a new finding`, id)));\n supersede.forEach((_, id) => entries.push(log(c, \"requirement\", `made \"${before.find((x) => x.id === id)?.title}\" obsolete`, id)));\n return nothing0({\n requirements: [\n ...create,\n ...s.requirements.map((r) => {\n let x = patches.has(r.id) ? { ...r, ...patches.get(r.id) } : r;\n if (supersede.has(r.id)) x = { ...x, status: \"obsolete\", obsoletedAt: c.now, obsoletedBy: supersede.get(r.id) };\n return x;\n }),\n ],\n activity: [...entries.reverse(), ...s.activity],\n });\n}\n\n/** Record the Linear issue an approved requirement became, and move it to \"in delivery\". */\nexport function markSentToDelivery(s: Collections, c: Ctx, id: string, delivery: Delivery): Change<boolean> {\n const r = s.requirements.find((x) => x.id === id);\n if (!r || r.delivery) return nothing(false);\n return {\n next: {\n requirements: s.requirements.map((x) => (x.id === id ? { ...x, status: \"in-delivery\", delivery } : x)),\n activity: [log(c, \"requirement\", `sent \"${r.title}\" to Linear as ${delivery.identifier}`, id), ...s.activity],\n },\n result: true,\n };\n}\n\nexport function updateDeliveryStates(s: Collections, byRequirement: Record<string, Delivery>): Change {\n return nothing0({ requirements: s.requirements.map((r) => (byRequirement[r.id] ? { ...r, delivery: byRequirement[r.id] } : r)) });\n}\n","import { z } from \"zod\";\n\n/**\n * Strict input shapes for items written by agents over MCP. Descriptions are shown to the agent, so they explain\n * what each field means in Groundwork's terms.\n *\n * The shapes take the id format as a parameter: the local file store uses readable ids (INS-0001), the hosted app\n * uses UUIDs. Everything else is the same, so agents see the same tools either way.\n */\n\nconst short = (max = 200) => z.string().trim().min(1).max(max);\nconst long = (max = 4000) => z.string().trim().max(max);\nconst area = z\n .string()\n .max(100)\n .optional()\n .describe(\"Product area: its label or id from get_workspace. Leave out to inherit it from linked evidence.\");\n\nexport const SOURCE = z.enum([\"interview\", \"support\", \"survey\", \"analytics\", \"observation\"]);\nexport const SENTIMENT = z.enum([\"negative\", \"neutral\", \"positive\"]);\nexport const HYPOTHESIS_STATUS = z.enum([\"draft\", \"testing\", \"validated\", \"invalidated\"]);\nexport const METHOD = z.enum([\"pilot\", \"ab-test\", \"prototype-test\", \"survey\", \"fake-door\", \"concierge\"]);\nexport const EXPERIMENT_STATUS = z.enum([\"planned\", \"running\", \"completed\"]);\nexport const PRIORITY = z.enum([\"must\", \"should\", \"could\"]);\nexport const REQUIREMENT_KIND = z.enum([\"stakeholder\", \"solution\"]);\nexport const REQUIREMENT_ORIGIN = z.enum([\"tender\", \"regulation\", \"contract\", \"customer-need\"]);\nexport const FINDING_CONFIDENCE = z.enum([\"low\", \"medium\", \"high\"]);\nexport const KIND = z.enum([\"insight\", \"hypothesis\", \"experiment\", \"finding\", \"requirement\"]);\nexport type Kind = z.infer<typeof KIND>;\n\n/** The input shapes for one id format. `id` validates a single item id. */\nexport function makeSchemas(id: z.ZodString) {\n const ids = (what: string) => z.array(id).max(100).describe(`Ids of ${what} in this workspace (from search_items or get_item).`);\n\n const insightInput = z.object({\n title: short().describe(\"One line naming the pain or need, in plain words.\"),\n quote: long(2000).min(1).describe(\"What the person actually said or did, verbatim where possible. This is the evidence.\"),\n source: SOURCE.describe(\"Where it came from.\"),\n persona: short(100).describe('Who said it, as a role or segment, e.g. \"Finance manager at a mid-size firm\".'),\n participant: z.string().trim().max(100).optional().describe(\"Optional participant reference, e.g. P07. Never a full name or contact details.\"),\n tags: z.array(short(40)).max(10).default([]),\n sentiment: SENTIMENT.default(\"neutral\"),\n productArea: area,\n });\n\n const successMetric = z.object({\n name: short(100),\n unit: z.string().trim().max(20).describe('e.g. \"%\", \"min\", \"tickets/week\"'),\n baseline: z.number(),\n target: z.number(),\n direction: z.enum([\"increase\", \"decrease\"]),\n timeframe: z.string().trim().max(100).describe('e.g. \"over a 4-week pilot\"'),\n });\n\n const hypothesisInput = z.object({\n title: short(),\n outcome: short(300).describe('\"We believe we will [outcome]\": the business result the team is after.'),\n forWhom: short(300).describe('\"…if [forWhom]\": the users.'),\n benefit: short(300).describe('\"…[get] [benefit]\": what the users gain, in their terms.'),\n feature: short(300).describe('\"…with [feature]\": the product idea.'),\n successMetric: successMetric.optional().describe(\"One number with a baseline, target and timeframe. Strongly recommended.\"),\n guardrail: z.string().trim().max(300).optional().describe(\"What must not get worse.\"),\n knowWhen: z\n .string()\n .trim()\n .max(600)\n .optional()\n .describe(\"Plain-language success statement. Composed from successMetric and guardrail when those are set.\"),\n alternatives: z.string().trim().max(600).optional().describe(\"What target users rely on today.\"),\n edge: z.string().trim().max(600).optional().describe(\"Why this wins against those alternatives.\"),\n riskiestAssumption: z.string().trim().max(600).optional(),\n confidence: z.number().int().min(0).max(100).default(50).describe(\"0-100, how confident the team is before testing.\"),\n insightIds: ids(\"the insights this hypothesis is built on\").default([]),\n productArea: area,\n });\n\n const metric = z.object({\n name: short(100),\n unit: z.string().trim().max(20),\n baseline: z.number(),\n target: z.number().describe('Success means actual <= target for \"decrease\" and actual >= target for \"increase\".'),\n direction: z.enum([\"increase\", \"decrease\"]),\n });\n\n const experimentInput = z.object({\n hypothesisId: id.describe(\"The hypothesis this experiment tests.\"),\n title: short(),\n method: METHOD,\n description: long(4000).min(1).describe(\"What will be done, with whom, and how results are measured.\"),\n primaryMetric: metric,\n guardrails: z.array(metric).max(5).default([]),\n sampleSize: z.string().trim().max(100).default(\"\").describe('e.g. \"40 accounts\"'),\n durationWeeks: z.number().min(0).max(52).default(2),\n checkBackDate: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .optional()\n .describe(\"For small bets: YYYY-MM-DD to check whether it made a difference.\"),\n });\n\n const findingInput = z.object({\n title: short(),\n summary: long(4000).min(1).describe(\"What was learned and what it means for the product.\"),\n experimentIds: ids(\"the experiments behind it\").default([]),\n hypothesisIds: ids(\"the hypotheses it speaks to\").default([]),\n insightIds: ids(\"supporting insights\").default([]),\n confidence: FINDING_CONFIDENCE.default(\"medium\"),\n productArea: area,\n });\n\n const requirementInput = z.object({\n kind: REQUIREMENT_KIND.default(\"solution\").describe(\n \"stakeholder = what a group of stakeholders needs, in their terms. solution = what the product must do to meet stakeholder needs.\",\n ),\n title: short(),\n story: long(2000).min(1).describe(\"Stakeholder: the need statement. Solution: the user story (As a … I want … so that …).\"),\n stakeholder: z.string().trim().max(100).optional().describe('Stakeholder requirements: who has the need, e.g. \"Finance managers\".'),\n product: z.string().trim().max(100).optional().describe(\"Solution requirements: the product that delivers it (one from get_workspace).\"),\n stakeholderIds: ids(\"the stakeholder requirements this solution requirement helps meet\").optional(),\n acceptanceCriteria: z.array(short(500)).min(1).max(20),\n priority: PRIORITY.default(\"should\"),\n findingIds: ids(\"the findings that justify it\").default([]),\n insightIds: ids(\"customer evidence linked directly\").optional(),\n hypothesisIds: ids(\"hypotheses it was committed from\").optional(),\n origin: REQUIREMENT_ORIGIN.optional().describe(\n \"Only for requirements decided outside the evidence loop (tender, regulation, contract, customer-need). Required when findingIds is empty.\",\n ),\n originNote: z.string().trim().max(300).optional().describe('Where the decision comes from, e.g. \"Region North tender 2026, section 4.2\".'),\n productArea: area,\n });\n\n /** Fields an agent may change with update_item, per kind. Status changes with rules have their own tools. */\n const PATCHES = {\n insight: insightInput.partial().extend({ tags: z.array(short(40)).max(10).optional(), sentiment: SENTIMENT.optional() }),\n hypothesis: hypothesisInput.partial().extend({\n status: HYPOTHESIS_STATUS.optional(),\n confidence: z.number().int().min(0).max(100).optional(),\n insightIds: z.array(id).max(100).optional(),\n }),\n experiment: experimentInput\n .omit({ hypothesisId: true })\n .partial()\n .extend({\n guardrails: z.array(metric).max(5).optional(),\n sampleSize: z.string().trim().max(100).optional(),\n durationWeeks: z.number().min(0).max(52).optional(),\n resultNotes: z.string().trim().max(4000).optional(),\n }),\n finding: findingInput.partial().extend({\n experimentIds: z.array(id).max(100).optional(),\n hypothesisIds: z.array(id).max(100).optional(),\n insightIds: z.array(id).max(100).optional(),\n confidence: FINDING_CONFIDENCE.optional(),\n }),\n requirement: requirementInput.partial().extend({\n priority: PRIORITY.optional(),\n findingIds: z.array(id).max(100).optional(),\n kind: REQUIREMENT_KIND.optional(),\n }),\n } as const;\n\n return { id, insightInput, hypothesisInput, experimentInput, findingInput, requirementInput, PATCHES };\n}\n\nexport type Schemas = ReturnType<typeof makeSchemas>;\n\n/** Readable ids used in files: a kind prefix and a number, e.g. INS-0007. */\nexport const ID_PREFIX = { insight: \"INS\", hypothesis: \"HYP\", experiment: \"EXP\", finding: \"FND\", requirement: \"REQ\" } as const satisfies Record<\n Kind,\n string\n>;\nexport const LOCAL_ID = /^(INS|HYP|EXP|FND|REQ)-\\d{4,}$/;\nexport const localId = z.string().regex(LOCAL_ID, \"an id like INS-0007\");\nexport const localSchemas = makeSchemas(localId);\n","import type { SuccessMetric } from \"./types\";\n\nexport function hasSuccessMetric(m?: SuccessMetric): m is SuccessMetric {\n return Boolean(m && m.name.trim());\n}\n\nfunction lowerFirst(s: string) {\n // Keep acronyms (\"NPS score\") intact.\n return s.length > 1 && s[1] === s[1].toUpperCase() && /[A-Z]/.test(s[1]) ? s : s.charAt(0).toLowerCase() + s.slice(1);\n}\n\n/** \"week-1 activation rises from 38 to 55% or more over a 4-week prototype test\" */\nexport function describeSuccess(m: SuccessMetric): string {\n const verb = m.direction === \"decrease\" ? \"falls\" : \"rises\";\n const bound = m.direction === \"decrease\" ? \"or less\" : \"or more\";\n const unit = m.unit ? ` ${m.unit}` : \"\";\n const when = m.timeframe.trim() ? ` ${m.timeframe.trim()}` : \"\";\n return `${lowerFirst(m.name.trim())} ${verb} from ${m.baseline} to ${m.target}${unit} ${bound}${when}`;\n}\n\n/** The plain-language success statement, from the success metric and the guardrail. Empty without a metric. */\nexport function composeKnowWhen(d: { successMetric?: SuccessMetric; guardrail?: string }): string {\n if (!hasSuccessMetric(d.successMetric)) return \"\";\n const g = (d.guardrail ?? \"\").trim();\n return describeSuccess(d.successMetric) + (g ? `, without ${g}` : \"\");\n}\n\n/** \"We believe we will [outcome] if [forWhom] get [benefit] with [feature].\" */\nexport function composeStatement(h: { outcome: string; forWhom: string; benefit: string; feature: string }): string {\n return `We believe we will ${h.outcome.trim()} if ${h.forWhom.trim()} get ${h.benefit.trim()} with ${h.feature.trim()}.`;\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport YAML from \"yaml\";\nimport { z } from \"zod\";\n\n/** The folder inside a project that holds everything Groundwork writes. */\nexport const DIR = \"groundwork\";\nexport const CONFIG_FILE = \"config.yml\";\nexport const SCHEMA_VERSION = 1;\n\nconst slugId = z.string().regex(/^[a-z0-9][a-z0-9-]{0,39}$/, \"lowercase letters, digits and dashes\");\n\nexport const configSchema = z.object({\n schemaVersion: z.number().int().positive().default(SCHEMA_VERSION),\n name: z.string().trim().min(1).max(100),\n productAreas: z.array(z.object({ id: slugId, label: z.string().trim().min(1).max(100) })).default([]),\n products: z.array(z.string().trim().min(1).max(100)).default([]),\n people: z\n .array(\n z.object({\n id: slugId,\n name: z.string().trim().min(1).max(100),\n role: z.enum([\"owner\", \"editor\", \"viewer\"]).default(\"editor\"),\n /** Optional: lets Groundwork recognise you from `git config user.email`. */\n email: z.string().trim().max(200).optional(),\n }),\n )\n .default([]),\n /** Set when this folder was imported into the Groundwork web app. Local writes stop, so the two can't drift apart. */\n migrated: z.string().url().optional(),\n});\n\nexport type Config = z.infer<typeof configSchema>;\nexport type Person = Config[\"people\"][number];\n\n/**\n * Where the project is: $GROUNDWORK_DIR, else the nearest folder above the working directory that has a\n * groundwork/config.yml, else the working directory itself (a new project).\n */\nexport function findRoot(cwd = process.cwd()): string {\n if (process.env.GROUNDWORK_DIR) return resolve(process.env.GROUNDWORK_DIR);\n let dir = resolve(cwd);\n for (;;) {\n if (existsSync(join(dir, DIR, CONFIG_FILE))) return dir;\n const up = dirname(dir);\n if (up === dir) return resolve(cwd);\n dir = up;\n }\n}\n\nexport const configPath = (root: string) => join(root, DIR, CONFIG_FILE);\nexport const isInitialized = (root: string) => existsSync(configPath(root));\n\nexport function defaultConfig(root: string): Config {\n return configSchema.parse({ name: basename(resolve(root)) || \"Product\" });\n}\n\nexport class ConfigError extends Error {}\n\nexport function readConfig(root: string): Config {\n const file = configPath(root);\n if (!existsSync(file)) return defaultConfig(root);\n let raw: unknown;\n try {\n raw = YAML.parse(readFileSync(file, \"utf8\")) ?? {};\n } catch (e) {\n throw new ConfigError(`${DIR}/${CONFIG_FILE} isn't valid YAML: ${(e as Error).message}`);\n }\n const parsed = configSchema.safeParse(raw);\n if (!parsed.success) throw new ConfigError(`${DIR}/${CONFIG_FILE} is invalid: ${z.prettifyError(parsed.error)}`);\n if (parsed.data.schemaVersion > SCHEMA_VERSION) {\n throw new ConfigError(`${DIR}/${CONFIG_FILE} uses schema version ${parsed.data.schemaVersion}; this Groundwork understands up to ${SCHEMA_VERSION}. Update groundwork-mcp.`);\n }\n return parsed.data;\n}\n\nconst CONFIG_HEADER = `# Groundwork settings. See SPEC.md in the groundwork-mcp package for every field.\n# productAreas: [{ id: onboarding, label: Onboarding }]\n# products: [Acme app]\n# people: [{ id: sam, name: Sam, role: owner }] # roles: owner, editor, viewer\n`;\n\nexport function writeConfig(root: string, config: Config) {\n mkdirSync(join(root, DIR), { recursive: true });\n writeFileSync(configPath(root), CONFIG_HEADER + YAML.stringify(config, { lineWidth: 0 }));\n}\n\nfunction gitEmail(root: string): string | undefined {\n try {\n return execFileSync(\"git\", [\"config\", \"user.email\"], { cwd: root, encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim() || undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Who is acting: $GROUNDWORK_USER (a person id), else the person whose email matches git's, else the only person\n * listed. Unknown people act as \"me\", which is fine for a one-person folder.\n */\nexport function resolveActor(root: string, config: Config): { id: string; person?: Person } {\n const byId = (id: string) => config.people.find((p) => p.id === id);\n const env = process.env.GROUNDWORK_USER?.trim();\n if (env) return { id: env, person: byId(env) };\n const email = gitEmail(root)?.toLowerCase();\n const match = email && config.people.find((p) => p.email?.toLowerCase() === email);\n if (match) return { id: match.id, person: match };\n if (config.people.length === 1) return { id: config.people[0].id, person: config.people[0] };\n return { id: \"me\" };\n}\n","import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport YAML from \"yaml\";\nimport { COLLECTION_KEYS, diffCollections, emptyCollections, type Collections } from \"../core/collections\";\nimport { ID_PREFIX, LOCAL_ID, type Kind } from \"../core/schemas\";\nimport { DIR } from \"./config\";\n\n/**\n * Items as files: groundwork/<collection>/<ID>-<slug>.md, YAML frontmatter for the fields, and a Markdown body\n * that is yours. Groundwork keeps the body as `notes` and never rewrites it.\n */\n\nexport type ItemCollection = Exclude<keyof Collections, \"activity\">;\n\nexport const COLLECTIONS: Record<Kind, ItemCollection> = {\n insight: \"insights\",\n hypothesis: \"hypotheses\",\n experiment: \"experiments\",\n finding: \"findings\",\n requirement: \"requirements\",\n};\n\nexport const KIND_OF: Record<ItemCollection, Kind> = {\n insights: \"insight\",\n hypotheses: \"hypothesis\",\n experiments: \"experiment\",\n findings: \"finding\",\n requirements: \"requirement\",\n};\n\nconst ITEM_COLLECTIONS = COLLECTION_KEYS.filter((k): k is ItemCollection => k !== \"activity\");\n\nexport interface FileProblem {\n file: string;\n message: string;\n}\n\nexport interface Loaded {\n items: Collections;\n /** Item id -> file path relative to the project root. */\n paths: Map<string, string>;\n problems: FileProblem[];\n}\n\nexport function slug(title: string): string {\n return (\n title\n .toLowerCase()\n .normalize(\"NFKD\")\n .replace(/[̀-ͯ]/g, \"\")\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60)\n .replace(/-+$/, \"\") || \"item\"\n );\n}\n\n/** Where a new item's file goes. */\nexport function newPath(kind: Kind, id: string, title: string) {\n return `${DIR}/${COLLECTIONS[kind]}/${id}-${slug(title)}.md`;\n}\n\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/;\n\nexport function parseItem(text: string): { data: Record<string, unknown>; notes: string } {\n const m = FRONTMATTER.exec(text);\n if (!m) throw new Error(\"no YAML frontmatter (the file must start with a line of three dashes)\");\n const data = YAML.parse(m[1]);\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new Error(\"the frontmatter isn't a set of fields\");\n return { data: data as Record<string, unknown>, notes: m[2].replace(/^\\r?\\n/, \"\").trimEnd() };\n}\n\n/** Drop undefined values, recursively, so they don't show up as `null` in YAML. */\nfunction clean(v: unknown): unknown {\n if (Array.isArray(v)) return v.map(clean);\n if (v && typeof v === \"object\") {\n return Object.fromEntries(Object.entries(v as Record<string, unknown>).flatMap(([k, x]) => (x === undefined ? [] : [[k, clean(x)]])));\n }\n return v;\n}\n\nexport function renderItem(item: Record<string, unknown>): string {\n const { id, title, notes, ...rest } = item;\n const fm = YAML.stringify(clean({ id, title, ...rest }), { lineWidth: 0 });\n const body = typeof notes === \"string\" && notes.trim() ? `\\n${notes.trim()}\\n` : \"\";\n return `---\\n${fm}---\\n${body}`;\n}\n\nexport function load(root: string): Loaded {\n const items = emptyCollections();\n const paths = new Map<string, string>();\n const problems: FileProblem[] = [];\n for (const key of ITEM_COLLECTIONS) {\n const dir = join(root, DIR, key);\n if (!existsSync(dir)) continue;\n const prefix = ID_PREFIX[KIND_OF[key]];\n for (const name of readdirSync(dir).sort()) {\n if (!name.endsWith(\".md\")) continue;\n const file = relative(root, join(dir, name));\n try {\n const { data, notes } = parseItem(readFileSync(join(dir, name), \"utf8\"));\n const id = data.id;\n if (typeof id !== \"string\" || !LOCAL_ID.test(id)) throw new Error(`id must look like ${prefix}-0001, not ${JSON.stringify(id)}`);\n if (!id.startsWith(`${prefix}-`)) throw new Error(`${id} is in ${key}/, but ${key} ids start with ${prefix}-`);\n if (paths.has(id)) {\n problems.push({ file, message: `duplicate id ${id}, also used by ${paths.get(id)}. Give one of them a new id.` });\n continue;\n }\n paths.set(id, file);\n (items[key] as unknown[]).push(notes ? { ...data, notes } : data);\n } catch (e) {\n problems.push({ file, message: (e as Error).message });\n }\n }\n }\n return { items, paths, problems };\n}\n\n/** The next free id per kind: one more than the highest in use. */\nexport function idAllocator(items: Collections) {\n const next = new Map<Kind, number>();\n for (const key of ITEM_COLLECTIONS) {\n let max = 0;\n for (const x of items[key] as { id: string }[]) {\n const n = Number(x.id.split(\"-\")[1]);\n if (Number.isFinite(n) && n > max) max = n;\n }\n next.set(KIND_OF[key], max + 1);\n }\n return (kind: Kind) => {\n const n = next.get(kind)!;\n next.set(kind, n + 1);\n return `${ID_PREFIX[kind]}-${String(n).padStart(4, \"0\")}`;\n };\n}\n\nconst LINK_FIELDS = [\"insightIds\", \"hypothesisIds\", \"experimentIds\", \"findingIds\", \"stakeholderIds\", \"obsoletedBy\"] as const;\n\n/**\n * The operations make new items with temporary ids. Give each a readable id (INS-0008…) in creation order, and\n * point every link at the new ids. Returns the new collections and the temporary -> final id map.\n */\nexport function assignIds(before: Collections, after: Collections): { items: Collections; renamed: Map<string, string> } {\n const known = new Set(ITEM_COLLECTIONS.flatMap((k) => (before[k] as { id: string }[]).map((x) => x.id)));\n const alloc = idAllocator(before);\n const renamed = new Map<string, string>();\n for (const key of ITEM_COLLECTIONS) {\n // The operations put new items first, newest batch first; within a batch, in the order given.\n for (const x of after[key] as { id: string }[]) if (!known.has(x.id) && !LOCAL_ID.test(x.id)) renamed.set(x.id, alloc(KIND_OF[key]));\n }\n if (!renamed.size) return { items: after, renamed };\n const map = (id: string) => renamed.get(id) ?? id;\n const items = { ...after };\n for (const key of ITEM_COLLECTIONS) {\n (items[key] as unknown[]) = (after[key] as unknown as Record<string, unknown>[]).map((x) => {\n let y = x;\n const touch = () => (y === x ? (y = { ...x }) : y);\n if (renamed.has(x.id as string)) touch().id = map(x.id as string);\n if (typeof x.hypothesisId === \"string\" && renamed.has(x.hypothesisId)) touch().hypothesisId = map(x.hypothesisId);\n for (const f of LINK_FIELDS) {\n const list = x[f];\n if (Array.isArray(list) && list.some((v) => renamed.has(v))) touch()[f] = list.map(map);\n }\n return y;\n });\n }\n return { items, renamed };\n}\n\n/** Equal as data: key order and undefined fields don't matter. */\nfunction sameJSON(a: unknown, b: unknown): boolean {\n const norm = (v: unknown): unknown =>\n Array.isArray(v)\n ? v.map(norm)\n : v && typeof v === \"object\"\n ? Object.fromEntries(\n Object.keys(v as object)\n .filter((k) => (v as Record<string, unknown>)[k] !== undefined)\n .sort()\n .map((k) => [k, norm((v as Record<string, unknown>)[k])]),\n )\n : v;\n return JSON.stringify(norm(a)) === JSON.stringify(norm(b));\n}\n\nfunction writeAtomic(file: string, text: string) {\n const tmp = `${file}.tmp-${process.pid}`;\n writeFileSync(tmp, text);\n renameSync(tmp, file);\n}\n\n/** Write what changed between two snapshots: changed items rewritten, new ones created, removed ones deleted. */\nexport function save(root: string, loaded: Loaded, after: Collections): string[] {\n const { upserts, deletes } = diffCollections(loaded.items, after);\n const before = new Map(ITEM_COLLECTIONS.flatMap((k) => (loaded.items[k] as { id: string }[]).map((x) => [x.id, x] as const)));\n const touched: string[] = [];\n for (const u of upserts) {\n if (u.kind === \"activity\") continue; // Git history is the activity log.\n // Cascades copy every item; only rewrite files whose content really changed, so hand formatting survives.\n const old = before.get(u.id);\n if (old && sameJSON(old, { id: u.id, ...u.data })) continue;\n const kind = u.kind as Kind;\n const rel = loaded.paths.get(u.id) ?? newPath(kind, u.id, String(u.data.title ?? \"\"));\n mkdirSync(join(root, DIR, COLLECTIONS[kind]), { recursive: true });\n writeAtomic(join(root, rel), renderItem({ id: u.id, ...u.data }));\n loaded.paths.set(u.id, rel);\n touched.push(rel);\n }\n for (const id of deletes) {\n const rel = loaded.paths.get(id);\n if (!rel) continue;\n if (existsSync(join(root, rel))) unlinkSync(join(root, rel));\n loaded.paths.delete(id);\n touched.push(rel);\n }\n loaded.items = after;\n return touched;\n}\n","import { z } from \"zod\";\nimport type { Collections } from \"../core/collections\";\nimport { kindOf } from \"../core/requirements\";\nimport { EXPERIMENT_STATUS, HYPOTHESIS_STATUS, localSchemas, type Kind } from \"../core/schemas\";\nimport type { Requirement } from \"../core/types\";\nimport type { Config } from \"./config\";\nimport { COLLECTIONS, type Loaded } from \"./files\";\n\nexport interface Problem {\n level: \"error\" | \"warning\";\n file: string;\n message: string;\n}\n\nconst REQUIREMENT_STATUS = z.enum([\"draft\", \"awaiting-approval\", \"approved\", \"in-delivery\", \"obsolete\"]);\nconst { insightInput, hypothesisInput, experimentInput, findingInput, requirementInput } = localSchemas;\n\n/** What a stored item must look like: the agent's input shape plus the fields Groundwork sets. Unknown fields are kept. */\nconst STORED: Record<Kind, z.ZodType> = {\n insight: insightInput.extend({ createdAt: z.string() }).loose(),\n hypothesis: hypothesisInput.extend({ status: HYPOTHESIS_STATUS, knowWhen: z.string().optional() }).loose(),\n experiment: experimentInput.extend({ status: EXPERIMENT_STATUS }).loose(),\n finding: findingInput.loose(),\n requirement: requirementInput.extend({ status: REQUIREMENT_STATUS, acceptanceCriteria: z.array(z.string()).default([]) }).loose(),\n};\n\n/** Every problem in a project: unreadable files, invalid fields, broken or wrong-kind links, unknown areas. */\nexport function validate(loaded: Loaded, config: Config): Problem[] {\n const out: Problem[] = loaded.problems.map((p) => ({ level: \"error\", ...p }));\n const s: Collections = loaded.items;\n const kindById = new Map<string, Kind>();\n for (const kind of Object.keys(COLLECTIONS) as Kind[]) for (const x of s[COLLECTIONS[kind]] as { id: string }[]) kindById.set(x.id, kind);\n const areaIds = new Set(config.productAreas.map((a) => a.id));\n const people = new Set(config.people.map((p) => p.id));\n\n for (const kind of Object.keys(COLLECTIONS) as Kind[]) {\n for (const item of s[COLLECTIONS[kind]] as unknown as (Record<string, unknown> & { id: string })[]) {\n const file = loaded.paths.get(item.id) ?? item.id;\n const err = (message: string) => out.push({ level: \"error\", file, message });\n const warn = (message: string) => out.push({ level: \"warning\", file, message });\n\n const parsed = STORED[kind].safeParse(item);\n if (!parsed.success) err(z.prettifyError(parsed.error).replace(/\\n/g, \"; \"));\n\n const link = (field: string, want: Kind, ids: unknown) => {\n for (const id of Array.isArray(ids) ? ids : ids === undefined ? [] : [ids]) {\n const got = kindById.get(id as string);\n if (!got) err(`${field}: ${id} doesn't exist`);\n else if (got !== want) err(`${field}: ${id} is a ${got}, not a ${want}`);\n else if (id === item.id) err(`${field}: an item can't link to itself`);\n }\n };\n\n const area = item.productArea as string | undefined;\n if (area && !areaIds.has(area)) warn(`productArea \"${area}\" isn't in config.yml productAreas`);\n\n switch (kind) {\n case \"hypothesis\":\n link(\"insightIds\", \"insight\", item.insightIds);\n if (!(item.insightIds as unknown[] | undefined)?.length) warn(\"no insights linked: what evidence is this built on?\");\n break;\n case \"experiment\":\n link(\"hypothesisId\", \"hypothesis\", item.hypothesisId);\n break;\n case \"finding\":\n link(\"experimentIds\", \"experiment\", item.experimentIds);\n link(\"hypothesisIds\", \"hypothesis\", item.hypothesisIds);\n link(\"insightIds\", \"insight\", item.insightIds);\n if (![item.experimentIds, item.hypothesisIds, item.insightIds].some((l) => (l as unknown[] | undefined)?.length)) {\n warn(\"no evidence linked: link the experiments, hypotheses or insights behind it\");\n }\n break;\n case \"requirement\": {\n const r = item as unknown as Requirement;\n link(\"findingIds\", \"finding\", r.findingIds);\n link(\"insightIds\", \"insight\", r.insightIds);\n link(\"hypothesisIds\", \"hypothesis\", r.hypothesisIds);\n link(\"stakeholderIds\", \"requirement\", r.stakeholderIds);\n link(\"obsoletedBy\", \"requirement\", r.obsoletedBy);\n for (const id of r.stakeholderIds ?? []) {\n const t = s.requirements.find((x) => x.id === id);\n if (t && kindOf(t) !== \"stakeholder\") err(`stakeholderIds: ${id} is a solution requirement, not a stakeholder requirement`);\n }\n if (r.stakeholderIds?.length && kindOf(r) === \"stakeholder\") err(\"stakeholderIds is only for solution requirements\");\n if (!r.findingIds?.length && !r.origin) err(\"needs findingIds, or an origin (tender, regulation, contract, customer-need) if it was decided elsewhere\");\n if (r.product && config.products.length && !config.products.includes(r.product)) warn(`product \"${r.product}\" isn't in config.yml products`);\n if (r.approver && !people.has(r.approver)) warn(`approver \"${r.approver}\" isn't in config.yml people`);\n break;\n }\n }\n }\n }\n return out;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport type { Collections } from \"../core/collections\";\nimport { composeKnowWhen } from \"../core/hypothesis\";\nimport * as ops from \"../core/ops\";\nimport { kindOf } from \"../core/requirements\";\nimport { KIND, localId, localSchemas, type Kind } from \"../core/schemas\";\nimport type { Experiment, Finding, Hypothesis, Insight, Requirement } from \"../core/types\";\nimport { isInitialized, readConfig, resolveActor, writeConfig, type Config } from \"../store/config\";\nimport { assignIds, COLLECTIONS, load, newPath, save, type Loaded } from \"../store/files\";\nimport { validate } from \"../store/validate\";\n\ndeclare const __VERSION__: string;\nconst VERSION = typeof __VERSION__ === \"string\" ? __VERSION__ : \"0.0.0-dev\";\n\nconst { insightInput, hypothesisInput, experimentInput, findingInput, requirementInput, PATCHES } = localSchemas;\n\nexport const INSTRUCTIONS = `Groundwork keeps this product's evidence and decisions as linked Markdown files in the groundwork/ folder, as a chain:\ninsight -> hypothesis -> experiment -> finding -> requirement.\n\n- 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.\n- Hypothesis: \"We believe we will [outcome] if [forWhom] get [benefit] with [feature]\", built on insights (insightIds), ideally with a successMetric (baseline, target, timeframe).\n- 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).\n- Finding: what was learned, linked to the experiments, hypotheses and insights behind it.\n- 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).\n\nHow to work:\n1. Call get_workspace first: it gives product areas, products and people (for approvers).\n2. Before creating anything, search_items for duplicates and for evidence to link. Prefer linking to existing items over creating near-duplicates.\n3. Always link evidence: hypotheses to insights, experiments to a hypothesis, findings to experiments/hypotheses/insights, requirements to findings.\n4. Ask the user before deleting items or approving requirements, unless they already told you to.\n5. 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.\n6. The Markdown body under an item's frontmatter is the user's own notes. Read it, but don't overwrite it.`;\n\ntype State = Collections;\ntype Result = { content: { type: \"text\"; text: string }[]; isError?: boolean };\ntype AnyItem = Insight | Hypothesis | Experiment | Finding | Requirement;\n\nclass UserError extends Error {}\n\nconst an = (kind: string) => `${/^[aeiou]/.test(kind) ? \"an\" : \"a\"} ${kind}`;\nconst ok = (value: unknown): Result => ({ content: [{ type: \"text\", text: JSON.stringify(value, null, 2) }] });\nconst fail = (message: string): Result => ({ content: [{ type: \"text\", text: message }], isError: true });\n\nfunction find(s: State, id: string): { kind: Kind; item: AnyItem } | undefined {\n for (const kind of KIND.options) {\n const item = (s[COLLECTIONS[kind]] as AnyItem[]).find((x) => x.id === id);\n if (item) return { kind, item };\n }\n return undefined;\n}\n\n/** The ids each kind links to. */\nexport function outgoing(kind: Kind, item: AnyItem): string[] {\n switch (kind) {\n case \"hypothesis\":\n return (item as Hypothesis).insightIds ?? [];\n case \"experiment\":\n return [(item as Experiment).hypothesisId];\n case \"finding\": {\n const f = item as Finding;\n return [...(f.experimentIds ?? []), ...(f.hypothesisIds ?? []), ...(f.insightIds ?? [])];\n }\n case \"requirement\": {\n const r = item as Requirement;\n return [...(r.findingIds ?? []), ...(r.insightIds ?? []), ...(r.hypothesisIds ?? []), ...(r.stakeholderIds ?? []), ...(r.obsoletedBy ?? [])];\n }\n default:\n return [];\n }\n}\n\nconst statusOf = (kind: Kind, item: AnyItem): string | undefined =>\n kind === \"hypothesis\" || kind === \"experiment\" || kind === \"requirement\" ? (item as { status: string }).status : undefined;\n\nfunction textOf(kind: Kind, item: AnyItem): string {\n const notes = (item as { notes?: string }).notes ?? \"\";\n switch (kind) {\n case \"insight\": {\n const i = item as Insight;\n return [i.title, i.quote, i.persona, (i.tags ?? []).join(\" \"), notes].join(\" \");\n }\n case \"hypothesis\": {\n const h = item as Hypothesis;\n return [h.title, h.outcome, h.forWhom, h.benefit, h.feature, h.knowWhen, notes].join(\" \");\n }\n case \"experiment\": {\n const e = item as Experiment;\n return [e.title, e.description, e.primaryMetric?.name, e.resultNotes ?? \"\", notes].join(\" \");\n }\n case \"finding\": {\n const f = item as Finding;\n return [f.title, f.summary, notes].join(\" \");\n }\n case \"requirement\": {\n const r = item as Requirement;\n return [r.title, r.story, r.stakeholder ?? \"\", r.product ?? \"\", (r.acceptanceCriteria ?? []).join(\" \"), notes].join(\" \");\n }\n }\n}\n\n/** One tool call's view of the project: config, actor and the files as they are on disk right now. */\nclass Session {\n readonly config: Config;\n readonly loaded: Loaded;\n readonly actor: ReturnType<typeof resolveActor>;\n\n constructor(readonly root: string) {\n this.config = readConfig(root);\n this.loaded = load(root);\n this.actor = resolveActor(root, this.config);\n }\n\n file(kind: Kind, item: AnyItem) {\n return this.loaded.paths.get(item.id) ?? newPath(kind, item.id, item.title);\n }\n\n areaLabel = (id: string | undefined) => this.config.productAreas.find((a) => a.id === id)?.label ?? \"\";\n\n /** Accept an area's id or label; undefined stays undefined. */\n area(value: string | undefined): string | undefined {\n if (!value) return undefined;\n const a = this.config.productAreas.find((x) => x.id === value || x.label.toLowerCase() === value.trim().toLowerCase());\n if (!a) {\n const known = this.config.productAreas.map((x) => x.label).join(\", \") || \"none defined\";\n throw new UserError(`Unknown product area \"${value}\". Areas in groundwork/config.yml: ${known}. Add it there first, or leave it out.`);\n }\n return a.id;\n }\n\n /** Every id must be an item of this kind. */\n check(s: State, kind: Kind, ids: string[] | undefined, field: string) {\n for (const id of ids ?? []) {\n const hit = find(s, id);\n if (!hit) throw new UserError(`${field}: no item with id ${id}.`);\n if (hit.kind !== kind) throw new UserError(`${field}: ${id} is ${an(hit.kind)}, not ${an(kind)}.`);\n }\n }\n\n checkStakeholders(s: State, ids: string[] | undefined) {\n this.check(s, \"requirement\", ids, \"stakeholderIds\");\n for (const id of ids ?? []) {\n const r = s.requirements.find((x) => x.id === id)!;\n if (kindOf(r) !== \"stakeholder\") throw new UserError(`stakeholderIds: \"${r.title}\" is a solution requirement, not a stakeholder requirement.`);\n }\n }\n\n summary(kind: Kind, item: AnyItem) {\n const area = this.areaLabel((item as { productArea?: string }).productArea) || undefined;\n return {\n kind,\n id: item.id,\n title: item.title,\n ...(statusOf(kind, item) ? { status: statusOf(kind, item) } : {}),\n ...(kind === \"requirement\" ? { requirementKind: kindOf(item as Requirement) } : {}),\n ...(area ? { area } : {}),\n file: this.file(kind, item),\n };\n }\n\n full(kind: Kind, item: AnyItem) {\n const area = this.areaLabel((item as { productArea?: string }).productArea) || undefined;\n return { kind, ...item, ...(area ? { areaLabel: area } : {}), file: this.file(kind, item) };\n }\n\n ctx(): ops.Ctx {\n // Temporary ids; the store swaps them for readable ones (INS-0008…) when it saves.\n return { actor: this.actor.id, now: new Date().toISOString(), newId: () => `new-${randomUUID()}` };\n }\n\n canEdit() {\n return !this.actor.person || this.actor.person.role !== \"viewer\";\n }\n}\n\nexport interface ServerOptions {\n /** The project folder (the one that holds groundwork/). */\n root: string;\n}\n\nexport function buildServer({ root }: ServerOptions): McpServer {\n const server = new McpServer({ name: \"groundwork\", version: VERSION }, { instructions: INSTRUCTIONS });\n\n const open = () => new Session(root);\n\n const read =\n <A>(fn: (s: Session, args: A) => unknown) =>\n async (args: A): Promise<Result> => {\n try {\n return ok(await fn(open(), args));\n } catch (e) {\n return fail(e instanceof UserError ? e.message : `Groundwork couldn't read the project: ${(e as Error).message}`);\n }\n };\n\n /**\n * Run a change against the files as they are now: `fn` returns the new state and what to tell the agent. New\n * items get readable ids, and only the files that changed are written.\n */\n const write =\n <A>(fn: (s: Session, state: State, ctx: ops.Ctx, args: A) => { state: State; result: unknown }) =>\n async (args: A): Promise<Result> => {\n try {\n const s = open();\n if (s.config.migrated) {\n return fail(\n `This folder was imported into the Groundwork web app (${s.config.migrated}), which is now where changes go. Connect its MCP server instead (Groundwork → Settings → Connect an agent). These files are kept as a read-only record.`,\n );\n }\n 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.`);\n if (!isInitialized(root)) writeConfig(root, s.config);\n const { state, result } = fn(s, s.loaded.items, s.ctx(), args);\n const { items, renamed } = assignIds(s.loaded.items, state);\n const files = save(root, s.loaded, items);\n let text = JSON.stringify({ ...(result as object), filesChanged: files }, null, 2);\n renamed.forEach((to, from) => (text = text.split(from).join(to)));\n return { content: [{ type: \"text\", text }] };\n } catch (e) {\n if (e instanceof UserError) return fail(e.message);\n return fail(`Groundwork couldn't save that: ${(e as Error).message}`);\n }\n };\n\n const apply = <R>(state: State, change: ops.Change<R>): [State, R] => [{ ...state, ...change.next }, change.result];\n const itemId = localId.describe(\"An item id, e.g. INS-0007.\");\n\n // -------------------------------------------------------------------------------------------\n // Read\n // -------------------------------------------------------------------------------------------\n\n server.registerTool(\n \"get_workspace\",\n {\n title: \"Get workspace\",\n description: \"The project's name, product areas, products, people, item counts and any file problems. Call this first.\",\n inputSchema: {},\n annotations: { readOnlyHint: true },\n },\n read((s) => {\n const items = s.loaded.items;\n const problems = validate(s.loaded, s.config);\n return {\n workspace: s.config.name,\n folder: `${s.root}/groundwork`,\n initialized: isInitialized(root),\n ...(s.config.migrated ? { migratedTo: s.config.migrated, readOnly: true } : {}),\n you: { id: s.actor.id, name: s.actor.person?.name, role: s.actor.person?.role ?? \"editor\" },\n productAreas: s.config.productAreas,\n products: s.config.products,\n members: s.config.people.map(({ id, name, role }) => ({ id, name, role })),\n counts: Object.fromEntries(KIND.options.map((k) => [k, items[COLLECTIONS[k]].length])),\n problems: {\n errors: problems.filter((p) => p.level === \"error\").length,\n warnings: problems.filter((p) => p.level === \"warning\").length,\n first: problems.slice(0, 10),\n },\n };\n }),\n );\n\n server.registerTool(\n \"search_items\",\n {\n title: \"Search items\",\n description:\n \"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.\",\n inputSchema: {\n kind: KIND.optional().describe(\"Only this kind.\"),\n query: z.string().max(200).optional().describe(\"Words to match, any order.\"),\n status: z.string().max(40).optional().describe(\"Only items with this status, e.g. draft, testing, running, awaiting-approval.\"),\n area: z.string().max(100).optional().describe(\"Only items in this product area (label or id).\"),\n limit: z.number().int().min(1).max(100).default(20),\n },\n annotations: { readOnlyHint: true },\n },\n read((s, { kind, query, status, area, limit }: { kind?: Kind; query?: string; status?: string; area?: string; limit: number }) => {\n const areaId = s.area(area);\n const words = (query ?? \"\").toLowerCase().split(/\\s+/).filter(Boolean);\n const out: ReturnType<Session[\"summary\"]>[] = [];\n let total = 0;\n for (const k of kind ? [kind] : KIND.options) {\n for (const item of s.loaded.items[COLLECTIONS[k]] as AnyItem[]) {\n if (status && statusOf(k, item) !== status) continue;\n if (areaId && (item as { productArea?: string }).productArea !== areaId) continue;\n if (words.length) {\n const text = textOf(k, item).toLowerCase();\n if (!words.every((w) => text.includes(w))) continue;\n }\n total++;\n if (out.length < limit) out.push(s.summary(k, item));\n }\n }\n return { total, shown: out.length, items: out };\n }),\n );\n\n server.registerTool(\n \"get_item\",\n {\n title: \"Get item\",\n description: \"One item in full, with its notes, the items it links to and the items that link to it.\",\n inputSchema: { id: itemId },\n annotations: { readOnlyHint: true },\n },\n read((s, { id }: { id: string }) => {\n const items = s.loaded.items;\n const hit = find(items, id);\n if (!hit) throw new UserError(`No item with id ${id}.`);\n const linksTo = outgoing(hit.kind, hit.item)\n .map((x) => find(items, x))\n .filter((x): x is NonNullable<typeof x> => Boolean(x))\n .map((x) => s.summary(x.kind, x.item));\n const linkedFrom: ReturnType<Session[\"summary\"]>[] = [];\n for (const k of KIND.options) {\n for (const item of items[COLLECTIONS[k]] as AnyItem[]) if (outgoing(k, item).includes(id)) linkedFrom.push(s.summary(k, item));\n }\n return { item: s.full(hit.kind, hit.item), linksTo, linkedFrom };\n }),\n );\n\n // -------------------------------------------------------------------------------------------\n // Create\n // -------------------------------------------------------------------------------------------\n\n server.registerTool(\n \"add_insights\",\n {\n title: \"Add insights\",\n description: \"Log customer evidence: one insight per distinct pain, need or behaviour, each with the quote that shows it.\",\n inputSchema: { insights: z.array(insightInput).min(1).max(50) },\n },\n write((s, state, c, { insights }: { insights: z.infer<typeof insightInput>[] }) => {\n const items = insights.map((i) => ({ ...i, productArea: s.area(i.productArea) }));\n const [next, created] = apply(state, ops.addInsights(state, c, items));\n return { state: next, result: { created: created.map((x) => s.summary(\"insight\", x)) } };\n }),\n );\n\n server.registerTool(\n \"add_hypotheses\",\n {\n title: \"Add hypotheses\",\n description: 'Draft hypotheses in the form \"We believe we will [outcome] if [forWhom] get [benefit] with [feature]\", linked to the insights behind them.',\n inputSchema: { hypotheses: z.array(hypothesisInput).min(1).max(20) },\n },\n write((s, state, c, { hypotheses }: { hypotheses: z.infer<typeof hypothesisInput>[] }) => {\n const items: ops.NewHypothesis[] = hypotheses.map((h) => {\n s.check(state, \"insight\", h.insightIds, \"insightIds\");\n return {\n ...h,\n knowWhen: composeKnowWhen({ successMetric: h.successMetric, guardrail: h.guardrail }) || h.knowWhen || \"\",\n productArea: s.area(h.productArea),\n status: \"draft\",\n aiGenerated: true,\n };\n });\n const [next, created] = apply(state, ops.addHypotheses(state, c, items));\n return { state: next, result: { created: created.map((x) => s.summary(\"hypothesis\", x)) } };\n }),\n );\n\n server.registerTool(\n \"add_experiment\",\n {\n title: \"Add experiment\",\n description: \"Design an experiment for one hypothesis. It starts as planned; call start_experiment when it begins.\",\n inputSchema: { experiment: experimentInput },\n },\n write((s, state, c, { experiment }: { experiment: z.infer<typeof experimentInput> }) => {\n s.check(state, \"hypothesis\", [experiment.hypothesisId], \"hypothesisId\");\n const [next, created] = apply(state, ops.addExperiment(state, c, { ...experiment, status: \"planned\", aiGenerated: true }));\n return { state: next, result: { created: s.summary(\"experiment\", created) } };\n }),\n );\n\n server.registerTool(\n \"add_findings\",\n {\n title: \"Add findings\",\n description: \"Record what was learned, linked to the experiments, hypotheses and insights behind it.\",\n inputSchema: { findings: z.array(findingInput).min(1).max(20) },\n },\n write((s, state, c, { findings }: { findings: z.infer<typeof findingInput>[] }) => {\n const items = findings.map((f) => {\n s.check(state, \"experiment\", f.experimentIds, \"experimentIds\");\n s.check(state, \"hypothesis\", f.hypothesisIds, \"hypothesisIds\");\n s.check(state, \"insight\", f.insightIds, \"insightIds\");\n return { ...f, productArea: s.area(f.productArea), aiGenerated: true };\n });\n const [next, created] = apply(state, ops.addFindings(state, c, items));\n return { state: next, result: { created: created.map((x) => s.summary(\"finding\", x)) } };\n }),\n );\n\n server.registerTool(\n \"add_requirements\",\n {\n title: \"Add requirements\",\n description:\n \"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.\",\n inputSchema: { requirements: z.array(requirementInput).min(1).max(30) },\n },\n write((s, state, c, { requirements }: { requirements: z.infer<typeof requirementInput>[] }) => {\n let next = state;\n const created: Requirement[] = [];\n const derived: ops.DerivedRequirement[] = [];\n for (const r of requirements) {\n s.check(state, \"finding\", r.findingIds, \"findingIds\");\n s.check(state, \"insight\", r.insightIds, \"insightIds\");\n s.check(state, \"hypothesis\", r.hypothesisIds, \"hypothesisIds\");\n s.checkStakeholders(state, r.stakeholderIds);\n if (r.product && s.config.products.length && !s.config.products.includes(r.product)) {\n throw new UserError(`Unknown product \"${r.product}\". Products in groundwork/config.yml: ${s.config.products.join(\", \")}.`);\n }\n const base = { ...r, productArea: s.area(r.productArea), aiGenerated: true };\n if (r.findingIds.length) {\n derived.push(base);\n } else {\n if (!r.origin) throw new UserError(`\"${r.title}\": link findingIds, or give an origin for a requirement decided elsewhere.`);\n const { findingIds: _unused, ...direct } = base;\n void _unused;\n const [after, one] = apply(next, ops.createRequirement(next, c, { ...direct, status: \"draft\" }));\n next = after;\n created.push(one);\n }\n }\n if (derived.length) {\n const [after, many] = apply(next, ops.addRequirements(next, c, derived));\n next = after;\n created.push(...many);\n }\n return { state: next, result: { created: created.map((x) => s.summary(\"requirement\", x)) } };\n }),\n );\n\n // -------------------------------------------------------------------------------------------\n // Change\n // -------------------------------------------------------------------------------------------\n\n server.registerTool(\n \"update_item\",\n {\n title: \"Update item\",\n description:\n \"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.\",\n inputSchema: { id: itemId, patch: z.record(z.string(), z.unknown()) },\n },\n write((s, state, c, { id, patch }: { id: string; patch: Record<string, unknown> }) => {\n const hit = find(state, id);\n if (!hit) throw new UserError(`No item with id ${id}.`);\n const parsed = PATCHES[hit.kind].strict().safeParse(patch);\n if (!parsed.success) throw new UserError(`Invalid patch for ${an(hit.kind)}: ${z.prettifyError(parsed.error)}`);\n const p = parsed.data as Record<string, unknown> & { productArea?: string };\n if (!Object.keys(p).length) throw new UserError(\"The patch has no fields to change.\");\n if (\"productArea\" in p) p.productArea = s.area(p.productArea);\n let change: ops.Change;\n switch (hit.kind) {\n case \"insight\":\n change = ops.updateInsight(state, id, p as Partial<Insight>);\n break;\n case \"hypothesis\": {\n s.check(state, \"insight\", p.insightIds as string[] | undefined, \"insightIds\");\n const merged = { ...(hit.item as Hypothesis), ...p } as Hypothesis;\n if (\"successMetric\" in p || \"guardrail\" in p) {\n const composed = composeKnowWhen({ successMetric: merged.successMetric, guardrail: merged.guardrail });\n if (composed) p.knowWhen = composed;\n }\n change = ops.updateHypothesis(state, c, id, p as Partial<Hypothesis>);\n break;\n }\n case \"experiment\":\n change = ops.updateExperiment(state, id, p as Partial<Experiment>);\n break;\n case \"finding\":\n s.check(state, \"experiment\", p.experimentIds as string[] | undefined, \"experimentIds\");\n s.check(state, \"hypothesis\", p.hypothesisIds as string[] | undefined, \"hypothesisIds\");\n s.check(state, \"insight\", p.insightIds as string[] | undefined, \"insightIds\");\n change = ops.updateFinding(state, id, p as Partial<Finding>);\n break;\n case \"requirement\": {\n const r = hit.item as Requirement;\n if (r.status === \"obsolete\" || r.status === \"in-delivery\") {\n throw new UserError(`\"${r.title}\" is ${r.status}, so it can't be edited. Create a new requirement instead.`);\n }\n s.check(state, \"finding\", p.findingIds as string[] | undefined, \"findingIds\");\n s.check(state, \"insight\", p.insightIds as string[] | undefined, \"insightIds\");\n s.check(state, \"hypothesis\", p.hypothesisIds as string[] | undefined, \"hypothesisIds\");\n s.checkStakeholders(state, p.stakeholderIds as string[] | undefined);\n change = ops.updateRequirement(state, id, { ...(p as Partial<Requirement>), updatedAt: c.now });\n break;\n }\n }\n const [next] = apply(state, change);\n const updated = find(next, id)!;\n return { state: next, result: { updated: s.full(updated.kind, updated.item) } };\n }),\n );\n\n server.registerTool(\n \"link_items\",\n {\n title: \"Link items\",\n description:\n \"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).\",\n inputSchema: { id: itemId, linkTo: z.array(localId).min(1).max(50) },\n },\n write((s, state, _c, { id, linkTo }: { id: string; linkTo: string[] }) => {\n const hit = find(state, id);\n if (!hit) throw new UserError(`No item with id ${id}.`);\n const add = (list: string[] | undefined, x: string) => (list?.includes(x) ? list : [...(list ?? []), x]);\n let item = { ...hit.item } as AnyItem & Record<string, unknown>;\n for (const target of linkTo) {\n const t = find(state, target);\n if (!t) throw new UserError(`No item with id ${target}.`);\n if (target === id) throw new UserError(\"An item can't link to itself.\");\n const field =\n hit.kind === \"hypothesis\" && t.kind === \"insight\"\n ? \"insightIds\"\n : hit.kind === \"experiment\" && t.kind === \"hypothesis\"\n ? \"hypothesisId\"\n : hit.kind === \"finding\" && (t.kind === \"experiment\" || t.kind === \"hypothesis\" || t.kind === \"insight\")\n ? (`${t.kind}Ids` as const)\n : hit.kind === \"requirement\" && t.kind === \"finding\"\n ? \"findingIds\"\n : hit.kind === \"requirement\" && t.kind === \"insight\"\n ? \"insightIds\"\n : hit.kind === \"requirement\" && t.kind === \"hypothesis\"\n ? \"hypothesisIds\"\n : hit.kind === \"requirement\" &&\n t.kind === \"requirement\" &&\n kindOf(hit.item as Requirement) === \"solution\" &&\n kindOf(t.item as Requirement) === \"stakeholder\"\n ? \"stakeholderIds\"\n : null;\n if (!field) {\n const what = t.kind === \"requirement\" ? `a ${kindOf(t.item as Requirement)} requirement` : an(t.kind);\n throw new UserError(`${an(hit.kind).replace(/^a/, \"A\")} can't link to ${what}.`);\n }\n item = field === \"hypothesisId\" ? { ...item, hypothesisId: target } : { ...item, [field]: add(item[field] as string[] | undefined, target) };\n }\n const key = COLLECTIONS[hit.kind];\n const next = { ...state, [key]: (state[key] as AnyItem[]).map((x) => (x.id === id ? item : x)) } as State;\n return { state: next, result: { updated: s.full(hit.kind, item) } };\n }),\n );\n\n server.registerTool(\n \"start_experiment\",\n {\n title: \"Start experiment\",\n description: \"Mark a planned experiment as running. A draft hypothesis it tests moves to testing.\",\n inputSchema: { id: itemId },\n },\n write((s, state, c, { id }: { id: string }) => {\n const e = state.experiments.find((x) => x.id === id);\n if (!e) throw new UserError(`No experiment with id ${id}.`);\n if (e.status !== \"planned\") throw new UserError(`\"${e.title}\" is already ${e.status}.`);\n const [next] = apply(state, ops.startExperiment(state, c, id));\n return { state: next, result: { started: s.summary(\"experiment\", next.experiments.find((x) => x.id === id)!) } };\n }),\n );\n\n server.registerTool(\n \"record_experiment_results\",\n {\n title: \"Record experiment results\",\n description:\n \"Record the measured values and complete the experiment. Groundwork computes the verdict (validated, invalidated or inconclusive) from the targets and moves the hypothesis accordingly.\",\n inputSchema: {\n id: itemId,\n primaryActual: z.number().describe(\"Measured value of the primary metric.\"),\n guardrailActuals: z.array(z.number()).max(5).default([]).describe(\"Measured value of each guardrail, in the experiment's order.\"),\n notes: z.string().trim().max(4000).default(\"\").describe(\"What happened, in a few sentences.\"),\n },\n },\n write((s, state, c, a: { id: string; primaryActual: number; guardrailActuals: number[]; notes: string }) => {\n const e = state.experiments.find((x) => x.id === a.id);\n if (!e) throw new UserError(`No experiment with id ${a.id}.`);\n if (e.status === \"completed\") throw new UserError(`\"${e.title}\" already has results (${e.verdict}).`);\n const guardrails = e.guardrails ?? [];\n if (a.guardrailActuals.length !== guardrails.length) {\n throw new UserError(`\"${e.title}\" has ${guardrails.length} guardrail(s): ${guardrails.map((g) => g.name).join(\", \") || \"none\"}. Give one value for each.`);\n }\n const [next, out] = apply(state, ops.recordResults(state, c, a.id, a.primaryActual, a.guardrailActuals, a.notes));\n const h = next.hypotheses.find((x) => x.id === e.hypothesisId);\n return {\n state: next,\n result: { verdict: out!.result.verdict, reason: out!.result.reason, experiment: s.summary(\"experiment\", e), hypothesis: h && s.summary(\"hypothesis\", h) },\n };\n }),\n );\n\n const requirementOf = (state: State, id: string) => {\n const r = state.requirements.find((x) => x.id === id);\n if (!r) throw new UserError(`No requirement with id ${id}.`);\n return r;\n };\n\n server.registerTool(\n \"submit_requirement_for_approval\",\n {\n title: \"Submit requirement for approval\",\n description: \"Ask a person (by id from get_workspace members) to sign off a draft requirement.\",\n inputSchema: { id: itemId, approverId: z.string().max(40) },\n },\n write((s, state, c, { id, approverId }: { id: string; approverId: string }) => {\n const r = requirementOf(state, id);\n const approver = s.config.people.find((m) => m.id === approverId);\n if (!approver) throw new UserError(`${approverId} isn't in groundwork/config.yml people. Add them there first.`);\n if (approver.role === \"viewer\") throw new UserError(`${approver.name} is a viewer, so they can't approve.`);\n if (r.status !== \"draft\") throw new UserError(`\"${r.title}\" is ${r.status}; only drafts can be submitted.`);\n const [next] = apply(state, ops.submitRequirement(state, c, id, approverId));\n return { state: next, result: { submitted: s.summary(\"requirement\", requirementOf(next, id)), approver: approver.name } };\n }),\n );\n\n server.registerTool(\n \"approve_requirement\",\n {\n title: \"Approve requirement\",\n description: \"Sign off a requirement that is awaiting your approval. Only the named approver can approve.\",\n inputSchema: { id: itemId },\n annotations: { destructiveHint: false },\n },\n write((s, state, c, { id }: { id: string }) => {\n const r = requirementOf(state, id);\n if (r.status !== \"awaiting-approval\") throw new UserError(`\"${r.title}\" is ${r.status}, not awaiting approval.`);\n if (r.approver !== s.actor.id) {\n const name = s.config.people.find((m) => m.id === r.approver)?.name ?? r.approver ?? \"someone else\";\n 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.`);\n }\n const [next] = apply(state, ops.approveRequirement(state, c, id));\n return { state: next, result: { approved: s.summary(\"requirement\", requirementOf(next, id)) } };\n }),\n );\n\n server.registerTool(\n \"send_back_requirement\",\n {\n title: \"Send requirement back\",\n description: \"Return a requirement awaiting your approval to draft, for changes. Only the named approver can do this.\",\n inputSchema: { id: itemId },\n },\n write((s, state, c, { id }: { id: string }) => {\n const r = requirementOf(state, id);\n if (r.status !== \"awaiting-approval\") throw new UserError(`\"${r.title}\" is ${r.status}, not awaiting approval.`);\n if (r.approver !== s.actor.id) throw new UserError(`Only the approver can send \"${r.title}\" back.`);\n const [next] = apply(state, ops.sendBackRequirement(state, c, id));\n return { state: next, result: { sentBack: s.summary(\"requirement\", requirementOf(next, id)) } };\n }),\n );\n\n server.registerTool(\n \"obsolete_requirement\",\n {\n title: \"Make requirement obsolete\",\n description: \"Retire an approved requirement, e.g. when newer evidence supersedes it, optionally naming the requirements that replace it.\",\n inputSchema: { id: itemId, replacedBy: z.array(localId).max(20).optional() },\n },\n write((s, state, c, { id, replacedBy }: { id: string; replacedBy?: string[] }) => {\n const r = requirementOf(state, id);\n if (r.status !== \"approved\") throw new UserError(`Only approved requirements can be made obsolete; \"${r.title}\" is ${r.status}.`);\n s.check(state, \"requirement\", replacedBy, \"replacedBy\");\n const [next] = apply(state, ops.obsoleteRequirement(state, c, id, replacedBy));\n return { state: next, result: { obsolete: s.summary(\"requirement\", requirementOf(next, id)) } };\n }),\n );\n\n server.registerTool(\n \"delete_item\",\n {\n title: \"Delete item\",\n description:\n \"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.\",\n inputSchema: { id: itemId },\n annotations: { destructiveHint: true },\n },\n write((_s, state, _c, { id }: { id: string }) => {\n const hit = find(state, id);\n if (!hit) throw new UserError(`No item with id ${id}.`);\n const change =\n hit.kind === \"insight\"\n ? ops.deleteInsight(state, id)\n : hit.kind === \"hypothesis\"\n ? ops.deleteHypothesis(state, id)\n : hit.kind === \"experiment\"\n ? ops.deleteExperiment(state, id)\n : hit.kind === \"finding\"\n ? ops.deleteFinding(state, id)\n : ops.deleteRequirement(state, id);\n const [next] = apply(state, change);\n const alsoDeleted = hit.kind === \"hypothesis\" ? state.experiments.filter((e) => e.hypothesisId === id).map((e) => e.id) : [];\n return { state: next, result: { deleted: { kind: hit.kind, id, title: hit.item.title }, ...(alsoDeleted.length ? { alsoDeletedExperiments: alsoDeleted } : {}) } };\n }),\n );\n\n return server;\n}\n"],"mappings":";;;;;;;AAYO,IAAM,kBAAkB;AAAA,EAC7B,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AAAA,EACV,cAAc;AAAA,EACd,UAAU;AACZ;AAEO,IAAM,kBAAkB,OAAO,KAAK,eAAe;AAEnD,IAAM,mBAAmB,OAAoB;AAAA,EAClD,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AAQ,EAAE,SAAS,EAAE,MAAM,IAAI,MAAM,IAAI,OAAO,IAAI,KAAK,MAAM,GAAG,GAAI,YAAY,SAAS,EAAE,wBAAwB,YAAY,IAAI,CAAC,EAAG,EAAE;AAAA,IACnK,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["insightInput","hypothesisInput","experimentInput","findingInput","requirementInput","PATCHES","z","existsSync","mkdirSync","readFileSync","writeFileSync","join","YAML","YAML","join","existsSync","readFileSync","writeFileSync","mkdirSync","z","z","area","z","insightInput","hypothesisInput","experimentInput","findingInput","requirementInput","area","z"]}