@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,48 @@
1
+ # Guardrails
2
+
3
+ The security model for `@heretek-ai/opencode-teamwork-v2`, and how each control is enforced
4
+ (in code, not just in a prompt).
5
+
6
+ ## Threat model
7
+
8
+ An agent that can **read untrusted content** (repo files, `prompt_draft.md`,
9
+ `state.json`, web pages, issues) and also **run shell / edit / fetch** is one
10
+ indirect-prompt-injection away from exfiltration or destruction. Teamwork agents
11
+ run with the user's full privileges by default, so the controls below exist to
12
+ remove the sharpest edges.
13
+
14
+ ## Controls
15
+
16
+ | Control | Where | What it stops |
17
+ | --- | --- | --- |
18
+ | **Session-id allowlist** `^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$` + containment assert | `plugins/opencode-teamwork/tools.ts` (`resolveRun`) | Path traversal / arbitrary file write or append via `sessionId` in any `teamwork_*` tool. |
19
+ | **Server-derived session id** — `teamwork_plan` generates and returns the id; prompts must use it, never a value read from a file | `tools.ts` + `agents/team/sentinel.md` | Command injection through a malicious `prompt_draft.md` session id interpolated into `git worktree` shell lines. |
20
+ | **Read-only enforcement (per-agent deny list)** | `tools.ts` `registerTeamworkHooks` → `permission.hook("evaluate")` | `edit` for the verifier, falsifier, scout and security auditor, so none can write through the `edit` tool; plus `shell` for the falsifier, `webfetch` for the verifier and security auditor, and `subagent` for all four. `shell` remains available to the verifier, scout and security auditor and **can modify files**, so only the falsifier is left without a shell write path. Fail-closed: a hook that cannot register fails plugin load. |
21
+ | **Sanitised run-state injection** — only whitelisted/enumerated fields, newlines stripped, id from the directory name | `tools.ts` `describeRun` → `session.hook("context")` | Stored prompt injection from an untrusted `state.json` into a system prompt. |
22
+ | **Non-destructive installer** — `refresh` defaults to false; `--refresh` opts in with backup | `lib/team.mjs` `installAgents` | Silent overwrite of a user's edited agent prompts. |
23
+ | **Non-destructive config edits** — refuse symlinks, never rewrite commented (JSONC) configs | `lib/team.mjs` `registerPlugin` | Comment loss / value corruption / symlink write-through when editing `opencode.json(c)`. |
24
+ | **Load-time writes are create-only** | `lib/team.mjs` `ensureAgents` / `writeReferenceFile({overwrite:false})` | `ARTIFACTS.md` / agents being rewritten on every plugin load. |
25
+
26
+ ## Known gaps / non-goals
27
+
28
+ - **No worktree/cwd confinement in code.** Worker/verifier prompts *say* "don't
29
+ edit outside your worktree," but with `resource: "*"` nothing enforces it.
30
+ `git worktree` isolation is prompt-level. (Mitigated only by the permission
31
+ hook: for the verifier, scout and security auditor it denies `edit` but not
32
+ `shell`, which can write anywhere; the falsifier also has `shell` denied.)
33
+ - **`constraints.network` / `constraints.sandbox`** in `docs/ARTIFACTS.md` are
34
+ descriptive; they are not enforced. "Network: denied" is honor-system.
35
+ - **Plugin tools are not agent-scoped.** The permission layer does not mediate
36
+ `teamwork_*` tool calls, so a read-only agent can still call `teamwork_cost`
37
+ etc. The session-id allowlist bounds the damage.
38
+ - **Run artifacts are trusted inputs.** `state.json` / `plan.dag.json` /
39
+ `prompt_draft.md` living in the repo are treated as control data (now
40
+ sanitised before injection, but still unauthenticated).
41
+ - **No sandbox for shell.** Agents run with full user privileges and network.
42
+
43
+ ## Running an audit
44
+
45
+ Use the `team/security-auditor` agent (clean context; `edit` denied, `shell`
46
+ available) or a fresh subagent. It is also wired into the prompt linter's
47
+ expectations; the guardrail invariants (session-id validation present, no stale
48
+ references) are checked in CI by `scripts/lint-prompts.mjs`.
package/lib/doctor.mjs ADDED
@@ -0,0 +1,280 @@
1
+ // @heretek-ai/opencode-teamwork-v2 — diagnostic engine
2
+ //
3
+ // Dependency-free health check shared by the `opencode-teamwork doctor` CLI and
4
+ // the plugin. It inspects the resolved OpenCode config directory, the installed
5
+ // `team/*` agents, the model map and the local git/worktree environment and
6
+ // returns a stable, ordered report:
7
+ //
8
+ // { ok, checks: [{ name, status: "pass"|"warn"|"fail", message }] }
9
+ //
10
+ // The seven check names and their order are a fixed contract — never omit,
11
+ // rename or reorder them. `ok` is true only when no check failed.
12
+ //
13
+ // Nothing here mutates state or calls process.exit(); exit codes are the CLI's
14
+ // job. Shell probes go through execFileSync with a fixed argv array and never
15
+ // interpolate a shell string (see SECURITY notes below).
16
+
17
+ import { existsSync, readFileSync, realpathSync } from "node:fs"
18
+ import { isAbsolute, join, relative, resolve } from "node:path"
19
+ import { execFileSync } from "node:child_process"
20
+ import {
21
+ TEAM_AGENTS,
22
+ PACKAGE_NAME,
23
+ resolveConfigDir,
24
+ findConfigFile,
25
+ stripJsonComments,
26
+ readModelFromFile,
27
+ readRawModelMap,
28
+ modelMapPath,
29
+ } from "./team.mjs"
30
+
31
+ /** The stable, ordered set of check names reported by runDoctor(). */
32
+ export const CHECK_NAMES = [
33
+ "config_file",
34
+ "plugin_registration",
35
+ "agents_installed",
36
+ "model_sync",
37
+ "git_installed",
38
+ "git_repository",
39
+ "worktrees_dir",
40
+ ]
41
+
42
+ // One advisory command per check. Only the first non-pass check is reported, so
43
+ // the user always gets a single next action rather than a wall of suggestions.
44
+ const NEXT_STEP_BY_CHECK = {
45
+ config_file: `opencode plugin add ${PACKAGE_NAME}`,
46
+ plugin_registration: `opencode plugin add ${PACKAGE_NAME}`,
47
+ agents_installed: "opencode-teamwork init",
48
+ model_sync: "opencode-teamwork models",
49
+ git_installed: "Install git (https://git-scm.com/downloads)",
50
+ git_repository: "git init",
51
+ worktrees_dir: "Set TEAMWORK_WORKTREES_DIR to a writable directory",
52
+ }
53
+
54
+ /**
55
+ * Advice for the first non-pass check; purely additive to the seven-check
56
+ * report. Returns a single-element array with one command, or [] when every
57
+ * check passed. Later failures are deliberately ignored once the first is
58
+ * matched, so the user fixes the environment one step at a time.
59
+ *
60
+ * @param {Array<{ name: string, status: "pass"|"warn"|"fail" }>} checks
61
+ * @returns {string[]}
62
+ */
63
+ export function nextSteps(checks) {
64
+ if (!Array.isArray(checks)) return []
65
+ const first = checks.find((check) => check && check.status !== "pass")
66
+ if (!first) return []
67
+ const step = NEXT_STEP_BY_CHECK[first.name]
68
+ return step ? [step] : []
69
+ }
70
+
71
+ // --- path safety ------------------------------------------------------------
72
+ //
73
+ // Every file we touch must stay inside the resolved config dir. Paths are
74
+ // always built with resolve()/join() from a trusted root and then verified with
75
+ // a relative() containment test so `..` traversal cannot escape. When the
76
+ // target exists we additionally compare realpath()s to reject symlink escapes.
77
+
78
+ /** True when `target` is `root` itself or nested inside it (both absolute). */
79
+ function isWithin(root, target) {
80
+ const rel = relative(root, target)
81
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))
82
+ }
83
+
84
+ /** Resolve `segments` under `root`, returning undefined if it escapes root. */
85
+ function containedJoin(root, ...segments) {
86
+ const base = resolve(root)
87
+ const target = resolve(base, ...segments)
88
+ return isWithin(base, target) ? target : undefined
89
+ }
90
+
91
+ /**
92
+ * existsSync for a path that must remain inside `root`. When the path exists we
93
+ * resolve symlinks and re-check containment so a symlinked agent file cannot
94
+ * point outside the config dir.
95
+ */
96
+ function safeExists(file, root) {
97
+ if (!file) return false
98
+ try {
99
+ const realFile = realpathSync(file)
100
+ const realRoot = realpathSync(root)
101
+ return isWithin(realRoot, realFile) && existsSync(realFile)
102
+ } catch {
103
+ // Missing path (or missing root): fall back to a plain existence check.
104
+ return existsSync(file)
105
+ }
106
+ }
107
+
108
+ // --- individual checks ------------------------------------------------------
109
+
110
+ function checkConfigFile({ configDir }) {
111
+ const file = findConfigFile(configDir)
112
+ if (file) return { status: "pass", message: `Found ${file}` }
113
+ return {
114
+ status: "warn",
115
+ message: `No opencode.json(c) in ${configDir} — it would be created on next install`,
116
+ }
117
+ }
118
+
119
+ function isTeamworkEntry(entry) {
120
+ const value = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry.package : undefined
121
+ return typeof value === "string" && value.includes("opencode-teamwork")
122
+ }
123
+
124
+ function checkPluginRegistration({ configDir }) {
125
+ const file = findConfigFile(configDir)
126
+ if (!file) {
127
+ return { status: "warn", message: `No config file in ${configDir} — plugin not registered yet` }
128
+ }
129
+
130
+ let raw
131
+ try {
132
+ raw = readFileSync(file, "utf8")
133
+ } catch (error) {
134
+ return { status: "warn", message: `Could not read ${file}: ${error?.message || error}` }
135
+ }
136
+
137
+ let data
138
+ try {
139
+ data = JSON.parse(stripJsonComments(raw))
140
+ } catch (error) {
141
+ return { status: "warn", message: `Could not parse ${file}: ${error?.message || error}` }
142
+ }
143
+
144
+ const plugins = Array.isArray(data?.plugins) ? data.plugins : []
145
+ const entry = plugins.find(isTeamworkEntry)
146
+ if (entry !== undefined) {
147
+ return { status: "pass", message: `Plugin registered in ${file}` }
148
+ }
149
+ return { status: "warn", message: `${file} does not register an opencode-teamwork plugin` }
150
+ }
151
+
152
+ function checkAgentsInstalled({ configDir }) {
153
+ const targetDir = containedJoin(configDir, "agents", "team")
154
+ const missing = []
155
+ for (const agent of TEAM_AGENTS) {
156
+ const file = targetDir ? containedJoin(targetDir, agent.file) : undefined
157
+ if (!safeExists(file, configDir)) missing.push(agent.id)
158
+ }
159
+
160
+ if (!missing.length) {
161
+ return { status: "pass", message: `All ${TEAM_AGENTS.length} team agents installed in ${targetDir}` }
162
+ }
163
+ return {
164
+ status: "fail",
165
+ message: `Missing ${missing.length}/${TEAM_AGENTS.length} agents: ${missing.join(", ")}`,
166
+ }
167
+ }
168
+
169
+ function checkModelSync({ configDir }) {
170
+ const raw = readRawModelMap(configDir)
171
+ const entries = Object.entries(raw).filter(([, value]) => value)
172
+ if (!existsSync(modelMapPath(configDir)) || !entries.length) {
173
+ return { status: "pass", message: "No teamwork.json overrides to compare" }
174
+ }
175
+
176
+ const targetDir = containedJoin(configDir, "agents", "team")
177
+ const disagreeing = []
178
+ for (const [id, expected] of entries) {
179
+ const agent = TEAM_AGENTS.find((a) => a.id === id)
180
+ if (!agent || !targetDir) continue
181
+ const file = containedJoin(targetDir, agent.file)
182
+ if (!safeExists(file, configDir)) continue
183
+ const actual = readModelFromFile(file)
184
+ if (actual !== expected) {
185
+ disagreeing.push(`${id} (file: ${actual || "none"}, teamwork.json: ${expected})`)
186
+ }
187
+ }
188
+
189
+ if (!disagreeing.length) {
190
+ return { status: "pass", message: `teamwork.json matches installed agents (${entries.length} entries)` }
191
+ }
192
+ return {
193
+ status: "warn",
194
+ message: `Model mismatch for ${disagreeing.length} agent(s): ${disagreeing.join("; ")}`,
195
+ }
196
+ }
197
+
198
+ // SECURITY: the only shell probe allowed here. Fixed argv, no shell, no
199
+ // interpolation, no user input — `git --version` and nothing else.
200
+ function checkGitInstalled() {
201
+ try {
202
+ execFileSync("git", ["--version"], { stdio: "ignore" })
203
+ return { status: "pass", message: "git is available on PATH" }
204
+ } catch {
205
+ return { status: "fail", message: "git was not found on PATH" }
206
+ }
207
+ }
208
+
209
+ // SECURITY: same discipline as checkGitInstalled — execFileSync + fixed argv.
210
+ function checkGitRepository({ cwd }) {
211
+ try {
212
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd, stdio: "ignore" })
213
+ return { status: "pass", message: `${cwd} is inside a git work tree` }
214
+ } catch {
215
+ return { status: "warn", message: `${cwd} is not inside a git work tree` }
216
+ }
217
+ }
218
+
219
+ function checkWorktreesDir({ cwd }) {
220
+ const configured = process.env.TEAMWORK_WORKTREES_DIR
221
+ let dir
222
+ try {
223
+ dir = configured ? resolve(configured) : resolve(cwd, "..", ".teamwork-worktrees")
224
+ } catch (error) {
225
+ return { status: "warn", message: `Could not resolve worktrees directory: ${error?.message || error}` }
226
+ }
227
+ if (!dir) return { status: "warn", message: "Could not resolve worktrees directory" }
228
+
229
+ const exists = existsSync(dir)
230
+ const source = configured ? " (from TEAMWORK_WORKTREES_DIR)" : ""
231
+ return {
232
+ status: "pass",
233
+ message: `${dir}${source} — ${exists ? "exists" : "will be created on first run"}`,
234
+ }
235
+ }
236
+
237
+ const PROBES = {
238
+ config_file: checkConfigFile,
239
+ plugin_registration: checkPluginRegistration,
240
+ agents_installed: checkAgentsInstalled,
241
+ model_sync: checkModelSync,
242
+ git_installed: checkGitInstalled,
243
+ git_repository: checkGitRepository,
244
+ worktrees_dir: checkWorktreesDir,
245
+ }
246
+
247
+ /**
248
+ * Run every diagnostic check and return the stable report object.
249
+ *
250
+ * @param {{ configDir?: string, cwd?: string }} [options]
251
+ * @returns {{ ok: boolean, checks: Array<{ name: string, status: "pass"|"warn"|"fail", message: string }> }}
252
+ */
253
+ export function runDoctor({ configDir, cwd } = {}) {
254
+ const resolvedConfigDir = resolve(configDir || resolveConfigDir())
255
+ const resolvedCwd = resolve(cwd || process.cwd())
256
+ const context = { configDir: resolvedConfigDir, cwd: resolvedCwd }
257
+
258
+ const checks = CHECK_NAMES.map((name) => {
259
+ try {
260
+ const result = PROBES[name](context)
261
+ return { name, status: result.status, message: result.message }
262
+ } catch (error) {
263
+ // A probe must never take down the whole runner.
264
+ return { name, status: "warn", message: `probe threw: ${error?.message || error}` }
265
+ }
266
+ })
267
+
268
+ return { ok: checks.every((check) => check.status !== "fail"), checks }
269
+ }
270
+
271
+ /** Render a report as a plain-text table suitable for the CLI. */
272
+ export function formatDoctorReport(report) {
273
+ const lines = []
274
+ for (const check of report.checks) {
275
+ const tag = check.status === "pass" ? "PASS" : check.status === "warn" ? "WARN" : "FAIL"
276
+ lines.push(`[${tag}] ${check.name.padEnd(20)} ${check.message}`)
277
+ }
278
+ lines.push(report.ok ? "\nAll checks passed." : "\nOne or more checks failed.")
279
+ return lines.join("\n")
280
+ }