groundwork-mcp 0.2.0 → 0.4.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/README.md CHANGED
@@ -17,6 +17,8 @@ insight ──▶ hypothesis ──▶ experiment ──▶ finding ──▶ re
17
17
 
18
18
  ## Quickstart (2 minutes)
19
19
 
20
+ ### Claude Code
21
+
20
22
  In your project folder:
21
23
 
22
24
  ```sh
@@ -30,7 +32,32 @@ Or install the plugin, which adds the MCP server and a skill that teaches Claude
30
32
  /plugin install groundwork@groundwork
31
33
  ```
32
34
 
33
- Then talk to Claude as you normally would:
35
+ ### Codex
36
+
37
+ ```sh
38
+ codex mcp add groundwork -- npx -y groundwork-mcp
39
+ ```
40
+
41
+ Or add it to `~/.codex/config.toml` by hand:
42
+
43
+ ```toml
44
+ [mcp_servers.groundwork]
45
+ command = "npx"
46
+ args = ["-y", "groundwork-mcp"]
47
+ ```
48
+
49
+ To teach Codex when to use it, copy the skill into your repo:
50
+
51
+ ```sh
52
+ mkdir -p .agents/skills/groundwork
53
+ curl -fsSL https://raw.githubusercontent.com/IdeatorlabsAB/groundwork/main/skills/groundwork/SKILL.md -o .agents/skills/groundwork/SKILL.md
54
+ ```
55
+
56
+ Start `codex` in your project folder, so Groundwork finds the project.
57
+
58
+ ### Then
59
+
60
+ Talk to your agent as you normally would:
34
61
 
35
62
  > Here are my notes from three customer interviews. Log the pains as insights.
36
63
  >
@@ -42,6 +69,19 @@ Then talk to Claude as you normally would:
42
69
 
43
70
  Groundwork writes files like `groundwork/insights/INS-0001-setup-takes-too-long.md`. Commit them like any other file.
44
71
 
72
+ ## Requirements in two layers
73
+
74
+ Write requirements before you build, and keep them in two linked layers:
75
+
76
+ - **Stakeholder requirements** say who needs what and why, as user stories: *"As a medical secretary I want a view of all practitioners' calendars with their unbooked slots highlighted so that I can find them and book appointments easily."*
77
+ - **Solution requirements** say what the solution must do to meet those needs, as "shall" statements: *"The appointment view shall show the calendars of the selected practitioners with the free slots highlighted. It shall be possible to click a free slot to start the booking flow."*
78
+
79
+ Every solution requirement fulfils at least one stakeholder requirement, and Groundwork refuses one that doesn't. `groundwork validate` warns about stakeholder requirements that no solution requirement fulfils yet, and about stories that don't fit their layer. Linking findings is optional, so you can write requirements before there's any experiment behind them.
80
+
81
+ ### Planning with Groundwork
82
+
83
+ When your agent plans a task, it first decides what kind of task it is. "Let's add a feature to book appointments" is a new need. "This path is broken, fix it" is a fix. It states the call in one line of the plan, such as *"New need: adds 2 stakeholder and 4 solution requirements"* or *"Bug fix under REQ-0007; no requirement changes"*. For a new need or a change, the plan records the requirements before any code. Tickets the workflow creates carry the REQ ids they implement. When a PM approves a requirement verbally, tell the agent and it records the approval on their behalf, noting who entered it.
84
+
45
85
  ## The CLI
46
86
 
47
87
  ```sh
@@ -82,7 +122,7 @@ jobs:
82
122
 
83
123
  ## Setup
84
124
 
85
- `groundwork/config.yml` holds your product areas, products and people (for approvals). The first write creates it if it's missing. Fill it in so agents can tag items by area and send requirements for sign-off:
125
+ `groundwork/config.yml` holds your product areas, products and people (for approvals). The first write creates it if it's missing. Fill it in so agents can tag items by area and send requirements for sign-off. Agents can also add product areas and products themselves, with `add_product_areas` and `add_products`; people are always added by hand:
86
126
 
87
127
  ```yaml
88
128
  name: Acme
