Skip to content

Commit 647f1ab

Browse files
turmindhalo
andcommitted
test: contract tests for the three least-protected spines — AgentLoop, acp-adapter, evo-wrapper
The release review found the test suite tracks bug history rather than contracts: the tool loop, the ACP stdio bridge and the 2k-line evolution wrapper had between zero and two tests each. This lands the missing layer and fixes one real bug the new tests exposed. AgentLoop (server/test/agent-loop-cycle.test.ts, 12 cases) - A scripted subclass replaces callModel; cases pin the message shapes the loop is allowed to produce: parallel tool_use → one trailing user message with results in call order, unknown / throwing tools → marked is_error and the loop continues, forceEndTurn, timeout vs cancel distinction, cancel-between-tools leaves no half-pushed tool_result, run() coalescing into a dangling user turn, beforeCallModel cadence. acp-adapter (18 cases, first tests in the package) - vitest wired in (package.json test script + vitest.config.ts) and a CI step; `parseSseStream` exported from halo-client.ts so the SSE parser is testable without a socket. jsonrpc-framing covers the stdio framing (partial lines, batched frames, malformed JSON, id echo, error shape); sse-parse covers event/data multi-line, comments, CRLF, mid-chunk splits. evo-wrapper (22 cases) - `main()` now runs only when the file is the entrypoint (`process.argv[1] === fileURLToPath(import.meta.url)`), and the phase functions are exported, so the Run / Apply phases can be driven in-process against a tmp workspace instead of spawning the wrapper. - Bug found by those tests: `buildEvoSandbox` copied `.halo/` with `fs.cpSync({ recursive: true, dereference: true })`, but on Node ≥ 22.17 nested symlinks are no longer dereferenced (nodejs/node#59168) — a symlinked skill one level down stayed a symlink INTO the live workspace, so the "sandbox" dry-run would have written through to the real `.halo/`. Replaced with a hand-rolled `copyDereferenced` walk that stats every entry; behaviour is now the same on every Node version. Co-Authored-By: halo <[email protected]>
1 parent 271dfea commit 647f1ab

10 files changed

Lines changed: 870 additions & 21 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ jobs:
5454
git config --global user.name "CI"
5555
git config --global user.email "[email protected]"
5656
57-
# 四个包都有测试,总数 1100+(具体数字看 vitest 输出,别在这里维护)。挂一个即红。
57+
# 五个包都有测试,总数 1100+(具体数字看 vitest 输出,别在这里维护)。挂一个即红。
5858
- name: Test (core)
5959
run: pnpm --filter @turmind/halo-core test
6060

@@ -64,5 +64,8 @@ jobs:
6464
- name: Test (cli)
6565
run: pnpm --filter @turmind/halo-cli test
6666

67+
- name: Test (acp-adapter)
68+
run: pnpm --filter @turmind/halo-acp-adapter test
69+
6770
- name: Test (admin)
6871
run: pnpm --filter @turmind/halo-admin test

‎packages/acp-adapter/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@
77
"main": "./dist/index.js",
88
"scripts": {
99
"build": "tsc",
10+
"test": "vitest run",
1011
"clean": "rm -rf dist"
1112
},
1213
"dependencies": {},
1314
"devDependencies": {
1415
"@types/node": "^22.0.0",
15-
"typescript": "^5.7.0"
16+
"typescript": "^5.7.0",
17+
"vitest": "^4.1.8"
1618
}
1719
}

