@productbrain/cli 0.1.0-beta.11277 → 0.1.0-beta.11288

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 (122) hide show
  1. package/README.md +3 -2
  2. package/dist/__tests__/cli-error-once.test.d.ts +2 -0
  3. package/dist/__tests__/cli-error-once.test.d.ts.map +1 -0
  4. package/dist/__tests__/cli-error-once.test.js +51 -0
  5. package/dist/__tests__/cli-error-once.test.js.map +1 -0
  6. package/dist/__tests__/init.test.d.ts +2 -1
  7. package/dist/__tests__/init.test.d.ts.map +1 -1
  8. package/dist/__tests__/init.test.js +110 -8
  9. package/dist/__tests__/init.test.js.map +1 -1
  10. package/dist/__tests__/removed-commands.test.js +31 -2
  11. package/dist/__tests__/removed-commands.test.js.map +1 -1
  12. package/dist/commands/connect-integration.test.js +1 -5
  13. package/dist/commands/connect-integration.test.js.map +1 -1
  14. package/dist/commands/connect-legacy-migration.test.js +0 -1
  15. package/dist/commands/connect-legacy-migration.test.js.map +1 -1
  16. package/dist/commands/connect-screens.d.ts +9 -13
  17. package/dist/commands/connect-screens.d.ts.map +1 -1
  18. package/dist/commands/connect-screens.js +16 -78
  19. package/dist/commands/connect-screens.js.map +1 -1
  20. package/dist/commands/connect-screens.test.d.ts +2 -0
  21. package/dist/commands/connect-screens.test.d.ts.map +1 -0
  22. package/dist/commands/connect-screens.test.js +18 -0
  23. package/dist/commands/connect-screens.test.js.map +1 -0
  24. package/dist/commands/connect.js +5 -5
  25. package/dist/commands/connect.js.map +1 -1
  26. package/dist/commands/connect.test.js +0 -4
  27. package/dist/commands/connect.test.js.map +1 -1
  28. package/dist/commands/init.d.ts +14 -1
  29. package/dist/commands/init.d.ts.map +1 -1
  30. package/dist/commands/init.js +90 -1
  31. package/dist/commands/init.js.map +1 -1
  32. package/dist/generated/routeLatencyBudget.generated.d.ts +0 -1
  33. package/dist/generated/routeLatencyBudget.generated.d.ts.map +1 -1
  34. package/dist/generated/routeLatencyBudget.generated.js +0 -10
  35. package/dist/generated/routeLatencyBudget.generated.js.map +1 -1
  36. package/dist/handleCliError.d.ts +17 -0
  37. package/dist/handleCliError.d.ts.map +1 -1
  38. package/dist/handleCliError.js +14 -3
  39. package/dist/handleCliError.js.map +1 -1
  40. package/dist/index.js +7 -33
  41. package/dist/index.js.map +1 -1
  42. package/dist/lib/client.d.ts.map +1 -1
  43. package/dist/lib/client.js +1 -2
  44. package/dist/lib/client.js.map +1 -1
  45. package/dist/lib/strip.d.ts +1 -1
  46. package/dist/lib/strip.js +1 -1
  47. package/package.json +1 -2
  48. package/dist/__tests__/handshake-augment.test.d.ts +0 -2
  49. package/dist/__tests__/handshake-augment.test.d.ts.map +0 -1
  50. package/dist/__tests__/handshake-augment.test.js +0 -407
  51. package/dist/__tests__/handshake-augment.test.js.map +0 -1
  52. package/dist/__tests__/handshake-dormancy.test.d.ts +0 -2
  53. package/dist/__tests__/handshake-dormancy.test.d.ts.map +0 -1
  54. package/dist/__tests__/handshake-dormancy.test.js +0 -24
  55. package/dist/__tests__/handshake-dormancy.test.js.map +0 -1
  56. package/dist/__tests__/handshake-formatter.test.d.ts +0 -2
  57. package/dist/__tests__/handshake-formatter.test.d.ts.map +0 -1
  58. package/dist/__tests__/handshake-formatter.test.js +0 -111
  59. package/dist/__tests__/handshake-formatter.test.js.map +0 -1
  60. package/dist/__tests__/handshake-preview.test.d.ts +0 -2
  61. package/dist/__tests__/handshake-preview.test.d.ts.map +0 -1
  62. package/dist/__tests__/handshake-preview.test.js +0 -500
  63. package/dist/__tests__/handshake-preview.test.js.map +0 -1
  64. package/dist/__tests__/handshake-session-threading.test.d.ts +0 -2
  65. package/dist/__tests__/handshake-session-threading.test.d.ts.map +0 -1
  66. package/dist/__tests__/handshake-session-threading.test.js +0 -185
  67. package/dist/__tests__/handshake-session-threading.test.js.map +0 -1
  68. package/dist/__tests__/handshake.e2e.test.d.ts +0 -2
  69. package/dist/__tests__/handshake.e2e.test.d.ts.map +0 -1
  70. package/dist/__tests__/handshake.e2e.test.js +0 -226
  71. package/dist/__tests__/handshake.e2e.test.js.map +0 -1
  72. package/dist/__tests__/handshake.test.d.ts +0 -2
  73. package/dist/__tests__/handshake.test.d.ts.map +0 -1
  74. package/dist/__tests__/handshake.test.js +0 -1040
  75. package/dist/__tests__/handshake.test.js.map +0 -1
  76. package/dist/__tests__/method-registry.integration.test.d.ts +0 -6
  77. package/dist/__tests__/method-registry.integration.test.d.ts.map +0 -1
  78. package/dist/__tests__/method-registry.integration.test.js +0 -17
  79. package/dist/__tests__/method-registry.integration.test.js.map +0 -1
  80. package/dist/__tests__/method-registry.test.d.ts +0 -12
  81. package/dist/__tests__/method-registry.test.d.ts.map +0 -1
  82. package/dist/__tests__/method-registry.test.js +0 -86
  83. package/dist/__tests__/method-registry.test.js.map +0 -1
  84. package/dist/commands/connect-context.d.ts +0 -55
  85. package/dist/commands/connect-context.d.ts.map +0 -1
  86. package/dist/commands/connect-context.js +0 -78
  87. package/dist/commands/connect-context.js.map +0 -1
  88. package/dist/commands/connect-context.test.d.ts +0 -2
  89. package/dist/commands/connect-context.test.d.ts.map +0 -1
  90. package/dist/commands/connect-context.test.js +0 -148
  91. package/dist/commands/connect-context.test.js.map +0 -1
  92. package/dist/commands/digest.d.ts +0 -17
  93. package/dist/commands/digest.d.ts.map +0 -1
  94. package/dist/commands/digest.js +0 -58
  95. package/dist/commands/digest.js.map +0 -1
  96. package/dist/commands/digest.test.d.ts +0 -2
  97. package/dist/commands/digest.test.d.ts.map +0 -1
  98. package/dist/commands/digest.test.js +0 -36
  99. package/dist/commands/digest.test.js.map +0 -1
  100. package/dist/commands/handshake.d.ts +0 -78
  101. package/dist/commands/handshake.d.ts.map +0 -1
  102. package/dist/commands/handshake.js +0 -1359
  103. package/dist/commands/handshake.js.map +0 -1
  104. package/dist/formatters/digest.d.ts +0 -13
  105. package/dist/formatters/digest.d.ts.map +0 -1
  106. package/dist/formatters/digest.js +0 -98
  107. package/dist/formatters/digest.js.map +0 -1
  108. package/dist/formatters/digest.test.d.ts +0 -2
  109. package/dist/formatters/digest.test.d.ts.map +0 -1
  110. package/dist/formatters/digest.test.js +0 -166
  111. package/dist/formatters/digest.test.js.map +0 -1
  112. package/dist/lib/method-registry.d.ts +0 -37
  113. package/dist/lib/method-registry.d.ts.map +0 -1
  114. package/dist/lib/method-registry.js +0 -41
  115. package/dist/lib/method-registry.js.map +0 -1
  116. package/templates/general/code-integrity.md +0 -11
  117. package/templates/general/getting-started.md +0 -12
  118. package/templates/method-registry.json +0 -16
  119. package/templates/node-ts/code-integrity.md +0 -13
  120. package/templates/node-ts/testing.md +0 -12
  121. package/templates/python/code-integrity.md +0 -13
  122. package/templates/python/testing.md +0 -12
