tdd-enforcer 0.3.3 → 0.3.5

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.
@@ -1,8 +1,8 @@
1
1
  import { mkdirSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
- import { describe, expect, it } from "vitest";
5
- import { loadPhaseState, savePhaseState } from "./state.js";
4
+ import { beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { loadPhaseState, loadTddState, savePhaseState } from "./state.js";
6
6
 
7
7
  function withTempDir(fn: (dir: string) => void) {
8
8
  const dir = join(tmpdir(), `tdd-state-test-${Date.now()}`);
@@ -82,3 +82,275 @@ describe("savePhaseState", () => {
82
82
  });
83
83
  });
84
84
  });
85
+
86
+ // ── loadTddState ────────────────────────────────────────────────────────────
87
+
88
+ const validRules = {
89
+ blockedInRed: ["tests/**/*.test.ts"],
90
+ blockedInGreen: ["src/**/*.ts"],
91
+ testCommands: ["npm test"],
92
+ timeoutSeconds: 30,
93
+ };
94
+
95
+ const validPhase = {
96
+ enabled: true,
97
+ current: "red",
98
+ };
99
+
100
+ describe("loadTddState", () => {
101
+ let mockExistsSync: ReturnType<typeof vi.fn>;
102
+ let mockLoadConfig: ReturnType<typeof vi.fn>;
103
+ let mockInitGit: ReturnType<typeof vi.fn>;
104
+ let mockLoadPhaseState: ReturnType<typeof vi.fn>;
105
+ let mockSavePhaseState: ReturnType<typeof vi.fn>;
106
+ let mockHeadMessage: ReturnType<typeof vi.fn>;
107
+ let mockNextPhase: ReturnType<typeof vi.fn>;
108
+ let mockStageFiles: ReturnType<typeof vi.fn>;
109
+
110
+ const realNextPhase = (p: string) =>
111
+ p === "red"
112
+ ? "green"
113
+ : p === "green"
114
+ ? "refactor"
115
+ : p === "refactor"
116
+ ? "red"
117
+ : null;
118
+
119
+ function makeDeps(overrides = {}) {
120
+ return {
121
+ existsSync: mockExistsSync,
122
+ loadConfig: mockLoadConfig,
123
+ initGit: mockInitGit,
124
+ loadPhaseState: mockLoadPhaseState,
125
+ savePhaseState: mockSavePhaseState,
126
+ headMessage: mockHeadMessage,
127
+ nextPhase: mockNextPhase,
128
+ stageFiles: mockStageFiles,
129
+ ...overrides,
130
+ };
131
+ }
132
+
133
+ beforeEach(() => {
134
+ vi.clearAllMocks();
135
+ mockExistsSync = vi.fn().mockImplementation((path: string) => {
136
+ if (path.includes(".git")) return false;
137
+ if (path.includes(".pi/tdd")) return true;
138
+ return true;
139
+ });
140
+ mockLoadConfig = vi.fn().mockReturnValue(validRules);
141
+ mockInitGit = vi.fn();
142
+ mockLoadPhaseState = vi.fn().mockReturnValue(validPhase);
143
+ mockSavePhaseState = vi.fn();
144
+ mockHeadMessage = vi.fn().mockReturnValue("tdd: red");
145
+ mockNextPhase = vi.fn().mockImplementation(realNextPhase);
146
+ mockStageFiles = vi.fn();
147
+ });
148
+
149
+ it("returns missing dir error when .pi/tdd does not exist", () => {
150
+ mockExistsSync.mockReturnValue(false);
151
+ const result = loadTddState("/test", makeDeps());
152
+ expect(result.ok).toBe(false);
153
+ expect(result.reason).toContain("Missing .pi/tdd/");
154
+ });
155
+
156
+ it("returns missing rules.json error when only dir exists", () => {
157
+ mockExistsSync.mockImplementation((path: string) => {
158
+ if (path.includes("rules.json")) return false;
159
+ if (path.includes(".pi/tdd")) return true;
160
+ return false;
161
+ });
162
+ const result = loadTddState("/test", makeDeps());
163
+ expect(result.ok).toBe(false);
164
+ expect(result.reason).toContain("rules.json");
165
+ });
166
+
167
+ it("auto-creates state.json when missing (default RED disabled)", () => {
168
+ mockExistsSync.mockImplementation((path: string) => {
169
+ if (path.includes("state.json")) return false;
170
+ if (path.includes(".git")) return false;
171
+ return true;
172
+ });
173
+ mockHeadMessage.mockReturnValue("tdd: init");
174
+ const result = loadTddState("/test", makeDeps());
175
+ expect(result.ok).toBe(true);
176
+ if (result.ok) {
177
+ expect(result.state.enabled).toBe(false);
178
+ expect(result.state.current).toBe("red");
179
+ }
180
+ expect(mockInitGit).toHaveBeenCalled();
181
+ expect(mockSavePhaseState).toHaveBeenCalledWith("/test", {
182
+ enabled: false,
183
+ current: "red",
184
+ });
185
+ });
186
+
187
+ it("auto-creates state.json when corrupted (recovers to default)", () => {
188
+ mockExistsSync.mockImplementation((path: string) => {
189
+ if (path.includes("state.json")) return true;
190
+ if (path.includes(".git")) return false;
191
+ return true;
192
+ });
193
+ mockLoadPhaseState.mockImplementation(() => {
194
+ throw new Error("corrupt");
195
+ });
196
+ mockHeadMessage.mockReturnValue("tdd: init");
197
+ const result = loadTddState("/test", makeDeps());
198
+ expect(result.ok).toBe(true);
199
+ if (result.ok) {
200
+ expect(result.state.enabled).toBe(false);
201
+ expect(result.state.current).toBe("red");
202
+ }
203
+ });
204
+
205
+ it("returns invalid rules.json error for malformed JSON", () => {
206
+ mockLoadConfig.mockImplementation(() => {
207
+ throw new Error("Unexpected token");
208
+ });
209
+ const result = loadTddState("/test", makeDeps());
210
+ expect(result.ok).toBe(false);
211
+ expect(result.reason).toContain("Invalid .pi/tdd/rules.json");
212
+ });
213
+
214
+ it("returns ok when state.json has enabled: false (callers check enabled)", () => {
215
+ mockLoadPhaseState.mockReturnValue({ enabled: false, current: "red" });
216
+ const result = loadTddState("/test", makeDeps());
217
+ expect(result.ok).toBe(true);
218
+ if (result.ok) {
219
+ expect(result.state.enabled).toBe(false);
220
+ expect(result.state.current).toBe("red");
221
+ }
222
+ });
223
+
224
+ it("returns ok with state and config when everything valid", () => {
225
+ mockLoadPhaseState.mockReturnValue(validPhase);
226
+ const result = loadTddState("/test", makeDeps());
227
+ expect(result.ok).toBe(true);
228
+ if (result.ok) {
229
+ expect(result.state.current).toBe("red");
230
+ expect(result.state.enabled).toBe(true);
231
+ expect(result.config.testCommands).toEqual(["npm test"]);
232
+ expect(result.config.blockedInRed).toEqual(["tests/**/*.test.ts"]);
233
+ }
234
+ });
235
+
236
+ it("auto-creates git repo when missing", () => {
237
+ let gitExists = false;
238
+ mockExistsSync.mockImplementation((path: string) => {
239
+ if (path.includes(".git")) return gitExists;
240
+ if (path.includes(".pi/tdd")) return true;
241
+ return true;
242
+ });
243
+ mockInitGit.mockImplementation(() => {
244
+ gitExists = true;
245
+ });
246
+ const result = loadTddState("/test", makeDeps());
247
+ expect(result.ok).toBe(true);
248
+ expect(mockInitGit).toHaveBeenCalled();
249
+ });
250
+
251
+ it("handles multiple calls without error", () => {
252
+ const r1 = loadTddState("/test", makeDeps());
253
+ expect(r1.ok).toBe(true);
254
+ const r2 = loadTddState("/test", makeDeps());
255
+ expect(r2.ok).toBe(true);
256
+ expect(mockLoadConfig).toHaveBeenCalledTimes(2);
257
+ });
258
+
259
+ it("recovers from invalid current phase in state.json (auto-creates default)", () => {
260
+ mockLoadPhaseState.mockImplementation(() => {
261
+ throw new Error("invalid phase");
262
+ });
263
+ mockHeadMessage.mockReturnValue("tdd: init");
264
+ const result = loadTddState("/test", makeDeps());
265
+ expect(result.ok).toBe(true);
266
+ if (result.ok) {
267
+ expect(result.state.enabled).toBe(false);
268
+ expect(result.state.current).toBe("red");
269
+ }
270
+ });
271
+
272
+ it("recoverState: HEAD tdd:red → enabled green", () => {
273
+ mockExistsSync.mockImplementation((path: string) => {
274
+ if (path.includes("state.json")) return false;
275
+ return true;
276
+ });
277
+ mockHeadMessage.mockReturnValue("tdd: red");
278
+ mockNextPhase.mockImplementation(realNextPhase);
279
+ const result = loadTddState("/test", makeDeps());
280
+ expect(result.ok).toBe(true);
281
+ if (result.ok) {
282
+ expect(result.state.enabled).toBe(true);
283
+ expect(result.state.current).toBe("green");
284
+ }
285
+ });
286
+
287
+ it("recoverState: HEAD tdd:green → enabled refactor", () => {
288
+ mockExistsSync.mockImplementation((path: string) => {
289
+ if (path.includes("state.json")) return false;
290
+ return true;
291
+ });
292
+ mockHeadMessage.mockReturnValue("tdd: green");
293
+ const result = loadTddState("/test", makeDeps());
294
+ expect(result.ok).toBe(true);
295
+ if (result.ok) {
296
+ expect(result.state.enabled).toBe(true);
297
+ expect(result.state.current).toBe("refactor");
298
+ }
299
+ });
300
+
301
+ it("recoverState: HEAD tdd:refactor → enabled red", () => {
302
+ mockExistsSync.mockImplementation((path: string) => {
303
+ if (path.includes("state.json")) return false;
304
+ return true;
305
+ });
306
+ mockHeadMessage.mockReturnValue("tdd: refactor");
307
+ const result = loadTddState("/test", makeDeps());
308
+ expect(result.ok).toBe(true);
309
+ if (result.ok) {
310
+ expect(result.state.enabled).toBe(true);
311
+ expect(result.state.current).toBe("red");
312
+ }
313
+ });
314
+
315
+ it("force-adds state.json after creating it from recovery", () => {
316
+ mockExistsSync.mockImplementation((path: string) => {
317
+ if (path.includes("state.json")) return false;
318
+ if (path.includes(".git")) return false;
319
+ return true;
320
+ });
321
+ mockHeadMessage.mockReturnValue("tdd: init");
322
+ const result = loadTddState("/test", makeDeps());
323
+ expect(result.ok).toBe(true);
324
+ expect(mockStageFiles).toHaveBeenCalledWith("/test", [
325
+ ".pi/tdd/state.json",
326
+ ]);
327
+ });
328
+
329
+ it("does not force-add state.json when it already exists and is valid", () => {
330
+ mockExistsSync.mockImplementation((path: string) => {
331
+ if (path.includes("state.json")) return true;
332
+ if (path.includes(".git")) return true;
333
+ return true;
334
+ });
335
+ const result = loadTddState("/test", makeDeps());
336
+ expect(result.ok).toBe(true);
337
+ expect(mockStageFiles).not.toHaveBeenCalled();
338
+ });
339
+
340
+ it("force-adds state.json after recovering from corrupted state", () => {
341
+ mockExistsSync.mockImplementation((path: string) => {
342
+ if (path.includes("state.json")) return true;
343
+ if (path.includes(".git")) return true;
344
+ return true;
345
+ });
346
+ mockLoadPhaseState.mockImplementation(() => {
347
+ throw new Error("corrupt");
348
+ });
349
+ mockHeadMessage.mockReturnValue("tdd: init");
350
+ const result = loadTddState("/test", makeDeps());
351
+ expect(result.ok).toBe(true);
352
+ expect(mockStageFiles).toHaveBeenCalledWith("/test", [
353
+ ".pi/tdd/state.json",
354
+ ]);
355
+ });
356
+ });
package/engine/state.ts CHANGED
@@ -1,10 +1,17 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
- import type { PhaseState } from "./types.js";
3
+ import { loadConfig } from "./config.js";
4
+ import { headMessage, initGit, stageFiles } from "./git.js";
5
+ import { nextPhase } from "./transition.js";
6
+ import type { Config, PhaseState } from "./types.js";
4
7
 
