@hegemonart/get-design-done 1.19.6 → 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 (93) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/CHANGELOG.md +60 -0
  4. package/README.md +12 -0
  5. package/agents/design-reflector.md +13 -0
  6. package/connections/connections.md +3 -0
  7. package/connections/figma.md +2 -0
  8. package/connections/gdd-state.md +186 -0
  9. package/hooks/budget-enforcer.ts +716 -0
  10. package/hooks/context-exhaustion.ts +251 -0
  11. package/hooks/gdd-read-injection-scanner.ts +172 -0
  12. package/hooks/hooks.json +3 -3
  13. package/package.json +19 -6
  14. package/reference/config-schema.md +2 -2
  15. package/reference/error-recovery.md +58 -0
  16. package/reference/registry.json +7 -0
  17. package/reference/schemas/budget.schema.json +42 -0
  18. package/reference/schemas/events.schema.json +55 -0
  19. package/reference/schemas/generated.d.ts +419 -0
  20. package/reference/schemas/iteration-budget.schema.json +36 -0
  21. package/reference/schemas/mcp-gdd-state-tools.schema.json +89 -0
  22. package/reference/schemas/rate-limits.schema.json +31 -0
  23. package/scripts/aggregate-agent-metrics.ts +282 -0
  24. package/scripts/codegen-schema-types.ts +149 -0
  25. package/scripts/lib/error-classifier.cjs +232 -0
  26. package/scripts/lib/error-classifier.d.cts +44 -0
  27. package/scripts/lib/event-stream/emitter.ts +88 -0
  28. package/scripts/lib/event-stream/index.ts +154 -0
  29. package/scripts/lib/event-stream/types.ts +127 -0
  30. package/scripts/lib/event-stream/writer.ts +154 -0
  31. package/scripts/lib/gdd-errors/classification.ts +124 -0
  32. package/scripts/lib/gdd-errors/index.ts +218 -0
  33. package/scripts/lib/gdd-state/gates.ts +216 -0
  34. package/scripts/lib/gdd-state/index.ts +167 -0
  35. package/scripts/lib/gdd-state/lockfile.ts +232 -0
  36. package/scripts/lib/gdd-state/mutator.ts +574 -0
  37. package/scripts/lib/gdd-state/parser.ts +523 -0
  38. package/scripts/lib/gdd-state/types.ts +179 -0
  39. package/scripts/lib/iteration-budget.cjs +205 -0
  40. package/scripts/lib/iteration-budget.d.cts +32 -0
  41. package/scripts/lib/jittered-backoff.cjs +112 -0
  42. package/scripts/lib/jittered-backoff.d.cts +38 -0
  43. package/scripts/lib/lockfile.cjs +177 -0
  44. package/scripts/lib/lockfile.d.cts +21 -0
  45. package/scripts/lib/prompt-sanitizer/index.ts +435 -0
  46. package/scripts/lib/prompt-sanitizer/patterns.ts +173 -0
  47. package/scripts/lib/rate-guard.cjs +365 -0
  48. package/scripts/lib/rate-guard.d.cts +38 -0
  49. package/scripts/mcp-servers/gdd-state/schemas/add_blocker.schema.json +67 -0
  50. package/scripts/mcp-servers/gdd-state/schemas/add_decision.schema.json +68 -0
  51. package/scripts/mcp-servers/gdd-state/schemas/add_must_have.schema.json +68 -0
  52. package/scripts/mcp-servers/gdd-state/schemas/checkpoint.schema.json +51 -0
  53. package/scripts/mcp-servers/gdd-state/schemas/frontmatter_update.schema.json +62 -0
  54. package/scripts/mcp-servers/gdd-state/schemas/get.schema.json +51 -0
  55. package/scripts/mcp-servers/gdd-state/schemas/probe_connections.schema.json +75 -0
  56. package/scripts/mcp-servers/gdd-state/schemas/resolve_blocker.schema.json +66 -0
  57. package/scripts/mcp-servers/gdd-state/schemas/set_status.schema.json +47 -0
  58. package/scripts/mcp-servers/gdd-state/schemas/transition_stage.schema.json +70 -0
  59. package/scripts/mcp-servers/gdd-state/schemas/update_progress.schema.json +58 -0
  60. package/scripts/mcp-servers/gdd-state/server.ts +288 -0
  61. package/scripts/mcp-servers/gdd-state/tools/add_blocker.ts +72 -0
  62. package/scripts/mcp-servers/gdd-state/tools/add_decision.ts +89 -0
  63. package/scripts/mcp-servers/gdd-state/tools/add_must_have.ts +113 -0
  64. package/scripts/mcp-servers/gdd-state/tools/checkpoint.ts +60 -0
  65. package/scripts/mcp-servers/gdd-state/tools/frontmatter_update.ts +91 -0
  66. package/scripts/mcp-servers/gdd-state/tools/get.ts +51 -0
  67. package/scripts/mcp-servers/gdd-state/tools/index.ts +51 -0
  68. package/scripts/mcp-servers/gdd-state/tools/probe_connections.ts +73 -0
  69. package/scripts/mcp-servers/gdd-state/tools/resolve_blocker.ts +84 -0
  70. package/scripts/mcp-servers/gdd-state/tools/set_status.ts +54 -0
  71. package/scripts/mcp-servers/gdd-state/tools/shared.ts +194 -0
  72. package/scripts/mcp-servers/gdd-state/tools/transition_stage.ts +80 -0
  73. package/scripts/mcp-servers/gdd-state/tools/update_progress.ts +81 -0
  74. package/scripts/validate-frontmatter.ts +114 -0
  75. package/scripts/validate-schemas.ts +401 -0
  76. package/skills/brief/SKILL.md +15 -6
  77. package/skills/design/SKILL.md +31 -13
  78. package/skills/explore/SKILL.md +41 -17
  79. package/skills/health/SKILL.md +15 -4
  80. package/skills/optimize/SKILL.md +3 -3
  81. package/skills/pause/SKILL.md +16 -10
  82. package/skills/plan/SKILL.md +33 -17
  83. package/skills/progress/SKILL.md +15 -11
  84. package/skills/resume/SKILL.md +19 -10
  85. package/skills/settings/SKILL.md +11 -3
  86. package/skills/todo/SKILL.md +12 -3
  87. package/skills/verify/SKILL.md +65 -29
  88. package/hooks/budget-enforcer.js +0 -329
  89. package/hooks/context-exhaustion.js +0 -127
  90. package/hooks/gdd-read-injection-scanner.js +0 -39
  91. package/scripts/aggregate-agent-metrics.js +0 -173
  92. package/scripts/validate-frontmatter.cjs +0 -68
  93. package/scripts/validate-schemas.cjs +0 -242