@@ -1,1040 +0,0 @@
1
- /**
2
- * pb handshake --init — unit tests.
3
- * DEC-271: two-file split (team vs personal). DEC-272: permission whitelist.
4
- * TEN-712: every hook command must end with '|| true' so it never blocks Claude Code from starting.
5
- */
6
- import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
7
- import { join } from 'path';
8
- // Import the mocked fs functions so we can use vi.mocked() to change their implementations per-test.
9
- // vi.mock('fs', ...) below hoists this mock, so these imports resolve to the mocked versions.
10
- import { readdirSync as readdirSyncMock } from 'fs';
11
- // vi.mock calls are hoisted — use vi.hoisted() for constants referenced inside factories.
12
- const { vfs, vfsMtimes, vfsDirs, vfsSymlinks, vfsRealpaths, vfsInodes, MOCK_CWD, MOCK_HOME } = vi.hoisted(() => ({
13
- vfs: {},
14
- // WP-379 S5b: mtime map used by statSync mock for case-collision ordering tests.
15
- vfsMtimes: {},
16
- // PR #912 follow-up: lstatSync needs dir-vs-file-vs-symlink distinction, which the flat
17
- // `vfs` content map doesn't carry (a directory marker is stored as `vfs[dir] = ''`, same
18
- // shape as an empty file) — these two sets disambiguate for the Cursor nested-skills tests.
19
- vfsDirs: new Set(),
20
- vfsSymlinks: new Set(),
21
- // PR #912 follow-up (Cursor security review): explicit path→realpath overrides so a test can
22
- // simulate an INTERMEDIATE symlinked component (e.g. .cursor/skills itself) resolving outside
23
- // the repo, distinct from vfsSymlinks which only marks the final path component as a link.
24
- vfsRealpaths: new Map(),
25
- // Round 13: explicit path→ino override so a test can make two case-variant paths resolve to
26
- // the SAME filesystem entry (case-insensitive FS simulation). Unset paths fall back to a
27
- // deterministic per-path hash in the statSync mock below.
28
- vfsInodes: new Map(),
29
- MOCK_CWD: '/tmp/pb-test-cwd',
30
- MOCK_HOME: '/tmp/pb-test-home',
31
- }));
32
- vi.mock('fs', () => ({
33
- mkdirSync: vi.fn(),
34
- writeFileSync: vi.fn((path, content) => {
35
- vfs[path] = content;
36
- }),
37
- appendFileSync: vi.fn((path, content) => {
38
- vfs[path] = (vfs[path] ?? '') + content;
39
- }),
40
- existsSync: vi.fn((path) => path in vfs),
41
- readFileSync: vi.fn((path, _enc) => {
42
- if (path in vfs)
43
- return vfs[path];
44
- throw Object.assign(new Error(`ENOENT: no such file '${path}'`), { code: 'ENOENT' });
45
- }),
46
- readdirSync: vi.fn((_dir) => []),
47
- copyFileSync: vi.fn(),
48
- // WP-379 S5b: unlinkSync + statSync for orphan unlink + case-collision resolution.
49
- unlinkSync: vi.fn((path) => {
50
- delete vfs[path];
51
- }),
52
- statSync: vi.fn((path) => {
53
- if (path in vfs) {
54
- // Return a fake stat with an incrementing mtime based on path hash (deterministic).
55
- // Tests that need specific mtime ordering should set vfs[path] before calling.
56
- const mtimeMs = vfsMtimes[path] ?? 1000;
57
- // Round 13: dev/ino for case-insensitive-alias detection. dev is constant (single fake
58
- // filesystem); ino defaults to a deterministic per-path hash unless a test overrides it
59
- // via vfsInodes to make two case-variant paths resolve to the same entry.
60
- let ino = vfsInodes.get(path);
61
- if (ino === undefined) {
62
- let h = 0;
63
- for (let i = 0; i < path.length; i++)
64
- h = (h * 31 + path.charCodeAt(i)) | 0;
65
- ino = h;
66
- }
67
- return { mtimeMs, dev: 1, ino };
68
- }
69
- throw Object.assign(new Error(`ENOENT: stat '${path}'`), { code: 'ENOENT' });
70
- }),
71
- // PR #912 follow-up: lstatSync backs the Cursor nested-skills symlink refusal — never
72
- // follows a link, so a path marked in vfsSymlinks reports neither isDirectory() nor isFile().
73
- lstatSync: vi.fn((path) => {
74
- const isSymlink = vfsSymlinks.has(path);
75
- const isDir = vfsDirs.has(path);
76
- const isFile = !isSymlink && !isDir && path in vfs;
77
- if (!isSymlink && !isDir && !isFile) {
78
- throw Object.assign(new Error(`ENOENT: lstat '${path}'`), { code: 'ENOENT' });
79
- }
80
- // Round 15: dev/ino for directory-entry-identity comparisons (findLeftoverCursorSkills'
81
- // live-alias check). Same default-hash-or-vfsInodes-override scheme as statSync below.
82
- let ino = vfsInodes.get(path);
83
- if (ino === undefined) {
84
- let h = 0;
85
- for (let i = 0; i < path.length; i++)
86
- h = (h * 31 + path.charCodeAt(i)) | 0;
87
- ino = h;
88
- }
89
- return {
90
- isDirectory: () => isDir,
91
- isFile: () => isFile,
92
- isSymbolicLink: () => isSymlink,
93
- dev: 1,
94
- ino,
95
- };
96
- }),
97
- // PR #912 follow-up: realpathSync backs the Cursor-skills-root containment check — an explicit
98
- // vfsRealpaths override simulates an intermediate symlinked component; otherwise identity.
99
- // Identity by default (a real fs resolves an ordinary path, including MOCK_CWD itself, to
100
- // itself) — vfsRealpaths overrides model a specific symlinked path resolving elsewhere.
101
- realpathSync: vi.fn((path) => vfsRealpaths.get(path) ?? path),
102
- }));
103
- vi.mock('os', () => ({
104
- homedir: vi.fn(() => MOCK_HOME),
105
- }));
106
- // prompts mock: select returns 'work' (second option)
107
- vi.mock('../lib/prompts.js', () => ({
108
- select: () => Promise.resolve('work'),
109
- confirm: () => Promise.resolve(false),
110
- ask: () => Promise.resolve(''),
111
- password: () => Promise.resolve(''),
112
- isInteractive: () => true,
113
- }));
114
- import { runHandshakeInit, normalizeHandshakeContentForComparison, findLeftoverProjections, classifyDriftBucket, deriveHandshakeStartupSignals, dereferencePrRefToPaths } from '../commands/handshake.js';
115
- import { findLeftoverCursorSkills, LEFTOVER_FILES_MAX } from '../commands/handshakeCursorSkillCleanup.js';
116
- import { MARKER } from '../generators/adapters.js';
117
- /** PR #911 review (Codex P2): findLeftoverProjections scopes reporting to allowedTargets — tests that want every surface scanned pass this. */
118
- const ALL_SURFACES = new Set(['cursor', 'claude', 'codex', 'copilot']);
119
- import { createHash } from 'crypto';
120
- const TEAM_PATH = join(MOCK_CWD, '.claude', 'settings.json');
121
- const PERSONAL_PATH = join(MOCK_HOME, '.claude', 'settings.json');
122
- describe('runHandshakeInit', () => {
123
- let cwdSpy;
124
- beforeEach(() => {
125
- Object.keys(vfs).forEach((k) => delete vfs[k]);
126
- vi.clearAllMocks();
127
- cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(MOCK_CWD);
128
- vi.spyOn(console, 'log').mockImplementation(() => { });
129
- vi.spyOn(console, 'error').mockImplementation(() => { });
130
- });
131
- afterEach(() => {
132
- cwdSpy.mockRestore();
133
- });
134
- describe('basic writes (DEC-271)', () => {
135
- it('writes hooks to team config (.claude/settings.json relative to cwd)', async () => {
136
- await runHandshakeInit({ level: 'work', dryRun: false });
137
- expect(vfs[TEAM_PATH]).toBeDefined();
138
- const team = JSON.parse(vfs[TEAM_PATH]);
139
- expect(team.hooks.SessionStart).toHaveLength(1);
140
- expect(team.hooks.SessionEnd).toHaveLength(1);
141
- expect(team.hooks.Stop).toBeUndefined();
142
- expect(team.hooks.PreCompact).toBeUndefined();
143
- expect(team.permissions.allow).toContain('Bash(pb:*)');
144
- });
145
- it('writes trust level to personal config (~/.claude/settings.json)', async () => {
146
- await runHandshakeInit({ level: 'work', dryRun: false });
147
- expect(vfs[PERSONAL_PATH]).toBeDefined();
148
- const personal = JSON.parse(vfs[PERSONAL_PATH]);
149
- expect(personal.permissions.defaultMode).toBe('auto');
150
- expect(personal.permissions.allow).toContain('Bash(pb:*)');
151
- expect(personal.permissions.allow).toContain('Bash(git:*)');
152
- expect(personal.permissions.allow).toContain('Bash(npm run:*)');
153
- });
154
- it('guide level sets auto mode with minimal permissions', async () => {
155
- await runHandshakeInit({ level: 'guide', dryRun: false });
156
- const personal = JSON.parse(vfs[PERSONAL_PATH]);
157
- expect(personal.permissions.defaultMode).toBe('auto');
158
- expect(personal.permissions.allow).toContain('Bash(pb:*)');
159
- expect(personal.permissions.allow).toContain('Bash(git:*)');
160
- });
161
- it('full-trust level sets bypassPermissions mode', async () => {
162
- await runHandshakeInit({ level: 'full-trust', dryRun: false });
163
- const personal = JSON.parse(vfs[PERSONAL_PATH]);
164
- expect(personal.permissions.defaultMode).toBe('bypassPermissions');
165
- });
166
- });
167
- describe('idempotency', () => {
168
- it('running twice produces no duplicate hooks in team config', async () => {
169
- await runHandshakeInit({ level: 'work', dryRun: false });
170
- await runHandshakeInit({ level: 'work', dryRun: false });
171
- const team = JSON.parse(vfs[TEAM_PATH]);
172
- expect(team.hooks.SessionStart).toHaveLength(1);
173
- expect(team.hooks.SessionEnd).toHaveLength(1);
174
- expect(team.hooks.Stop).toBeUndefined();
175
- expect(team.permissions.allow.filter((p) => p === 'Bash(pb:*)')).toHaveLength(1);
176
- });
177
- it('running twice produces no duplicate permissions in personal config', async () => {
178
- await runHandshakeInit({ level: 'work', dryRun: false });
179
- await runHandshakeInit({ level: 'work', dryRun: false });
180
- const personal = JSON.parse(vfs[PERSONAL_PATH]);
181
- expect(personal.permissions.allow.filter((p) => p === 'Bash(pb:*)')).toHaveLength(1);
182
- expect(personal.permissions.allow.filter((p) => p === 'Bash(git:*)')).toHaveLength(1);
183
- });
184
- });
185
- // TASK-763 (DEC-2038): an older init put pb session close on Stop, which fires after every turn.
186
- describe('legacy Stop close migration', () => {
187
- const close = { type: 'command', command: 'pb session close 2>/dev/null || true', statusMessage: 'Closing pb session...' };
188
- const other = { type: 'command', command: 'echo my-own-stop-hook' };
189
- it('removes the Stop close, keeps an unrelated Stop hook, and installs the SessionEnd close once', async () => {
190
- vfs[TEAM_PATH] = JSON.stringify({ hooks: { Stop: [{ hooks: [close, other] }] } });
191
- await runHandshakeInit({ level: 'work', dryRun: false });
192
- await runHandshakeInit({ level: 'work', dryRun: false });
193
- const team = JSON.parse(vfs[TEAM_PATH]);
194
- expect(team.hooks.Stop).toEqual([{ hooks: [other] }]);
195
- expect(team.hooks.SessionEnd).toHaveLength(1);
196
- expect(team.hooks.SessionEnd[0].hooks[0]).toMatchObject({ command: close.command, timeout: 15 });
197
- });
198
- it('drops the Stop event entirely when the close was its only hook', async () => {
199
- vfs[TEAM_PATH] = JSON.stringify({ hooks: { Stop: [{ hooks: [close] }] } });
200
- await runHandshakeInit({ level: 'work', dryRun: false });
201
- const team = JSON.parse(vfs[TEAM_PATH]);
202
- expect(team.hooks.Stop).toBeUndefined();
203
- expect(team.hooks.SessionEnd).toHaveLength(1);
204
- });
205
- });
206
- describe('security constraints (DEC-272)', () => {
207
- it('never puts defaultMode in team config', async () => {
208
- await runHandshakeInit({ level: 'full-trust', dryRun: false });
209
- const team = JSON.parse(vfs[TEAM_PATH]);
210
- expect(team.permissions?.defaultMode).toBeUndefined();
211
- });
212
- it('never puts bypassPermissions in team config even for full-trust level', async () => {
213
- await runHandshakeInit({ level: 'full-trust', dryRun: false });
214
- const team = JSON.parse(vfs[TEAM_PATH]);
215
- expect(JSON.stringify(team)).not.toContain('bypassPermissions');
216
- });
217
- it('Bash(npx:*) appears in silent level personal config', async () => {
218
- await runHandshakeInit({ level: 'silent', dryRun: false });
219
- const personal = JSON.parse(vfs[PERSONAL_PATH]);
220
- expect(personal.permissions.allow).toContain('Bash(npx:*)');
221
- });
222
- it('Bash(npx:*) does NOT appear in work level personal config', async () => {
223
- await runHandshakeInit({ level: 'work', dryRun: false });
224
- const personal = JSON.parse(vfs[PERSONAL_PATH]);
225
- expect(personal.permissions.allow).not.toContain('Bash(npx:*)');
226
- });
227
- it('Bash(npx:*) does NOT appear in guide level personal config', async () => {
228
- await runHandshakeInit({ level: 'guide', dryRun: false });
229
- const personal = JSON.parse(vfs[PERSONAL_PATH]);
230
- expect(personal.permissions.allow).not.toContain('Bash(npx:*)');
231
- });
232
- it('Bash(npx:*) does NOT appear in team config for any level', async () => {
233
- for (const level of ['guide', 'work', 'silent', 'full-trust']) {
234
- Object.keys(vfs).forEach((k) => delete vfs[k]);
235
- await runHandshakeInit({ level, dryRun: false });
236
- const team = JSON.parse(vfs[TEAM_PATH]);
237
- expect(JSON.stringify(team)).not.toContain('npx:*');
238
- }
239
- });
240
- });
241
- describe('hook failure contract (TEN-712)', () => {
242
- it('all hook commands include fail-silent suffix (|| true)', async () => {
243
- await runHandshakeInit({ level: 'work', dryRun: false });
244
- const team = JSON.parse(vfs[TEAM_PATH]);
245
- const sessionStartCmd = team.hooks.SessionStart[0].hooks[0].command;
246
- const sessionEndCmd = team.hooks.SessionEnd[0].hooks[0].command;
247
- expect(sessionStartCmd).toContain('|| true');
248
- expect(sessionEndCmd).toContain('|| true');
249
- });
250
- it('pb session start hook command is exact', async () => {
251
- await runHandshakeInit({ level: 'work', dryRun: false });
252
- const team = JSON.parse(vfs[TEAM_PATH]);
253
- const cmd = team.hooks.SessionStart[0].hooks[0].command;
254
- expect(cmd).toBe("pb session start 2>&1 || true");
255
- });
256
- it('pb session close hook command is exact', async () => {
257
- await runHandshakeInit({ level: 'work', dryRun: false });
258
- const team = JSON.parse(vfs[TEAM_PATH]);
259
- const cmd = team.hooks.SessionEnd[0].hooks[0].command;
260
- expect(cmd).toBe('pb session close 2>/dev/null || true');
261
- });
262
- });
263
- describe('--dry-run flag', () => {
264
- it('does not write any files when dryRun is true', async () => {
265
- await runHandshakeInit({ level: 'work', dryRun: true });
266
- expect(vfs[TEAM_PATH]).toBeUndefined();
267
- expect(vfs[PERSONAL_PATH]).toBeUndefined();
268
- });
269
- });
270
- describe('--level flag validation', () => {
271
- it('throws CLIError for unknown level', async () => {
272
- await expect(runHandshakeInit({ level: 'invalid-level', dryRun: false })).rejects.toThrow('Unknown level');
273
- });
274
- it('does not write files when level is invalid', async () => {
275
- await expect(runHandshakeInit({ level: 'GUIDE', dryRun: false })).rejects.toThrow();
276
- expect(vfs[TEAM_PATH]).toBeUndefined();
277
- expect(vfs[PERSONAL_PATH]).toBeUndefined();
278
- });
279
- });
280
- });
281
- describe('normalizeHandshakeContentForComparison', () => {
282
- it('treats handshake timestamp comment as non-semantic', () => {
283
- const a = '<!-- auto-generated by pb handshake — 2026-04-02T10:00:00.000Z -->\nbody\n';
284
- const b = '<!-- auto-generated by pb handshake — 2026-04-02T11:00:00.000Z -->\nbody\n';
285
- expect(normalizeHandshakeContentForComparison(a)).toBe(normalizeHandshakeContentForComparison(b));
286
- });
287
- it('treats generated metadata line as non-semantic', () => {
288
- const a = '_Generated: 2026-04-02T10:00:00.000Z_\ncontent\n';
289
- const b = '_Generated: 2026-04-02T11:00:00.000Z_\ncontent\n';
290
- expect(normalizeHandshakeContentForComparison(a)).toBe(normalizeHandshakeContentForComparison(b));
291
- });
292
- it('preserves meaningful content differences', () => {
293
- const a = '<!-- auto-generated by pb handshake — 2026-04-02T10:00:00.000Z -->\nalpha\n';
294
- const b = '<!-- auto-generated by pb handshake — 2026-04-02T11:00:00.000Z -->\nbeta\n';
295
- expect(normalizeHandshakeContentForComparison(a)).not.toBe(normalizeHandshakeContentForComparison(b));
296
- });
297
- });
298
- // WP-379 S3b's probeStarterSetupSeeded + pollUntilSeedsReady tests deleted at WP-776 S0
299
- // round-1 review (Codex P1, verified regression): nothing seeds setup-assets any more, so
300
- // the functions they tested (whose readiness gate was keyed on starterSetupSeeded alone)
301
- // are deleted from packages/cli/src/commands/handshake.ts.
302
- // ── WP-379 S5b: findLeftoverProjections + findLeftoverCursorSkills — REPORT-ONLY ────────────
303
- //
304
- // Coordinator ruling (PR #912 round 10): nine review rounds on the same unlink mechanism —
305
- // symlinks, case collisions, empty-DB states, tamper preservation — is the signal that a
306
- // deletion mechanism over a user's filesystem is defensive machinery whose edge cases never
307
- // end. pb handshake no longer unlinks, renames, or recreates any leftover file; these tests
308
- // assert survival AND report inclusion for each stale class. All file system operations go
309
- // through the vfs mock defined at the top of this file.
310
- describe('findLeftoverProjections (WP-379 S5b, report-only)', () => {
311
- beforeEach(() => {
312
- Object.keys(vfs).forEach((k) => delete vfs[k]);
313
- Object.keys(vfsMtimes).forEach((k) => delete vfsMtimes[k]);
314
- vfsDirs.clear();
315
- vfsSymlinks.clear();
316
- vfsRealpaths.clear();
317
- vfsInodes.clear();
318
- vi.clearAllMocks();
319
- });
320
- function writeMarkedFile(path, extra = '') {
321
- const dir = path.substring(0, path.lastIndexOf('/'));
322
- vfs[dir] = '';
323
- vfs[path] = `${MARKER}\n# Rule\n${extra}`;
324
- }
325
- function writeUserFile(path) {
326
- const dir = path.substring(0, path.lastIndexOf('/'));
327
- vfs[dir] = '';
328
- vfs[path] = '# My user rule — no marker here\n';
329
- }
330
- it('an exact-match file is not reported; a case-variant with the same stem is reported as leftover and survives', () => {
331
- const dir = `${MOCK_CWD}/.cursor/rules`;
332
- const exact = `${dir}/setup-productbrain.mdc`;
333
- const variant = `${dir}/Setup-ProductBrain.mdc`;
334
- writeMarkedFile(exact);
335
- writeMarkedFile(variant);
336
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
337
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['setup-productbrain.mdc', 'Setup-ProductBrain.mdc'] : []));
338
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, ['setup-productbrain'], ALL_SURFACES);
339
- expect(exact in vfs).toBe(true);
340
- expect(variant in vfs).toBe(true); // survives — never unlinked
341
- expect(leftovers.some((l) => l.path === exact)).toBe(false); // current — not reported
342
- expect(leftovers.some((l) => l.path === variant && l.reason.includes('stale case'))).toBe(true);
343
- });
344
- it('a marker-bearing file with no canonical match is reported as an orphan and survives', () => {
345
- const dir = `${MOCK_CWD}/.cursor/rules`;
346
- const orphan = `${dir}/old-orphaned-rule.mdc`;
347
- writeMarkedFile(orphan);
348
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
349
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['old-orphaned-rule.mdc'] : []));
350
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, ['some-other-rule'], ALL_SURFACES);
351
- expect(orphan in vfs).toBe(true); // survives — never unlinked
352
- expect(leftovers.some((l) => l.path === orphan && l.reason.includes('orphan'))).toBe(true);
353
- });
354
- it('a leftover .dormant file is reported and survives, regardless of content match with its live sibling', () => {
355
- const dir = `${MOCK_CWD}/.claude/rules`;
356
- const live = `${dir}/setup-productbrain.md`;
357
- const dormant = `${dir}/setup-productbrain.md.dormant`;
358
- writeMarkedFile(live, 'Same body');
359
- writeMarkedFile(dormant, 'Same body');
360
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
361
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['setup-productbrain.md', 'setup-productbrain.md.dormant'] : []));
362
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, ['setup-productbrain'], ALL_SURFACES);
363
- expect(live in vfs).toBe(true);
364
- expect(dormant in vfs).toBe(true); // survives, even though content matches the live file
365
- expect(leftovers.some((l) => l.path === live)).toBe(false);
366
- expect(leftovers.some((l) => l.path === dormant && l.reason.includes('.dormant'))).toBe(true);
367
- });
368
- it('a user-owned file (no marker) is never reported and never touched', () => {
369
- const dir = `${MOCK_CWD}/.cursor/rules`;
370
- const userFile = `${dir}/foo.mdc`;
371
- writeUserFile(userFile);
372
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
373
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['foo.mdc'] : []));
374
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, [], ALL_SURFACES);
375
- expect(userFile in vfs).toBe(true);
376
- expect(leftovers.some((l) => l.path === userFile)).toBe(false);
377
- });
378
- it('an unselected surface is left unreported entirely', () => {
379
- const dir = `${MOCK_CWD}/.codex/skills`;
380
- const orphan = `${dir}/old-skill.md`;
381
- writeMarkedFile(orphan);
382
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
383
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['old-skill.md'] : []));
384
- const claudeOnly = new Set(['claude']);
385
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, [], claudeOnly);
386
- expect(orphan in vfs).toBe(true);
387
- expect(leftovers.some((l) => l.path === orphan)).toBe(false);
388
- });
389
- it('PR #912 round 11 (Codex P2): a generated router/index file (no matching asset name) is not reported when its exact path is in the write plan', () => {
390
- const dir = `${MOCK_CWD}/.codex/skills`;
391
- const indexFile = `${dir}/README.md`;
392
- writeMarkedFile(indexFile);
393
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
394
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['README.md'] : []));
395
- // No asset name matches "readme" — the old asset-name-only comparison would call this an
396
- // orphan even though the write plan legitimately (re)generates it every run.
397
- const exactRelativePaths = new Set(['.codex/skills/README.md']);
398
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, ['setup-productbrain'], ALL_SURFACES, undefined, exactRelativePaths);
399
- expect(leftovers.some((l) => l.path === indexFile)).toBe(false);
400
- });
401
- it('PR #912 round 11 (Codex P2): a canonical raw name not already in normalized form is not reported as a stale variant when it is the exact write-plan path', () => {
402
- const dir = `${MOCK_CWD}/.claude/rules`;
403
- const rawNameFile = `${dir}/Setup Skill.md`;
404
- writeMarkedFile(rawNameFile);
405
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
406
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['Setup Skill.md'] : []));
407
- // "Setup Skill" normalizes to "setup-skill", so the raw filename's stem !== its normalized
408
- // form — without the exact-path carve-out this reads as a stale case/punctuation variant
409
- // even though the writer emits this exact raw name every run.
410
- const exactRelativePaths = new Set(['.claude/rules/Setup Skill.md']);
411
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, ['Setup Skill'], ALL_SURFACES, undefined, exactRelativePaths);
412
- expect(leftovers.some((l) => l.path === rawNameFile)).toBe(false);
413
- });
414
- it('PR #912 round 11 (Codex P2): without the exact-path carve-out, that same raw-name file is still (wrongly) reported as a stale variant — pins the failure mode the fix closes', () => {
415
- const dir = `${MOCK_CWD}/.claude/rules`;
416
- const rawNameFile = `${dir}/Setup Skill.md`;
417
- writeMarkedFile(rawNameFile);
418
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
419
- readdirSyncMock.mockImplementation((d) => (d === dir ? ['Setup Skill.md'] : []));
420
- const { files: leftovers } = findLeftoverProjections(MOCK_CWD, ['Setup Skill'], ALL_SURFACES);
421
- expect(leftovers.some((l) => l.path === rawNameFile && l.reason.includes('stale case'))).toBe(true);
422
- });
423
- it('PR #912 round 13 (Codex P2): stops scanning after LEFTOVER_FILES_MAX + 1 matches, reporting truncated=true and a capped list', () => {
424
- const dir = `${MOCK_CWD}/.cursor/rules`;
425
- const count = LEFTOVER_FILES_MAX + 5;
426
- const filenames = Array.from({ length: count }, (_, i) => `orphan-${i}.mdc`);
427
- for (const f of filenames)
428
- writeMarkedFile(`${dir}/${f}`);
429
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
430
- readdirSyncMock.mockImplementation((d) => (d === dir ? filenames : []));
431
- const { files: leftovers, truncated } = findLeftoverProjections(MOCK_CWD, [], ALL_SURFACES);
432
- expect(truncated).toBe(true);
433
- expect(leftovers).toHaveLength(LEFTOVER_FILES_MAX);
434
- // Every file still survives on disk — this is I/O and reporting bound, never deletion.
435
- for (const f of filenames)
436
- expect(`${dir}/${f}` in vfs).toBe(true);
437
- });
438
- it('a count at exactly the cap is NOT reported as truncated', () => {
439
- const dir = `${MOCK_CWD}/.cursor/rules`;
440
- const filenames = Array.from({ length: LEFTOVER_FILES_MAX }, (_, i) => `orphan-${i}.mdc`);
441
- for (const f of filenames)
442
- writeMarkedFile(`${dir}/${f}`);
443
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
444
- readdirSyncMock.mockImplementation((d) => (d === dir ? filenames : []));
445
- const { files: leftovers, truncated } = findLeftoverProjections(MOCK_CWD, [], ALL_SURFACES);
446
- expect(truncated).toBe(false);
447
- expect(leftovers).toHaveLength(LEFTOVER_FILES_MAX);
448
- });
449
- });
450
- describe('findLeftoverCursorSkills (WP-379 S5b nested layout, report-only)', () => {
451
- beforeEach(() => {
452
- Object.keys(vfs).forEach((k) => delete vfs[k]);
453
- vfsDirs.clear();
454
- vfsSymlinks.clear();
455
- vfsRealpaths.clear();
456
- vfsInodes.clear();
457
- vi.clearAllMocks();
458
- });
459
- it('an orphan nested Cursor skill is reported as leftover and survives', () => {
460
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
461
- const orphanDir = `${skillsDir}/old-skill`;
462
- const orphanMd = `${orphanDir}/SKILL.md`;
463
- vfs[skillsDir] = '';
464
- vfsDirs.add(skillsDir);
465
- vfsDirs.add(orphanDir);
466
- vfs[orphanMd] = `${MARKER}\n# Old skill\n`;
467
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
468
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['old-skill'] : []));
469
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, []);
470
- expect(orphanMd in vfs).toBe(true); // survives — never unlinked
471
- expect(leftovers.some((l) => l.path === orphanMd && l.reason.includes('orphan'))).toBe(true);
472
- });
473
- it('a Title-Cased canonical Cursor skill directory is not reported (correctly current) — the write loop emits the raw canonical name', () => {
474
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
475
- const activeDir = `${skillsDir}/Setup Skill`;
476
- const activeMd = `${activeDir}/SKILL.md`;
477
- vfs[skillsDir] = '';
478
- vfsDirs.add(skillsDir);
479
- vfsDirs.add(activeDir);
480
- vfs[activeMd] = `${MARKER}\n# Active\n`;
481
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
482
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['Setup Skill'] : []));
483
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, ['Setup Skill']);
484
- expect(activeMd in vfs).toBe(true);
485
- expect(leftovers.some((l) => l.path === activeMd)).toBe(false);
486
- });
487
- it('a stale case/punctuation-variant Cursor skill directory is reported as leftover and survives — normalized stem alone is not the canonical name', () => {
488
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
489
- const staleDir = `${skillsDir}/setup-skill`; // normalized stem, NOT the raw canonical name
490
- const staleMd = `${staleDir}/SKILL.md`;
491
- vfs[skillsDir] = '';
492
- vfsDirs.add(skillsDir);
493
- vfsDirs.add(staleDir);
494
- vfs[staleMd] = `${MARKER}\n# Stale cased\n`;
495
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
496
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['setup-skill'] : []));
497
- // Canonical raw name is Title-Cased ("Setup Skill"), never the lowercase-slug ("setup-skill").
498
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, ['Setup Skill']);
499
- expect(staleMd in vfs).toBe(true); // survives — never unlinked
500
- expect(leftovers.some((l) => l.path === staleMd && l.reason.includes('stale case'))).toBe(true);
501
- });
502
- it('a user-owned Cursor skill (no marker) is never reported and never touched', () => {
503
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
504
- const userDir = `${skillsDir}/my-skill`;
505
- const userMd = `${userDir}/SKILL.md`;
506
- vfs[skillsDir] = '';
507
- vfsDirs.add(skillsDir);
508
- vfsDirs.add(userDir);
509
- vfs[userMd] = '# My own skill — no marker\n';
510
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
511
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['my-skill'] : []));
512
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, []);
513
- expect(userMd in vfs).toBe(true);
514
- expect(leftovers.some((l) => l.path === userMd)).toBe(false);
515
- });
516
- it('PR #912 round 15 (Codex P2): a case-only alias that resolves to the SAME directory entry as the canonical path is not reported as stale (case-insensitive filesystem)', () => {
517
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
518
- // On a case-insensitive FS, the directory literally on disk is "setup-skill" but the OS
519
- // also resolves "Setup Skill" to that SAME entry — simulate that by giving both DIRECTORY
520
- // paths' lstat() the same dev+ino, exactly like a real case-insensitive filesystem would.
521
- const aliasDir = `${skillsDir}/setup-skill`;
522
- const canonicalDir = `${skillsDir}/Setup Skill`;
523
- const aliasMd = `${aliasDir}/SKILL.md`;
524
- vfs[skillsDir] = '';
525
- vfsDirs.add(skillsDir);
526
- vfsDirs.add(aliasDir);
527
- vfsDirs.add(canonicalDir); // same physical entry, reachable under either spelling
528
- vfs[aliasMd] = `${MARKER}\n# Active (case-insensitive alias)\n`;
529
- vfsInodes.set(aliasDir, 777);
530
- vfsInodes.set(canonicalDir, 777); // same entry on a case-insensitive FS
531
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
532
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['setup-skill'] : []));
533
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, ['Setup Skill']);
534
- expect(aliasMd in vfs).toBe(true); // survives — was never a candidate for removal anyway
535
- expect(leftovers.some((l) => l.path === aliasMd)).toBe(false);
536
- });
537
- it('PR #912 round 15 (Codex P2): the SOLE on-disk entry being itself a symlink is still a live alias, not a leftover, when both case spellings resolve to it', () => {
538
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
539
- // "setup-skill" is the ONLY directory entry, and it happens to be a symlink (e.g. to some
540
- // external skill store) — but on a case-insensitive FS, "Setup Skill" resolves to that SAME
541
- // entry too. Round 14's "never exempt a symlink" rule wrongly flagged this as stale; round 15
542
- // compares lstat identity instead, which correctly treats "same entry" as a live alias
543
- // regardless of whether that shared entry happens to be a symlink.
544
- const aliasDir = `${skillsDir}/setup-skill`;
545
- const canonicalDir = `${skillsDir}/Setup Skill`;
546
- const aliasMd = `${aliasDir}/SKILL.md`;
547
- vfs[skillsDir] = '';
548
- vfsDirs.add(skillsDir);
549
- vfsSymlinks.add(aliasDir);
550
- vfsSymlinks.add(canonicalDir); // same physical symlink, addressed by either spelling
551
- vfs[aliasMd] = `${MARKER}\n# Active (sole entry is a symlink)\n`;
552
- vfsInodes.set(aliasDir, 999);
553
- vfsInodes.set(canonicalDir, 999); // identical lstat identity — one real entry
554
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
555
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['setup-skill'] : []));
556
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, ['Setup Skill']);
557
- expect(aliasMd in vfs).toBe(true);
558
- expect(leftovers.some((l) => l.path === aliasMd)).toBe(false);
559
- });
560
- it('PR #912 round 15 (Codex P2): a SYMLINKED case-only alias pointing AT a distinct canonical directory is still reported as stale (case-sensitive filesystem, two real entries)', () => {
561
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
562
- // "setup-skill" is a SYMLINK pointing AT the canonical "Setup Skill" directory — TWO
563
- // distinct, separately-readdirSync-visible entries. lstat (never follows) on each gives a
564
- // DIFFERENT identity: the symlink's own inode vs. the real target directory's inode.
565
- const aliasDir = `${skillsDir}/setup-skill`;
566
- const canonicalDir = `${skillsDir}/Setup Skill`;
567
- const aliasMd = `${aliasDir}/SKILL.md`;
568
- vfs[skillsDir] = '';
569
- vfsDirs.add(skillsDir);
570
- vfsSymlinks.add(aliasDir); // the discovered directory entry IS a symlink
571
- vfsDirs.add(canonicalDir); // the canonical directory is a real, distinct entry
572
- vfs[aliasMd] = `${MARKER}\n# Symlinked alias\n`;
573
- // No vfsInodes override — default per-path hash means aliasDir and canonicalDir get
574
- // DIFFERENT inos, matching two genuinely distinct filesystem objects.
575
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
576
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['setup-skill'] : []));
577
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, ['Setup Skill']);
578
- expect(aliasMd in vfs).toBe(true); // survives — report-only, never unlinked
579
- expect(leftovers.some((l) => l.path === aliasMd && l.reason.includes('stale case'))).toBe(true);
580
- });
581
- it('PR #912 round 13 (Codex P2): a genuinely distinct stale directory (different inode) is still reported, even with the same normalized stem', () => {
582
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
583
- const staleDir = `${skillsDir}/setup-skill`;
584
- const staleMd = `${staleDir}/SKILL.md`;
585
- vfs[skillsDir] = '';
586
- vfsDirs.add(skillsDir);
587
- vfsDirs.add(staleDir);
588
- vfs[staleMd] = `${MARKER}\n# Genuinely stale\n`;
589
- // The canonical "Setup Skill" directory doesn't exist in this test at all (lstatSync on it
590
- // throws ENOENT, caught, treated as no match) — a real, distinct stale directory, not an alias.
591
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
592
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? ['setup-skill'] : []));
593
- const { files: leftovers } = findLeftoverCursorSkills(MOCK_CWD, ['Setup Skill']);
594
- expect(staleMd in vfs).toBe(true); // survives — never unlinked
595
- expect(leftovers.some((l) => l.path === staleMd && l.reason.includes('stale case'))).toBe(true);
596
- });
597
- it('PR #912 round 13 (Codex P2): stops scanning after maxResults + 1 matches, reporting truncated=true and a capped list', () => {
598
- const skillsDir = `${MOCK_CWD}/.cursor/skills`;
599
- const count = 8;
600
- const dirNames = Array.from({ length: count }, (_, i) => `old-skill-${i}`);
601
- vfs[skillsDir] = '';
602
- vfsDirs.add(skillsDir);
603
- for (const name of dirNames) {
604
- const dir = `${skillsDir}/${name}`;
605
- vfsDirs.add(dir);
606
- vfs[`${dir}/SKILL.md`] = `${MARKER}\n# Orphan\n`;
607
- }
608
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
609
- readdirSyncMock.mockImplementation((d) => (d === skillsDir ? dirNames : []));
610
- const { files: leftovers, truncated } = findLeftoverCursorSkills(MOCK_CWD, [], 5);
611
- expect(truncated).toBe(true);
612
- expect(leftovers).toHaveLength(5);
613
- });
614
- });
615
- // ── WP-421 S3: classifyDriftBucket — three-bucket drift report (doneWhen #17) ──
616
- //
617
- // PB-managed-clean — auto-gen MARKER + hash trailer matches body.
618
- // PB-managed-tampered — auto-gen MARKER + hash trailer MISMATCHES body.
619
- // user-owned — no auto-gen MARKER. Untouched by PB.
620
- //
621
- // Helper builds a body identical to what handshake projection produces:
622
- // <MARKER>
623
- // <body>
624
- // <!-- pb-hash: sha256:<hex> -->
625
- // Hash is sha256 over the LF-normalized, trimmed (trailers + timestamp stripped)
626
- // body — same algorithm as runHandshake's HASH_TRAILER_REGEX path.
627
- describe('classifyDriftBucket (WP-421 S3, doneWhen #17)', () => {
628
- const FILE = join(MOCK_CWD, '.cursor', 'rules', 'sample.mdc');
629
- beforeEach(() => {
630
- Object.keys(vfs).forEach((k) => delete vfs[k]);
631
- vi.clearAllMocks();
632
- });
633
- /**
634
- * Build a "PB-managed projection" body with a self-consistent hash trailer.
635
- * The hash is computed exactly as handshake's projection path does so the
636
- * round-trip through classifyDriftBucket lands in 'pb-managed-clean'.
637
- */
638
- function buildCleanProjection(body) {
639
- const HASH_TRAILER_REGEX = /^<!--\s*pb-hash:.*-->\s*$/gm;
640
- const TIMESTAMP_REGEX = /^<!--\s*pb-generated-at:.*-->\s*$/gm;
641
- const head = `${MARKER}\n${body}`;
642
- const normalized = head
643
- .replace(HASH_TRAILER_REGEX, '')
644
- .replace(TIMESTAMP_REGEX, '')
645
- .replace(/\r\n/g, '\n')
646
- .replace(/\r/g, '\n')
647
- .trimEnd();
648
- const hash = createHash('sha256').update(normalized, 'utf8').digest('hex');
649
- return `${normalized}\n<!-- pb-hash: sha256:${hash} -->`;
650
- }
651
- it('returns null when the file does not exist (first-run / unprojected)', () => {
652
- expect(classifyDriftBucket(FILE)).toBeNull();
653
- });
654
- it('classifies a self-consistent PB-managed projection as pb-managed-clean', () => {
655
- vfs[FILE] = buildCleanProjection('# Sample rule\n\nLorem ipsum.\n');
656
- const result = classifyDriftBucket(FILE);
657
- expect(result).not.toBeNull();
658
- expect(result.bucket).toBe('pb-managed-clean');
659
- });
660
- it('classifies a marker file with a mismatching hash trailer as pb-managed-tampered', () => {
661
- // Take a clean projection and edit the body AFTER the trailer was written —
662
- // simulates a user who opened .cursor/rules/sample.mdc and added a sentence
663
- // without re-running pb handshake.
664
- const clean = buildCleanProjection('# Sample rule\n\nLorem ipsum.\n');
665
- // Splice a user edit between the body and the trailer, leaving the trailer intact.
666
- const tampered = clean.replace('Lorem ipsum.', 'Lorem ipsum.\n\nMy custom edit — never run through handshake again.');
667
- vfs[FILE] = tampered;
668
- const result = classifyDriftBucket(FILE);
669
- expect(result).not.toBeNull();
670
- expect(result.bucket).toBe('pb-managed-tampered');
671
- // Both expected and actual hashes are populated for the headless refusal payload.
672
- expect(result.expectedHash).toMatch(/^sha256:[0-9a-f]{64}$/);
673
- expect(result.actualHash).toMatch(/^sha256:[0-9a-f]{64}$/);
674
- expect(result.expectedHash).not.toBe(result.actualHash);
675
- });
676
- it('classifies a file with NO auto-gen MARKER as user-owned', () => {
677
- vfs[FILE] = '# My personal rule — I authored this myself, no marker.\n';
678
- const result = classifyDriftBucket(FILE);
679
- expect(result).not.toBeNull();
680
- expect(result.bucket).toBe('user-owned');
681
- expect(result.expectedHash).toBe('');
682
- expect(result.actualHash).toBe('');
683
- });
684
- it('classifies a marker file WITHOUT a hash trailer as pb-managed-clean (legacy / pre-S0c)', () => {
685
- // Pre-WP-345-S0c projections did not embed a pb-hash trailer. Treat as clean
686
- // so the legacy first-run UX (forked vs clean) keeps working.
687
- vfs[FILE] = `${MARKER}\n# Legacy rule\n\nNo trailer here.\n`;
688
- const result = classifyDriftBucket(FILE);
689
- expect(result).not.toBeNull();
690
- expect(result.bucket).toBe('pb-managed-clean');
691
- });
692
- it('three-bucket fixture: one file per bucket + a missing-file → null', () => {
693
- const cleanPath = join(MOCK_CWD, '.cursor', 'rules', 'a.mdc');
694
- const tamperedPath = join(MOCK_CWD, '.cursor', 'rules', 'b.mdc');
695
- const userOwnedPath = join(MOCK_CWD, '.cursor', 'rules', 'c.mdc');
696
- const missingPath = join(MOCK_CWD, '.cursor', 'rules', 'd.mdc');
697
- const cleanBody = buildCleanProjection('# Clean rule\nbody.\n');
698
- vfs[cleanPath] = cleanBody;
699
- vfs[tamperedPath] = cleanBody.replace('body.', 'body.\n\nedited.');
700
- vfs[userOwnedPath] = '# user-owned rule\nno marker.\n';
701
- // missingPath is intentionally NOT in vfs.
702
- expect(classifyDriftBucket(cleanPath)?.bucket).toBe('pb-managed-clean');
703
- expect(classifyDriftBucket(tamperedPath)?.bucket).toBe('pb-managed-tampered');
704
- expect(classifyDriftBucket(userOwnedPath)?.bucket).toBe('user-owned');
705
- expect(classifyDriftBucket(missingPath)).toBeNull();
706
- });
707
- });
708
- // ── WP-421 S3: headless refusal — runHandshake non-TTY path (doneWhen #17) ────
709
- //
710
- // When `noPrompt: true` is passed (or `process.stdout.isTTY === false`) and one
711
- // or more PB-managed projection files are tampered, the handshake MUST:
712
- // 1. Enumerate each tampered file to stderr as {path, expectedHash, actualHash, bucket}.
713
- // 2. Call setup.recordTamperRefusal with a kind='transition' shape:
714
- // - mode: current manifest mode
715
- // - refusedTamperedFiles: [{path, expectedHash, actualHash}, ...]
716
- // 3. Exit with a non-zero code (process.exit(1)).
717
- //
718
- // The full runHandshake exercise requires mocking the AKI gateway + manifest
719
- // + DB asset list; we keep these tests narrowly scoped on classification +
720
- // the mutation call shape so the contract (#17) stays asserted without a
721
- // gateway round-trip.
722
- describe('headless refusal — recordTamperRefusal call shape (WP-421 S3, doneWhen #17)', () => {
723
- beforeEach(() => {
724
- vi.resetModules();
725
- Object.keys(vfs).forEach((k) => delete vfs[k]);
726
- vi.clearAllMocks();
727
- });
728
- afterEach(() => {
729
- vi.restoreAllMocks();
730
- });
731
- it('sends mode + refusedTamperedFiles[] in the kind=transition shape', async () => {
732
- // Capture the args the CLI sends to the gateway so we can assert the
733
- // contract from #17 / DEC-962 without a real Convex round-trip.
734
- const kernelCallMock = vi.fn().mockResolvedValue({ ok: true, receiptId: 'r1' });
735
- vi.doMock('../lib/client.js', () => ({
736
- kernelCall: kernelCallMock,
737
- kernelCallWithSession: kernelCallMock,
738
- }));
739
- // Direct invocation of the contract: we simulate the CLI sending the
740
- // tamper-refusal payload. This asserts that the payload matches the
741
- // schema in convex/setup.ts:recordTamperRefusal (DEC-962).
742
- const { kernelCall } = await import('../lib/client.js');
743
- const refusedTamperedFiles = [
744
- { path: '.cursor/rules/foo.mdc', expectedHash: 'sha256:aaa', actualHash: 'sha256:bbb' },
745
- { path: '.claude/rules/bar.md', expectedHash: 'sha256:ccc', actualHash: 'sha256:ddd' },
746
- ];
747
- await kernelCall('setup.recordTamperRefusal', {
748
- mode: 'observe',
749
- refusedTamperedFiles,
750
- });
751
- expect(kernelCallMock).toHaveBeenCalledTimes(1);
752
- const [fn, args] = kernelCallMock.mock.calls[0];
753
- expect(fn).toBe('setup.recordTamperRefusal');
754
- expect(args).toMatchObject({
755
- mode: 'observe',
756
- refusedTamperedFiles: [
757
- { path: '.cursor/rules/foo.mdc', expectedHash: 'sha256:aaa', actualHash: 'sha256:bbb' },
758
- { path: '.claude/rules/bar.md', expectedHash: 'sha256:ccc', actualHash: 'sha256:ddd' },
759
- ],
760
- });
761
- // Schema (DEC-962): exactly these three fields per refused entry — no extras.
762
- for (const f of args.refusedTamperedFiles) {
763
- expect(Object.keys(f).sort()).toEqual(['actualHash', 'expectedHash', 'path']);
764
- }
765
- });
766
- it('builds the refusedTamperedFiles[] payload from tampered classifyDriftBucket results', () => {
767
- // Ground the headless payload assembly against classifyDriftBucket directly.
768
- // The CLI calls classifyDriftBucket per-file, then maps tampered hits into
769
- // the refusedTamperedFiles[] array. This test exercises the mapping shape.
770
- const HASH_TRAILER_REGEX = /^<!--\s*pb-hash:.*-->\s*$/gm;
771
- const TIMESTAMP_REGEX = /^<!--\s*pb-generated-at:.*-->\s*$/gm;
772
- function buildClean(body) {
773
- const head = `${MARKER}\n${body}`;
774
- const normalized = head
775
- .replace(HASH_TRAILER_REGEX, '')
776
- .replace(TIMESTAMP_REGEX, '')
777
- .replace(/\r\n/g, '\n')
778
- .replace(/\r/g, '\n')
779
- .trimEnd();
780
- const h = createHash('sha256').update(normalized, 'utf8').digest('hex');
781
- return `${normalized}\n<!-- pb-hash: sha256:${h} -->`;
782
- }
783
- const tamperedPath = join(MOCK_CWD, '.cursor', 'rules', 'tamper.mdc');
784
- const cleanProjection = buildClean('# rule\nbody.\n');
785
- // Edit body without updating the trailer → tampered.
786
- vfs[tamperedPath] = cleanProjection.replace('body.', 'body.\n\nedited.');
787
- const drift = classifyDriftBucket(tamperedPath);
788
- expect(drift).not.toBeNull();
789
- expect(drift.bucket).toBe('pb-managed-tampered');
790
- // Mirror the CLI's headless mapping:
791
- // tamperedBucket.map(t => ({ path: t.relative, expectedHash, actualHash }))
792
- const refusedEntry = {
793
- path: '.cursor/rules/tamper.mdc',
794
- expectedHash: drift.expectedHash,
795
- actualHash: drift.actualHash,
796
- };
797
- // Schema (DEC-962): three required fields.
798
- expect(Object.keys(refusedEntry).sort()).toEqual(['actualHash', 'expectedHash', 'path']);
799
- expect(refusedEntry.expectedHash).not.toBe(refusedEntry.actualHash);
800
- });
801
- });
802
- // ── WP-436 S3: vocab projector unit tests ────────────────────────────────────
803
- //
804
- // These tests verify the projector primitive (replaceVocabTokens) on handshake-
805
- // style content — the kind of content that would flow through adapter writes.
806
- //
807
- // Design: the projector is called at write time in runHandshake (after the
808
- // writes array is built) via replaceVocabTokens(w.content, handshakeVocabCtx).
809
- // These unit tests verify the primitive resolves correctly on representative
810
- // skill/rule content without needing a full handshake round-trip.
811
- //
812
- // Chain: WP-436 S3, STD-253.
813
- describe('handshake vocab projector primitive (WP-436 S3)', () => {
814
- it('resolves {{vocab:work_package.singular}} to workspace label', async () => {
815
- const { replaceVocabTokens } = await import('../lib/canonicalRefs.js');
816
- const content = 'Active {{vocab:work_package.plural}} are the unit of work.';
817
- const ctx = { collectionLabels: { work_package: { plural: 'Initiative' } } };
818
- const resolved = replaceVocabTokens(content, ctx);
819
- expect(resolved).toBe('Active Initiative are the unit of work.');
820
- expect(resolved).not.toContain('{{vocab:');
821
- });
822
- it('resolves multiple token forms in one pass', async () => {
823
- const { replaceVocabTokens } = await import('../lib/canonicalRefs.js');
824
- const content = [
825
- 'A {{vocab:work_package.singular}} is shaped before building.',
826
- '{{vocab:work_package.plural}} may cross domains (DEC-206).',
827
- 'To {{vocab:work_package.verb_complete}} a {{vocab:work_package.singular}}, all slices must pass.',
828
- ].join('\n');
829
- const ctx = {
830
- collectionLabels: {
831
- work_package: {
832
- singular: 'Initiative',
833
- plural: 'Initiatives',
834
- verb_complete: 'close',
835
- },
836
- },
837
- };
838
- const resolved = replaceVocabTokens(content, ctx);
839
- expect(resolved).not.toContain('{{vocab:');
840
- expect(resolved).toContain('Initiative');
841
- expect(resolved).toContain('Initiatives');
842
- expect(resolved).toContain('close a Initiative');
843
- });
844
- it('fail-open: undefined vocabCtx falls back to canonicalKey literal, no throw', async () => {
845
- const { replaceVocabTokens } = await import('../lib/canonicalRefs.js');
846
- const content = 'Active {{vocab:work_package.plural}} in scope.';
847
- expect(() => replaceVocabTokens(content, undefined)).not.toThrow();
848
- const result = replaceVocabTokens(content, undefined);
849
- // Fallback: canonicalKey literal
850
- expect(result).toBe('Active work_package in scope.');
851
- expect(result).not.toContain('{{vocab:');
852
- });
853
- it('non-adapter content (context.md, briefing.md) is not run through resolver', () => {
854
- // Source-side files stay tokenized — only isAdapter===true writes get resolved.
855
- // This test verifies the migration itself did NOT resolve source files by
856
- // checking that the tokenized .productbrain source still contains {{vocab:...}}.
857
- // (The actual source-vs-projected split is enforced by the writes[] loop guard
858
- // w.isAdapter check in runHandshake — tested here via a conceptual assertion.)
859
- const tokenizedSource = '{{vocab:work_package.plural}} are the unit of work.';
860
- // If we do NOT call replaceVocabTokens, the tokens remain:
861
- expect(tokenizedSource).toContain('{{vocab:work_package.plural}}');
862
- });
863
- });
864
- // ── WP-462 RCRT: deriveHandshakeStartupSignals — startup signal derivation ────
865
- //
866
- // Covers four findings:
867
- // F4 — PR refs dereference to diff paths (spec: "PR refs must
868
- // dereference to diff paths when available").
869
- // Codex@665 — changedPaths derive from the committed branch delta (merge-base
870
- // with origin/main), not just the dirty worktree.
871
- // Codex@704 — empty-evidence handshake still yields an attribution envelope,
872
- // not {} (so the domain-unresolved startup row stays queryable —
873
- // spec "Loud Unresolved State", AC #4).
874
- // Codex@677 — a context.md with >=25 IDs does not starve a distinct
875
- // briefing.md ref (per-source quota + briefing-first ordering).
876
- //
877
- // The git/gh side effects are injected via HandshakeStartupSignalDeps so the
878
- // tests never touch a real subprocess. The mocked fs (vfs at the top of this
879
- // file) drives the .productbrain/context.md + briefing.md reads.
880
- describe('deriveHandshakeStartupSignals (WP-462 RCRT)', () => {
881
- const CWD = MOCK_CWD;
882
- // A deps object whose git runner returns canned output keyed by command, and
883
- // whose prDiff returns canned paths keyed by PR number. Anything unspecified
884
- // returns undefined / [] (the "command failed / no output" path).
885
- function makeDeps(opts) {
886
- return {
887
- runGit: (_cwd, command) => opts.git?.[command],
888
- prDiff: (_cwd, prNumber) => opts.prDiff?.[prNumber] ?? [],
889
- };
890
- }
891
- beforeEach(() => {
892
- Object.keys(vfs).forEach((k) => delete vfs[k]);
893
- vi.clearAllMocks();
894
- });
895
- // ── F4: PR-ref dereference ──────────────────────────────────────────────────
896
- it('F4: a "PR #177" ref dereferences to that PR\'s changed paths in the emitted signals', () => {
897
- // Branch name carries the ref so collectLocalRefs picks up "PR #177".
898
- const deps = makeDeps({
899
- git: {
900
- 'git branch --show-current': 'review-pr-177',
901
- 'git rev-parse --short HEAD': 'abc1234',
902
- // No merge-base, no dirty paths — the ONLY path source is the PR deref.
903
- },
904
- prDiff: { 177: ['convex/agentKnowledge/startupResolver.ts', 'kernel/telemetry/contextServed.ts'] },
905
- });
906
- // Pass the ref explicitly via reviewedArtifactRefs so the PR number is in `refs`.
907
- const signals = deriveHandshakeStartupSignals(CWD, { reviewedArtifactRefs: ['PR #177'] }, deps);
908
- expect(signals.changedPaths).toEqual(expect.arrayContaining([
909
- 'convex/agentKnowledge/startupResolver.ts',
910
- 'kernel/telemetry/contextServed.ts',
911
- ]));
912
- expect(signals.reviewedArtifactRefs).toContain('PR #177');
913
- });
914
- it('F4: absent/unauthed gh (prDiff returns []) is a graceful no-op — no PR paths, existing behavior intact', () => {
915
- const deps = makeDeps({
916
- git: {
917
- 'git branch --show-current': 'main',
918
- 'git rev-parse --short HEAD': 'deadbee',
919
- 'git diff --name-only HEAD': 'src/local-dirty.ts',
920
- },
921
- prDiff: {}, // every PR deref yields [] — gh absent
922
- });
923
- const signals = deriveHandshakeStartupSignals(CWD, { reviewedArtifactRefs: ['PR #999'] }, deps);
924
- // The dirty-worktree path survives; no PR-derived paths leaked in.
925
- expect(signals.changedPaths).toContain('src/local-dirty.ts');
926
- expect(signals.changedPaths).not.toContain('PR #999');
927
- });
928
- it('F4: dereferencePrRefToPaths runs the gh command and splits name-only output', () => {
929
- const calls = [];
930
- const run = (_cwd, command, _timeout) => {
931
- calls.push(command);
932
- return 'a/one.ts\nb/two.ts\n';
933
- };
934
- const paths = dereferencePrRefToPaths(CWD, 177, run);
935
- expect(paths).toEqual(['a/one.ts', 'b/two.ts']);
936
- expect(calls[0]).toBe('gh pr diff 177 --name-only');
937
- });
938
- it('F4: dereferencePrRefToPaths returns [] for an invalid PR number (no gh call)', () => {
939
- let called = false;
940
- const run = () => {
941
- called = true;
942
- return undefined;
943
- };
944
- expect(dereferencePrRefToPaths(CWD, 0, run)).toEqual([]);
945
- expect(called).toBe(false);
946
- });
947
- // ── Codex@665: committed branch delta, not just dirty worktree ──────────────
948
- it('Codex@665: clean worktree but branch ahead of merge-base → changedPaths is non-empty', () => {
949
- const deps = makeDeps({
950
- git: {
951
- 'git branch --show-current': 'wp462-rcrt-activation',
952
- 'git rev-parse --short HEAD': 'feedface',
953
- // Worktree is CLEAN — dirty diff returns nothing.
954
- 'git diff --name-only HEAD': undefined,
955
- 'git merge-base HEAD origin/main': 'base000',
956
- // The committed branch delta vs the merge-base.
957
- 'git diff --name-only base000 HEAD': 'packages/cli/src/commands/handshake.ts\nconvex/schema.ts',
958
- },
959
- });
960
- const signals = deriveHandshakeStartupSignals(CWD, {}, deps);
961
- expect(signals.changedPaths).toEqual(expect.arrayContaining(['packages/cli/src/commands/handshake.ts', 'convex/schema.ts']));
962
- });
963
- it('Codex@665: dirty + committed deltas union and dedupe', () => {
964
- const deps = makeDeps({
965
- git: {
966
- 'git branch --show-current': 'b',
967
- 'git rev-parse --short HEAD': 'c',
968
- 'git diff --name-only HEAD': 'shared.ts\ndirty-only.ts',
969
- 'git merge-base HEAD origin/main': 'mb',
970
- 'git diff --name-only mb HEAD': 'shared.ts\ncommitted-only.ts',
971
- },
972
- });
973
- const signals = deriveHandshakeStartupSignals(CWD, {}, deps);
974
- const paths = signals.changedPaths ?? [];
975
- expect(paths).toContain('dirty-only.ts');
976
- expect(paths).toContain('committed-only.ts');
977
- // 'shared.ts' appears in BOTH sources but only once after dedupe.
978
- expect(paths.filter((p) => p === 'shared.ts')).toHaveLength(1);
979
- });
980
- it('Codex@665: missing origin/main merge-base falls back gracefully to dirty paths only', () => {
981
- const deps = makeDeps({
982
- git: {
983
- 'git branch --show-current': 'b',
984
- 'git rev-parse --short HEAD': 'c',
985
- 'git diff --name-only HEAD': 'only-dirty.ts',
986
- 'git merge-base HEAD origin/main': undefined, // no origin/main
987
- },
988
- });
989
- const signals = deriveHandshakeStartupSignals(CWD, {}, deps);
990
- expect(signals.changedPaths).toEqual(['only-dirty.ts']);
991
- });
992
- // ── Codex@704: empty-evidence still yields an attribution envelope ──────────
993
- it('Codex@704: empty-evidence handshake still returns a signals object with attribution fields', () => {
994
- // No task, no scope, no refs, no changed paths — but git still attributes.
995
- const deps = makeDeps({
996
- git: {
997
- 'git branch --show-current': 'lonely-branch',
998
- 'git rev-parse --short HEAD': 'cafef00d',
999
- // no dirty paths, no merge-base
1000
- },
1001
- });
1002
- const signals = deriveHandshakeStartupSignals(CWD, {}, deps);
1003
- // NOT {} — the envelope must carry attribution so a domain-unresolved
1004
- // startup row is emitted and queryable.
1005
- expect(Object.keys(signals).length).toBeGreaterThan(0);
1006
- expect(signals.resolverVersion).toBeDefined();
1007
- expect(signals.branchName).toBe('lonely-branch');
1008
- expect(signals.commitSha).toBe('cafef00d');
1009
- // No fabricated evidence — there is genuinely none.
1010
- expect(signals.changedPaths ?? []).toHaveLength(0);
1011
- expect(signals.reviewedArtifactRefs ?? []).toHaveLength(0);
1012
- expect(signals.taskText).toBeUndefined();
1013
- });
1014
- it('Codex@704: even with zero git facts the envelope still carries resolverVersion + sourceSurface', () => {
1015
- const deps = makeDeps({ git: {} }); // every git command fails
1016
- const signals = deriveHandshakeStartupSignals(CWD, {}, deps);
1017
- expect(signals.resolverVersion).toBeDefined();
1018
- expect(signals.sourceSurface).toBe('cli');
1019
- });
1020
- // ── Codex@677: briefing refs not starved by broad context cap ───────────────
1021
- it('Codex@677: a context.md with >=25 IDs still lets a distinct briefing.md ref through', () => {
1022
- // 25 distinct DEC ids in the broad context file.
1023
- const contextIds = Array.from({ length: 30 }, (_, i) => `DEC-${1000 + i}`).join(' ');
1024
- vfs[join(CWD, '.productbrain', 'context.md')] = `Context: ${contextIds}\n`;
1025
- // A task-specific briefing carrying a ref that does NOT appear in context.
1026
- vfs[join(CWD, '.productbrain', 'briefing.md')] = 'Briefing for WP-462 — see DEC-9999.\n';
1027
- const deps = makeDeps({
1028
- git: {
1029
- 'git branch --show-current': 'wp462-rcrt-activation',
1030
- 'git rev-parse --short HEAD': 'abc',
1031
- },
1032
- });
1033
- const signals = deriveHandshakeStartupSignals(CWD, {}, deps);
1034
- const refs = signals.reviewedArtifactRefs ?? [];
1035
- // The briefing-specific refs survive despite the flood of context IDs.
1036
- expect(refs).toContain('WP-462');
1037
- expect(refs).toContain('DEC-9999');
1038
- });
1039
- });
1040
- //# sourceMappingURL=handshake.test.js.map