5
8
  const TDD_DIR = ".pi/tdd";
6
9
  const VALID_PHASES = new Set(["red", "green", "refactor"]);
7
10
 
11
+ export type TddLoadResult =
12
+ | { ok: true; state: PhaseState; config: Config }
13
+ | { ok: false; reason: string };
14
+
8
15
  export function phaseStatePath(projectRoot: string): string {
9
16
  return join(projectRoot, TDD_DIR, "state.json");
10
17
  }
@@ -38,3 +45,130 @@ export function savePhaseState(projectRoot: string, state: PhaseState): void {
38
45
  ensureDir(path);
39
46
  writeFileSync(path, JSON.stringify(state, null, 2), "utf-8");
40
47
  }
48
+
49
+ /**
50
+ * Recover state.json from private git HEAD, or create default.
51
+ * Returns the state (does not save to disk — caller does that).
52
+ */
53
+ function recoverState(
54
+ root: string,
55
+ tddDir: string,
56
+ deps: {
57
+ existsSync: typeof existsSync;
58
+ headMessage: typeof headMessage;
59
+ nextPhase: typeof nextPhase;
60
+ } = { existsSync, headMessage, nextPhase },
61
+ ): PhaseState {
62
+ const gitDir = join(tddDir, ".git");
63
+ if (deps.existsSync(gitDir)) {
64
+ try {
65
+ const msg = deps.headMessage(root);
66
+ const m = msg.match(/^tdd: (red|green|refactor|init)$/);
67
+ if (m) {
68
+ const label = m[1];
69
+ if (label === "init") {
70
+ return { enabled: false, current: "red" };
71
+ }
72
+ const next = deps.nextPhase(label);
73
+ return { enabled: true, current: next ?? "red" };
74
+ }
75
+ } catch {
76
+ // No commits or bad HEAD — fall through to default
77
+ }
78
+ }
79
+ return { enabled: false, current: "red" };
80
+ }
81
+
82
+ /**
83
+ * Load TDD state + config in one go.
84
+ * Auto-creates state.json from private git HEAD when missing or corrupted.
85
+ * Returns ok:true with state and config when rules.json is valid.
86
+ * Returns ok:false with a specific reason string otherwise.
87
+ *
88
+ * Callers must check state.enabled themselves if they need active enforcement.
89
+ */
90
+ export function loadTddState(
91
+ root: string,
92
+ deps: {
93
+ existsSync: typeof existsSync;
94
+ loadConfig: typeof loadConfig;
95
+ initGit: typeof initGit;
96
+ loadPhaseState: typeof loadPhaseState;
97
+ savePhaseState: typeof savePhaseState;
98
+ headMessage: typeof headMessage;
99
+ nextPhase: typeof nextPhase;
100
+ stageFiles: typeof stageFiles;
101
+ } = {
102
+ existsSync,
103
+ loadConfig,
104
+ initGit,
105
+ loadPhaseState,
106
+ savePhaseState,
107
+ headMessage,
108
+ nextPhase,
109
+ stageFiles,
110
+ },
111
+ ): TddLoadResult {
112
+ const tddDir = join(root, ".pi", "tdd");
113
+ if (!deps.existsSync(tddDir)) {
114
+ return {
115
+ ok: false,
116
+ reason:
117
+ "Missing .pi/tdd/ directory. See the tdd-enforcer skill to learn how to set up TDD configs.",
118
+ };
119
+ }
120
+
121
+ const rulesPath = join(tddDir, "rules.json");
122
+ if (!deps.existsSync(rulesPath)) {
123
+ return {
124
+ ok: false,
125
+ reason:
126
+ "Missing .pi/tdd/rules.json. See the tdd-enforcer skill to learn how to set up TDD configs.",
127
+ };
128
+ }
129
+
130
+ let config: Config;
131
+ try {
132
+ config = deps.loadConfig(root);
133
+ } catch (e) {
134
+ return {
135
+ ok: false,
136
+ reason: `Invalid .pi/tdd/rules.json: ${(e as Error).message}. See the tdd-enforcer skill.`,
137
+ };
138
+ }
139
+
140
+ // Init git if missing — required for state recovery and all consumers
141
+ const gitDir = join(tddDir, ".git");
142
+ if (!deps.existsSync(gitDir)) {
143
+ try {
144
+ deps.initGit(root);
145
+ } catch (e) {
146
+ return {
147
+ ok: false,
148
+ reason: `Failed to initialise private git repo: ${(e as Error).message}`,
149
+ };
150
+ }
151
+ }
152
+
153
+ // Auto-create state.json if missing or corrupted
154
+ const phasePath = join(tddDir, "state.json");
155
+ let state: PhaseState | undefined;
156
+ if (deps.existsSync(phasePath)) {
157
+ try {
158
+ state = deps.loadPhaseState(root);
159
+ } catch {
160
+ // Corrupted — recover below
161
+ }
162
+ }
163
+ if (!state) {
164
+ state = recoverState(root, tddDir, {
165
+ existsSync: deps.existsSync,
166
+ headMessage: deps.headMessage,
167
+ nextPhase: deps.nextPhase,
168
+ });
169
+ deps.savePhaseState(root, state);
170
+ deps.stageFiles(root, [".pi/tdd/state.json"]);
171
+ }
172
+
173
+ return { ok: true, state, config };
174
+ }
@@ -25,10 +25,15 @@ describe("nextPhase", () => {
25
25
 
26
26
  // ── Pure unit tests: checkGate ──────────────────────────────────────────────
27
27
 
28
- function makeRunner(passed: boolean): TestRunner {
28
+ function makeRunner(passed: boolean, timeout?: boolean): TestRunner {
29
29
  return async (_cmds, _timeout) => ({
30
30
  passed,
31
- message: passed ? "all ok" : "tests failed",
31
+ timeout,
32
+ message: timeout
33
+ ? "npm test: timed out"
34
+ : passed
35
+ ? "all ok"
36
+ : "tests failed",
32
37
  });
33
38
  }
34
39
 
@@ -52,6 +57,19 @@ describe("checkGate", () => {
52
57
  expect(r.passed).toBe(false);
53
58
  expect(r.message).toMatch(/transitioning to GREEN/i);
54
59
  });
60
+
61
+ it("blocks on timeout — does not treat as test failure", async () => {
62
+ const r = await checkGate(
63
+ "red",
64
+ "green",
65
+ makeRunner(false, true),
66
+ testConfig,
67
+ );
68
+ expect(r.passed).toBe(false);
69
+ expect(r.timeout).toBe(true);
70
+ expect(r.message).toMatch(/timed out/i);
71
+ expect(r.message).not.toMatch(/proceed|fail/i);
72
+ });
55
73
  });
56
74
 
57
75
  describe("green → refactor (tests must pass)", () => {
@@ -76,6 +94,19 @@ describe("checkGate", () => {
76
94
  expect(r.passed).toBe(false);
77
95
  expect(r.message).toMatch(/transitioning to REFACTOR/i);
78
96
  });
97
+
98
+ it("blocks on timeout with timeout message", async () => {
99
+ const r = await checkGate(
100
+ "green",
101
+ "refactor",
102
+ makeRunner(false, true),
103
+ testConfig,
104
+ );
105
+ expect(r.passed).toBe(false);
106
+ expect(r.timeout).toBe(true);
107
+ expect(r.message).toMatch(/timed out/i);
108
+ expect(r.message).not.toMatch(/fix them/i);
109
+ });
79
110
  });
80
111
 
81
112
  describe("refactor → red (tests must pass)", () => {
@@ -100,6 +131,19 @@ describe("checkGate", () => {
100
131
  expect(r.passed).toBe(false);
101
132
  expect(r.message).toMatch(/transitioning to RED/i);
102
133
  });
134
+
135
+ it("blocks on timeout with timeout message", async () => {
136
+ const r = await checkGate(
137
+ "refactor",
138
+ "red",
139
+ makeRunner(false, true),
140
+ testConfig,
141
+ );
142
+ expect(r.passed).toBe(false);
143
+ expect(r.timeout).toBe(true);
144
+ expect(r.message).toMatch(/timed out/i);
145
+ expect(r.message).not.toMatch(/fix them/i);
146
+ });
103
147
  });
104
148
 
105
149
  it("passes test commands to the runner", async () => {
@@ -13,6 +13,7 @@ export function nextPhase(current: Phase): Phase | null {
13
13
  export interface GateResult {
14
14
  passed: boolean;
15
15
  message: string;
16
+ timeout?: boolean;
16
17
  }
17
18
 
18
19
  export type TestRunner = (
@@ -34,6 +35,15 @@ export async function checkGate(
34
35
  ): Promise<GateResult> {
35
36
  const result = await testRunner(config.testCommands, config.timeoutSeconds);
36
37
 
38
+ // Timeout blocks all transitions — don't suggest "fix tests"
39
+ if (result.timeout) {
40
+ return {
41
+ passed: false,
42
+ timeout: true,
43
+ message: `Tests timed out after ${config.timeoutSeconds}s. The test command may have hung or an operation may be blocking.`,
44
+ };
45
+ }
46
+
37
47
  switch (`${from}→${to}` as Transition) {
38
48
  case "red→green":
39
49
  if (result.passed) {
package/package.json CHANGED
@@ -1,8 +1,20 @@
1
1
  {
2
2
  "name": "tdd-enforcer",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "type": "module",
5
+ "description": "TDD enforcer extension for the pi coding agent — enforces Red-Green-Refactor phases with file access restrictions and transition gates",
6
+ "license": "MIT",
7
+ "author": "Cyclone1070 <hoangmai1070@gmail.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Cyclone1070/tdd-enforcer.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/Cyclone1070/tdd-enforcer/issues"
14
+ },
15
+ "homepage": "https://github.com/Cyclone1070/tdd-enforcer#readme",
5
16
  "scripts": {
17
+ "check": "biome check --write . && vitest run",
6
18
  "lint": "biome check .",
7
19
  "lint:fix": "biome check --write .",
8
20
  "test": "vitest run"