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

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,71 @@
1
+ // @heretek-ai/opencode-teamwork-v2 — postinstall hook
2
+ //
3
+ // Installs the 11 `team/*` agent markdown files into the OpenCode config
4
+ // directory and asks the user which model each agent should use.
5
+ //
6
+ // It deliberately does NOT edit opencode.json: OpenCode's own
7
+ // `opencode plugin add` handles registration, and silently rewriting a user's
8
+ // config from a lifecycle script is more surprising than helpful. Use
9
+ // `opencode-teamwork init` when the plugin was installed another way.
10
+ //
11
+ // The hook is best-effort: it never fails the surrounding install and skips
12
+ // entirely in CI or when OPENCODE_TEAMWORK_SKIP=1.
13
+
14
+ import {
15
+ PACKAGE_NAME,
16
+ resolveConfigDir,
17
+ currentModels,
18
+ writeModelMap,
19
+ installAgents,
20
+ } from "./lib/team.mjs"
21
+ import { detectAvailableModels, pickModels } from "./lib/picker.mjs"
22
+
23
+ function truthy(value) {
24
+ return value === "1" || value === "true" || value === "yes"
25
+ }
26
+
27
+ async function main() {
28
+ // Skip throwaway installs that npm performs outside the user's project:
29
+ // * ~/.npm/_npx/... -> `npx <pkg>` / `npm exec`
30
+ // * ~/.npm/_cacache/tmp/... -> git dependency checkout/build step
31
+ // The real setup for those flows is the explicit `init` command, so running
32
+ // here too would double-prompt (and write to config during a build).
33
+ const url = import.meta.url
34
+ const throwaway = process.env.npm_command === "exec" || url.includes("/_npx/") || url.includes("/_cacache/")
35
+ if (throwaway) return
36
+
37
+ if (truthy(process.env.OPENCODE_TEAMWORK_SKIP) || truthy(process.env.CI)) {
38
+ console.log(`[${PACKAGE_NAME}] Skipping interactive setup (CI / OPENCODE_TEAMWORK_SKIP).`)
39
+ console.log(`[${PACKAGE_NAME}] Run \`npx ${PACKAGE_NAME} init\` to choose agent models.`)
40
+ return
41
+ }
42
+
43
+ const configDir = resolveConfigDir()
44
+ const current = currentModels(configDir)
45
+
46
+ let models = current
47
+ const interactive = Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY)
48
+ if (interactive) {
49
+ try {
50
+ const available = await detectAvailableModels()
51
+ models = await pickModels({ current, available })
52
+ } catch {
53
+ models = current
54
+ }
55
+ }
56
+
57
+ writeModelMap(configDir, models)
58
+ const install = installAgents({ configDir, models })
59
+ console.log(
60
+ `[${PACKAGE_NAME}] Installed ${install.created.length} agent(s), updated ${install.updated.length} in ${configDir}/agents/team.`,
61
+ )
62
+ console.log(`[${PACKAGE_NAME}] Models saved to ${configDir}/teamwork.json.`)
63
+ if (!interactive) {
64
+ console.log(`[${PACKAGE_NAME}] (non-interactive) Run \`npx ${PACKAGE_NAME} init\` to choose models per agent.`)
65
+ }
66
+ console.log(`[${PACKAGE_NAME}] If the plugin isn't registered yet, run \`opencode plugin add ${PACKAGE_NAME}\`.`)
67
+ }
68
+
69
+ main().catch((error) => {
70
+ console.log(`[${PACKAGE_NAME}] postinstall skipped: ${error?.message || error}`)
71
+ })
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env node
2
+ // Prompt/agent linter for @heretek-ai/opencode-teamwork-v2.
3
+ //
4
+ // Guards the invariants we keep breaking by hand:
5
+ // * one canonical artifact root (.opencode/teamwork/<session-id>/)
6
+ // * one canonical topology enum (parsed from docs/ARTIFACTS.md)
7
+ // * no duplicated "run-time reminder" blocks / self-referential "agent file"
8
+ // * no stale references (Antigravity, defaults.ts, agent.team/*)
9
+ // * no `effect: ask` in agents that run in parallel (would stall a run)
10
+ // * every command template consumes $ARGUMENTS
11
+ //
12
+ // Usage: node scripts/lint-prompts.mjs (exit 1 on any violation)
13
+
14
+ import { readFileSync, readdirSync, existsSync } from "node:fs"
15
+ import { join, basename } from "node:path"
16
+ import { fileURLToPath } from "node:url"
17
+
18
+ const root = fileURLToPath(new URL("../", import.meta.url))
19
+ const agentsDir = join(root, "agents", "team")
20
+ const pluginFile = join(root, "plugins", "opencode-teamwork", "index.ts")
21
+ const artifactsFile = join(root, "docs", "ARTIFACTS.md")
22
+
23
+ const errors = []
24
+ const fail = (file, msg) => errors.push(`${basename(file)}: ${msg}`)
25
+
26
+ const agents = readdirSync(agentsDir).filter((f) => f.endsWith(".md"))
27
+ const read = (p) => readFileSync(p, "utf8")
28
+
29
+ // Canonical topologies, parsed from docs/ARTIFACTS.md so there is one source.
30
+ // The table lives in the level-2 "Topologies" section; scoping the parse to that
31
+ // section keeps unrelated documentation tables (feedbackLog fields, plan inputs,
32
+ // …) from being mistaken for topologies.
33
+ const EXPECTED_TOPOLOGIES = [
34
+ "small-focused",
35
+ "iterative-coding",
36
+ "distributed-coding",
37
+ "proof",
38
+ "massive-proof",
39
+ "document-review",
40
+ ]
41
+
42
+ // Text of the level-2 "Topologies" section, up to the next level-2 heading.
43
+ function topologySection(md) {
44
+ const heading = /^##[ \t]+Topologies[ \t]*$/m.exec(md)
45
+ if (!heading) return null
46
+ const rest = md.slice(heading.index + heading[0].length)
47
+ const next = /^##[ \t]+\S/m.exec(rest)
48
+ return next ? rest.slice(0, next.index) : rest
49
+ }
50
+
51
+ let canonical = []
52
+ if (!existsSync(artifactsFile)) {
53
+ errors.push("docs/ARTIFACTS.md is missing")
54
+ } else {
55
+ const md = read(artifactsFile)
56
+ const section = topologySection(md)
57
+ if (section === null) {
58
+ errors.push("docs/ARTIFACTS.md: topology section not found")
59
+ } else {
60
+ canonical = [...section.matchAll(/^\| `([a-z][a-z-]+)` \|/gm)].map((m) => m[1])
61
+ if (canonical.length < 6) errors.push(`docs/ARTIFACTS.md: expected >=6 topologies, found ${canonical.length}`)
62
+
63
+ // The parsed set must be exactly the canonical six. This catches a misparse
64
+ // with a message about the document, not about the agent prompts.
65
+ const found = new Set(canonical)
66
+ const missing = EXPECTED_TOPOLOGIES.filter((t) => !found.has(t))
67
+ const extra = [...found].filter((t) => !EXPECTED_TOPOLOGIES.includes(t))
68
+ const duplicates = canonical.filter((t, i) => canonical.indexOf(t) !== i)
69
+ if (missing.length) errors.push(`docs/ARTIFACTS.md: topology section missing canonical topologies: ${missing.join(", ")}`)
70
+ if (extra.length) errors.push(`docs/ARTIFACTS.md: topology section has unknown entries: ${extra.join(", ")}`)
71
+ if (duplicates.length) errors.push(`docs/ARTIFACTS.md: topology section has duplicate entries: ${duplicates.join(", ")}`)
72
+ }
73
+ }
74
+
75
+ const LEGACY = ["large-swarm", "doc-review", "long-proof", "massive-proof-swarm"]
76
+ const FORBIDDEN = [
77
+ ["Antigravity", "attribution removed; describe behavior, don't name-drop"],
78
+ ["defaults.ts", "stale path — models live in agent frontmatter / teamwork.json"],
79
+ ["agent.team/*", "stale V1 config key"],
80
+ ["run-time reminder", "duplicated prompt block"],
81
+ ["are in your agent file", "self-referential instruction"],
82
+ ["in your agent file", "self-referential instruction"],
83
+ [".teamwork-runs", "old artifact root"],
84
+ ["<run-id>", "old id terminology"],
85
+ ]
86
+
87
+ const PARALLEL_AGENTS = new Set([
88
+ "proposer.md", "synthesizer.md", "worker.md", "proof-worker.md",
89
+ "falsifier.md", "scout.md", "verifier.md",
90
+ ])
91
+
92
+ for (const file of agents) {
93
+ const path = join(agentsDir, file)
94
+ const text = read(path)
95
+
96
+ // Frontmatter
97
+ const fm = text.match(/^---\n([\s\S]*?)\n---/)
98
+ if (!fm) { fail(path, "missing frontmatter"); continue }
99
+ for (const key of ["description", "mode", "model"]) {
100
+ if (!new RegExp(`^${key}:`, "m").test(fm[1])) fail(path, `frontmatter missing '${key}'`)
101
+ }
102
+
103
+ // Forbidden references
104
+ for (const [needle, why] of FORBIDDEN) {
105
+ if (text.includes(needle)) fail(path, `contains '${needle}' (${why})`)
106
+ }
107
+
108
+ // Legacy topology names allowed only on an alias-mapping line (contains '→')
109
+ for (const line of text.split("\n")) {
110
+ if (line.includes("→")) continue
111
+ for (const legacy of LEGACY) {
112
+ if (line.includes(legacy)) fail(path, `uses legacy topology '${legacy}'`)
113
+ }
114
+ }
115
+
116
+ // Parallel agents must not block on 'ask'
117
+ if (PARALLEL_AGENTS.has(file) && /effect:\s*ask/.test(text)) {
118
+ fail(path, "uses 'effect: ask' but runs in parallel (would stall the run)")
119
+ }
120
+ }
121
+
122
+ // Plugin: commands must consume $ARGUMENTS and not use old paths
123
+ const plugin = read(pluginFile)
124
+ if (plugin.includes(".teamwork-runs")) fail(pluginFile, "old artifact root")
125
+ const argCount = (plugin.match(/\$ARGUMENTS/g) || []).length
126
+ const cmdCount = (plugin.match(/name:\s*"/g) || []).length
127
+ if (argCount < 1) fail(pluginFile, "no $ARGUMENTS substitution found")
128
+ if (argCount < cmdCount - 1) fail(pluginFile, `only ${argCount} $ARGUMENTS for ~${cmdCount} commands`)
129
+
130
+ // Canonical topology names must appear in the agents that route on them
131
+ for (const file of ["sentinel.md", "crafter.md"]) {
132
+ const text = read(join(agentsDir, file))
133
+ const missing = canonical.filter((t) => !text.includes(`\`${t}\``))
134
+ if (missing.length) fail(join(agentsDir, file), `missing canonical topologies: ${missing.join(", ")}`)
135
+ }
136
+
137
+ // Guardrail invariants (see docs/GUARDRAILS.md)
138
+ if (!existsSync(join(root, "docs", "GUARDRAILS.md"))) errors.push("docs/GUARDRAILS.md is missing")
139
+ if (!agents.includes("security-auditor.md")) errors.push("agents/team/security-auditor.md is missing")
140
+
141
+ const toolsFile = join(root, "plugins", "opencode-teamwork", "tools.ts")
142
+ if (existsSync(toolsFile)) {
143
+ const t = read(toolsFile)
144
+ if (!/SESSION_ID/.test(t)) fail(toolsFile, "no session-id allowlist found")
145
+ if (!/relative\(/.test(t) || !/startsWith\("\.\."\)/.test(t)) fail(toolsFile, "no path-containment check found")
146
+ if (!/realpathSync\(/.test(t)) fail(toolsFile, "no realpath containment check (symlink escape)")
147
+ if (!/lstatSync\(/.test(t)) fail(toolsFile, "no lstat check (symlinked run dir)")
148
+ if (!/permission\?\.hook|permission\.hook/.test(t)) fail(toolsFile, "no permission hook found")
149
+ }
150
+
151
+ // No unquoted session-id / command substitution in a git command (injection).
152
+ // Scans the agent files AND the plugin's command templates.
153
+ const shellScanFiles = [...agents.map((f) => join(agentsDir, f)), pluginFile]
154
+ for (const path of shellScanFiles) {
155
+ // Join backslash line-continuations so a split command can't slip through.
156
+ for (const line of read(path).replace(/\\\r?\n/g, " ").split("\n")) {
157
+ if (!/\bgit\s/.test(line)) continue
158
+ if (line.includes("<session-id>")) fail(path, "unquoted <session-id> in a git command (command-injection risk)")
159
+ if (line.includes("$(")) fail(path, "command substitution in a git command")
160
+ }
161
+ }
162
+
163
+ if (errors.length) {
164
+ console.error(`✗ prompt lint failed (${errors.length}):`)
165
+ for (const e of errors) console.error(` - ${e}`)
166
+ process.exit(1)
167
+ }
168
+ console.log(`✓ prompt lint passed (${agents.length} agents, ${canonical.length} topologies)`)
@@ -0,0 +1,242 @@
1
+ // test-cost — verifies session-tree cost aggregation and the manual addUsd fallback.
2
+ //
3
+ // Hermeticity: the tree-aggregation assertions need a real OpenCode session that
4
+ // already recorded cost, which cannot be manufactured here without mutating the
5
+ // user's database. Instead of pinning a machine-specific session id:
6
+ // * TEAMWORK_TEST_SESSION_ID overrides discovery when set.
7
+ // * Otherwise the most recently updated session with enough recorded cost in
8
+ // the local OpenCode DB is used. Path discovery and the node:sqlite ->
9
+ // sqlite3 backends mirror plugins/opencode-teamwork/tools.ts, so the test
10
+ // reads the same database the cost tool reads.
11
+ // * With no usable session the script prints one SKIP line and exits 0. A
12
+ // vacuous pass would hide untested behaviour; an explicit skip is honest,
13
+ // and CI without an OpenCode DB must not fail on an environment assumption.
14
+ //
15
+ // Discovered spend must reach 1% of the plan tool's default $20 budget because
16
+ // the cost tool floors the percentage; otherwise an existing assertion (pct > 0)
17
+ // could not hold and the test would fail for environmental reasons.
18
+
19
+ import { registerTeamworkTools } from "../plugins/opencode-teamwork/tools.ts"
20
+ import { existsSync, mkdtempSync, rmSync } from "node:fs"
21
+ import { homedir, tmpdir } from "node:os"
22
+ import { join } from "node:path"
23
+ import assert from "node:assert"
24
+ import { execFileSync } from "node:child_process"
25
+
26
+ const SKIP_NOTICE =
27
+ "SKIP: test-cost needs a real OpenCode session with cost data; set TEAMWORK_TEST_SESSION_ID to one, or run after at least one OpenCode session."
28
+
29
+ const DEFAULT_PLAN_BUDGET_USD = 20
30
+ const MIN_DISCOVERED_COST_USD = DEFAULT_PLAN_BUDGET_USD / 100
31
+
32
+ // Mirrors getOpencodeDbPath() in plugins/opencode-teamwork/tools.ts.
33
+ function getOpencodeDbPath() {
34
+ const candidates = []
35
+ if (process.env.XDG_DATA_HOME) {
36
+ candidates.push(join(process.env.XDG_DATA_HOME, "opencode", "opencode.db"))
37
+ }
38
+ const home = homedir()
39
+ candidates.push(join(home, ".local", "share", "opencode", "opencode.db"))
40
+ candidates.push(join(home, "Library", "Application Support", "opencode", "opencode.db"))
41
+ if (process.env.LOCALAPPDATA) {
42
+ candidates.push(join(process.env.LOCALAPPDATA, "opencode", "opencode.db"))
43
+ }
44
+ candidates.push(join(home, "AppData", "Local", "opencode", "opencode.db"))
45
+ for (const p of candidates) {
46
+ try {
47
+ if (existsSync(p)) return p
48
+ } catch {}
49
+ }
50
+ return undefined
51
+ }
52
+
53
+ let nodeSqlitePromise
54
+
55
+ function loadNodeSqlite() {
56
+ if (nodeSqlitePromise === undefined) {
57
+ nodeSqlitePromise = import("node:sqlite").catch(() => null)
58
+ }
59
+ return nodeSqlitePromise
60
+ }
61
+
62
+ function inlineParams(sql, params) {
63
+ let i = 0
64
+ return sql.replace(/\?/g, () => {
65
+ const value = params[i++]
66
+ if (typeof value === "number" && Number.isFinite(value)) return String(value)
67
+ return `'${String(value).replace(/'/g, "''")}'`
68
+ })
69
+ }
70
+
71
+ // Same backend order as tools.ts: node:sqlite first, sqlite3 CLI second.
72
+ async function queryRows(dbPath, sql, params = []) {
73
+ const mod = await loadNodeSqlite()
74
+ if (mod && typeof mod.DatabaseSync === "function") {
75
+ try {
76
+ const db = new mod.DatabaseSync(dbPath, { readOnly: true })
77
+ try {
78
+ return db.prepare(sql).all(...params).map((row) => ({ ...row }))
79
+ } finally {
80
+ db.close()
81
+ }
82
+ } catch {}
83
+ }
84
+ try {
85
+ const raw = execFileSync("sqlite3", [dbPath, "-json", inlineParams(sql, params)], {
86
+ encoding: "utf8",
87
+ timeout: 5000,
88
+ })
89
+ const parsed = JSON.parse(raw || "[]")
90
+ return Array.isArray(parsed) ? parsed : []
91
+ } catch {
92
+ return []
93
+ }
94
+ }
95
+
96
+ async function findSessionWithCost(dbPath) {
97
+ const rows = await queryRows(
98
+ dbPath,
99
+ `WITH RECURSIVE tree(root_id, id, cost, depth) AS (
100
+ SELECT id, id, cost, 0 FROM session_v2 WHERE cost > 0
101
+ UNION ALL
102
+ SELECT t.root_id, s.id, s.cost, t.depth + 1
103
+ FROM session_v2 s JOIN tree t ON s.parent_id = t.id
104
+ WHERE t.depth < 32
105
+ )
106
+ SELECT t.root_id AS id, SUM(t.cost) AS total, MAX(s.time_updated) AS updated
107
+ FROM tree t JOIN session_v2 s ON s.id = t.root_id
108
+ GROUP BY t.root_id
109
+ HAVING SUM(t.cost) >= ?
110
+ ORDER BY updated DESC
111
+ LIMIT 1`,
112
+ [MIN_DISCOVERED_COST_USD],
113
+ )
114
+ const row = rows[0]
115
+ return row && typeof row.id === "string" ? row.id : undefined
116
+ }
117
+
118
+ async function readTreeCost(dbPath, sessionId) {
119
+ const rows = await queryRows(
120
+ dbPath,
121
+ `WITH RECURSIVE tree(id, cost, depth) AS (
122
+ SELECT id, cost, 0 FROM session_v2 WHERE id = ?
123
+ UNION ALL
124
+ SELECT s.id, s.cost, t.depth + 1
125
+ FROM session_v2 s JOIN tree t ON s.parent_id = t.id
126
+ WHERE t.depth < 32
127
+ )
128
+ SELECT COUNT(*) AS n, COALESCE(SUM(cost), 0) AS total FROM tree`,
129
+ [sessionId],
130
+ )
131
+ const row = rows[0]
132
+ if (!row || Number(row.n) === 0) return undefined
133
+ return Number(row.total) || 0
134
+ }
135
+
136
+ async function resolveTestSession() {
137
+ const dbPath = getOpencodeDbPath()
138
+ if (!dbPath) return undefined
139
+
140
+ const override = process.env.TEAMWORK_TEST_SESSION_ID?.trim()
141
+ if (override) {
142
+ // A bad override must skip, not crash and not pass vacuously.
143
+ if (!/^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(override)) return undefined
144
+ const total = await readTreeCost(dbPath, override)
145
+ return total !== undefined && total >= MIN_DISCOVERED_COST_USD ? override : undefined
146
+ }
147
+
148
+ return await findSessionWithCost(dbPath)
149
+ }
150
+
151
+ const testSessionId = await resolveTestSession()
152
+ if (!testSessionId) {
153
+ console.log(SKIP_NOTICE)
154
+ process.exit(0)
155
+ }
156
+
157
+ const testDir = mkdtempSync(join(tmpdir(), "teamwork-test-"))
158
+
159
+ try {
160
+ let registeredTools = {}
161
+ const mockCtx = {
162
+ tool: {
163
+ transform: async (cb) => {
164
+ const editor = {
165
+ namespace: () => {},
166
+ add: (tool) => {
167
+ registeredTools[tool.name] = tool
168
+ },
169
+ }
170
+ await cb(editor)
171
+ },
172
+ },
173
+ session: {
174
+ get: async ({ sessionID }) => {
175
+ if (sessionID === "ses_mock_root") {
176
+ return { cost: 0.15, tokens: { input: 100, output: 50, reasoning: 0, cache: { read: 0, write: 0 } } }
177
+ }
178
+ return undefined
179
+ },
180
+ },
181
+ }
182
+
183
+ await registerTeamworkTools(mockCtx, testDir)
184
+
185
+ assert(registeredTools.plan, "plan tool must be registered")
186
+ assert(registeredTools.cost, "cost tool must be registered")
187
+
188
+ // 1. Test plan creates run and records root session
189
+ const planRes = await registeredTools.plan.execute(
190
+ {
191
+ topology: "small-focused",
192
+ tasks: [{ id: "task-1" }],
193
+ skipInterview: true, // fixture: this test exercises cost aggregation, not the spec gate
194
+ },
195
+ { sessionID: testSessionId },
196
+ )
197
+
198
+ assert(planRes.content.includes("Planned 1 task"), "Plan should succeed")
199
+
200
+ // 2. Test cost tool reading real opencode DB session tree
201
+ const costRes = await registeredTools.cost.execute({}, { sessionID: testSessionId })
202
+ assert(costRes.content.includes("opencode session tree"), "Should report opencode session tree as source")
203
+ assert(costRes.content.includes("spent: $"), "Should report spent amount")
204
+ assert(costRes.pct > 0, "Percentage should reflect total consumption")
205
+
206
+ // 3. Second call should not double count
207
+ const costRes2 = await registeredTools.cost.execute({}, { sessionID: testSessionId })
208
+ assert.strictEqual(costRes.pct, costRes2.pct, "Percentage should remain identical on immediate re-call")
209
+
210
+ // 4. Test manual addUsd fallback when native client/tree is unavailable
211
+ const mockOfflineCtx = {
212
+ tool: mockCtx.tool,
213
+ session: { get: async () => undefined },
214
+ }
215
+ let offlineTools = {}
216
+ mockOfflineCtx.tool.transform = async (cb) => {
217
+ await cb({
218
+ namespace: () => {},
219
+ add: (tool) => {
220
+ offlineTools[tool.name] = tool
221
+ },
222
+ })
223
+ }
224
+ await registerTeamworkTools(mockOfflineCtx, testDir)
225
+
226
+ await offlineTools.plan.execute(
227
+ {
228
+ topology: "small-focused",
229
+ tasks: [{ id: "task-1" }],
230
+ skipInterview: true, // fixture: this test exercises cost aggregation, not the spec gate
231
+ },
232
+ { sessionID: "ses_offline_test" },
233
+ )
234
+
235
+ const costOffline = await offlineTools.cost.execute({ addUsd: 1.5, taskId: "T1" }, { sessionID: "ses_offline_test" })
236
+ assert(costOffline.content.includes("spent: $1.5"), "Should record 1.5 in manual fallback mode")
237
+ assert(costOffline.content.includes("manual (client unavailable)"), "Source should be manual")
238
+
239
+ console.log("✓ test-cost passed: session tree aggregation & manual fallback verified")
240
+ } finally {
241
+ rmSync(testDir, { recursive: true, force: true })
242
+ }