@@ -108,6 +148,7 @@ The full format, every field and the rules are in [SPEC.md](SPEC.md). See [examp
108
148
  | | `add_requirements` | `send_back_requirement` |
109
149
  | | `update_item`, `link_items` | `obsolete_requirement` |
110
150
  | | `delete_item` | |
151
+ | | `add_product_areas`, `add_products` | |
111
152
 
112
153
  ## Privacy
113
154
 
@@ -125,7 +166,13 @@ npx -p groundwork-mcp groundwork import --to https://your-groundwork-app --dry-r
125
166
  npx -p groundwork-mcp groundwork import --to https://your-groundwork-app
126
167
  ```
127
168
 
128
- Every item keeps its links, and its original id (`INS-0001`) is stored with it. Running the import again skips items already there (`--overwrite` replaces them). Afterwards `groundwork/config.yml` says `migrated:`, so local tools only read the files and the web app is where changes go. The command prints how to point your agent at the web app's MCP server.
169
+ Every item keeps its links, and its original id (`INS-0001`) is stored with it. Running the import again skips items already there (`--overwrite` replaces them). Afterwards `groundwork/config.yml` says `migrated:`, so local tools only read the files and the web app is where changes go. The command prints how to point your agent at the web app's MCP server. For Codex, run `codex mcp remove groundwork` and add this to `~/.codex/config.toml`:
170
+
171
+ ```toml
172
+ [mcp_servers.groundwork]
173
+ url = "https://your-groundwork-app/api/mcp"
174
+ bearer_token_env_var = "GROUNDWORK_TOKEN"
175
+ ```
129
176
 
130
177
  ## Contributing
131
178
 
package/SPEC.md CHANGED
@@ -56,10 +56,16 @@ Required fields are in bold.
56
56
  **Finding** (`findings/`, `FND-`): what was learned.
57
57
  **`title`**, **`summary`**, `experimentIds`, `hypothesisIds`, `insightIds`, `confidence` (`low` | `medium` | `high`), `productArea`, `createdAt`.
58
58
 
59
- **Requirement** (`requirements/`, `REQ-`): a stakeholder need, or what the product must do to meet one.
60
- **`title`**, **`story`**, **`acceptanceCriteria`** (a list), **`status`** (`draft` | `awaiting-approval` | `approved` | `in-delivery` | `obsolete`), `kind` (`stakeholder` | `solution`; `solution` if left out), `stakeholder` (stakeholder requirements: who has the need), `product` and `stakeholderIds` (solution requirements), `priority` (`must` | `should` | `could`), `findingIds`, `insightIds`, `hypothesisIds`, `origin` (`tender` | `regulation` | `contract` | `customer-need`) and `originNote`, `approver`, `approvedBy`, `approvedAt`, `obsoletedBy`, `obsoletedAt`, `productArea`, `createdAt`, `updatedAt`.
59
+ **Requirement** (`requirements/`, `REQ-`): what is needed before building, in two layers.
60
+ **`title`**, **`kind`** (`stakeholder` | `solution`; files without it are read as `solution`), **`story`**, **`acceptanceCriteria`** (a list), **`status`** (`draft` | `awaiting-approval` | `approved` | `in-delivery` | `obsolete`), `stakeholder` (stakeholder requirements: who has the need), `stakeholderIds` (solution requirements: **required**, the stakeholder requirements it fulfils), `product` (solution requirements), `priority` (`must` | `should` | `could`), `findingIds`, `insightIds`, `hypothesisIds`, `origin` (`tender` | `regulation` | `contract` | `customer-need`) and `originNote`, `approver`, `approvedBy`, `approvedAt`, `recordedBy` (who entered an approval given by someone else), `approvalNote`, `obsoletedBy`, `obsoletedAt`, `productArea`, `createdAt`, `updatedAt`.
61
61
 
62
- A requirement needs `findingIds`, or an `origin` when it was decided outside the evidence loop.
62
+ The two layers:
63
+
64
+ - A **stakeholder requirement** says who needs what and why. Its `story` is a user story: "As a medical secretary I want a view of the calendars of all practitioners in the clinic with their unbooked slots highlighted so that I can find them and book appointments easily."
65
+ - A **solution requirement** describes the qualities and behaviour the solution must have to meet stakeholder needs. Its `story` is one or more "shall" statements: "The appointment view used by medical secretaries shall show the calendars of the selected practitioners with the free slots highlighted. It shall be possible to click a free slot to start the booking flow. It shall be possible to add or remove practitioners in the view."
66
+ - Every active solution requirement fulfils at least one stakeholder requirement (`stakeholderIds`). A stakeholder requirement is fulfilled by one or more solution requirements.
67
+
68
+ `findingIds`, `insightIds`, `hypothesisIds` and `origin` are optional: link them when the requirement rests on evidence or comes from a tender, regulation or contract.
63
69
 
64
70
  ### Links
65
71
 
@@ -79,6 +85,9 @@ These rules live in the core library, so every Groundwork tool applies them the
79
85
  - Starting an experiment moves a `draft` hypothesis to `testing`.
80
86
  - Recording results computes the verdict. It is **validated** when the primary metric reaches its target (`actual >= target` for `increase`, `<=` for `decrease`) and every guardrail holds. It is **invalidated** when either fails. The hypothesis moves to the same status.
81
87
  - New hypotheses, findings and requirements without a `productArea` take the most common one among their linked evidence.
88
+ - A solution requirement can't be saved without at least one stakeholder requirement in `stakeholderIds`, and a stakeholder requirement can't have any. A stakeholder requirement can't be deleted while it is the only one a solution requirement fulfils. `validate` reports an active solution requirement without stakeholder links as an error.
89
+ - `validate` warns about an active stakeholder requirement that no solution requirement fulfils yet, and about a `story` that doesn't fit its layer: a stakeholder story without "As a … I want … so that …", or a solution requirement without "shall". The tools save these and return the same warnings.
90
+ - An approval given outside Groundwork (e.g. verbally) can be recorded with `approvedBy` and an optional note; the person recording it is stored as `recordedBy`.
82
91
  - Requirements go from `draft` to `awaiting-approval` (with an `approver`) to `approved`. The approver can send one back to `draft`. Only `approved` requirements can become `obsolete`.
83
92
  - Deleting an item removes links to it. Deleting a hypothesis also deletes its experiments.
84
93
 
@@ -100,6 +109,8 @@ people:
100
109
  migrated: https://… # set by the web app importer; local writes stop
101
110
  ```
102
111
 
112
+ `add_product_areas` and `add_products` append to `productAreas` and `products`. They skip entries already there (matched by label or name, ignoring case) and never rename, reorder or remove anything. Area ids are made from the label unless given. Rename or remove by editing the file.
113
+
103
114
  The person acting is `$GROUNDWORK_USER` (a person id). Otherwise it's the person whose `email` matches git's, or the only person listed. If none of those apply, it's `me`.
104
115
 
105
116
  ## Versioning
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildServer,
3
3
  findRoot
4
- } from "./chunk-5LIKTHEE.js";
4
+ } from "./chunk-TXXV5YDG.js";
5
5
 
6
6
  // src/mcp/run.ts
