@heretek-ai/opencode-teamwork-v2 0.0.0-stage → 0.5.9

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.
@@ -0,0 +1,287 @@
1
+ // @heretek-ai/opencode-teamwork-v2 — doctor diagnostics test suite
2
+ //
3
+ // Hermetic, zero-dependency coverage for `lib/doctor.mjs` and the
4
+ // `opencode-teamwork doctor` CLI. Every fixture lives in its own temp dir and
5
+ // every invocation gets an explicit `configDir` / `--config-dir` plus an
6
+ // explicit `cwd`, so the developer's real ~/.config/opencode is never touched.
7
+ //
8
+ // Run with plain Node (no test framework): an uncaught assertion exits non-zero.
9
+
10
+ import { runDoctor, CHECK_NAMES, nextSteps } from "../lib/doctor.mjs"
11
+ import { TEAM_AGENTS, PACKAGE_NAME, writeModelMap } from "../lib/team.mjs"
12
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"
13
+ import { tmpdir } from "node:os"
14
+ import { join, dirname } from "node:path"
15
+ import { fileURLToPath } from "node:url"
16
+ import { execFileSync, spawnSync } from "node:child_process"
17
+ import assert from "node:assert"
18
+
19
+ const here = dirname(fileURLToPath(import.meta.url))
20
+ const cliPath = join(here, "..", "bin", "opencode-teamwork.mjs")
21
+
22
+ // Root temp dir for this run; fixture dirs are tracked so they are always
23
+ // removed, even when an assertion throws.
24
+ const testDir = mkdtempSync(join(tmpdir(), "teamwork-doctor-test-"))
25
+ const fixtureDirs = []
26
+
27
+ /** Create (and register for cleanup) a fresh temp directory. */
28
+ function makeTemp(prefix) {
29
+ const dir = mkdtempSync(join(tmpdir(), prefix))
30
+ fixtureDirs.push(dir)
31
+ return dir
32
+ }
33
+
34
+ /**
35
+ * Build a fully healthy config fixture:
36
+ * - opencode.json registering the teamwork plugin
37
+ * - all TEAM_AGENTS markdown files with a model: frontmatter line
38
+ * - a teamwork.json model map that matches every agent file
39
+ */
40
+ function makeHealthyConfig() {
41
+ const configDir = makeTemp("teamwork-doctor-config-")
42
+
43
+ writeFileSync(
44
+ join(configDir, "opencode.json"),
45
+ JSON.stringify({ $schema: "https://opencode.ai/config.json", plugins: [PACKAGE_NAME] }, null, 2) + "\n",
46
+ )
47
+
48
+ const agentsDir = join(configDir, "agents", "team")
49
+ mkdirSync(agentsDir, { recursive: true })
50
+
51
+ const models = {}
52
+ for (const agent of TEAM_AGENTS) {
53
+ writeFileSync(join(agentsDir, agent.file), `---\nmodel: ${agent.defaultModel}\n---\n\n# ${agent.id}\n`)
54
+ models[agent.id] = agent.defaultModel
55
+ }
56
+
57
+ writeModelMap(configDir, models)
58
+ return { configDir, models, agentsDir }
59
+ }
60
+
61
+ /** A fresh temp dir that is an actual git work tree (for the pass path). */
62
+ function makeGitRepo() {
63
+ const dir = makeTemp("teamwork-doctor-git-")
64
+ execFileSync("git", ["init"], { cwd: dir, stdio: "ignore" })
65
+ return dir
66
+ }
67
+
68
+ /** Assert the report carries exactly the seven checks in the fixed order. */
69
+ function assertCheckOrder(checks) {
70
+ assert.strictEqual(CHECK_NAMES.length, 7, "the check contract must define exactly seven names")
71
+ assert.deepStrictEqual(
72
+ checks.map((check) => check.name),
73
+ CHECK_NAMES,
74
+ "checks must be present in the fixed order",
75
+ )
76
+ }
77
+
78
+ function findCheck(report, name) {
79
+ const check = report.checks.find((c) => c.name === name)
80
+ assert(check, `check "${name}" must be present`)
81
+ return check
82
+ }
83
+
84
+ try {
85
+ // Keep worktree-dir resolution deterministic and hermetic (the check reads
86
+ // this env var; it is inherited by CLI subprocesses too).
87
+ process.env.TEAMWORK_WORKTREES_DIR = join(testDir, "worktrees")
88
+
89
+ const gitRepo = makeGitRepo()
90
+
91
+ // ==========================================
92
+ // Part 1: Healthy environment passes every check
93
+ // ==========================================
94
+ console.log("Testing healthy environment...")
95
+
96
+ const healthy = makeHealthyConfig()
97
+ const healthyReport = runDoctor({ configDir: healthy.configDir, cwd: gitRepo })
98
+
99
+ assert.strictEqual(healthyReport.ok, true, "healthy environment must report ok: true")
100
+ assert.strictEqual(healthyReport.checks.length, 7, "doctor must report exactly 7 checks")
101
+ assertCheckOrder(healthyReport.checks)
102
+ for (const check of healthyReport.checks) {
103
+ assert.strictEqual(check.status, "pass", `expected ${check.name} to pass, got ${check.status}: ${check.message}`)
104
+ }
105
+ assert.deepStrictEqual(nextSteps(healthyReport.checks), [], "a fully passing report must yield no next steps")
106
+
107
+ console.log("✓ Healthy environment passes all 7 checks in fixed order (ok: true)")
108
+
109
+ // ==========================================
110
+ // Part 2: Missing agent file fails the run
111
+ // ==========================================
112
+ console.log("Testing missing agent file...")
113
+
114
+ const missingFixture = makeHealthyConfig()
115
+ const missingAgent = TEAM_AGENTS[2] // team/orchestrator
116
+ rmSync(join(missingFixture.agentsDir, missingAgent.file))
117
+
118
+ const missingReport = runDoctor({ configDir: missingFixture.configDir, cwd: gitRepo })
119
+ const agentsCheck = findCheck(missingReport, "agents_installed")
120
+
121
+ assert.strictEqual(agentsCheck.status, "fail", "agents_installed must fail when an agent file is missing")
122
+ assert.strictEqual(missingReport.ok, false, "a failing check must make ok false")
123
+ assert(
124
+ agentsCheck.message.includes(missingAgent.id),
125
+ `failure message must name the missing agent id (${missingAgent.id}), got: ${agentsCheck.message}`,
126
+ )
127
+
128
+ console.log("✓ Missing agent file fails agents_installed and sets ok: false")
129
+
130
+ // ==========================================
131
+ // Part 3: Desynchronized model map warns but stays healthy
132
+ // ==========================================
133
+ console.log("Testing desynchronized model map...")
134
+
135
+ const desyncFixture = makeHealthyConfig()
136
+ const desyncAgent = TEAM_AGENTS[0] // team/crafter
137
+ writeModelMap(desyncFixture.configDir, {
138
+ ...desyncFixture.models,
139
+ [desyncAgent.id]: "some-other-provider/some-other-model",
140
+ })
141
+
142
+ const desyncReport = runDoctor({ configDir: desyncFixture.configDir, cwd: gitRepo })
143
+ const modelCheck = findCheck(desyncReport, "model_sync")
144
+
145
+ assert.strictEqual(modelCheck.status, "warn", "model_sync must warn when teamwork.json disagrees with the agent file")
146
+ assert.strictEqual(desyncReport.ok, true, "a warning must not fail the run (ok must remain true)")
147
+ assert(
148
+ modelCheck.message.includes(desyncAgent.id),
149
+ `mismatch message must name the desynchronized agent (${desyncAgent.id}), got: ${modelCheck.message}`,
150
+ )
151
+ assert(
152
+ desyncReport.checks.every((check) => check.status !== "fail"),
153
+ "no check may fail for the desync fixture",
154
+ )
155
+
156
+ console.log("✓ Desynchronized model map warns without failing the run (ok: true)")
157
+
158
+ // ==========================================
159
+ // Part 4: cwd outside any git work tree
160
+ // ==========================================
161
+ console.log("Testing non-git cwd...")
162
+
163
+ // A bare mkdtemp dir under the OS temp root. Assert on the real result rather
164
+ // than assuming the ancestors are repo-free.
165
+ const noGitDir = makeTemp("teamwork-doctor-nogit-")
166
+ const noGitReport = runDoctor({ configDir: healthy.configDir, cwd: noGitDir })
167
+ const gitRepoCheck = findCheck(noGitReport, "git_repository")
168
+
169
+ assert(
170
+ gitRepoCheck.status === "warn" || gitRepoCheck.status === "fail",
171
+ `git_repository must warn or fail outside a work tree, got ${gitRepoCheck.status}: ${gitRepoCheck.message}`,
172
+ )
173
+
174
+ console.log("✓ Non-git cwd yields warn/fail for git_repository")
175
+
176
+ // ==========================================
177
+ // Part 5: CLI --json contract
178
+ // ==========================================
179
+ console.log("Testing CLI JSON contract...")
180
+
181
+ const jsonOut = execFileSync(process.execPath, [cliPath, "doctor", "--json", "--config-dir", healthy.configDir], {
182
+ cwd: gitRepo,
183
+ encoding: "utf8",
184
+ })
185
+
186
+ assert(!jsonOut.includes("\u001b["), "doctor --json stdout must not contain ANSI escape sequences")
187
+
188
+ const parsed = JSON.parse(jsonOut)
189
+ assert.strictEqual(parsed.ok, true, "CLI JSON must report ok: true for a healthy fixture")
190
+ assert.strictEqual(parsed.checks.length, 7, "CLI JSON must report exactly 7 checks")
191
+ assertCheckOrder(parsed.checks)
192
+ assert(Array.isArray(parsed.nextSteps), "CLI JSON must expose an additive nextSteps array")
193
+ assert.deepStrictEqual(parsed.nextSteps, [], "healthy CLI JSON must carry an empty nextSteps array")
194
+ assert(
195
+ parsed.checks.every((check) => check.status === "pass"),
196
+ "CLI JSON checks must all be pass for a healthy fixture",
197
+ )
198
+
199
+ console.log("✓ CLI --json emits pure parseable JSON with 7 ordered checks and no ANSI")
200
+
201
+ // ==========================================
202
+ // Part 6: CLI exit codes
203
+ // ==========================================
204
+ console.log("Testing CLI exit codes...")
205
+
206
+ const healthyExit = spawnSync(process.execPath, [cliPath, "doctor", "--json", "--config-dir", healthy.configDir], {
207
+ cwd: gitRepo,
208
+ encoding: "utf8",
209
+ })
210
+ assert.strictEqual(healthyExit.status, 0, `healthy doctor must exit 0, got ${healthyExit.status}`)
211
+
212
+ const brokenFixture = makeHealthyConfig()
213
+ rmSync(join(brokenFixture.agentsDir, TEAM_AGENTS[4].file))
214
+ const brokenExit = spawnSync(process.execPath, [cliPath, "doctor", "--json", "--config-dir", brokenFixture.configDir], {
215
+ cwd: gitRepo,
216
+ encoding: "utf8",
217
+ })
218
+ assert.strictEqual(brokenExit.status, 1, `doctor with a missing agent must exit 1, got ${brokenExit.status}`)
219
+ const brokenJson = JSON.parse(brokenExit.stdout)
220
+ assert.deepStrictEqual(
221
+ brokenJson.nextSteps,
222
+ ["opencode-teamwork init"],
223
+ "JSON nextSteps must name the init command for a missing-agent failure",
224
+ )
225
+
226
+ const brokenText = spawnSync(process.execPath, [cliPath, "doctor", "--config-dir", brokenFixture.configDir], {
227
+ cwd: gitRepo,
228
+ encoding: "utf8",
229
+ })
230
+ assert.strictEqual(brokenText.status, 1, `text doctor with a missing agent must exit 1, got ${brokenText.status}`)
231
+ assert(
232
+ brokenText.stdout.includes("→ opencode-teamwork init"),
233
+ `text doctor output must render the actionable step, got:\n${brokenText.stdout}`,
234
+ )
235
+ assert(
236
+ !brokenText.stdout.includes("→ opencode-teamwork models"),
237
+ "text doctor output must not render steps for later checks once one is matched",
238
+ )
239
+
240
+ console.log("✓ CLI exit codes verified (0 healthy, 1 on failure)")
241
+
242
+ // ==========================================
243
+ // Part 7: nextSteps advice is additive and first-failure only
244
+ // ==========================================
245
+ console.log("Testing nextSteps advice...")
246
+
247
+ assert.deepStrictEqual(nextSteps(missingReport.checks), ["opencode-teamwork init"], "agents_installed must map to init")
248
+ assert.deepStrictEqual(nextSteps(desyncReport.checks), ["opencode-teamwork models"], "model_sync must map to models")
249
+
250
+ // A non-pass config check comes first, so later agent failures must not add a
251
+ // second command.
252
+ assert.deepStrictEqual(
253
+ nextSteps([
254
+ { name: "config_file", status: "warn", message: "" },
255
+ { name: "agents_installed", status: "fail", message: "" },
256
+ ]),
257
+ [`opencode plugin add ${PACKAGE_NAME}`],
258
+ "only the first non-pass check may produce a step",
259
+ )
260
+
261
+ const expectedSteps = {
262
+ config_file: `opencode plugin add ${PACKAGE_NAME}`,
263
+ plugin_registration: `opencode plugin add ${PACKAGE_NAME}`,
264
+ agents_installed: "opencode-teamwork init",
265
+ model_sync: "opencode-teamwork models",
266
+ git_installed: "Install git (https://git-scm.com/downloads)",
267
+ git_repository: "git init",
268
+ worktrees_dir: "Set TEAMWORK_WORKTREES_DIR to a writable directory",
269
+ }
270
+ assert.deepStrictEqual(
271
+ Object.keys(expectedSteps),
272
+ CHECK_NAMES,
273
+ "every check in the contract must have exactly one mapping",
274
+ )
275
+ for (const [name, command] of Object.entries(expectedSteps)) {
276
+ assert.deepStrictEqual(
277
+ nextSteps([{ name, status: name === "git_installed" ? "fail" : "warn", message: "" }]),
278
+ [command],
279
+ `${name} must map to its actionable command`,
280
+ )
281
+ }
282
+
283
+ console.log("✓ nextSteps maps the first non-pass check only; all-pass yields []")
284
+ } finally {
285
+ rmSync(testDir, { recursive: true, force: true })
286
+ for (const dir of fixtureDirs) rmSync(dir, { recursive: true, force: true })
287
+ }