@hegemonart/get-design-done 1.47.0 → 1.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+ /**
3
+ * scripts/lib/worktree-resolve.cjs — Phase 49 (Quick Anti-Slop Floor).
4
+ *
5
+ * Redirect `.design/` and `.planning/` writes to the MAIN repo root when GDD
6
+ * runs inside a git WORKTREE. A worktree has its own ephemeral checkout dir; a
7
+ * naive `process.cwd()`-relative `.design/STATE.md` write would land inside the
8
+ * throwaway worktree and get lost (or leak) when the worktree is removed. We
9
+ * detect the worktree, resolve the main repo root, and point artifact writes
10
+ * there so state survives across worktree lifecycles.
11
+ *
12
+ * Detection: `git rev-parse --git-dir` and `--git-common-dir` DIFFER inside a
13
+ * linked worktree (git-dir is `<main>/.git/worktrees/<name>`, common-dir is
14
+ * `<main>/.git`); in the main checkout they are EQUAL. The main repo root is the
15
+ * PARENT of the common git dir.
16
+ *
17
+ * Pure + dependency-free except for spawning `git`, and the `git` call is fully
18
+ * injectable via an `exec` parameter so tests run without a real worktree. NEVER
19
+ * throws: when git is unavailable (no repo, git not on PATH) every resolver
20
+ * degrades gracefully to the caller's `cwd`, so non-git consumers are unaffected.
21
+ *
22
+ * No top-level `Date.now()` / `Math.random()` — the only module-level mutable
23
+ * state is the one-shot `noticeOnce` flag, intentionally per-process.
24
+ *
25
+ * CommonJS so it ships in the npm package and loads from `.cjs` callers and the
26
+ * dual-mode `.ts`/`.js` MCP servers alike.
27
+ */
28
+
29
+ const { spawnSync } = require('node:child_process');
30
+ const path = require('node:path');
31
+
32
+ /**
33
+ * Default `exec`: synchronously run `git <args...>` in `cwd` and return its
34
+ * trimmed stdout. Returns null on ANY failure (git missing, non-zero exit,
35
+ * not a repo) so callers can treat "no git" as "not a worktree".
36
+ *
37
+ * @param {string[]} args git arguments, e.g. ['rev-parse', '--git-dir']
38
+ * @param {string} cwd working directory to run git in
39
+ * @returns {string | null} trimmed stdout, or null on failure
40
+ */
41
+ function defaultExec(args, cwd) {
42
+ try {
43
+ const res = spawnSync('git', args, {
44
+ cwd,
45
+ encoding: 'utf8',
46
+ windowsHide: true,
47
+ });
48
+ if (!res || res.status !== 0 || typeof res.stdout !== 'string') return null;
49
+ const out = res.stdout.trim();
50
+ return out.length ? out : null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Normalize an injectable `exec` into a uniform `(args, cwd) => string|null`.
58
+ *
59
+ * The injectable form callers/tests pass is `(cmd, args) => string` where `cmd`
60
+ * is the literal `'git'` and `args` is the argv array (matching the prompt
61
+ * contract). We adapt it here and swallow throws into null so a test exec that
62
+ * throws models "git unavailable" exactly like the real one returning null.
63
+ *
64
+ * @param {undefined | ((cmd: string, args: string[]) => string)} exec
65
+ * @param {string} cwd
66
+ * @returns {(args: string[]) => string | null}
67
+ */
68
+ function makeRunner(exec, cwd) {
69
+ if (typeof exec === 'function') {
70
+ return (args) => {
71
+ try {
72
+ const out = exec('git', args);
73
+ if (typeof out !== 'string') return null;
74
+ const trimmed = out.trim();
75
+ return trimmed.length ? trimmed : null;
76
+ } catch {
77
+ return null;
78
+ }
79
+ };
80
+ }
81
+ return (args) => defaultExec(args, cwd);
82
+ }
83
+
84
+ /**
85
+ * Resolve the absolute git-dir and git-common-dir for `cwd`.
86
+ *
87
+ * `git rev-parse` prints these relative to `cwd` in some setups and absolute in
88
+ * others; we resolve both against `cwd` so comparison and parent-of logic is
89
+ * always done on absolute, normalized paths.
90
+ *
91
+ * @returns {{ gitDir: string, commonDir: string } | null} null when not a repo
92
+ */
93
+ function gitDirs(run, cwd) {
94
+ const gitDirRaw = run(['rev-parse', '--git-dir']);
95
+ if (gitDirRaw == null) return null;
96
+ const commonDirRaw = run(['rev-parse', '--git-common-dir']);
97
+ if (commonDirRaw == null) return null;
98
+ const gitDir = path.resolve(cwd, gitDirRaw);
99
+ const commonDir = path.resolve(cwd, commonDirRaw);
100
+ return { gitDir, commonDir };
101
+ }
102
+
103
+ /**
104
+ * True when `cwd` sits inside a linked git WORKTREE (git-dir !== git-common-dir).
105
+ * False in the main checkout, and false (degrade gracefully) when git is
106
+ * unavailable or `cwd` is not inside any repo.
107
+ *
108
+ * @param {string} [cwd=process.cwd()]
109
+ * @param {(cmd: string, args: string[]) => string} [exec] injectable git runner
110
+ * @returns {boolean}
111
+ */
112
+ function isWorktree(cwd = process.cwd(), exec) {
113
+ const run = makeRunner(exec, cwd);
114
+ const dirs = gitDirs(run, cwd);
115
+ if (dirs == null) return false;
116
+ return dirs.gitDir !== dirs.commonDir;
117
+ }
118
+
119
+ /**
120
+ * Resolve the MAIN repo root for `cwd`.
121
+ *
122
+ * - In a worktree: the parent of the git-common-dir (`<main>/.git` -> `<main>`).
123
+ * - In the main checkout: the toplevel (`git rev-parse --show-toplevel`).
124
+ * - git unavailable / not a repo: falls back to `path.resolve(cwd)`.
125
+ *
126
+ * Never throws.
127
+ *
128
+ * @param {string} [cwd=process.cwd()]
129
+ * @param {(cmd: string, args: string[]) => string} [exec] injectable git runner
130
+ * @returns {string} absolute main repo root
131
+ */
132
+ function resolveRepoRoot(cwd = process.cwd(), exec) {
133
+ const run = makeRunner(exec, cwd);
134
+ const dirs = gitDirs(run, cwd);
135
+ if (dirs == null) {
136
+ // Not a repo / git unavailable — degrade to cwd.
137
+ return path.resolve(cwd);
138
+ }
139
+ if (dirs.gitDir !== dirs.commonDir) {
140
+ // Worktree: the main repo root is the parent of the common `.git` dir.
141
+ // common-dir is typically `<main>/.git`; its dirname is `<main>`. Guard the
142
+ // (unusual) bare-repo case where common-dir has no `.git` basename by only
143
+ // climbing when the basename looks like a git dir.
144
+ const base = path.basename(dirs.commonDir);
145
+ if (base === '.git' || base.endsWith('.git')) {
146
+ return path.dirname(dirs.commonDir);
147
+ }
148
+ // Bare/relocated git dir: best effort — fall through to toplevel below.
149
+ }
150
+ // Main checkout (or odd common-dir shape): prefer the toplevel.
151
+ const top = run(['rev-parse', '--show-toplevel']);
152
+ if (top != null) return path.resolve(cwd, top);
153
+ // Last resort: parent of the git dir, else cwd.
154
+ const base = path.basename(dirs.commonDir);
155
+ if (base === '.git' || base.endsWith('.git')) return path.dirname(dirs.commonDir);
156
+ return path.resolve(cwd);
157
+ }
158
+
159
+ /**
160
+ * Absolute `.design` root in the MAIN repo (worktree-safe).
161
+ *
162
+ * @param {string} [cwd=process.cwd()]
163
+ * @param {(cmd: string, args: string[]) => string} [exec]
164
+ * @returns {string}
165
+ */
166
+ function resolveDesignRoot(cwd = process.cwd(), exec) {
167
+ return path.join(resolveRepoRoot(cwd, exec), '.design');
168
+ }
169
+
170
+ /**
171
+ * Absolute `.planning` root in the MAIN repo (worktree-safe).
172
+ *
173
+ * @param {string} [cwd=process.cwd()]
174
+ * @param {(cmd: string, args: string[]) => string} [exec]
175
+ * @returns {string}
176
+ */
177
+ function resolvePlanningRoot(cwd = process.cwd(), exec) {
178
+ return path.join(resolveRepoRoot(cwd, exec), '.planning');
179
+ }
180
+
181
+ /** One-shot guard so the redirect notice prints at most once per process. */
182
+ let NOTICE_EMITTED = false;
183
+
184
+ /**
185
+ * Emit a single one-line stderr notice — exactly once per process — announcing
186
+ * that worktree redirection is in effect. Subsequent calls are no-ops, so a
187
+ * caller can invoke this freely on every redirect without spamming stderr.
188
+ *
189
+ * @param {string} targetRoot the resolved MAIN repo root writes are redirected to
190
+ * @param {(line: string) => void} [write] injectable sink (default process.stderr)
191
+ * @returns {boolean} true if THIS call emitted the notice, false if already emitted
192
+ */
193
+ function noticeOnce(targetRoot, write) {
194
+ if (NOTICE_EMITTED) return false;
195
+ NOTICE_EMITTED = true;
196
+ const line = `worktree detected -> .design/.planning redirected to ${targetRoot}\n`;
197
+ try {
198
+ if (typeof write === 'function') {
199
+ write(line);
200
+ } else {
201
+ process.stderr.write(line);
202
+ }
203
+ } catch {
204
+ /* never let a logging failure break a write path */
205
+ }
206
+ return true;
207
+ }
208
+
209
+ /** Test-only: reset the one-shot notice flag. Not part of the public contract. */
210
+ function _resetNoticeForTests() {
211
+ NOTICE_EMITTED = false;
212
+ }
213
+
214
+ module.exports = {
215
+ isWorktree,
216
+ resolveRepoRoot,
217
+ resolveDesignRoot,
218
+ resolvePlanningRoot,
219
+ noticeOnce,
220
+ _resetNoticeForTests,
221
+ };
@@ -35,7 +35,7 @@ __export(server_exports, {
35
35
  runStdio: () => runStdio
36
36
  });
37
37
  module.exports = __toCommonJS(server_exports);
38
- var import_node_fs4 = require("node:fs");
38
+ var import_node_fs5 = require("node:fs");
39
39
  var import_node_path3 = require("node:path");
40
40
  var import_server = require("@modelcontextprotocol/sdk/server/index.js");
41
41
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
@@ -1799,6 +1799,8 @@ async function transition(path2, toStage) {
1799
1799
 
1800
1800
  // sdk/mcp/gdd-state/tools/shared.ts
1801
1801
  var import_node_path2 = __toESM(require("node:path"));
1802
+ var import_node_fs4 = require("node:fs");
1803
+ var import_node_module2 = require("node:module");
1802
1804
 
1803
1805
  // sdk/event-stream/index.ts
1804
1806
  var import_node_os2 = require("node:os");
@@ -2012,9 +2014,40 @@ function getSessionId() {
2012
2014
  if (CACHED_SESSION_ID === null) CACHED_SESSION_ID = makeSessionId();
2013
2015
  return CACHED_SESSION_ID;
2014
2016
  }
2017
+ function _findRepoRoot2() {
2018
+ let dir = process.cwd();
2019
+ for (let i = 0; i < 8; i++) {
2020
+ if ((0, import_node_fs4.existsSync)(import_node_path2.default.join(dir, "package.json"))) return dir;
2021
+ const parent = import_node_path2.default.dirname(dir);
2022
+ if (parent === dir) break;
2023
+ dir = parent;
2024
+ }
2025
+ return process.cwd();
2026
+ }
2027
+ var _worktree = (() => {
2028
+ try {
2029
+ const root = _findRepoRoot2();
2030
+ const candidate = import_node_path2.default.resolve(root, "scripts/lib/worktree-resolve.cjs");
2031
+ if (!(0, import_node_fs4.existsSync)(candidate)) return null;
2032
+ const req = (0, import_node_module2.createRequire)(import_node_path2.default.join(root, "package.json"));
2033
+ return req(candidate);
2034
+ } catch {
2035
+ return null;
2036
+ }
2037
+ })();
2015
2038
  function resolveStatePath() {
2016
2039
  const override = process.env["GDD_STATE_PATH"];
2017
2040
  if (typeof override !== "string" || override.length === 0) {
2041
+ if (_worktree !== null) {
2042
+ try {
2043
+ const designRoot = _worktree.resolveDesignRoot();
2044
+ if (_worktree.isWorktree()) {
2045
+ _worktree.noticeOnce(import_node_path2.default.dirname(designRoot));
2046
+ }
2047
+ return import_node_path2.default.join(designRoot, "STATE.md");
2048
+ } catch {
2049
+ }
2050
+ }
2018
2051
  return ".design/STATE.md";
2019
2052
  }
2020
2053
  if (import_node_path2.default.isAbsolute(override)) {
@@ -2734,12 +2767,12 @@ function here() {
2734
2767
  const entry = process.argv[1];
2735
2768
  if (typeof entry === "string" && entry.length > 0) {
2736
2769
  const entryDir = (0, import_node_path3.dirname)((0, import_node_path3.resolve)(entry));
2737
- if ((0, import_node_fs4.existsSync)((0, import_node_path3.join)(entryDir, "tools", "index.ts"))) {
2770
+ if ((0, import_node_fs5.existsSync)((0, import_node_path3.join)(entryDir, "tools", "index.ts"))) {
2738
2771
  return entryDir;
2739
2772
  }
2740
2773
  }
2741
2774
  const candidate = (0, import_node_path3.resolve)(process.cwd(), expectedRel);
2742
- if ((0, import_node_fs4.existsSync)((0, import_node_path3.join)(candidate, "tools", "index.ts"))) {
2775
+ if ((0, import_node_fs5.existsSync)((0, import_node_path3.join)(candidate, "tools", "index.ts"))) {
2743
2776
  return candidate;
2744
2777
  }
2745
2778
  return candidate;
@@ -2748,7 +2781,7 @@ function loadTools() {
2748
2781
  const baseDir = here();
2749
2782
  return TOOL_MODULES.map((m) => {
2750
2783
  const absPath = (0, import_node_path3.join)(baseDir, "tools", m.schemaPath);
2751
- const raw = (0, import_node_fs4.readFileSync)(absPath, "utf8");
2784
+ const raw = (0, import_node_fs5.readFileSync)(absPath, "utf8");
2752
2785
  const parsed = JSON.parse(raw);
2753
2786
  const rawInput = parsed.properties?.input;
2754
2787
  const inputSchema = rawInput !== void 0 && typeof rawInput === "object" ? rawInput : { type: "object" };
@@ -12,6 +12,8 @@
12
12
  // {success:false, error} — handlers never propagate exceptions."
13
13
 
14
14
  import path from 'node:path';
15
+ import { existsSync } from 'node:fs';
16
+ import { createRequire } from 'node:module';
15
17
  import {
16
18
  ValidationError,
17
19
  OperationFailedError,
@@ -50,6 +52,49 @@ export function getSessionId(): string {
50
52
  return CACHED_SESSION_ID;
51
53
  }
52
54
 
55
+ /**
56
+ * Worktree redirect (Phase 49). When GDD runs inside a git WORKTREE, a naive
57
+ * `process.cwd()`-relative `.design/STATE.md` write lands in the ephemeral
58
+ * worktree and is lost when it is removed. `scripts/lib/worktree-resolve.cjs`
59
+ * resolves the MAIN repo root and points STATE writes there.
60
+ *
61
+ * Soft-loaded via createRequire (mirrors sdk/event-stream/writer.ts): tsc's
62
+ * Node16 module mode classifies this .ts as CJS output, so `import.meta` is
63
+ * unavailable — we anchor createRequire on the repo-root package.json found by
64
+ * walking up from cwd. If the helper is unreachable (a test subprocess running
65
+ * far above the plugin tree), every resolver degrades to a null shim and the
66
+ * default falls back to the legacy relative path. Production callers always run
67
+ * inside the plugin tree.
68
+ */
69
+ interface WorktreeResolver {
70
+ resolveDesignRoot: (cwd?: string) => string;
71
+ isWorktree: (cwd?: string) => boolean;
72
+ noticeOnce: (targetRoot: string) => boolean;
73
+ }
74
+
75
+ function _findRepoRoot(): string {
76
+ let dir = process.cwd();
77
+ for (let i = 0; i < 8; i++) {
78
+ if (existsSync(path.join(dir, 'package.json'))) return dir;
79
+ const parent = path.dirname(dir);
80
+ if (parent === dir) break;
81
+ dir = parent;
82
+ }
83
+ return process.cwd();
84
+ }
85
+
86
+ const _worktree: WorktreeResolver | null = (() => {
87
+ try {
88
+ const root = _findRepoRoot();
89
+ const candidate = path.resolve(root, 'scripts/lib/worktree-resolve.cjs');
90
+ if (!existsSync(candidate)) return null;
91
+ const req = createRequire(path.join(root, 'package.json'));
92
+ return req(candidate) as WorktreeResolver;
93
+ } catch {
94
+ return null;
95
+ }
96
+ })();
97
+
53
98
  /**
54
99
  * Resolve the target STATE.md path from the environment, with a
55
100
  * PATH-TRAVERSAL guard (Plan 33.5-03, D-08).
@@ -69,6 +114,22 @@ export function getSessionId(): string {
69
114
  export function resolveStatePath(): string {
70
115
  const override = process.env['GDD_STATE_PATH'];
71
116
  if (typeof override !== 'string' || override.length === 0) {
117
+ // No override: resolve STATE.md under the worktree-aware `.design` root
118
+ // (Phase 49). Outside a worktree this equals the legacy `<cwd>/.design`
119
+ // (when cwd is the repo root) so behavior is unchanged; inside a worktree
120
+ // the design root points at the MAIN repo so state is not lost. The notice
121
+ // fires at most once per process, only on an actual worktree redirect.
122
+ if (_worktree !== null) {
123
+ try {
124
+ const designRoot = _worktree.resolveDesignRoot();
125
+ if (_worktree.isWorktree()) {
126
+ _worktree.noticeOnce(path.dirname(designRoot));
127
+ }
128
+ return path.join(designRoot, 'STATE.md');
129
+ } catch {
130
+ // Fall through to the legacy relative default on any resolver fault.
131
+ }
132
+ }
72
133
  return '.design/STATE.md';
73
134
  }
74
135
 
@@ -108,6 +108,23 @@ Run this final spec-quality pass over `.design/BRIEF.md` before the brief→expl
108
108
  - Scope check: nothing in the artifact exceeds (or silently drops) the agreed scope.
109
109
  - Ambiguity check: every requirement/decision is specific enough to act on without a follow-up question.
110
110
 
111
+ ## Optional brief audit (non-blocking)
112
+
113
+ Before the gate, you MAY spawn `agents/brief-auditor.md` via `Task` to grade the brief against the five
114
+ brief anti-patterns (vague verbs, missing audience, immeasurable success criteria, scope creep, missing
115
+ anti-goals). The auditor reads `.design/BRIEF.md` plus `reference/brief-quality-rubric.md` and writes
116
+ advisory findings to `.design/BRIEF-AUDIT.md`. This step is advisory and MUST NOT block the brief to
117
+ explore transition.
118
+
119
+ If the auditor reports one or more fired anti-patterns, surface a single-line pointer to the user:
120
+
121
+ ```
122
+ Brief audit flagged N issue(s) - run /gdd:discuss brief to refine, or proceed to explore.
123
+ ```
124
+
125
+ The user decides. Proceeding to explore with a flagged brief is allowed; the pointer is a nudge, not a gate.
126
+ If the auditor reports no fired anti-patterns, or you skip the audit, continue to the gate unchanged.
127
+
111
128
  <HARD-GATE>
112
129
  Do NOT transition to explore (or invoke `/gdd:explore`) until the brief artifact (default `.design/BRIEF.md`) is committed AND the user has approved it. If this project uses a custom `.design` location, read the artifact path from `.design/STATE.md` rather than assuming the default.
113
130
  </HARD-GATE>
@@ -39,7 +39,7 @@ Read once at start from `.design/config.json` (all optional; defaults in parens)
39
39
  Stop at the first tier that produces ≥ 1 command:
40
40
 
41
41
  1. **Authoritative config.** If `.design/config.json` has `quality_gate.commands` non-empty, use verbatim.
42
- 2. **Auto-detect from `package.json#scripts`** - match against allowlist: `lint`, `typecheck`, `tsc` (only if `typecheck` absent), `test`, `chromatic`, `test:visual`, `lint:design` (Phase 41 - the `gdd-detect` deterministic anti-pattern gate, alongside `axe`/`pa11y`/`lighthouse`). Exclude by name: `test:e2e`, `test:integration` (if separate `test`), anything starting `dev:`, `build:`, `start:`. Run via `npm run <name>` unless `quality_gate.package_manager` overrides.
42
+ 2. **Auto-detect from `package.json#scripts`** - match against allowlist: `lint`, `typecheck`, `tsc` (only if `typecheck` absent), `test`, `chromatic`, `test:visual`, `lint:design` (Phase 41 - the `gdd-detect` deterministic anti-pattern gate), and the accessibility scripts `axe`, `pa11y`, `lighthouse`, `eslint-plugin-jsx-a11y` (or a script named `jsx-a11y`) which classify into the `a11y` bucket. Exclude by name: `test:e2e`, `test:integration` (if separate `test`), anything starting `dev:`, `build:`, `start:`. Run via `npm run <name>` unless `quality_gate.package_manager` overrides.
43
43
  3. **Skip with notice.** Emit `quality_gate_skipped` (Step 6) and write a `<run/>` with `status="skipped"`. Verify treats skipped as non-blocking.
44
44
 
45
45
  ## Step 2 - Parallel run
@@ -48,7 +48,7 @@ Emit `quality_gate_started`. Spawn each command in a separate `Bash`; collect `{
48
48
 
49
49
  ## Step 3 - Classification
50
50
 
51
- Spawn `quality-gate-runner` agent via `Task` with payload `{outputs: [{command, exit_code, stderr}, ...]}`. Agent returns `{status: "pass"|"fail", classified_failures: {lint, type, test, visual}}`. `pass` → Step 5. `fail` → Step 4.
51
+ Spawn `quality-gate-runner` agent via `Task` with payload `{outputs: [{command, exit_code, stderr}, ...]}`. Agent returns `{status: "pass"|"fail", classified_failures: {lint, type, test, visual, a11y}}`. The `a11y` bucket groups accessibility failures from axe / pa11y / lighthouse / jsx-a11y. `pass` → Step 5. `fail` → Step 4.
52
52
 
53
53
  ## Step 4 - Fix loop (D-08)
54
54