@hegemonart/get-design-done 1.19.5 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/CHANGELOG.md +90 -0
  4. package/README.md +12 -0
  5. package/agents/design-auditor.md +12 -0
  6. package/agents/design-discussant.md +14 -0
  7. package/agents/design-reflector.md +23 -0
  8. package/connections/connections.md +3 -0
  9. package/connections/figma.md +2 -0
  10. package/connections/gdd-state.md +186 -0
  11. package/hooks/budget-enforcer.ts +716 -0
  12. package/hooks/context-exhaustion.ts +251 -0
  13. package/hooks/gdd-read-injection-scanner.ts +172 -0
  14. package/hooks/hooks.json +3 -3
  15. package/package.json +29 -7
  16. package/reference/authority-feeds.md +4 -2
  17. package/reference/checklists.md +30 -0
  18. package/reference/component-authoring.md +184 -0
  19. package/reference/config-schema.md +2 -2
  20. package/reference/emotional-design.md +124 -0
  21. package/reference/error-recovery.md +58 -0
  22. package/reference/first-principles.md +89 -0
  23. package/reference/heuristics.md +70 -0
  24. package/reference/motion-advanced.md +192 -3
  25. package/reference/registry.json +28 -0
  26. package/reference/schemas/budget.schema.json +42 -0
  27. package/reference/schemas/events.schema.json +55 -0
  28. package/reference/schemas/generated.d.ts +419 -0
  29. package/reference/schemas/iteration-budget.schema.json +36 -0
  30. package/reference/schemas/mcp-gdd-state-tools.schema.json +89 -0
  31. package/reference/schemas/rate-limits.schema.json +31 -0
  32. package/reference/shared-preamble.md +10 -0
  33. package/scripts/aggregate-agent-metrics.ts +282 -0
  34. package/scripts/codegen-schema-types.ts +149 -0
  35. package/scripts/lib/error-classifier.cjs +232 -0
  36. package/scripts/lib/error-classifier.d.cts +44 -0
  37. package/scripts/lib/event-stream/emitter.ts +88 -0
  38. package/scripts/lib/event-stream/index.ts +154 -0
  39. package/scripts/lib/event-stream/types.ts +127 -0
  40. package/scripts/lib/event-stream/writer.ts +154 -0
  41. package/scripts/lib/gdd-errors/classification.ts +124 -0
  42. package/scripts/lib/gdd-errors/index.ts +218 -0
  43. package/scripts/lib/gdd-state/gates.ts +216 -0
  44. package/scripts/lib/gdd-state/index.ts +167 -0
  45. package/scripts/lib/gdd-state/lockfile.ts +232 -0
  46. package/scripts/lib/gdd-state/mutator.ts +574 -0
  47. package/scripts/lib/gdd-state/parser.ts +523 -0
  48. package/scripts/lib/gdd-state/types.ts +179 -0
  49. package/scripts/lib/iteration-budget.cjs +205 -0
  50. package/scripts/lib/iteration-budget.d.cts +32 -0
  51. package/scripts/lib/jittered-backoff.cjs +112 -0
  52. package/scripts/lib/jittered-backoff.d.cts +38 -0
  53. package/scripts/lib/lockfile.cjs +177 -0
  54. package/scripts/lib/lockfile.d.cts +21 -0
  55. package/scripts/lib/prompt-sanitizer/index.ts +435 -0
  56. package/scripts/lib/prompt-sanitizer/patterns.ts +173 -0
  57. package/scripts/lib/rate-guard.cjs +365 -0
  58. package/scripts/lib/rate-guard.d.cts +38 -0
  59. package/scripts/mcp-servers/gdd-state/schemas/add_blocker.schema.json +67 -0
  60. package/scripts/mcp-servers/gdd-state/schemas/add_decision.schema.json +68 -0
  61. package/scripts/mcp-servers/gdd-state/schemas/add_must_have.schema.json +68 -0
  62. package/scripts/mcp-servers/gdd-state/schemas/checkpoint.schema.json +51 -0
  63. package/scripts/mcp-servers/gdd-state/schemas/frontmatter_update.schema.json +62 -0
  64. package/scripts/mcp-servers/gdd-state/schemas/get.schema.json +51 -0
  65. package/scripts/mcp-servers/gdd-state/schemas/probe_connections.schema.json +75 -0
  66. package/scripts/mcp-servers/gdd-state/schemas/resolve_blocker.schema.json +66 -0
  67. package/scripts/mcp-servers/gdd-state/schemas/set_status.schema.json +47 -0
  68. package/scripts/mcp-servers/gdd-state/schemas/transition_stage.schema.json +70 -0
  69. package/scripts/mcp-servers/gdd-state/schemas/update_progress.schema.json +58 -0
  70. package/scripts/mcp-servers/gdd-state/server.ts +288 -0
  71. package/scripts/mcp-servers/gdd-state/tools/add_blocker.ts +72 -0
  72. package/scripts/mcp-servers/gdd-state/tools/add_decision.ts +89 -0
  73. package/scripts/mcp-servers/gdd-state/tools/add_must_have.ts +113 -0
  74. package/scripts/mcp-servers/gdd-state/tools/checkpoint.ts +60 -0
  75. package/scripts/mcp-servers/gdd-state/tools/frontmatter_update.ts +91 -0
  76. package/scripts/mcp-servers/gdd-state/tools/get.ts +51 -0
  77. package/scripts/mcp-servers/gdd-state/tools/index.ts +51 -0
  78. package/scripts/mcp-servers/gdd-state/tools/probe_connections.ts +73 -0
  79. package/scripts/mcp-servers/gdd-state/tools/resolve_blocker.ts +84 -0
  80. package/scripts/mcp-servers/gdd-state/tools/set_status.ts +54 -0
  81. package/scripts/mcp-servers/gdd-state/tools/shared.ts +194 -0
  82. package/scripts/mcp-servers/gdd-state/tools/transition_stage.ts +80 -0
  83. package/scripts/mcp-servers/gdd-state/tools/update_progress.ts +81 -0
  84. package/scripts/validate-frontmatter.ts +114 -0
  85. package/scripts/validate-schemas.ts +401 -0
  86. package/skills/brief/SKILL.md +15 -6
  87. package/skills/design/SKILL.md +31 -13
  88. package/skills/explore/SKILL.md +41 -17
  89. package/skills/health/SKILL.md +15 -4
  90. package/skills/optimize/SKILL.md +3 -3
  91. package/skills/pause/SKILL.md +16 -10
  92. package/skills/plan/SKILL.md +33 -17
  93. package/skills/progress/SKILL.md +15 -11
  94. package/skills/resume/SKILL.md +19 -10
  95. package/skills/settings/SKILL.md +11 -3
  96. package/skills/todo/SKILL.md +12 -3
  97. package/skills/verify/SKILL.md +65 -29
  98. package/hooks/budget-enforcer.js +0 -329
  99. package/hooks/context-exhaustion.js +0 -127
  100. package/hooks/gdd-read-injection-scanner.js +0 -39
  101. package/scripts/aggregate-agent-metrics.js +0 -173
  102. package/scripts/validate-frontmatter.cjs +0 -68
  103. package/scripts/validate-schemas.cjs +0 -242
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env -S node --experimental-strip-types
2
+ // scripts/mcp-servers/gdd-state/server.ts
3
+ //
4
+ // MCP server `gdd-state` — exposes the 11 typed STATE.md tools implemented
5
+ // under `./tools/` via stdio transport. Plan 20-05 (SDK-06/07).
6
+ //
7
+ // Lifecycle:
8
+ // 1. Construct a low-level Server (we use the low-level surface so we
9
+ // can speak JSON Schema directly — the high-level McpServer wants
10
+ // Zod shapes, and our per-tool schemas are Draft-07 JSON.)
11
+ // 2. Register `tools/list` — returns all 11 tools with their input
12
+ // JSON Schemas loaded from disk.
13
+ // 3. Register `tools/call` — dispatches by name to the matching
14
+ // handler. Each handler returns a typed ToolResponse; the server
15
+ // wraps it into the MCP CallToolResult shape (one text content
16
+ // item, JSON-stringified response; plus `structuredContent` for
17
+ // richer clients; `isError: true` when `success:false`).
18
+ // 4. Attach StdioServerTransport; await connect.
19
+ // 5. On SIGINT / SIGTERM: close the transport, flush nothing (the
20
+ // event writer uses `appendFileSync` so every write is already
21
+ // durable), and exit 0.
22
+ //
23
+ // Invariant: handler throws are contained. The dispatcher wraps every
24
+ // call in a try/catch that funnels through toToolError() — the MCP
25
+ // harness never sees an uncaught throw from our tools.
26
+
27
+ import { readFileSync, existsSync } from 'node:fs';
28
+ import { dirname, join, resolve } from 'node:path';
29
+
30
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
31
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
32
+ import {
33
+ CallToolRequestSchema,
34
+ ListToolsRequestSchema,
35
+ } from '@modelcontextprotocol/sdk/types.js';
36
+
37
+ import { toToolError } from '../../lib/gdd-errors/classification.ts';
38
+ import { TOOL_MODULES, type ToolModule } from './tools/index.ts';
39
+
40
+ /** Server metadata advertised on initialize. */
41
+ const SERVER_NAME = 'gdd-state';
42
+ const SERVER_VERSION = '1.20.0';
43
+
44
+ /**
45
+ * Resolve this module's directory. We deliberately avoid `import.meta.url`
46
+ * (not permitted by our tsconfig's Node16+CommonJS-compatible module
47
+ * resolution) and `__dirname` (not portable under strip-types ESM).
48
+ *
49
+ * Strategy: when this module is invoked as a script, `process.argv[1]`
50
+ * points at this file; resolve its dirname. When it is imported for
51
+ * tests, we fall back to walking from `process.cwd()` — tests run
52
+ * from the repo root by convention, so `scripts/mcp-servers/gdd-state`
53
+ * resolves reliably. Both branches are canonicalized against the
54
+ * on-disk tools directory.
55
+ */
56
+ function here(): string {
57
+ const expectedRel = join('scripts', 'mcp-servers', 'gdd-state');
58
+ // Script invocation: process.argv[1] === .../server.ts (or a shim).
59
+ const entry = process.argv[1];
60
+ if (typeof entry === 'string' && entry.length > 0) {
61
+ const entryDir = dirname(resolve(entry));
62
+ if (existsSync(join(entryDir, 'tools', 'index.ts'))) {
63
+ return entryDir;
64
+ }
65
+ }
66
+ // Library-import path (tests): walk cwd forward.
67
+ const candidate = resolve(process.cwd(), expectedRel);
68
+ if (existsSync(join(candidate, 'tools', 'index.ts'))) {
69
+ return candidate;
70
+ }
71
+ // Last-resort: return the expected path even if it does not exist —
72
+ // the subsequent readFileSync() call will produce a clear error.
73
+ return candidate;
74
+ }
75
+
76
+ /** Eager cache of input schemas keyed by tool name. We load them once at
77
+ * startup so a tool-call handler never hits the filesystem in the hot
78
+ * path; subsequent schema edits (JSON file on disk) require a server
79
+ * restart, which matches every other part of the pipeline. */
80
+ interface LoadedTool extends ToolModule {
81
+ inputSchema: Record<string, unknown>;
82
+ }
83
+
84
+ function loadTools(): LoadedTool[] {
85
+ const baseDir = here();
86
+ return TOOL_MODULES.map((m) => {
87
+ const absPath = join(baseDir, 'tools', m.schemaPath);
88
+ const raw = readFileSync(absPath, 'utf8');
89
+ const parsed = JSON.parse(raw) as {
90
+ properties?: {
91
+ input?: { type?: string; properties?: Record<string, unknown> };
92
+ };
93
+ };
94
+ // The per-tool schema files are Draft-07 wrappers shaped as:
95
+ // { type: "object", properties: { input: {...}, output: {...} } }
96
+ // MCP's tools/list advertises only the INPUT half. We project
97
+ // `properties.input` here; when the schema is malformed we fall
98
+ // back to an open object so the tool is still listable.
99
+ const rawInput = parsed.properties?.input;
100
+ const inputSchema: Record<string, unknown> =
101
+ rawInput !== undefined && typeof rawInput === 'object'
102
+ ? (rawInput as Record<string, unknown>)
103
+ : { type: 'object' };
104
+ // MCP clients require inputSchema.type === "object" for tools/list.
105
+ // Our per-tool inputs are already objects; defensively stamp the
106
+ // field when absent.
107
+ if (!('type' in inputSchema)) inputSchema['type'] = 'object';
108
+ return { ...m, inputSchema };
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Tool descriptions — short, scannable, lifted from the plan. Skill
114
+ * prose uses these verbatim when suggesting a tool to the model.
115
+ */
116
+ const TOOL_DESCRIPTIONS: Record<string, string> = {
117
+ gdd_state__get:
118
+ 'Read current STATE.md (parsed). Read-only; no event emitted. Optionally projects a subset of fields.',
119
+ gdd_state__update_progress:
120
+ 'Update <position>.task_progress and/or status. Emits state.mutation.',
121
+ gdd_state__transition_stage:
122
+ 'Run gate and advance <position>.stage on pass. Gate vetoes return {success:false, error:{context:{blockers:[...]}}}; never crashes the server. Emits state.transition.',
123
+ gdd_state__add_blocker:
124
+ 'Append one entry to <blockers>. Defaults stage to current position.stage and date to today (UTC). Emits state.mutation.',
125
+ gdd_state__resolve_blocker:
126
+ 'Remove one <blockers> entry by 0-based index or exact text match. Returns operation_failed when no row matches. Emits state.mutation on removal.',
127
+ gdd_state__add_decision:
128
+ 'Append one entry to <decisions>. Auto-allocates D-N id when not supplied. Emits state.mutation.',
129
+ gdd_state__add_must_have:
130
+ 'Append one entry to <must_haves>. Auto-allocates M-N id when not supplied. Emits state.mutation.',
131
+ gdd_state__set_status:
132
+ 'Update <position>.status. Emits state.mutation.',
133
+ gdd_state__checkpoint:
134
+ 'Update frontmatter.last_checkpoint and append a <timestamps> entry. Emits state.mutation.',
135
+ gdd_state__probe_connections:
136
+ 'Merge probe results into <connections>. Overwrites keys present in the input; does NOT delete keys not in the input. Emits state.mutation.',
137
+ gdd_state__frontmatter_update:
138
+ 'Patch one or more frontmatter fields. Rejects pipeline_state_version and stage (use transition_stage). Emits state.mutation.',
139
+ };
140
+
141
+ /** Human-readable annotation hints (MCP clients use these to style the
142
+ * tool in UI). `readOnlyHint: true` — tells clients this tool does NOT
143
+ * modify disk; `false` — tells them it does. */
144
+ const TOOL_READONLY: Record<string, boolean> = {
145
+ gdd_state__get: true,
146
+ };
147
+
148
+ /**
149
+ * Build the MCP server. The tools list and call handlers are the only
150
+ * two request handlers we register; everything else (initialize, ping,
151
+ * cancellation, shutdown) is handled internally by the Protocol class.
152
+ */
153
+ export function buildServer(): Server {
154
+ const tools = loadTools();
155
+ const byName: Map<string, LoadedTool> = new Map();
156
+ for (const t of tools) byName.set(t.name, t);
157
+
158
+ const server = new Server(
159
+ { name: SERVER_NAME, version: SERVER_VERSION },
160
+ {
161
+ capabilities: { tools: {} },
162
+ },
163
+ );
164
+
165
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
166
+ return {
167
+ tools: tools.map((t) => {
168
+ const description = TOOL_DESCRIPTIONS[t.name] ?? t.name;
169
+ const readOnly = TOOL_READONLY[t.name] ?? false;
170
+ return {
171
+ name: t.name,
172
+ description,
173
+ inputSchema: t.inputSchema as {
174
+ type: 'object';
175
+ properties?: Record<string, unknown>;
176
+ required?: string[];
177
+ },
178
+ annotations: {
179
+ readOnlyHint: readOnly,
180
+ destructiveHint: !readOnly,
181
+ idempotentHint: false,
182
+ },
183
+ };
184
+ }),
185
+ };
186
+ });
187
+
188
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
189
+ const { name: toolName, arguments: args } = req.params;
190
+ const tool = byName.get(toolName);
191
+ if (tool === undefined) {
192
+ // Unknown tool — return as CallToolResult isError=true so the
193
+ // client gets a structured error rather than a JSON-RPC error.
194
+ const payload = toToolError(
195
+ new Error(`unknown tool: ${toolName}`),
196
+ );
197
+ return {
198
+ isError: true,
199
+ content: [
200
+ { type: 'text' as const, text: JSON.stringify({ success: false, error: payload.error }) },
201
+ ],
202
+ structuredContent: { success: false, error: payload.error },
203
+ };
204
+ }
205
+
206
+ let response;
207
+ try {
208
+ response = await tool.handle(args ?? {});
209
+ } catch (err) {
210
+ // Defensive catch — handlers shouldn't throw, but if one does
211
+ // we translate rather than crashing the server.
212
+ const payload = toToolError(err);
213
+ response = { success: false as const, error: payload.error };
214
+ }
215
+
216
+ const text = JSON.stringify(response);
217
+ if (response.success === true) {
218
+ return {
219
+ content: [{ type: 'text' as const, text }],
220
+ structuredContent: response as unknown as Record<string, unknown>,
221
+ };
222
+ }
223
+ return {
224
+ isError: true,
225
+ content: [{ type: 'text' as const, text }],
226
+ structuredContent: response as unknown as Record<string, unknown>,
227
+ };
228
+ });
229
+
230
+ return server;
231
+ }
232
+
233
+ /**
234
+ * Run the server against stdio and block until the transport closes.
235
+ * Called from CLI when this file is invoked as a script.
236
+ */
237
+ export async function runStdio(): Promise<void> {
238
+ const server = buildServer();
239
+ const transport = new StdioServerTransport();
240
+
241
+ const shutdown = async (signal: string): Promise<void> => {
242
+ // Re-entrant: signal handlers can fire more than once on flaky
243
+ // shells. Guard with a module-level flag.
244
+ if (SHUTTING_DOWN) return;
245
+ SHUTTING_DOWN = true;
246
+ try {
247
+ await server.close();
248
+ } catch {
249
+ // best-effort; we're exiting anyway.
250
+ }
251
+ // SIGTERM / SIGINT convention: exit(0) — orderly shutdown.
252
+ process.exit(signal === 'SIGTERM' ? 0 : 0);
253
+ };
254
+
255
+ process.on('SIGINT', () => {
256
+ void shutdown('SIGINT');
257
+ });
258
+ process.on('SIGTERM', () => {
259
+ void shutdown('SIGTERM');
260
+ });
261
+
262
+ await server.connect(transport);
263
+ }
264
+
265
+ /** Re-entrancy guard for `shutdown()`. */
266
+ let SHUTTING_DOWN = false;
267
+
268
+ /**
269
+ * Are we being invoked as a script? We compare the argv[1] file path's
270
+ * basename to `server.ts` — test imports never match this because
271
+ * `node --test tests/*.ts` sets argv[1] to the test runner entry, not
272
+ * our file. A direct `node scripts/mcp-servers/gdd-state/server.ts`
273
+ * invocation DOES match.
274
+ */
275
+ function isMain(): boolean {
276
+ const entry = process.argv[1];
277
+ if (typeof entry !== 'string' || entry.length === 0) return false;
278
+ return entry.replace(/\\/g, '/').endsWith('scripts/mcp-servers/gdd-state/server.ts');
279
+ }
280
+
281
+ if (isMain()) {
282
+ runStdio().catch((err) => {
283
+ const msg = err instanceof Error ? err.message : String(err);
284
+ // eslint-disable-next-line no-console
285
+ console.error(`[gdd-state] fatal: ${msg}`);
286
+ process.exit(1);
287
+ });
288
+ }
@@ -0,0 +1,72 @@
1
+ // scripts/mcp-servers/gdd-state/tools/add_blocker.ts
2
+ //
3
+ // Tool: gdd_state__add_blocker
4
+ // Purpose: Append one entry to <blockers>. Defaults the stage to the
5
+ // current <position>.stage and the date to today (UTC) when omitted.
6
+ // Emits state.mutation on success.
7
+
8
+ import { mutate } from '../../../lib/gdd-state/index.ts';
9
+ import type { Blocker } from '../../../lib/gdd-state/types.ts';
10
+ import {
11
+ emitStateMutation,
12
+ errorResponse,
13
+ okResponse,
14
+ resolveStatePath,
15
+ throwValidation,
16
+ type ToolResponse,
17
+ } from './shared.ts';
18
+
19
+ export const name = 'gdd_state__add_blocker';
20
+ export const schemaPath = '../schemas/add_blocker.schema.json';
21
+
22
+ export interface AddBlockerInput {
23
+ text: string;
24
+ stage?: string;
25
+ date?: string;
26
+ }
27
+
28
+ const DATE_RE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
29
+
30
+ /** Return today's date in YYYY-MM-DD (UTC). */
31
+ function today(): string {
32
+ return new Date().toISOString().slice(0, 10);
33
+ }
34
+
35
+ export async function handle(input: unknown): Promise<ToolResponse> {
36
+ try {
37
+ const typed = (input ?? {}) as AddBlockerInput;
38
+ if (typeof typed.text !== 'string' || typed.text.length === 0) {
39
+ throwValidation('MISSING_FIELD', 'add_blocker requires a non-empty text');
40
+ }
41
+ if (typed.date !== undefined && !DATE_RE.test(typed.date)) {
42
+ throwValidation(
43
+ 'DATE_FORMAT',
44
+ `date "${typed.date}" must be YYYY-MM-DD`,
45
+ );
46
+ }
47
+
48
+ const path = resolveStatePath();
49
+ let appended: Blocker | null = null;
50
+ let countAfter = 0;
51
+ const after = await mutate(path, (s) => {
52
+ const blocker: Blocker = {
53
+ stage: typed.stage ?? s.position.stage ?? '',
54
+ date: typed.date ?? today(),
55
+ text: typed.text,
56
+ };
57
+ s.blockers.push(blocker);
58
+ appended = blocker;
59
+ countAfter = s.blockers.length;
60
+ return s;
61
+ });
62
+ // appended is definitely set because mutate() ran fn(); but TS cannot
63
+ // reason about that — narrow by asserting.
64
+ if (appended === null) {
65
+ throwValidation('INTERNAL', 'blocker was not appended (unreachable)');
66
+ }
67
+ emitStateMutation(name, { appended, count: countAfter }, after);
68
+ return okResponse({ blocker: appended, count: countAfter });
69
+ } catch (err) {
70
+ return errorResponse(err);
71
+ }
72
+ }
@@ -0,0 +1,89 @@
1
+ // scripts/mcp-servers/gdd-state/tools/add_decision.ts
2
+ //
3
+ // Tool: gdd_state__add_decision
4
+ // Purpose: Append one entry to <decisions>. Auto-allocates D-N id by
5
+ // scanning existing decisions when the caller doesn't supply one.
6
+ // Emits state.mutation on success.
7
+
8
+ import { mutate } from '../../../lib/gdd-state/index.ts';
9
+ import type { Decision } from '../../../lib/gdd-state/types.ts';
10
+ import {
11
+ emitStateMutation,
12
+ errorResponse,
13
+ okResponse,
14
+ resolveStatePath,
15
+ throwValidation,
16
+ type ToolResponse,
17
+ } from './shared.ts';
18
+
19
+ export const name = 'gdd_state__add_decision';
20
+ export const schemaPath = '../schemas/add_decision.schema.json';
21
+
22
+ export interface AddDecisionInput {
23
+ text: string;
24
+ status?: 'locked' | 'tentative';
25
+ id?: string;
26
+ }
27
+
28
+ const ID_RE = /^D-([0-9]+)$/;
29
+
30
+ /**
31
+ * Compute the next `D-N` id. The strategy mirrors the existing
32
+ * reference template: take the max numeric suffix seen and add 1.
33
+ * Falls back to `D-1` when the list is empty.
34
+ */
35
+ function nextDecisionId(existing: Decision[]): string {
36
+ let max = 0;
37
+ for (const d of existing) {
38
+ const m = d.id.match(ID_RE);
39
+ if (m && m[1] !== undefined) {
40
+ const n = Number.parseInt(m[1], 10);
41
+ if (Number.isFinite(n) && n > max) max = n;
42
+ }
43
+ }
44
+ return `D-${max + 1}`;
45
+ }
46
+
47
+ export async function handle(input: unknown): Promise<ToolResponse> {
48
+ try {
49
+ const typed = (input ?? {}) as AddDecisionInput;
50
+ if (typeof typed.text !== 'string' || typed.text.length === 0) {
51
+ throwValidation('MISSING_FIELD', 'add_decision requires a non-empty text');
52
+ }
53
+ if (
54
+ typed.status !== undefined &&
55
+ typed.status !== 'locked' &&
56
+ typed.status !== 'tentative'
57
+ ) {
58
+ throwValidation(
59
+ 'STATUS_INVALID',
60
+ `status "${String(typed.status)}" is not one of locked/tentative`,
61
+ );
62
+ }
63
+ if (typed.id !== undefined && !ID_RE.test(typed.id)) {
64
+ throwValidation('ID_FORMAT', `id "${typed.id}" must match D-<digits>`);
65
+ }
66
+
67
+ const path = resolveStatePath();
68
+ let appended: Decision | null = null;
69
+ let countAfter = 0;
70
+ const after = await mutate(path, (s) => {
71
+ const decision: Decision = {
72
+ id: typed.id ?? nextDecisionId(s.decisions),
73
+ text: typed.text,
74
+ status: typed.status ?? 'tentative',
75
+ };
76
+ s.decisions.push(decision);
77
+ appended = decision;
78
+ countAfter = s.decisions.length;
79
+ return s;
80
+ });
81
+ if (appended === null) {
82
+ throwValidation('INTERNAL', 'decision was not appended (unreachable)');
83
+ }
84
+ emitStateMutation(name, { appended, count: countAfter }, after);
85
+ return okResponse({ decision: appended, count: countAfter });
86
+ } catch (err) {
87
+ return errorResponse(err);
88
+ }
89
+ }
@@ -0,0 +1,113 @@
1
+ // scripts/mcp-servers/gdd-state/tools/add_must_have.ts
2
+ //
3
+ // Tool: gdd_state__add_must_have
4
+ // Purpose: Insert-or-update one entry in <must_haves>. Auto-allocates
5
+ // M-N id by scanning existing must_haves when the caller doesn't
6
+ // supply one. When the caller supplies an `id` that already exists,
7
+ // the entry is updated in-place (same position in the block) — this
8
+ // is the canonical "flip a must-have status" idiom used by the verify
9
+ // skill (see skills/verify/SKILL.md "Flipping a must-have status").
10
+ // Emits state.mutation on success with `action: "insert" | "update"`.
11
+
12
+ import { mutate } from '../../../lib/gdd-state/index.ts';
13
+ import type { MustHave } from '../../../lib/gdd-state/types.ts';
14
+ import {
15
+ emitStateMutation,
16
+ errorResponse,
17
+ okResponse,
18
+ resolveStatePath,
19
+ throwValidation,
20
+ type ToolResponse,
21
+ } from './shared.ts';
22
+
23
+ export const name = 'gdd_state__add_must_have';
24
+ export const schemaPath = '../schemas/add_must_have.schema.json';
25
+
26
+ export interface AddMustHaveInput {
27
+ text: string;
28
+ status?: 'pending' | 'pass' | 'fail';
29
+ id?: string;
30
+ }
31
+
32
+ const ID_RE = /^M-([0-9]+)$/;
33
+
34
+ /** Max `M-N` suffix + 1, or `M-1` when the list is empty. */
35
+ function nextMustHaveId(existing: MustHave[]): string {
36
+ let max = 0;
37
+ for (const m of existing) {
38
+ const match = m.id.match(ID_RE);
39
+ if (match && match[1] !== undefined) {
40
+ const n = Number.parseInt(match[1], 10);
41
+ if (Number.isFinite(n) && n > max) max = n;
42
+ }
43
+ }
44
+ return `M-${max + 1}`;
45
+ }
46
+
47
+ export async function handle(input: unknown): Promise<ToolResponse> {
48
+ try {
49
+ const typed = (input ?? {}) as AddMustHaveInput;
50
+ if (typeof typed.text !== 'string' || typed.text.length === 0) {
51
+ throwValidation(
52
+ 'MISSING_FIELD',
53
+ 'add_must_have requires a non-empty text',
54
+ );
55
+ }
56
+ if (
57
+ typed.status !== undefined &&
58
+ typed.status !== 'pending' &&
59
+ typed.status !== 'pass' &&
60
+ typed.status !== 'fail'
61
+ ) {
62
+ throwValidation(
63
+ 'STATUS_INVALID',
64
+ `status "${String(typed.status)}" is not one of pending/pass/fail`,
65
+ );
66
+ }
67
+ if (typed.id !== undefined && !ID_RE.test(typed.id)) {
68
+ throwValidation('ID_FORMAT', `id "${typed.id}" must match M-<digits>`);
69
+ }
70
+
71
+ const path = resolveStatePath();
72
+ let written: MustHave | null = null;
73
+ let action: 'insert' | 'update' = 'insert';
74
+ let countAfter = 0;
75
+ const after = await mutate(path, (s) => {
76
+ const mh: MustHave = {
77
+ id: typed.id ?? nextMustHaveId(s.must_haves),
78
+ text: typed.text,
79
+ status: typed.status ?? 'pending',
80
+ };
81
+ // Update-in-place when the caller supplied an id that already
82
+ // exists — preserves the entry's position in the <must_haves>
83
+ // block. This is the canonical idiom the verify skill relies on
84
+ // to flip `pending` → `pass`/`fail` without a dedicated
85
+ // update_must_have_status tool.
86
+ const existingIdx =
87
+ typed.id !== undefined
88
+ ? s.must_haves.findIndex((existing) => existing.id === mh.id)
89
+ : -1;
90
+ if (existingIdx >= 0) {
91
+ s.must_haves[existingIdx] = mh;
92
+ action = 'update';
93
+ } else {
94
+ s.must_haves.push(mh);
95
+ action = 'insert';
96
+ }
97
+ written = mh;
98
+ countAfter = s.must_haves.length;
99
+ return s;
100
+ });
101
+ if (written === null) {
102
+ throwValidation('INTERNAL', 'must_have was not written (unreachable)');
103
+ }
104
+ emitStateMutation(
105
+ name,
106
+ { must_have: written, action, count: countAfter },
107
+ after,
108
+ );
109
+ return okResponse({ must_have: written, action, count: countAfter });
110
+ } catch (err) {
111
+ return errorResponse(err);
112
+ }
113
+ }
@@ -0,0 +1,60 @@
1
+ // scripts/mcp-servers/gdd-state/tools/checkpoint.ts
2
+ //
3
+ // Tool: gdd_state__checkpoint
4
+ // Purpose: Update frontmatter.last_checkpoint and append an entry in
5
+ // <timestamps>. The timestamp key is `<label>_at` when `input.label` is
6
+ // supplied, otherwise `<stage>_checkpoint_at` falling back to
7
+ // `checkpoint_at` if the position.stage is empty. Emits state.mutation.
8
+
9
+ import { mutate } from '../../../lib/gdd-state/index.ts';
10
+ import {
11
+ emitStateMutation,
12
+ errorResponse,
13
+ okResponse,
14
+ resolveStatePath,
15
+ throwValidation,
16
+ type ToolResponse,
17
+ } from './shared.ts';
18
+
19
+ export const name = 'gdd_state__checkpoint';
20
+ export const schemaPath = '../schemas/checkpoint.schema.json';
21
+
22
+ export interface CheckpointInput {
23
+ label?: string;
24
+ }
25
+
26
+ export async function handle(input: unknown): Promise<ToolResponse> {
27
+ try {
28
+ const typed = (input ?? {}) as CheckpointInput;
29
+ if (
30
+ typed.label !== undefined &&
31
+ (typeof typed.label !== 'string' || typed.label.length === 0)
32
+ ) {
33
+ throwValidation('LABEL_FORMAT', 'label must be a non-empty string');
34
+ }
35
+
36
+ const path = resolveStatePath();
37
+ const nowIso = new Date().toISOString();
38
+ let timestampKey = '';
39
+ const after = await mutate(path, (s) => {
40
+ s.frontmatter.last_checkpoint = nowIso;
41
+ const stage = typeof s.position.stage === 'string' ? s.position.stage : '';
42
+ timestampKey =
43
+ typed.label !== undefined
44
+ ? `${typed.label}_at`
45
+ : stage.length > 0
46
+ ? `${stage}_checkpoint_at`
47
+ : 'checkpoint_at';
48
+ s.timestamps[timestampKey] = nowIso;
49
+ return s;
50
+ });
51
+ emitStateMutation(
52
+ name,
53
+ { last_checkpoint: nowIso, timestamp_key: timestampKey },
54
+ after,
55
+ );
56
+ return okResponse({ last_checkpoint: nowIso, timestamp_key: timestampKey });
57
+ } catch (err) {
58
+ return errorResponse(err);
59
+ }
60
+ }