-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclaude.test.ts
More file actions
217 lines (189 loc) · 7.38 KB
/
Copy pathclaude.test.ts
File metadata and controls
217 lines (189 loc) · 7.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import { describe, it, expect, vi, beforeEach } from 'vitest'
const fsState: { files: Map<string, string> } = { files: new Map() }
vi.mock('fs', () => ({
existsSync: (p: string) => fsState.files.has(p),
readFileSync: (p: string) => {
if (!fsState.files.has(p)) throw new Error(`ENOENT: ${p}`)
return fsState.files.get(p) as string
},
writeFileSync: (p: string, data: string) => {
fsState.files.set(p, data)
},
mkdirSync: () => {},
readdirSync: () => [],
statSync: () => ({ mtimeMs: 0 })
}))
vi.mock('../debug', () => ({
log: () => {}
}))
vi.mock('../hooks', () => ({
// Match the real shape — every Harness hook command embeds the
// status-dir path. That substring is what dedup recognizes.
makeHookCommand: (event: string) =>
`bash -c 'd=/tmp/harness-status; printf "${event}" >> "$d/$h.ndjson"'`
}))
import { homedir } from 'os'
import { join } from 'path'
import { buildSpawnArgs, hooksInstalled, installHooks, hookEvents, uninstallHooks } from './claude'
const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
beforeEach(() => {
fsState.files.clear()
})
describe('buildSpawnArgs', () => {
const base = { command: 'claude', cwd: '/tmp/test' }
it('includes --append-system-prompt when systemPrompt is provided', () => {
const result = buildSpawnArgs({ ...base, systemPrompt: 'You are in Harness.' })
expect(result).toContain('--append-system-prompt')
expect(result).toContain('You are in Harness.')
})
it('omits --append-system-prompt when systemPrompt is undefined', () => {
const result = buildSpawnArgs({ ...base })
expect(result).not.toContain('--append-system-prompt')
})
it('omits --append-system-prompt when systemPrompt is empty', () => {
const result = buildSpawnArgs({ ...base, systemPrompt: '' })
expect(result).not.toContain('--append-system-prompt')
})
it('shell-quotes the system prompt safely', () => {
const prompt = "it's a \"test\" with\nnewlines"
const result = buildSpawnArgs({ ...base, systemPrompt: prompt })
expect(result).toContain('--append-system-prompt')
expect(result).toContain("'\\''")
})
const sessionPath = (cwd: string, id: string): string =>
join(homedir(), '.claude', 'projects', cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${id}.jsonl`)
it('blank: --session-id when no transcript exists for the session id', () => {
const result = buildSpawnArgs({ ...base, sessionId: 'fresh-id' })
expect(result).toContain('--session-id fresh-id')
expect(result).not.toContain('--resume')
expect(result).not.toContain('--fork-session')
})
it('resume: --resume when a transcript exists for the session id', () => {
fsState.files.set(sessionPath(base.cwd, 'old-id'), '{}')
const result = buildSpawnArgs({ ...base, sessionId: 'old-id' })
expect(result).toContain('--resume old-id')
expect(result).not.toContain('--session-id')
})
it('fork: --resume <src> --fork-session, never --session-id (even if sessionId set)', () => {
const result = buildSpawnArgs({ ...base, sessionId: 'tab-id', forkFromSessionId: 'src-id' })
expect(result).toContain('--resume src-id')
expect(result).toContain('--fork-session')
expect(result).not.toContain('--session-id')
})
})
describe('hook install / dedup', () => {
it('hooksInstalled() recognizes normalized entries with no _marker field', () => {
// Simulate what Claude Code leaves behind after normalizing settings.json:
// the _marker and _version sidecar fields are stripped, only the
// {type, command, timeout} triple remains.
const settings = {
hooks: {
UserPromptSubmit: [
{
hooks: [
{
type: 'command',
command:
"bash -c 'd=/tmp/harness-status; printf hi >> \"$d/$h.ndjson\"'",
timeout: 5
}
]
}
]
}
}
fsState.files.set(SETTINGS_PATH, JSON.stringify(settings))
expect(hooksInstalled()).toBe(true)
})
it('hooksInstalled() returns false when only user-authored hooks exist', () => {
const settings = {
hooks: {
UserPromptSubmit: [
{
hooks: [{ type: 'command', command: 'echo user hook', timeout: 5 }]
}
]
}
}
fsState.files.set(SETTINGS_PATH, JSON.stringify(settings))
expect(hooksInstalled()).toBe(false)
})
it('installHooks() called twice yields exactly one harness entry per event', () => {
installHooks()
installHooks()
const settings = JSON.parse(fsState.files.get(SETTINGS_PATH) as string)
for (const event of hookEvents) {
const entries = settings.hooks[event]
expect(entries).toHaveLength(1)
expect(entries[0].hooks[0].command).toContain('/tmp/harness-status')
}
})
it('installHooks() collapses pre-existing duplicates left by buggy passes', () => {
// Three duplicate harness entries per event, all in normalized form
// (no _marker / _version). This is the exact shape the user reports
// after several buggy install passes.
const dupEntry = {
hooks: [
{
type: 'command',
command:
"bash -c 'd=/tmp/harness-status; printf hi >> \"$d/$h.ndjson\"'",
timeout: 5
}
]
}
const settings: { hooks: Record<string, unknown[]> } = { hooks: {} }
for (const event of hookEvents) {
settings.hooks[event] = [dupEntry, dupEntry, dupEntry]
}
fsState.files.set(SETTINGS_PATH, JSON.stringify(settings))
installHooks()
const after = JSON.parse(fsState.files.get(SETTINGS_PATH) as string)
for (const event of hookEvents) {
expect(after.hooks[event]).toHaveLength(1)
}
})
it('installHooks() preserves user-authored hooks (commands not pointing at /tmp/harness-status)', () => {
const userHook = {
hooks: [{ type: 'command', command: 'echo user hook', timeout: 10 }]
}
fsState.files.set(
SETTINGS_PATH,
JSON.stringify({
hooks: {
UserPromptSubmit: [userHook],
PreToolUse: [userHook]
},
unrelatedKey: 'preserve-me'
})
)
installHooks()
const after = JSON.parse(fsState.files.get(SETTINGS_PATH) as string)
expect(after.unrelatedKey).toBe('preserve-me')
// User hook still there + one harness entry appended
expect(after.hooks.UserPromptSubmit).toContainEqual(userHook)
expect(after.hooks.PreToolUse).toContainEqual(userHook)
for (const event of hookEvents) {
const harnessEntries = (after.hooks[event] as Array<{ hooks: { command: string }[] }>).filter(
(e) => e.hooks.some((h) => h.command.includes('/tmp/harness-status'))
)
expect(harnessEntries).toHaveLength(1)
}
})
it('uninstallHooks() removes harness entries but preserves user-authored hooks', () => {
installHooks()
// Add a user-authored hook alongside
const after = JSON.parse(fsState.files.get(SETTINGS_PATH) as string)
after.hooks.UserPromptSubmit.push({
hooks: [{ type: 'command', command: 'echo user hook' }]
})
fsState.files.set(SETTINGS_PATH, JSON.stringify(after))
uninstallHooks()
const final = JSON.parse(fsState.files.get(SETTINGS_PATH) as string)
expect(final.hooks?.UserPromptSubmit).toEqual([
{ hooks: [{ type: 'command', command: 'echo user hook' }] }
])
// Other events had no user hooks, so they should be gone entirely.
expect(final.hooks?.PreToolUse).toBeUndefined()
})
})