@@ -0,0 +1,205 @@
1
+ // scripts/lib/iteration-budget.cjs
2
+ //
3
+ // Plan 20-14 — bounded fix-loop iteration budget.
4
+ //
5
+ // Stops infinite fix cycles from burning unbounded context. Every fix-
6
+ // iteration consumes 1 unit; Layer-B cache hits refund 1 unit so
7
+ // cached answers don't count against the ceiling. When the budget
8
+ // reaches 0, consume() throws and the caller must surface to user.
9
+ //
10
+ // State file: `.design/iteration-budget.json`. All mutations go through
11
+ // `scripts/lib/lockfile.cjs` with atomic temp+rename writes so
12
+ // concurrent callers (hook + fix-loop + verify) don't clobber each
13
+ // other. The lock scope is the state file itself, so refund + consume
14
+ // from different children serialize correctly.
15
+ //
16
+ // Shape on disk matches reference/schemas/iteration-budget.schema.json:
17
+ // { budget, remaining, consumed, refunded, updatedAt }
18
+
19
+ 'use strict';
20
+
21
+ const fs = require('node:fs');
22
+ const path = require('node:path');
23
+
24
+ const { acquire } = require('./lockfile.cjs');
25
+
26
+ const STATE_PATH_REL = path.join('.design', 'iteration-budget.json');
27
+ const DEFAULT_BUDGET = 50;
28
+ const LOCK_MAX_WAIT_MS = 5_000;
29
+
30
+ /** Error thrown by `consume()` when the remaining budget would go below 0. */
31
+ class IterationBudgetExhaustedError extends Error {
32
+ constructor(amount, state) {
33
+ super(
34
+ `IterationBudgetExhausted: cannot consume ${amount} — remaining=${state.remaining}, budget=${state.budget}, consumed=${state.consumed}. Caller must surface to user (fix-loop has stopped converging).`,
35
+ );
36
+ this.name = 'IterationBudgetExhaustedError';
37
+ this.amount = amount;
38
+ this.state = state;
39
+ }
40
+ }
41
+
42
+ function stateAbsPath() {
43
+ return path.join(process.cwd(), STATE_PATH_REL);
44
+ }
45
+
46
+ /** Read and validate the state file. Returns null on missing/corrupt. */
47
+ function readStateSync() {
48
+ const p = stateAbsPath();
49
+ if (!fs.existsSync(p)) return null;
50
+ try {
51
+ const raw = fs.readFileSync(p, 'utf8');
52
+ const parsed = JSON.parse(raw);
53
+ if (
54
+ parsed &&
55
+ typeof parsed === 'object' &&
56
+ Number.isInteger(parsed.budget) && parsed.budget >= 0 &&
57
+ Number.isInteger(parsed.remaining) && parsed.remaining >= 0 &&
58
+ Number.isInteger(parsed.consumed) && parsed.consumed >= 0 &&
59
+ Number.isInteger(parsed.refunded) && parsed.refunded >= 0 &&
60
+ typeof parsed.updatedAt === 'string'
61
+ ) {
62
+ return parsed;
63
+ }
64
+ return null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ /** Atomically write state under a file-lock. */
71
+ async function writeStateAtomic(state) {
72
+ const p = stateAbsPath();
73
+ const dir = path.dirname(p);
74
+ fs.mkdirSync(dir, { recursive: true });
75
+ const release = await acquire(p, { maxWaitMs: LOCK_MAX_WAIT_MS });
76
+ try {
77
+ // Re-read inside the lock so we merge against the very latest
78
+ // on-disk state, not the value the caller observed pre-lock. This
79
+ // is what makes concurrent consume() from 10 children add up to
80
+ // consumed=10 rather than racing each other.
81
+ const latest = readStateSync();
82
+ const merged = state.mergeFn ? state.mergeFn(latest || state.seed) : state.seed;
83
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}`;
84
+ fs.writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', 'utf8');
85
+ fs.renameSync(tmp, p);
86
+ return merged;
87
+ } finally {
88
+ await release();
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Initialize or restart the iteration budget.
94
+ *
95
+ * @param {number} [budget] default 50
96
+ * @returns {Promise<{budget, remaining, consumed, refunded, updatedAt}>}
97
+ */
98
+ async function reset(budget = DEFAULT_BUDGET) {
99
+ if (!Number.isFinite(budget) || budget < 0) {
100
+ throw new Error(`iteration-budget.reset: budget must be a non-negative finite number, got ${budget}`);
101
+ }
102
+ const b = Math.floor(budget);
103
+ const state = {
104
+ budget: b,
105
+ remaining: b,
106
+ consumed: 0,
107
+ refunded: 0,
108
+ updatedAt: new Date().toISOString(),
109
+ };
110
+ return writeStateAtomic({ seed: state, mergeFn: () => state });
111
+ }
112
+
113
+ /**
114
+ * Consume N units from the remaining budget. Throws
115
+ * IterationBudgetExhaustedError when N would send remaining below zero.
116
+ *
117
+ * @param {number} [amount] default 1
118
+ * @returns {Promise<{budget, remaining, consumed, refunded, updatedAt}>}
119
+ * the new on-disk state after consumption.
120
+ */
121
+ async function consume(amount = 1) {
122
+ const n = normalizeAmount(amount);
123
+ // Seed for the case when no state exists yet: auto-init to default budget.
124
+ const seed = defaultState();
125
+ return writeStateAtomic({
126
+ seed,
127
+ mergeFn: (current) => {
128
+ const base = current || seed;
129
+ const nextRemaining = base.remaining - n;
130
+ if (nextRemaining < 0) {
131
+ // Throw without writing — atomic: either consume fully or not at all.
132
+ throw new IterationBudgetExhaustedError(n, base);
133
+ }
134
+ return {
135
+ budget: base.budget,
136
+ remaining: nextRemaining,
137
+ consumed: base.consumed + n,
138
+ refunded: base.refunded,
139
+ updatedAt: new Date().toISOString(),
140
+ };
141
+ },
142
+ });
143
+ }
144
+
145
+ /**
146
+ * Refund N units to the remaining budget, capped at `budget`.
147
+ *
148
+ * @param {number} [amount] default 1
149
+ * @returns {Promise<{budget, remaining, consumed, refunded, updatedAt}>}
150
+ */
151
+ async function refund(amount = 1) {
152
+ const n = normalizeAmount(amount);
153
+ const seed = defaultState();
154
+ return writeStateAtomic({
155
+ seed,
156
+ mergeFn: (current) => {
157
+ const base = current || seed;
158
+ const nextRemaining = Math.min(base.budget, base.remaining + n);
159
+ // Only count the portion that actually landed — if we were already
160
+ // at budget, the refund is a no-op.
161
+ const actuallyRefunded = nextRemaining - base.remaining;
162
+ return {
163
+ budget: base.budget,
164
+ remaining: nextRemaining,
165
+ consumed: base.consumed,
166
+ refunded: base.refunded + actuallyRefunded,
167
+ updatedAt: new Date().toISOString(),
168
+ };
169
+ },
170
+ });
171
+ }
172
+
173
+ /**
174
+ * Return the current on-disk state. Reads without the lock — callers
175
+ * using this for UI display only see a best-effort snapshot; mutating
176
+ * paths (consume/refund) always re-read inside the lock.
177
+ */
178
+ function remaining() {
179
+ return readStateSync() || defaultState();
180
+ }
181
+
182
+ function normalizeAmount(amount) {
183
+ if (!Number.isFinite(amount) || amount <= 0) {
184
+ throw new Error(`iteration-budget: amount must be a positive finite number, got ${amount}`);
185
+ }
186
+ return Math.floor(amount);
187
+ }
188
+
189
+ function defaultState() {
190
+ return {
191
+ budget: DEFAULT_BUDGET,
192
+ remaining: DEFAULT_BUDGET,
193
+ consumed: 0,
194
+ refunded: 0,
195
+ updatedAt: new Date().toISOString(),
196
+ };
197
+ }
198
+
199
+ module.exports = {
200
+ consume,
201
+ refund,
202
+ remaining,
203
+ reset,
204
+ IterationBudgetExhaustedError,
205
+ };
@@ -0,0 +1,32 @@
1
+ // scripts/lib/iteration-budget.d.cts — types for iteration-budget.cjs.
2
+
3
+ export interface BudgetState {
4
+ budget: number;
5
+ remaining: number;
6
+ consumed: number;
7
+ refunded: number;
8
+ updatedAt: string; // ISO-8601
9
+ }
10
+
11
+ /** Error thrown by {@link consume} when remaining would drop below 0. */
12
+ export class IterationBudgetExhaustedError extends Error {
13
+ readonly name: 'IterationBudgetExhaustedError';
14
+ readonly amount: number;
15
+ readonly state: BudgetState;
16
+ constructor(amount: number, state: BudgetState);
17
+ }
18
+
19
+ /**
20
+ * Consume N units from the remaining budget. Throws
21
+ * {@link IterationBudgetExhaustedError} when N would send remaining below zero.
22
+ */
23
+ export function consume(amount?: number): Promise<BudgetState>;
24
+
25
+ /** Refund N units, capped at `budget`. */
26
+ export function refund(amount?: number): Promise<BudgetState>;
27
+
28
+ /** Current snapshot; non-locking read. */
29
+ export function remaining(): BudgetState;
30
+
31
+ /** Initialize or restart the budget. Default 50. */
32
+ export function reset(budget?: number): Promise<BudgetState>;
@@ -0,0 +1,112 @@
1
+ // scripts/lib/jittered-backoff.cjs
2
+ //
3
+ // Plan 20-14 — jittered exponential backoff primitive.
4
+ //
5
+ // Replaces fixed-interval retry sleeps across the codebase (update-check,
6
+ // watch-authorities, figma probes, connection probes, hook retry loops) with
7
+ // a deterministic, capped, jittered backoff curve.
8
+ //
9
+ // Formula:
10
+ // base = min(maxMs, baseMs * factor^attempt)
11
+ // delay = base * (1 + rand(-jitter, +jitter))
12
+ // clamp to [0, maxMs * (1 + jitter)]
13
+ //
14
+ // The zero-based `attempt` counter gives `baseMs` on the first call, then
15
+ // multiplies by `factor` per attempt up to the cap. Jitter is full-width
16
+ // symmetric (not AWS-style equal/decorrelated) because our consumers are
17
+ // single-threaded retry loops — there's no thundering-herd problem to
18
+ // smooth; the jitter is cosmetic protection against synchronized retries
19
+ // between siblings like the watcher + update-check running at the same
20
+ // session boundary.
21
+ //
22
+ // Defaults (baseMs=100, maxMs=30_000, factor=2, jitter=0.2) yield:
23
+ // attempt 0 → 80-120ms
24
+ // attempt 1 → 160-240ms
25
+ // attempt 2 → 320-480ms
26
+ // ...
27
+ // attempt 9 → ~24s-30s (capped)
28
+ //
29
+ // This module is `.cjs` (not `.ts`) per Plan 20-14 D-01 so it can be
30
+ // `require()`d from both the `.ts` runtime (hooks, MCP server) and future
31
+ // `.cjs` CLI invocations without needing `--experimental-strip-types` at
32
+ // every consumer site. Types live in the paired `jittered-backoff.d.cts`.
33
+ //
34
+ // No external dependencies; pure Math.random + setTimeout.
35
+
36
+ 'use strict';
37
+
38
+ /**
39
+ * Default backoff parameters — chosen to cover retry-after-Xms through
40
+ * retry-after-30s with reasonable mid-range distribution.
41
+ */
42
+ const DEFAULTS = Object.freeze({
43
+ baseMs: 100,
44
+ maxMs: 30_000,
45
+ factor: 2,
46
+ jitter: 0.2,
47
+ });
48
+
49
+ /**
50
+ * Compute the jittered delay in milliseconds for a given attempt number.
51
+ *
52
+ * @param {number} attempt zero-based attempt counter (0 = first retry)
53
+ * @param {object} [opts]
54
+ * @param {number} [opts.baseMs] initial delay before any jitter. Default 100.
55
+ * @param {number} [opts.maxMs] maximum un-jittered base. Default 30_000.
56
+ * @param {number} [opts.factor] per-attempt multiplier. Default 2.
57
+ * @param {number} [opts.jitter] symmetric jitter fraction in [0, 1). Default 0.2.
58
+ * @returns {number} delay in ms. Never negative. May exceed `maxMs` by up
59
+ * to `jitter * maxMs` on the high side.
60
+ *
61
+ * Invariants:
62
+ * - `delayMs(n, opts) >= 0` for every non-negative `n`.
63
+ * - `delayMs(n, opts) <= maxMs * (1 + jitter)` for every non-negative `n`.
64
+ * - The distribution has nonzero stddev whenever `jitter > 0`.
65
+ */
66
+ function delayMs(attempt, opts) {
67
+ const baseMs = (opts && Number.isFinite(opts.baseMs)) ? opts.baseMs : DEFAULTS.baseMs;
68
+ const maxMs = (opts && Number.isFinite(opts.maxMs)) ? opts.maxMs : DEFAULTS.maxMs;
69
+ const factor = (opts && Number.isFinite(opts.factor)) ? opts.factor : DEFAULTS.factor;
70
+ const jitter = (opts && Number.isFinite(opts.jitter)) ? opts.jitter : DEFAULTS.jitter;
71
+
72
+ // Guard against nonsense inputs — callers that pass garbage shouldn't
73
+ // cause NaN or Infinity to propagate into setTimeout.
74
+ const a = Math.max(0, Number.isFinite(attempt) ? Math.floor(attempt) : 0);
75
+ const safeBase = Math.max(0, baseMs);
76
+ const safeMax = Math.max(safeBase, maxMs);
77
+ const safeFactor = factor > 0 ? factor : DEFAULTS.factor;
78
+ // Clamp jitter to [0, 1) — full-range (>=1) would allow negative values
79
+ // after subtraction, which we want to forbid by invariant.
80
+ const safeJitter = Math.min(0.999, Math.max(0, jitter));
81
+
82
+ // Exponential growth capped at safeMax.
83
+ // Math.pow with a huge attempt count can overflow to Infinity; the
84
+ // Math.min picks up safeMax before Infinity escapes.
85
+ const unjittered = Math.min(safeMax, safeBase * Math.pow(safeFactor, a));
86
+
87
+ // Symmetric jitter in [-jitter, +jitter).
88
+ // Math.random() returns [0, 1); 2r - 1 maps to [-1, 1); scale by jitter.
89
+ const noise = (Math.random() * 2 - 1) * safeJitter;
90
+ const delay = unjittered * (1 + noise);
91
+
92
+ // Floor at zero (noise could in theory go slightly negative due to FP
93
+ // precision even with safeJitter < 1, for very small unjittered values).
94
+ return Math.max(0, delay);
95
+ }
96
+
97
+ /**
98
+ * Sleep for a jittered backoff interval. Convenience wrapper around
99
+ * `delayMs` + `setTimeout`.
100
+ *
101
+ * @param {number} attempt zero-based attempt counter
102
+ * @param {object} [opts] see {@link delayMs}
103
+ * @returns {Promise<number>} resolves to the actual delay that was applied
104
+ */
105
+ function sleep(attempt, opts) {
106
+ const ms = delayMs(attempt, opts);
107
+ return new Promise((resolve) => {
108
+ setTimeout(() => resolve(ms), ms);
109
+ });
110
+ }
111
+
112
+ module.exports = { delayMs, sleep, DEFAULTS };
@@ -0,0 +1,38 @@
1
+ // scripts/lib/jittered-backoff.d.cts — types for jittered-backoff.cjs.
2
+ //
3
+ // Paired ambient declaration for TS consumers that `require()` the .cjs
4
+ // module. `.d.cts` suffix matches the `.cjs` runtime file so TS's Node16
5
+ // resolver picks it up for CommonJS require calls from .ts files.
6
+
7
+ export interface BackoffOptions {
8
+ /** Initial delay before any jitter. Default 100ms. */
9
+ baseMs?: number;
10
+ /** Maximum un-jittered base. Default 30_000ms. */
11
+ maxMs?: number;
12
+ /** Per-attempt multiplier. Default 2. */
13
+ factor?: number;
14
+ /** Symmetric jitter fraction in [0, 1). Default 0.2. */
15
+ jitter?: number;
16
+ }
17
+
18
+ /** Default backoff parameters (frozen). */
19
+ export const DEFAULTS: Readonly<Required<BackoffOptions>>;
20
+
21
+ /**
22
+ * Compute the jittered delay in milliseconds for a given attempt number.
23
+ *
24
+ * @param attempt zero-based attempt counter (0 = first retry)
25
+ * @param opts optional overrides for the four backoff parameters
26
+ * @returns delay in ms. Never negative. May exceed `maxMs` by up to
27
+ * `jitter * maxMs` on the high side.
28
+ */
29
+ export function delayMs(attempt: number, opts?: BackoffOptions): number;
30
+
31
+ /**
32
+ * Sleep for a jittered backoff interval.
33
+ *
34
+ * @param attempt zero-based attempt counter
35
+ * @param opts see {@link BackoffOptions}
36
+ * @returns the actual delay that was applied
37
+ */
38
+ export function sleep(attempt: number, opts?: BackoffOptions): Promise<number>;
@@ -0,0 +1,177 @@
1
+ // scripts/lib/lockfile.cjs
2
+ //
3
+ // Plan 20-14 — PID+timestamp sibling lockfile for `.cjs` consumers.
4
+ //
5
+ // Algorithm mirrors scripts/lib/gdd-state/lockfile.ts (Plan 20-01):
6
+ // Lock path: `${target}.lock`
7
+ // Payload: { pid: number, host: string, acquired_at: ISO8601 }
8
+ // Acquire: atomic `writeFileSync(..., { flag: 'wx' })`
9
+ // Stale rule: pid dead (ESRCH via `kill(pid, 0)`) OR `acquired_at` older
10
+ // than `staleMs` OR unparseable payload
11
+ // Release: unlink; ENOENT is not an error; idempotent
12
+ //
13
+ // Windows: AV scanners and file-indexers can hold a file briefly after
14
+ // close. `wx` create may fail with EPERM/EBUSY even when the target is
15
+ // free; we treat these as transient and loop (same code path as EEXIST).
16
+ //
17
+ // Dependency-cycle note: Plan 20-14's rate-guard + iteration-budget
18
+ // consume this module, and both are required to stay dependency-light so
19
+ // that hooks/budget-enforcer.ts can import them without dragging the
20
+ // gdd-state MCP graph along. Hence this standalone .cjs port instead of
21
+ // calling the .ts version.
22
+
23
+ 'use strict';
24
+
25
+ const fs = require('node:fs');
26
+ const os = require('node:os');
27
+
28
+ const DEFAULT_STALE_MS = 60_000;
29
+ const DEFAULT_MAX_WAIT_MS = 5_000;
30
+ const DEFAULT_POLL_MS = 50;
31
+
32
+ /**
33
+ * Acquire an advisory lock at `${path}.lock`. Returns an idempotent
34
+ * async release function.
35
+ *
36
+ * @param {string} path path being locked (we append `.lock`)
37
+ * @param {object} [opts]
38
+ * @param {number} [opts.staleMs] ms after which an existing lock is stale. Default 60_000.
39
+ * @param {number} [opts.maxWaitMs] total ms to wait before throwing. Default 5_000.
40
+ * @param {number} [opts.pollMs] ms between retry attempts. Default 50.
41
+ * @returns {Promise<() => Promise<void>>} release function
42
+ * @throws {Error} with name === 'LockAcquisitionError' when maxWaitMs elapses
43
+ */
44
+ async function acquire(path, opts) {
45
+ const o = opts || {};
46
+ const staleMs = Number.isFinite(o.staleMs) ? o.staleMs : DEFAULT_STALE_MS;
47
+ const maxWaitMs = Number.isFinite(o.maxWaitMs) ? o.maxWaitMs : DEFAULT_MAX_WAIT_MS;
48
+ const pollMs = Number.isFinite(o.pollMs) ? o.pollMs : DEFAULT_POLL_MS;
49
+
50
+ if (staleMs < 0 || maxWaitMs < 0 || pollMs < 0) {
51
+ throw new Error(
52
+ `lockfile.acquire: invalid options (staleMs=${staleMs}, maxWaitMs=${maxWaitMs}, pollMs=${pollMs})`,
53
+ );
54
+ }
55
+
56
+ const lockPath = `${path}.lock`;
57
+ const payload = JSON.stringify({
58
+ pid: process.pid,
59
+ host: os.hostname(),
60
+ acquired_at: new Date().toISOString(),
61
+ });
62
+ const startedAt = Date.now();
63
+
64
+ while (true) {
65
+ try {
66
+ fs.writeFileSync(lockPath, payload, { flag: 'wx', encoding: 'utf8' });
67
+ return makeRelease(lockPath);
68
+ } catch (err) {
69
+ const code = err && typeof err === 'object' ? err.code : undefined;
70
+ if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EBUSY') {
71
+ throw err;
72
+ }
73
+ // Try to read the current holder; if it vanished between EEXIST and
74
+ // read, loop immediately.
75
+ const existing = readLockSafe(lockPath);
76
+ if (existing === null) continue;
77
+
78
+ const parsed = parseLock(existing);
79
+ if (parsed === null || isStale(parsed, staleMs)) {
80
+ // Clear stale/garbage lock; race-tolerant — if it's already gone
81
+ // we'll just get ENOENT, no-op.
82
+ try { fs.unlinkSync(lockPath); } catch { /* ignore */ }
83
+ continue;
84
+ }
85
+
86
+ if (Date.now() - startedAt >= maxWaitMs) {
87
+ const e = new Error(
88
+ `lockfile: failed to acquire ${lockPath} within ${maxWaitMs}ms (held by ${existing})`,
89
+ );
90
+ e.name = 'LockAcquisitionError';
91
+ e.lockPath = lockPath;
92
+ e.holder = existing;
93
+ e.waitedMs = Date.now() - startedAt;
94
+ throw e;
95
+ }
96
+ await sleep(pollMs);
97
+ }
98
+ }
99
+ }
100
+
101
+ function makeRelease(lockPath) {
102
+ let released = false;
103
+ return async function release() {
104
+ if (released) return;
105
+ released = true;
106
+ try {
107
+ fs.unlinkSync(lockPath);
108
+ } catch (err) {
109
+ const code = err && typeof err === 'object' ? err.code : undefined;
110
+ if (code === 'ENOENT') return; // idempotent — already gone
111
+ if (code === 'EPERM' || code === 'EBUSY') {
112
+ // Windows AV/indexer: retry once.
113
+ await sleep(50);
114
+ try {
115
+ if (fs.existsSync(lockPath)) fs.unlinkSync(lockPath);
116
+ } catch { /* give up; stale-detection will reclaim */ }
117
+ return;
118
+ }
119
+ // Any other errno: swallow. Best-effort cleanup; stale-age check
120
+ // will eventually reclaim the lock.
121
+ }
122
+ };
123
+ }
124
+
125
+ function readLockSafe(p) {
126
+ try {
127
+ return fs.readFileSync(p, 'utf8');
128
+ } catch (err) {
129
+ const code = err && typeof err === 'object' ? err.code : undefined;
130
+ if (code === 'ENOENT') return null;
131
+ return '<unreadable>';
132
+ }
133
+ }
134
+
135
+ function parseLock(raw) {
136
+ try {
137
+ const obj = JSON.parse(raw);
138
+ if (
139
+ obj && typeof obj === 'object' &&
140
+ typeof obj.pid === 'number' &&
141
+ typeof obj.host === 'string' &&
142
+ typeof obj.acquired_at === 'string'
143
+ ) {
144
+ return obj;
145
+ }
146
+ return null;
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ function isStale(payload, staleMs) {
153
+ if (!isPidAlive(payload.pid, payload.host)) return true;
154
+ const t = Date.parse(payload.acquired_at);
155
+ if (!Number.isFinite(t)) return true;
156
+ return Date.now() - t > staleMs;
157
+ }
158
+
159
+ function isPidAlive(pid, host) {
160
+ if (host !== os.hostname()) return true; // can't introspect other hosts
161
+ if (pid === process.pid) return true;
162
+ try {
163
+ process.kill(pid, 0); // signal 0 = validate, don't deliver
164
+ return true;
165
+ } catch (err) {
166
+ const code = err && typeof err === 'object' ? err.code : undefined;
167
+ if (code === 'ESRCH') return false;
168
+ // EPERM / EACCES: process exists but is unsignalable; treat as alive.
169
+ return true;
170
+ }
171
+ }
172
+
173
+ function sleep(ms) {
174
+ return new Promise((resolve) => setTimeout(resolve, ms));
175
+ }
176
+
177
+ module.exports = { acquire };
@@ -0,0 +1,21 @@
1
+ // scripts/lib/lockfile.d.cts — types for lockfile.cjs.
2
+
3
+ export interface AcquireOptions {
4
+ /** ms after which an existing lock is considered stale. Default 60_000. */
5
+ staleMs?: number;
6
+ /** total ms to wait before throwing LockAcquisitionError. Default 5_000. */
7
+ maxWaitMs?: number;
8
+ /** ms between retry attempts. Default 50. */
9
+ pollMs?: number;
10
+ }
11
+
12
+ /** Release function returned by `acquire()`. Idempotent. */
13
+ export type LockRelease = () => Promise<void>;
14
+
15
+ /**
16
+ * Acquire an advisory lock at `${path}.lock`. Returns a release function.
17
+ *
18
+ * @throws Error with `name === 'LockAcquisitionError'` when `maxWaitMs`
19
+ * elapses without acquiring.
20
+ */
21
+ export function acquire(path: string, opts?: AcquireOptions): Promise<LockRelease>;