7
7
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -13,4 +13,4 @@ async function runMcp() {
13
13
  export {
14
14
  runMcp
15
15
  };
16
- //# sourceMappingURL=chunk-7CAQUVOH.js.map
16
+ //# sourceMappingURL=chunk-4F24STNS.js.map
@@ -48,9 +48,29 @@ function kindOf(r) {
48
48
  return r.kind ?? "solution";
49
49
  }
50
50
  var isObsolete = (r) => r.status === "obsolete";
51
+ var isActive = (r) => !isObsolete(r);
51
52
  var canObsolete = (r) => r.status === "approved";
52
53
  var canUpdateInPlace = (r) => r.status === "draft";
53
54
  var canSendToDelivery = (r) => kindOf(r) === "solution" && r.status === "approved" && !r.delivery;
55
+ var STAKEHOLDER_STORY = /^\s*as\s+an?\s+.+?\bI\s+(want|need)\b.+?\bso\s+that\b/is;
56
+ var SOLUTION_STATEMENT = /\bshall\b/i;
57
+ function wordingWarnings(r) {
58
+ const story = r.story ?? "";
59
+ if (kindOf(r) === "stakeholder") {
60
+ return STAKEHOLDER_STORY.test(story) ? [] : ['a stakeholder requirement should be a user story: "As a <role> I want <need> so that <reason>"'];
61
+ }
62
+ return SOLUTION_STATEMENT.test(story) ? [] : ['a solution requirement should be written as "shall" statements, e.g. "The <system or part> shall \u2026"'];
63
+ }
64
+ function fulfilledBy(id, requirements) {
65
+ return requirements.filter((r) => kindOf(r) === "solution" && isActive(r) && r.stakeholderIds?.includes(id));
66
+ }
67
+ function layerProblem(r) {
68
+ if (kindOf(r) === "solution" && !r.stakeholderIds?.length) {
69
+ return "a solution requirement must fulfil at least one stakeholder requirement: add stakeholderIds (add the stakeholder requirement first if it doesn't exist)";
70
+ }
71
+ if (kindOf(r) === "stakeholder" && r.stakeholderIds?.length) return "stakeholderIds is only for solution requirements";
72
+ return void 0;
73
+ }
54
74
 
55
75
  // src/core/verdict.ts
56
76
  function metricPasses(m) {
@@ -332,13 +352,24 @@ function submitRequirement(s, c, id, approver) {
332
352
  result: true
333
353
  };
334
354
  }
335
- function approveRequirement(s, c, id) {
355
+ function approveRequirement(s, c, id, by) {
336
356
  const r = s.requirements.find((x) => x.id === id);
337
357
  if (!r || r.status === "approved" || r.status === "in-delivery" || r.status === "obsolete") return nothing(false);
358
+ const approvedBy = by?.approvedBy ?? c.actor;
359
+ const onBehalf = approvedBy !== c.actor;
360
+ const approved = {
361
+ ...r,
362
+ status: "approved",
363
+ approvedBy,
364
+ approvedAt: c.now,
365
+ approver: r.approver ?? approvedBy,
366
+ ...onBehalf ? { recordedBy: c.actor } : {},
367
+ ...by?.note ? { approvalNote: by.note } : {}
368
+ };
338
369
  return {
339
370
  next: {
340
- requirements: s.requirements.map((x) => x.id === id ? { ...x, status: "approved", approvedBy: c.actor, approvedAt: c.now } : x),
341
- activity: [log(c, "requirement", `approved "${r.title}"`, id), ...s.activity]
371
+ requirements: s.requirements.map((x) => x.id === id ? approved : x),
372
+ activity: [log(c, "requirement", onBehalf ? `approved "${r.title}" for ${approvedBy}` : `approved "${r.title}"`, id), ...s.activity]
342
373
  },
343
374
  result: true
344
375
  };
@@ -490,21 +521,23 @@ function makeSchemas(id) {
490
521
  productArea: area
491
522
  });
492
523
  const requirementInput3 = z.object({
493
- kind: REQUIREMENT_KIND.default("solution").describe(
494
- "stakeholder = what a group of stakeholders needs, in their terms. solution = what the product must do to meet stakeholder needs."
524
+ kind: REQUIREMENT_KIND.describe(
525
+ 'stakeholder = who needs what and why, as a user story. solution = the qualities and behaviour the solution must have to meet stakeholder requirements, as "shall" statements.'
495
526
  ),
496
527
  title: short(),
497
- story: long(2e3).min(1).describe("Stakeholder: the need statement. Solution: the user story (As a \u2026 I want \u2026 so that \u2026)."),
498
- stakeholder: z.string().trim().max(100).optional().describe('Stakeholder requirements: who has the need, e.g. "Finance managers".'),
528
+ story: long(2e3).min(1).describe(
529
+ 'Stakeholder: a user story, "As a <role> I want <need> so that <reason>". Solution: one or more "shall" statements, e.g. "The booking view shall show the calendars of the selected practitioners."'
530
+ ),
531
+ stakeholder: z.string().trim().max(100).optional().describe('Stakeholder requirements: who has the need (the role in the story), e.g. "Medical secretaries".'),
499
532
  product: z.string().trim().max(100).optional().describe("Solution requirements: the product that delivers it (one from get_workspace)."),
500
- stakeholderIds: ids("the stakeholder requirements this solution requirement helps meet").optional(),
533
+ stakeholderIds: ids("Solution requirements: required, at least one. The stakeholder requirements this one fulfils").optional(),
501
534
  acceptanceCriteria: z.array(short(500)).min(1).max(20),
502
535
  priority: PRIORITY.default("should"),
503
536
  findingIds: ids("the findings that justify it").default([]),
504
537
  insightIds: ids("customer evidence linked directly").optional(),
505
538
  hypothesisIds: ids("hypotheses it was committed from").optional(),
506
539
  origin: REQUIREMENT_ORIGIN.optional().describe(
507
- "Only for requirements decided outside the evidence loop (tender, regulation, contract, customer-need). Required when findingIds is empty."
540
+ "Where a requirement decided outside the evidence loop comes from (tender, regulation, contract, customer-need). Optional."
508
541
  ),
509
542
  originNote: z.string().trim().max(300).optional().describe('Where the decision comes from, e.g. "Region North tender 2026, section 4.2".'),
510
543
  productArea: area
@@ -633,6 +666,18 @@ function writeConfig(root, config) {
633
666
  mkdirSync(join(root, DIR), { recursive: true });
634
667
  writeFileSync(configPath(root), CONFIG_HEADER + YAML.stringify(config, { lineWidth: 0 }));
635
668
  }
669
+ function appendToConfig(root, add) {
670
+ const file = configPath(root);
671
+ const doc = YAML.parseDocument(readFileSync(file, "utf8"));
672
+ for (const key of ["productAreas", "products"]) {
673
+ const values = add[key];
674
+ if (!values?.length) continue;
675
+ if (!YAML.isSeq(doc.get(key))) doc.set(key, doc.createNode([]));
676
+ const seq = doc.get(key);
677
+ for (const v of values) seq.add(doc.createNode(v));
678
+ }
679
+ writeFileSync(file, doc.toString({ lineWidth: 0 }));
680
+ }
636
681
  function gitEmail(root) {
637
682
  try {
638
683
  return execFileSync("git", ["config", "user.email"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
@@ -818,7 +863,7 @@ var STORED = {
818
863
  hypothesis: hypothesisInput.extend({ status: HYPOTHESIS_STATUS, knowWhen: z3.string().optional() }).loose(),
819
864
  experiment: experimentInput.extend({ status: EXPERIMENT_STATUS }).loose(),
820
865
  finding: findingInput.loose(),
821
- requirement: requirementInput.extend({ status: REQUIREMENT_STATUS, acceptanceCriteria: z3.array(z3.string()).default([]) }).loose()
866
+ requirement: requirementInput.extend({ kind: REQUIREMENT_KIND.optional(), status: REQUIREMENT_STATUS, acceptanceCriteria: z3.array(z3.string()).default([]) }).loose()
822
867
  };
823
868
  function validate(loaded, config) {
824
869
  const out = loaded.problems.map((p) => ({ level: "error", ...p }));
@@ -871,8 +916,14 @@ function validate(loaded, config) {
871
916
  const t = s.requirements.find((x) => x.id === id);
872
917
  if (t && kindOf(t) !== "stakeholder") err(`stakeholderIds: ${id} is a solution requirement, not a stakeholder requirement`);
873
918
  }
874
- if (r.stakeholderIds?.length && kindOf(r) === "stakeholder") err("stakeholderIds is only for solution requirements");
875
- if (!r.findingIds?.length && !r.origin) err("needs findingIds, or an origin (tender, regulation, contract, customer-need) if it was decided elsewhere");
919
+ if (isActive(r)) {
920
+ const problem = layerProblem(r);
921
+ if (problem) err(problem);
922
+ if (kindOf(r) === "stakeholder" && !fulfilledBy(r.id, s.requirements).length) {
923
+ warn("not yet fulfilled by any solution requirement");
924
+ }
925
+ wordingWarnings(r).forEach(warn);
926
+ }
876
927
  if (r.product && config.products.length && !config.products.includes(r.product)) warn(`product "${r.product}" isn't in config.yml products`);
877
928
  if (r.approver && !people.has(r.approver)) warn(`approver "${r.approver}" isn't in config.yml people`);
878
929
  break;
@@ -887,7 +938,58 @@ function validate(loaded, config) {
887
938
  import { randomUUID } from "crypto";
888
939
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
889
940
  import { z as z4 } from "zod";
890
- var VERSION = true ? "0.2.0" : "0.0.0-dev";
941
+
942
+ // src/core/workspace.ts
943
+ var WorkspaceError = class extends Error {
944
+ };
945
+ var SLUG_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
946
+ function slugify(label) {
947
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
948
+ }
949
+ var same = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
950
+ function mergeAreas(existing, input) {
951
+ const list = [...existing];
952
+ const added = [];
953
+ const alreadyThere = [];
954
+ for (const raw of input) {
955
+ const label = raw.label.trim();
956
+ const given = raw.id?.trim();
957
+ const id = given ?? slugify(label);
958
+ if (!id) throw new WorkspaceError(`"${label}" has no letters or digits to make an id from. Give an id (lowercase letters, digits and dashes).`);
959
+ if (!SLUG_ID.test(id)) throw new WorkspaceError(`"${id}" isn't a valid area id: use up to 40 lowercase letters, digits and dashes, starting with a letter or digit.`);
960
+ const byLabel = list.find((a) => same(a.label, label));
961
+ if (byLabel) {
962
+ alreadyThere.push(byLabel);
963
+ continue;
964
+ }
965
+ const byId = list.find((a) => a.id === id);
966
+ if (byId) throw new WorkspaceError(`"${label}" would get the id "${id}", which "${byId.label}" already uses. Give a different id.`);
967
+ const area2 = { id, label };
968
+ list.push(area2);
969
+ added.push(area2);
970
+ }
971
+ return { list, added, alreadyThere };
972
+ }
973
+ function mergeProducts(existing, input) {
974
+ const list = [...existing];
975
+ const added = [];
976
+ const alreadyThere = [];
977
+ for (const raw of input) {
978
+ const name = raw.trim();
979
+ if (!name) throw new WorkspaceError("A product name can't be empty.");
980
+ const hit = list.find((p) => same(p, name));
981
+ if (hit) {
982
+ alreadyThere.push(hit);
983
+ continue;
984
+ }
985
+ list.push(name);
986
+ added.push(name);
987
+ }
988
+ return { list, added, alreadyThere };
989
+ }
990
+
991
+ // src/mcp/server.ts
992
+ var VERSION = true ? "0.4.0" : "0.0.0-dev";
891
993
  var { insightInput: insightInput2, hypothesisInput: hypothesisInput2, experimentInput: experimentInput2, findingInput: findingInput2, requirementInput: requirementInput2, PATCHES } = localSchemas;
892
994
  var INSTRUCTIONS = `Groundwork keeps this product's evidence and decisions as linked Markdown files in the groundwork/ folder, as a chain:
893
995
  insight -> hypothesis -> experiment -> finding -> requirement.
@@ -896,15 +998,33 @@ insight -> hypothesis -> experiment -> finding -> requirement.
896
998
  - Hypothesis: "We believe we will [outcome] if [forWhom] get [benefit] with [feature]", built on insights (insightIds), ideally with a successMetric (baseline, target, timeframe).
897
999
  - Experiment: tests exactly one hypothesis (hypothesisId) with one primary metric and optional guardrails. Lifecycle: planned -> start_experiment -> record_experiment_results (Groundwork computes the verdict and updates the hypothesis).
898
1000
  - Finding: what was learned, linked to the experiments, hypotheses and insights behind it.
899
- - Requirement: "stakeholder" (a need, in the stakeholder's words) or "solution" (what the product must do). Justified by findingIds, or, when decided elsewhere, by an origin (tender, regulation, contract, customer-need).
1001
+ - Requirement, in two layers, written before building:
1002
+ - "stakeholder": who needs what and why, as a user story: "As a <role> I want <need> so that <reason>".
1003
+ - "solution": the qualities and behaviour the solution must have, as "shall" statements: "The <system or part> shall \u2026". Every solution requirement fulfils at least one stakeholder requirement (stakeholderIds); one stakeholder requirement is usually fulfilled by several solution requirements.
1004
+ Add the stakeholder requirements first, then the solution requirements that reference their ids. Link findingIds, insightIds or an origin (tender, regulation, contract, customer-need) when there is evidence or an outside source; they're optional.
900
1005
 
901
1006
  How to work:
902
- 1. Call get_workspace first: it gives product areas, products and people (for approvers).
1007
+ 1. 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.
903
1008
  2. Before creating anything, search_items for duplicates and for evidence to link. Prefer linking to existing items over creating near-duplicates.
904
- 3. Always link evidence: hypotheses to insights, experiments to a hypothesis, findings to experiments/hypotheses/insights, requirements to findings.
1009
+ 3. Always link evidence: hypotheses to insights, experiments to a hypothesis, findings to experiments/hypotheses/insights, solution requirements to the stakeholder requirements they fulfil, and requirements to findings when there are any.
905
1010
  4. Ask the user before deleting items or approving requirements, unless they already told you to.
906
1011
  5. Use these tools rather than editing the files directly: they keep ids unique and links valid. Each result includes the item's file: mention it so the user can open it.
907
- 6. The Markdown body under an item's frontmatter is the user's own notes. Read it, but don't overwrite it.`;
1012
+ 6. The Markdown body under an item's frontmatter is the user's own notes. Read it, but don't overwrite it.
1013
+
1014
+ When you plan work (a plan, plan mode, or a step in an autonomous workflow):
1015
+ 1. Classify the task first. If unsure, search_items for related requirements.
1016
+ - New need: something users can't do today, e.g. "Let's add a feature to book appointments".
1017
+ - Change: existing behaviour that should work differently.
1018
+ - Fix: restores intended behaviour, e.g. "This path is broken, fix it". Refactors and dependency bumps count as fixes.
1019
+ 2. State the call in one line of the plan, e.g. "New need: adds 2 stakeholder and 4 solution requirements" or "Bug fix under REQ-0007; no requirement changes".
1020
+ 3. New need: the plan's first steps add the stakeholder requirements, then the solution requirements that fulfil them, before writing code.
1021
+ 4. Change: update the requirement with update_item if it's a draft. If it's approved, add a new one, and once that's agreed make the old one obsolete with obsolete_requirement and replacedBy.
1022
+ 5. Fix: don't write requirements. Name the requirement the fix restores when you can tell.
1023
+ 6. With no person to review the plan (an autonomous workflow), follow your own call. The one-line call stays in the plan as the record.
1024
+ 7. When the workflow creates tickets or user stories, use the solution requirements and the stakeholder stories they fulfil as a source. Put the REQ ids and each requirement's file path in the ticket. By default, one ticket per solution requirement.
1025
+ 8. Approval given outside Groundwork (e.g. verbally by a PM): record it with approve_requirement, passing approvedBy and a note. Only do this when the user tells you who approved it.
1026
+
1027
+ Recording evidence or requirements directly isn't planning work. A product manager logging interview notes, drafting hypotheses, recording experiment results or writing requirements gets no new need / change / fix call: record what they ask for with the tools above.`;
908
1028
  var UserError = class extends Error {
909
1029
  };
910
1030
  var an = (kind) => `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind}`;
@@ -982,7 +1102,7 @@ var Session = class {
982
1102
  const a = this.config.productAreas.find((x) => x.id === value || x.label.toLowerCase() === value.trim().toLowerCase());
983
1103
  if (!a) {
984
1104
  const known = this.config.productAreas.map((x) => x.label).join(", ") || "none defined";
985
- throw new UserError(`Unknown product area "${value}". Areas in groundwork/config.yml: ${known}. Add it there first, or leave it out.`);
1105
+ throw new UserError(`Unknown product area "${value}". Areas in groundwork/config.yml: ${known}. Add it with add_product_areas, or leave it out.`);
986
1106
  }
987
1107
  return a.id;
988
1108
  }
@@ -1034,15 +1154,39 @@ function buildServer({ root }) {
1034
1154
  return fail(e instanceof UserError ? e.message : `Groundwork couldn't read the project: ${e.message}`);
1035
1155
  }
1036
1156
  };
1037
- const write = (fn) => async (args) => {
1157
+ const refusal = (s) => {
1158
+ if (s.config.migrated) {
1159
+ return `This folder was imported into the Groundwork web app (${s.config.migrated}), which is now where changes go. Connect its MCP server instead (Groundwork \u2192 Settings \u2192 Connect an agent). These files are kept as a read-only record.`;
1160
+ }
1161
+ if (!s.canEdit()) return `${s.actor.person?.name ?? s.actor.id} is a viewer in groundwork/config.yml, so this agent can't change anything.`;
1162
+ return void 0;
1163
+ };
1164
+ const writeConfigOnly = (fn) => async (args) => {
1038
1165
  try {
1039
1166
  const s = open();
1040
- if (s.config.migrated) {
1041
- return fail(
1042
- `This folder was imported into the Groundwork web app (${s.config.migrated}), which is now where changes go. Connect its MCP server instead (Groundwork \u2192 Settings \u2192 Connect an agent). These files are kept as a read-only record.`
1043
- );
1167
+ const refused = refusal(s);
1168
+ if (refused) return fail(refused);
1169
+ const { add, result } = fn(s, args);
1170
+ if (!isInitialized(root)) {
1171
+ writeConfig(root, {
1172
+ ...s.config,
1173
+ productAreas: [...s.config.productAreas, ...add.productAreas ?? []],
1174
+ products: [...s.config.products, ...add.products ?? []]
1175
+ });
1176
+ } else if (add.productAreas?.length || add.products?.length) {
1177
+ appendToConfig(root, add);
1044
1178
  }
1045
- if (!s.canEdit()) return fail(`${s.actor.person?.name ?? s.actor.id} is a viewer in groundwork/config.yml, so this agent can't change anything.`);
1179
+ return ok({ ...result, file: "groundwork/config.yml" });
1180
+ } catch (e) {
1181
+ if (e instanceof UserError || e instanceof WorkspaceError) return fail(e.message);
1182
+ return fail(`Groundwork couldn't save that: ${e.message}`);
1183
+ }
1184
+ };
1185
+ const write = (fn) => async (args) => {
1186
+ try {
1187
+ const s = open();
1188
+ const refused = refusal(s);
1189
+ if (refused) return fail(refused);
1046
1190
  if (!isInitialized(root)) writeConfig(root, s.config);
1047
1191
  const { state, result } = fn(s, s.loaded.items, s.ctx(), args);
1048
1192
  const { items, renamed } = assignIds(s.loaded.items, state);
@@ -1137,6 +1281,16 @@ function buildServer({ root }) {
1137
1281
  for (const k of KIND.options) {
1138
1282
  for (const item of items[COLLECTIONS[k]]) if (outgoing(k, item).includes(id)) linkedFrom.push(s.summary(k, item));
1139
1283
  }
1284
+ if (hit.kind === "requirement" && kindOf(hit.item) === "stakeholder") {
1285
+ const fulfilling = fulfilledBy(id, items.requirements).map((x) => s.summary("requirement", x));
1286
+ return {
1287
+ item: s.full(hit.kind, hit.item),
1288
+ fulfilledBy: fulfilling,
1289
+ ...fulfilling.length ? {} : { warnings: ["Not yet fulfilled by any solution requirement."] },
1290
+ linksTo,
1291
+ linkedFrom
1292
+ };
1293
+ }
1140
1294
  return { item: s.full(hit.kind, hit.item), linksTo, linkedFrom };
1141
1295
  })
1142
1296
  );
@@ -1210,26 +1364,30 @@ function buildServer({ root }) {
1210
1364
  "add_requirements",
1211
1365
  {
1212
1366
  title: "Add requirements",
1213
- description: "Add stakeholder or solution requirements as drafts. Link findingIds when they come from evidence; otherwise give an origin (tender, regulation, contract, customer-need). To ask for sign-off afterwards, use submit_requirement_for_approval.",
1367
+ description: 'Add requirements as drafts. Stakeholder requirements are user stories ("As a <role> I want <need> so that <reason>"). Solution requirements are "shall" statements and must list the stakeholder requirements they fulfil in stakeholderIds, so add the stakeholder requirements first, in an earlier call. findingIds, insightIds and origin are optional evidence. The result lists wording warnings, if any. To ask for sign-off afterwards, use submit_requirement_for_approval.',
1214
1368
  inputSchema: { requirements: z4.array(requirementInput2).min(1).max(30) }
1215
1369
  },
1216
1370
  write((s, state, c, { requirements }) => {
1217
1371
  let next = state;
1218
1372
  const created = [];
1219
1373
  const derived = [];
1374
+ const warnings = [];
1220
1375
  for (const r of requirements) {
1376
+ const problem = layerProblem(r);
1377
+ if (problem) throw new UserError(`"${r.title}": ${problem}.`);
1378
+ wordingWarnings(r).forEach((w) => warnings.push(`"${r.title}": ${w}.`));
1221
1379
  s.check(state, "finding", r.findingIds, "findingIds");
1222
1380
  s.check(state, "insight", r.insightIds, "insightIds");
1223
1381
  s.check(state, "hypothesis", r.hypothesisIds, "hypothesisIds");
1224
1382
  s.checkStakeholders(state, r.stakeholderIds);
1225
- if (r.product && s.config.products.length && !s.config.products.includes(r.product)) {
1226
- throw new UserError(`Unknown product "${r.product}". Products in groundwork/config.yml: ${s.config.products.join(", ")}.`);
1383
+ const product = r.product && s.config.products.find((p) => p.toLowerCase() === r.product.toLowerCase());
1384
+ if (r.product && s.config.products.length && !product) {
1385
+ throw new UserError(`Unknown product "${r.product}". Products in groundwork/config.yml: ${s.config.products.join(", ")}. Add it with add_products, or leave it out.`);
1227
1386
  }
1228
- const base = { ...r, productArea: s.area(r.productArea), aiGenerated: true };
1387
+ const base = { ...r, ...product ? { product } : {}, productArea: s.area(r.productArea), aiGenerated: true };
1229
1388
  if (r.findingIds.length) {
1230
1389
  derived.push(base);
1231
1390
  } else {
1232
- if (!r.origin) throw new UserError(`"${r.title}": link findingIds, or give an origin for a requirement decided elsewhere.`);
1233
1391
  const { findingIds: _unused, ...direct } = base;
1234
1392
  void _unused;
1235
1393
  const [after, one] = apply(next, createRequirement(next, c, { ...direct, status: "draft" }));
@@ -1242,7 +1400,38 @@ function buildServer({ root }) {
1242
1400
  next = after;
1243
1401
  created.push(...many);
1244
1402
  }
1245
- return { state: next, result: { created: created.map((x) => s.summary("requirement", x)) } };
1403
+ return { state: next, result: { created: created.map((x) => s.summary("requirement", x)), ...warnings.length ? { warnings } : {} } };
1404
+ })
1405
+ );
1406
+ server.registerTool(
1407
+ "add_product_areas",
1408
+ {
1409
+ title: "Add product areas",
1410
+ description: "Add product areas to groundwork/config.yml so items can be tagged with them. Give labels; ids are made from them unless you pass one. Areas already there are skipped. Check get_workspace first and reuse an existing area rather than adding a near-duplicate. Can't rename or remove areas: those are edits to config.yml.",
1411
+ inputSchema: {
1412
+ areas: z4.array(
1413
+ z4.object({
1414
+ label: z4.string().trim().min(1).max(100),
1415
+ id: z4.string().trim().max(40).optional().describe("Optional: lowercase letters, digits and dashes. Made from the label if left out.")
1416
+ })
1417
+ ).min(1).max(20)
1418
+ }
1419
+ },
1420
+ writeConfigOnly((s, { areas }) => {
1421
+ const { list, added, alreadyThere } = mergeAreas(s.config.productAreas, areas);
1422
+ return { add: { productAreas: added }, result: { added, alreadyThere, productAreas: list } };
1423
+ })
1424
+ );
1425
+ server.registerTool(
1426
+ "add_products",
1427
+ {
1428
+ title: "Add products",
1429
+ description: "Add products to groundwork/config.yml so requirements can name them. Products already there are skipped. Check get_workspace first and reuse an existing name rather than adding a near-duplicate.",
1430
+ inputSchema: { products: z4.array(z4.string().trim().min(1).max(100)).min(1).max(20) }
1431
+ },
1432
+ writeConfigOnly((s, { products }) => {
1433
+ const { list, added, alreadyThere } = mergeProducts(s.config.products, products);
1434
+ return { add: { products: added }, result: { added, alreadyThere, products: list } };
1246
1435
  })
1247
1436
  );
1248
1437
  server.registerTool(
@@ -1260,6 +1449,7 @@ function buildServer({ root }) {
1260
1449
  const p = parsed.data;
1261
1450
  if (!Object.keys(p).length) throw new UserError("The patch has no fields to change.");
1262
1451
  if ("productArea" in p) p.productArea = s.area(p.productArea);
1452
+ const warnings = [];
1263
1453
  let change;
1264
1454
  switch (hit.kind) {
1265
1455
  case "insight":
@@ -1293,13 +1483,23 @@ function buildServer({ root }) {
1293
1483
  s.check(state, "insight", p.insightIds, "insightIds");
1294
1484
  s.check(state, "hypothesis", p.hypothesisIds, "hypothesisIds");
1295
1485
  s.checkStakeholders(state, p.stakeholderIds);
1486
+ const merged = { ...r, ...p };
1487
+ const problem = layerProblem(merged);
1488
+ if (problem) throw new UserError(`"${merged.title}": ${problem}.`);
1489
+ if (kindOf(r) === "stakeholder" && kindOf(merged) === "solution") {
1490
+ const fulfilling = fulfilledBy(id, state.requirements);
1491
+ if (fulfilling.length) {
1492
+ throw new UserError(`"${r.title}" is fulfilled by ${fulfilling.map((x) => x.id).join(", ")}, so it can't become a solution requirement.`);
1493
+ }
1494
+ }
1495
+ warnings.push(...wordingWarnings(merged).map((w) => `"${merged.title}": ${w}.`));
1296
1496
  change = updateRequirement(state, id, { ...p, updatedAt: c.now });
1297
1497
  break;
1298
1498
  }
1299
1499
  }
1300
1500
  const [next] = apply(state, change);
1301
1501
  const updated = find(next, id);
1302
- return { state: next, result: { updated: s.full(updated.kind, updated.item) } };
1502
+ return { state: next, result: { updated: s.full(updated.kind, updated.item), ...warnings.length ? { warnings } : {} } };
1303
1503
  })
1304
1504
  );
1305
1505
  server.registerTool(
@@ -1399,13 +1599,36 @@ function buildServer({ root }) {
1399
1599
  "approve_requirement",
1400
1600
  {
1401
1601
  title: "Approve requirement",
1402
- description: "Sign off a requirement that is awaiting your approval. Only the named approver can approve.",
1403
- inputSchema: { id: itemId },
1602
+ description: "Sign off a requirement that is awaiting your approval. Only the named approver can approve. If the approver signed off outside Groundwork (e.g. verbally), pass approvedBy and a note. Groundwork records who entered it.",
1603
+ inputSchema: {
1604
+ id: itemId,
1605
+ approvedBy: z4.string().max(40).optional().describe("Who approved it, when they did so outside Groundwork, e.g. verbally. A person id from get_workspace."),
1606
+ note: z4.string().trim().max(300).optional().describe('How or where it was approved, e.g. "Approved by Maria in sprint planning".')
1607
+ },
1404
1608
  annotations: { destructiveHint: false }
1405
1609
  },
1406
- write((s, state, c, { id }) => {
1610
+ write((s, state, c, { id, approvedBy, note }) => {
1407
1611
  const r = requirementOf(state, id);
1408
- if (r.status !== "awaiting-approval") throw new UserError(`"${r.title}" is ${r.status}, not awaiting approval.`);
1612
+ if (approvedBy && approvedBy !== s.actor.id) {
1613
+ const person = s.config.people.find((m) => m.id === approvedBy);
1614
+ if (!person) throw new UserError(`${approvedBy} isn't in groundwork/config.yml people. Add them there first.`);
1615
+ if (person.role === "viewer") throw new UserError(`${person.name} is a viewer, so they can't approve.`);
1616
+ if (r.status !== "draft" && r.status !== "awaiting-approval") {
1617
+ throw new UserError(`"${r.title}" is ${r.status}; only drafts and requirements awaiting approval can be approved.`);
1618
+ }
1619
+ if (r.approver && r.approver !== approvedBy) {
1620
+ const asked = s.config.people.find((m) => m.id === r.approver)?.name ?? r.approver;
1621
+ throw new UserError(
1622
+ `"${r.title}" is waiting for ${asked}, not ${person.name}. Record ${asked}'s approval, or ask ${asked} to send it back so it can be submitted to ${person.name}.`
1623
+ );
1624
+ }
1625
+ const [next2] = apply(state, approveRequirement(state, c, id, { approvedBy, note }));
1626
+ return { state: next2, result: { approved: s.summary("requirement", requirementOf(next2, id)) } };
1627
+ }
1628
+ if (r.status !== "awaiting-approval") {
1629
+ const hint = r.status === "draft" ? " If someone approved it outside Groundwork, record it with approvedBy." : "";
1630
+ throw new UserError(`"${r.title}" is ${r.status}, not awaiting approval.${hint}`);
1631
+ }
1409
1632
  if (r.approver !== s.actor.id) {
1410
1633
  const name = s.config.people.find((m) => m.id === r.approver)?.name ?? r.approver ?? "someone else";
1411
1634
  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.`);
@@ -1455,6 +1678,14 @@ function buildServer({ root }) {
1455
1678
  write((_s, state, _c, { id }) => {
1456
1679
  const hit = find(state, id);
1457
1680
  if (!hit) throw new UserError(`No item with id ${id}.`);
1681
+ if (hit.kind === "requirement") {
1682
+ const orphaned = fulfilledBy(id, state.requirements).filter((r) => r.stakeholderIds?.length === 1);
1683
+ if (orphaned.length) {
1684
+ throw new UserError(
1685
+ `${orphaned.map((r) => `${r.id} "${r.title}"`).join(", ")} only fulfil${orphaned.length === 1 ? "s" : ""} "${hit.item.title}". Link ${orphaned.length === 1 ? "it" : "them"} to another stakeholder requirement or delete ${orphaned.length === 1 ? "it" : "them"} first.`
1686
+ );
1687
+ }
1688
+ }
1458
1689
  const change = hit.kind === "insight" ? deleteInsight(state, id) : hit.kind === "hypothesis" ? deleteHypothesis(state, id) : hit.kind === "experiment" ? deleteExperiment(state, id) : hit.kind === "finding" ? deleteFinding(state, id) : deleteRequirement(state, id);
1459
1690
  const [next] = apply(state, change);
1460
1691
  const alsoDeleted = hit.kind === "hypothesis" ? state.experiments.filter((e) => e.hypothesisId === id).map((e) => e.id) : [];
@@ -1471,9 +1702,15 @@ export {
1471
1702
  diffCollections,
1472
1703
  kindOf,
1473
1704
  isObsolete,
1705
+ isActive,
1474
1706
  canObsolete,
1475
1707
  canUpdateInPlace,
1476
1708
  canSendToDelivery,
1709
+ STAKEHOLDER_STORY,
1710
+ SOLUTION_STATEMENT,
1711
+ wordingWarnings,
1712
+ fulfilledBy,
1713
+ layerProblem,
1477
1714
  metricPasses,
1478
1715
  computeVerdict,
1479
1716
  fmtMetric,
@@ -1509,6 +1746,7 @@ export {
1509
1746
  ConfigError,
1510
1747
  readConfig,
1511
1748
  writeConfig,
1749
+ appendToConfig,
1512
1750
  resolveActor,
1513
1751
  COLLECTIONS,
1514
1752
  parseItem,
@@ -1521,4 +1759,4 @@ export {
1521
1759
  outgoing,
1522
1760
  buildServer
1523
1761
  };
1524
- //# sourceMappingURL=chunk-5LIKTHEE.js.map
1762
+ //# sourceMappingURL=chunk-TXXV5YDG.js.map