‎packages/acp-adapter/src/halo-client.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ async function safeText(res: Response): Promise<string> {
148148
* emits `data:` frames (no `event:` / `id:` discipline) and JSON payloads
149149
* are single-line, so a simple line-buffer is enough.
150150
*/
151-
async function *parseSseStream(body: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent> {
151+
export async function *parseSseStream(body: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent> {
152152
const decoder = new TextDecoder()
153153
const reader = body.getReader()
154154
let buffer = ''
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
import { PassThrough } from 'node:stream'
2+
import { describe, it, expect, vi } from 'vitest'
3+
import { JsonRpcConnection, ERROR_PARSE, ERROR_METHOD_NOT_FOUND, ERROR_INVALID_PARAMS, ERROR_INTERNAL } from '../src/jsonrpc.js'
4+
5+
function harness() {
6+
const input = new PassThrough()
7+
const output = new PassThrough()
8+
const lines: unknown[] = []
9+
output.on('data', (chunk: Buffer) => {
10+
for (const line of chunk.toString('utf-8').split('\n')) {
11+
if (line.trim()) lines.push(JSON.parse(line))
12+
}
13+
})
14+
const conn = new JsonRpcConnection(input, output)
15+
return { input, output, lines, conn }
16+
}
17+
18+
async function flush() {
19+
await new Promise((r) => setImmediate(r))
20+
await new Promise((r) => setImmediate(r))
21+
}
22+
23+
describe('JsonRpcConnection framing', () => {
24+
it('dispatches a request split across two writes mid-JSON exactly once', async () => {
25+
const { input, lines, conn } = harness()
26+
const handler = vi.fn().mockReturnValue('pong')
27+
conn.onRequest('ping', handler)
28+
29+
input.write('{"jsonrpc":"2.0","id":1,"me')
30+
input.write('thod":"ping","params":{}}\n')
31+
await flush()
32+
33+
expect(handler).toHaveBeenCalledTimes(1)
34+
expect(lines).toEqual([{ jsonrpc: '2.0', id: 1, result: 'pong' }])
35+
})
36+
37+
it('dispatches two complete messages in one write, in order', async () => {
38+
const { input, lines, conn } = harness()
39+
const seen: string[] = []
40+
conn.onRequest('a', () => {
41+
seen.push('a')
42+
return 1
43+
})
44+
conn.onRequest('b', () => {
45+
seen.push('b')
46+
return 2
47+
})
48+
49+
input.write('{"jsonrpc":"2.0","id":1,"method":"a","params":{}}\n{"jsonrpc":"2.0","id":2,"method":"b","params":{}}\n')
50+
await flush()
51+
52+
expect(seen).toEqual(['a', 'b'])
53+
expect(lines).toEqual([
54+
{ jsonrpc: '2.0', id: 1, result: 1 },
55+
{ jsonrpc: '2.0', id: 2, result: 2 },
56+
])
57+
})
58+
59+
it('tolerates \\r\\n line endings and blank lines between messages', async () => {
60+
const { input, lines, conn } = harness()
61+
conn.onRequest('ping', () => 'pong')
62+
63+
input.write('{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}\r\n\r\n{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}\r\n')
64+
await flush()
65+
66+
expect(lines).toEqual([
67+
{ jsonrpc: '2.0', id: 1, result: 'pong' },
68+
{ jsonrpc: '2.0', id: 2, result: 'pong' },
69+
])
70+
})
71+
72+
it('responds with a parse error for an unparseable line, then keeps working', async () => {
73+
const { input, lines, conn } = harness()
74+
conn.onRequest('ping', () => 'pong')
75+
76+
input.write('not json at all\n{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}\n')
77+
await flush()
78+
79+
expect(lines[0]).toEqual({ jsonrpc: '2.0', id: null, error: { code: ERROR_PARSE, message: 'parse error' } })
80+
expect(lines[1]).toEqual({ jsonrpc: '2.0', id: 1, result: 'pong' })
81+
})
82+
83+
it('responds with method not found for an unknown method, carrying the id', async () => {
84+
const { input, lines, conn } = harness()
85+
void conn
86+
87+
input.write('{"jsonrpc":"2.0","id":7,"method":"nope","params":{}}\n')
88+
await flush()
89+
90+
expect(lines).toHaveLength(1)
91+
const [msg] = lines as Array<{ id: number; error: { code: number } }>
92+
expect(msg.id).toBe(7)
93+
expect(msg.error.code).toBe(ERROR_METHOD_NOT_FOUND)
94+
})
95+
96+
it('maps a handler throw carrying a code to that error code', async () => {
97+
const { input, lines, conn } = harness()
98+
conn.onRequest('bad', () => {
99+
throw Object.assign(new Error('bad'), { code: ERROR_INVALID_PARAMS })
100+
})
101+
102+
input.write('{"jsonrpc":"2.0","id":1,"method":"bad","params":{}}\n')
103+
await flush()
104+
105+
const [msg] = lines as Array<{ error: { code: number } }>
106+
expect(msg.error.code).toBe(ERROR_INVALID_PARAMS)
107+
})
108+
109+
it('maps a plain Error throw to the internal error code', async () => {
110+
const { input, lines, conn } = harness()
111+
conn.onRequest('bad', () => {
112+
throw new Error('x')
113+
})
114+
115+
input.write('{"jsonrpc":"2.0","id":1,"method":"bad","params":{}}\n')
116+
await flush()
117+
118+
const [msg] = lines as Array<{ error: { code: number } }>
119+
expect(msg.error.code).toBe(ERROR_INTERNAL)
120+
})
121+
122+
it('calls the notification handler for a message with no id, and writes nothing', async () => {
123+
const { input, output, lines, conn } = harness()
124+
const handler = vi.fn()
125+
conn.onNotification('note', handler)
126+
const written = vi.fn()
127+
output.on('data', written)
128+
129+
input.write('{"jsonrpc":"2.0","method":"note","params":{"x":1}}\n')
130+
await flush()
131+
132+
expect(handler).toHaveBeenCalledTimes(1)
133+
expect(handler).toHaveBeenCalledWith({ x: 1 })
134+
expect(lines).toHaveLength(0)
135+
})
136+
137+
it('outbound request writes a framed request and resolves on a matching success response', async () => {
138+
const { input, lines, conn } = harness()
139+
140+
const pending = conn.request('foo', { a: 1 })
141+
await flush()
142+
143+
expect(lines).toEqual([{ jsonrpc: '2.0', id: 1, method: 'foo', params: { a: 1 } }])
144+
145+
input.write('{"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n')
146+
await expect(pending).resolves.toEqual({ ok: true })
147+
})
148+
149+
it('outbound request rejects on a matching error response', async () => {
150+
const { input, conn } = harness()
151+
152+
const pending = conn.request('foo')
153+
await flush()
154+
155+
input.write('{"jsonrpc":"2.0","id":1,"error":{"code":-1,"message":"nope"}}\n')
156+
await expect(pending).rejects.toThrow('nope')
157+
})
158+
159+
it('rejects a pending outbound request with "connection closed" on input end', async () => {
160+
const { input, conn } = harness()
161+
162+
const pending = conn.request('foo')
163+
await flush()
164+
input.end()
165+
166+
await expect(pending).rejects.toThrow('connection closed')
167+
})
168+
})
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { parseSseStream } from '../src/halo-client.js'
3+
4+
function streamOf(chunks: Array<string | Uint8Array>): ReadableStream<Uint8Array> {
5+
return new ReadableStream({
6+
start(c) {
7+
for (const chunk of chunks) {
8+
c.enqueue(typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk)
9+
}
10+
c.close()
11+
},
12+
})
13+
}
14+
15+
async function collect(stream: ReadableStream<Uint8Array>) {
16+
const out: unknown[] = []
17+
for await (const ev of parseSseStream(stream)) out.push(ev)
18+
return out
19+
}
20+
21+
describe('parseSseStream', () => {
22+
it('parses one frame', async () => {
23+
const events = await collect(streamOf(['data: {"type":"text","text":"hi"}\n\n']))
24+
expect(events).toEqual([{ type: 'text', text: 'hi' }])
25+
})
26+
27+
it('reassembles a data: line split across two chunks mid-JSON', async () => {
28+
const events = await collect(streamOf(['data: {"type":"text","te', 'xt":"hi"}\n\n']))
29+
expect(events).toEqual([{ type: 'text', text: 'hi' }])
30+
})
31+
32+
it('decodes a multibyte UTF-8 char whose bytes straddle two chunks', async () => {
33+
const full = new TextEncoder().encode('data: {"type":"text","text":"中"}\n\n')
34+
// Split mid-character: find the 3-byte UTF-8 sequence for 中 and cut it.
35+
const marker = new TextEncoder().encode('中')
36+
let idx = -1
37+
for (let i = 0; i <= full.length - marker.length; i++) {
38+
if (full[i] === marker[0] && full[i + 1] === marker[1] && full[i + 2] === marker[2]) {
39+
idx = i
40+
break
41+
}
42+
}
43+
expect(idx).toBeGreaterThan(-1)
44+
const cut = idx + 1 // split inside the 3-byte sequence
45+
const events = await collect(streamOf([full.slice(0, cut), full.slice(cut)]))
46+
expect(events).toEqual([{ type: 'text', text: '中' }])
47+
})
48+
49+
it('yields several frames from one chunk, in order', async () => {
50+
const events = await collect(
51+
streamOf(['data: {"type":"a"}\n\ndata: {"type":"b"}\n\ndata: {"type":"c"}\n\n']),
52+
)
53+
expect(events).toEqual([{ type: 'a' }, { type: 'b' }, { type: 'c' }])
54+
})
55+
56+
it('ignores lines not starting with "data: "', async () => {
57+
const events = await collect(
58+
streamOf(['event: foo\n: comment\nid: 3\n\ndata: {"type":"a"}\n\n']),
59+
)
60+
expect(events).toEqual([{ type: 'a' }])
61+
})
62+
63+
it('skips malformed JSON in a data line and still yields the next valid frame', async () => {
64+
const events = await collect(streamOf(['data: {not json}\n\ndata: {"type":"ok"}\n\n']))
65+
expect(events).toEqual([{ type: 'ok' }])
66+
})
67+
68+
it('yields nothing for "data: " with an empty payload', async () => {
69+
const events = await collect(streamOf(['data: \n\n']))
70+
expect(events).toEqual([])
71+
})
72+
})
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { defineConfig } from 'vitest/config'
2+
3+
export default defineConfig({
4+
test: {
5+
environment: 'node',
6+
include: ['test/**/*.test.ts'],
7+
},
8+
})

0 commit comments

Comments
 (0)