development-companion 1.6.0 → 1.8.0
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.
- package/CHANGELOG.md +82 -0
- package/README.md +133 -57
- package/RELEASE.md +49 -32
- package/adapters/README.md +15 -4
- package/adapters/opencode/README.md +116 -24
- package/adapters/opencode/plugin/devcomp/gates.mjs +688 -0
- package/adapters/opencode/plugin/devcomp/index.ts +603 -0
- package/core/guidelines/coordination.md +138 -4
- package/core/process.md +141 -7
- package/core/quality-gates.md +41 -1
- package/core/roles/README.md +4 -1
- package/core/roles/backend-engineer.md +10 -0
- package/core/roles/coordinator.md +171 -0
- package/core/roles/desktop-linux-engineer.md +10 -0
- package/core/roles/desktop-macos-engineer.md +10 -0
- package/core/roles/desktop-windows-engineer.md +10 -0
- package/core/roles/frontend-engineer.md +10 -0
- package/core/roles/mobile-engineer.md +10 -0
- package/core/roles/multiplatform-engineer.md +10 -0
- package/core/roles/sre-engineer.md +10 -0
- package/core/workflow.md +62 -9
- package/package.json +1 -1
- package/skills/delivery-orchestration/SKILL.md +58 -3
- package/skills/development-workflow/SKILL.md +44 -8
- package/skills/test-strategy/SKILL.md +12 -0
- package/src/cli.mjs +211 -19
- package/src/content.mjs +16 -0
- package/src/install.mjs +397 -44
- package/templates/artifacts/01-operational-brief.md +14 -1
- package/templates/artifacts/11-feature-plan.md +83 -0
- package/templates/artifacts/README.md +8 -5
- package/templates/rules/AGENTS.block.md +117 -8
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
import { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
3
|
+
import { homedir } from "node:os"
|
|
4
|
+
import { dirname, join, resolve } from "node:path"
|
|
5
|
+
import { fileURLToPath } from "node:url"
|
|
6
|
+
import {
|
|
7
|
+
approvalStateChange,
|
|
8
|
+
extractToolPaths,
|
|
9
|
+
inScope,
|
|
10
|
+
isDestructiveCommand,
|
|
11
|
+
isGlobalPluginPath,
|
|
12
|
+
isScopeSubset,
|
|
13
|
+
parseDelegation,
|
|
14
|
+
planContentHash,
|
|
15
|
+
planRevisionDecision,
|
|
16
|
+
planScopeFor,
|
|
17
|
+
readPlanApproval,
|
|
18
|
+
resolvePlan,
|
|
19
|
+
selectPendingScope,
|
|
20
|
+
validatePlanContent
|
|
21
|
+
} from "./gates.mjs"
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Development Companion runtime adapter for OpenCode.
|
|
25
|
+
*
|
|
26
|
+
* Why this exists: AGENTS.md and opencode.json instructions are discovery-based. Sessions
|
|
27
|
+
* started inside a child repository do not resolve the meta-repo's relative instruction
|
|
28
|
+
* paths, and a configured install can pass doctor while the canonical process is absent from
|
|
29
|
+
* the model context. This plugin injects the canonical files on every primary request and
|
|
30
|
+
* enforces the delivery contract:
|
|
31
|
+
*
|
|
32
|
+
* - an implementation delegation needs `Plan:` and `Scope:`, an existing plan inside the
|
|
33
|
+
* workspace, an affirmative `Aprobado:`, and a `Scope` that does not exceed the plan;
|
|
34
|
+
* - `edit`, `write` and `patch` stay inside the approved `Scope` of the child session;
|
|
35
|
+
* - a user approval message marks the session, so approved delegations do not prompt per
|
|
36
|
+
* subagent; observations revoke the mark and the native `subagent: ask` is the fallback;
|
|
37
|
+
* - known destructive shell patterns force `ask`, even after an "always" approval.
|
|
38
|
+
*
|
|
39
|
+
* It is intentionally dependency-free and project-scoped: it searches upward for the nearest
|
|
40
|
+
* .companion/config.json and does nothing when the workspace is not a devcomp project.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
const MARKER = "[devcomp-runtime]"
|
|
44
|
+
|
|
45
|
+
const CANONICAL = [
|
|
46
|
+
{ path: "core/process.md", heading: "# Development Process" },
|
|
47
|
+
{ path: "core/principles.md", heading: "# Engineering Principles" },
|
|
48
|
+
{ path: "core/quality-gates.md", heading: "# Quality Gates" },
|
|
49
|
+
{ path: "core/workflow.md", heading: "# Development Workflow" },
|
|
50
|
+
{ path: "core/guidelines/coordination.md", heading: "# Coordinated Delivery" }
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
const IMPLEMENTATION_AGENTS = new Set([
|
|
54
|
+
"mobile-engineer",
|
|
55
|
+
"backend-engineer",
|
|
56
|
+
"frontend-engineer",
|
|
57
|
+
"multiplatform-engineer",
|
|
58
|
+
"desktop-windows-engineer",
|
|
59
|
+
"desktop-macos-engineer",
|
|
60
|
+
"desktop-linux-engineer",
|
|
61
|
+
"sre-engineer",
|
|
62
|
+
"general"
|
|
63
|
+
])
|
|
64
|
+
|
|
65
|
+
// Read-only roles write their own reports under the planning directory. Their binding is the
|
|
66
|
+
// path policy; the delegation scope does not apply to report writes.
|
|
67
|
+
const READ_ONLY_AGENTS = new Set([
|
|
68
|
+
"team-lead",
|
|
69
|
+
"architect",
|
|
70
|
+
"cybersecurity-engineer",
|
|
71
|
+
"qa-engineer"
|
|
72
|
+
])
|
|
73
|
+
|
|
74
|
+
// Root agents keep their own permissions when session verification is unavailable.
|
|
75
|
+
const ROOT_AGENTS = new Set(["coordinator", "build"])
|
|
76
|
+
|
|
77
|
+
// Tools that write files. `patch` and `apply_patch` can touch several paths at once.
|
|
78
|
+
const EDIT_TOOLS = new Set(["edit", "write", "patch", "apply_patch", "multiedit"])
|
|
79
|
+
|
|
80
|
+
const PENDING_TTL_MS = 30 * 60 * 1000
|
|
81
|
+
|
|
82
|
+
type Manifest = {
|
|
83
|
+
packageVersion?: string
|
|
84
|
+
contentVersion?: string
|
|
85
|
+
docs?: string
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
type Companion = {
|
|
89
|
+
root: string
|
|
90
|
+
manifest: Manifest
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
type ScopeRecord = {
|
|
94
|
+
agent: string
|
|
95
|
+
parentSessionID: string
|
|
96
|
+
childSessionID?: string
|
|
97
|
+
callID?: string
|
|
98
|
+
planPath: string
|
|
99
|
+
scope: string[]
|
|
100
|
+
step: string | null
|
|
101
|
+
createdAt: number
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
type ScopeResolution =
|
|
105
|
+
| { status: "ok"; record: ScopeRecord }
|
|
106
|
+
| { status: "none" | "ambiguous" | "unverified" | "root" }
|
|
107
|
+
|
|
108
|
+
// Root session -> the user's approval words. In memory only: a session mark must not outlive
|
|
109
|
+
// the session or be written to a file by the Coordinator.
|
|
110
|
+
const approvals = new Map<string, string>()
|
|
111
|
+
|
|
112
|
+
// Root session -> the plan content the user's approval is bound to. A different plan or a
|
|
113
|
+
// changed plan revokes the approval until the user approves again.
|
|
114
|
+
const sessionPlans = new Map<string, { path: string; hash: string }>()
|
|
115
|
+
|
|
116
|
+
// Delegations waiting for their child session, and the scope claimed by each child.
|
|
117
|
+
const pendingScopes: ScopeRecord[] = []
|
|
118
|
+
const sessionScopes = new Map<string, ScopeRecord>()
|
|
119
|
+
|
|
120
|
+
function findCompanion(start: string): Companion | null {
|
|
121
|
+
let dir = resolve(start)
|
|
122
|
+
while (true) {
|
|
123
|
+
const manifestPath = join(dir, ".companion", "config.json")
|
|
124
|
+
if (existsSync(manifestPath)) {
|
|
125
|
+
try {
|
|
126
|
+
return { root: dir, manifest: JSON.parse(readFileSync(manifestPath, "utf8")) as Manifest }
|
|
127
|
+
} catch {
|
|
128
|
+
return null
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const parent = dirname(dir)
|
|
132
|
+
if (parent === dir) return null
|
|
133
|
+
dir = parent
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function systemText(event: unknown): string {
|
|
138
|
+
const parts = (event as { system?: Array<{ text?: string }> })?.system
|
|
139
|
+
if (!Array.isArray(parts)) return ""
|
|
140
|
+
return parts.map((part) => (typeof part?.text === "string" ? part.text : "")).join("\n")
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function banner(companion: Companion): string {
|
|
144
|
+
const version = companion.manifest.contentVersion ?? companion.manifest.packageVersion ?? "unknown"
|
|
145
|
+
const planning = companion.manifest.docs === "tracked" ? "docs/companion" : ".companion/local"
|
|
146
|
+
return `${MARKER} Development Companion ${version} loaded at runtime.
|
|
147
|
+
Project root: ${companion.root}
|
|
148
|
+
Planning: ${planning}
|
|
149
|
+
Gate: the Coordinator cannot edit product code. Implementation delegation needs \`Plan:\` and \`Scope:\` inside an approved plan; edits stay inside \`Scope\`; known destructive patterns ask the user, and shell writes remain a residual risk.
|
|
150
|
+
If a relative \`.companion/core/...\` path does not exist in this workspace (for example, a child repository), use the content injected here; do not treat the missing path as a blocker.`
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function canonicalBlocks(companion: Companion, current: string): string[] {
|
|
154
|
+
const blocks: string[] = []
|
|
155
|
+
for (const file of CANONICAL) {
|
|
156
|
+
if (current.includes(file.heading)) continue
|
|
157
|
+
const path = join(companion.root, ".companion", file.path)
|
|
158
|
+
if (!existsSync(path)) continue
|
|
159
|
+
blocks.push(`--- ${file.path} ---\n${readFileSync(path, "utf8").trim()}`)
|
|
160
|
+
}
|
|
161
|
+
return blocks
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function globalPluginRoots(): string[] {
|
|
165
|
+
const roots = []
|
|
166
|
+
const home = homedir()
|
|
167
|
+
if (home) roots.push(join(home, ".config", "opencode", "plugins"))
|
|
168
|
+
if (process.env.XDG_CONFIG_HOME) roots.push(join(process.env.XDG_CONFIG_HOME, "opencode", "plugins"))
|
|
169
|
+
return roots
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function implementationTarget(input: Record<string, unknown> | undefined): string {
|
|
173
|
+
const raw = input?.agent ?? input?.subagent_type ?? input?.subagent ?? input?.name
|
|
174
|
+
return typeof raw === "string" ? raw : ""
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function delegationText(input: Record<string, unknown> | undefined): string {
|
|
178
|
+
if (!input) return ""
|
|
179
|
+
if (typeof input.prompt === "string") return input.prompt
|
|
180
|
+
for (const key of ["message", "task", "description", "instructions"]) {
|
|
181
|
+
if (typeof input[key] === "string") return input[key] as string
|
|
182
|
+
}
|
|
183
|
+
return ""
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function sessionInfo(ctx: any, sessionID: string): Promise<any> {
|
|
187
|
+
try {
|
|
188
|
+
return await ctx.session.get({ sessionID })
|
|
189
|
+
} catch {
|
|
190
|
+
return null
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* The subagent tool returns its child session immediately. Mapping that ID to the delegation
|
|
196
|
+
* avoids guessing between parallel siblings of the same agent.
|
|
197
|
+
*/
|
|
198
|
+
function subagentSessionID(result: any): string | null {
|
|
199
|
+
if (!result || typeof result !== "object") {
|
|
200
|
+
const match = typeof result === "string" ? result.match(/\bses_[A-Za-z0-9]+\b/) : null
|
|
201
|
+
return match ? match[0] : null
|
|
202
|
+
}
|
|
203
|
+
for (const candidate of [result?.metadata?.sessionID, result?.output?.sessionID, result?.sessionID]) {
|
|
204
|
+
if (typeof candidate === "string" && candidate.startsWith("ses_")) return candidate
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
const match = JSON.stringify(result).match(/\bses_[A-Za-z0-9]+\b/)
|
|
208
|
+
return match ? match[0] : null
|
|
209
|
+
} catch {
|
|
210
|
+
return null
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function prunePending(now = Date.now()): void {
|
|
215
|
+
for (let index = pendingScopes.length - 1; index >= 0; index -= 1) {
|
|
216
|
+
if (now - pendingScopes[index].createdAt > PENDING_TTL_MS) pendingScopes.splice(index, 1)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* A child session claims the delegation mapped to its session ID. If the result did not expose
|
|
222
|
+
* the ID, exactly one matching delegation may be claimed; more than one is ambiguous and denies.
|
|
223
|
+
*/
|
|
224
|
+
async function scopeForSession(ctx: any, sessionID: string, agent?: string): Promise<ScopeResolution> {
|
|
225
|
+
const existing = sessionScopes.get(sessionID)
|
|
226
|
+
if (existing) return { status: "ok", record: existing }
|
|
227
|
+
|
|
228
|
+
const mappedIndex = pendingScopes.findIndex((record) =>
|
|
229
|
+
record.childSessionID === sessionID && Date.now() - record.createdAt <= PENDING_TTL_MS)
|
|
230
|
+
if (mappedIndex !== -1) {
|
|
231
|
+
const [record] = pendingScopes.splice(mappedIndex, 1)
|
|
232
|
+
sessionScopes.set(sessionID, record)
|
|
233
|
+
return { status: "ok", record }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const info = await sessionInfo(ctx, sessionID)
|
|
237
|
+
if (!info) return { status: "unverified" }
|
|
238
|
+
if (!info.parentID) return { status: "root" }
|
|
239
|
+
|
|
240
|
+
const role = typeof info.agent === "string" ? info.agent : agent ?? ""
|
|
241
|
+
const now = Date.now()
|
|
242
|
+
prunePending(now)
|
|
243
|
+
const selection = selectPendingScope(pendingScopes, {
|
|
244
|
+
sessionID,
|
|
245
|
+
parentID: info.parentID,
|
|
246
|
+
role,
|
|
247
|
+
now,
|
|
248
|
+
ttl: PENDING_TTL_MS
|
|
249
|
+
})
|
|
250
|
+
if (selection.status === "mapped" || selection.status === "single") {
|
|
251
|
+
const [record] = pendingScopes.splice(selection.index, 1)
|
|
252
|
+
sessionScopes.set(sessionID, record)
|
|
253
|
+
return { status: "ok", record }
|
|
254
|
+
}
|
|
255
|
+
if (selection.status === "ambiguous") return { status: "ambiguous" }
|
|
256
|
+
return { status: "none" }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function scopeFailure(status: Exclude<ScopeResolution["status"], "ok" | "root">): string {
|
|
260
|
+
if (status === "ambiguous") {
|
|
261
|
+
return "Development Companion scope gate: more than one pending delegation matches this " +
|
|
262
|
+
"subagent session. Start one writer at a time, or start a new child for each scope."
|
|
263
|
+
}
|
|
264
|
+
if (status === "unverified") {
|
|
265
|
+
return "Development Companion scope gate: the subagent session could not be verified. " +
|
|
266
|
+
"Retry the delegation; edits outside an approved Scope are blocked."
|
|
267
|
+
}
|
|
268
|
+
return "Development Companion scope gate: no approved `Scope:` is recorded for this " +
|
|
269
|
+
"subagent session. Launch it through the Coordinator with `Plan:` and `Scope:`."
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* M4: a read-only child may write its report paths, but must not rewrite the plan that the
|
|
274
|
+
* root session approved. The binding is keyed by the root session, so look up the child's
|
|
275
|
+
* parent.
|
|
276
|
+
*/
|
|
277
|
+
async function isBoundPlanWrite(ctx: any, companion: Companion, info: any, paths: string[]): Promise<boolean> {
|
|
278
|
+
if (!info?.parentID) return false
|
|
279
|
+
const binding = sessionPlans.get(info.parentID)
|
|
280
|
+
if (!binding) return false
|
|
281
|
+
const workspaceRoot = companion.root
|
|
282
|
+
const cwd = ctx.location?.directory ?? workspaceRoot
|
|
283
|
+
return paths.some((path) => inScope(path, [binding.path], { workspaceRoot, cwd }))
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function enforcePlanGate(ctx: any, companion: Companion, event: any): Promise<void> {
|
|
287
|
+
const input = event?.input ?? {}
|
|
288
|
+
const target = implementationTarget(input)
|
|
289
|
+
if (!IMPLEMENTATION_AGENTS.has(target)) return
|
|
290
|
+
|
|
291
|
+
const delegation = parseDelegation(delegationText(input))
|
|
292
|
+
if (delegation.missing.length > 0) {
|
|
293
|
+
throw new Error(
|
|
294
|
+
`Development Companion plan gate: implementation delegation to ${target} requires ` +
|
|
295
|
+
`\`Plan: <path>\` and \`Scope: <globs>\`. Missing: ${delegation.missing.join(", ")}. ` +
|
|
296
|
+
"Present the approved plan and delegate again."
|
|
297
|
+
)
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const plan = resolvePlan({
|
|
301
|
+
planPath: delegation.planPath,
|
|
302
|
+
workspaceRoot: companion.root,
|
|
303
|
+
cwd: ctx.location?.directory ?? companion.root
|
|
304
|
+
})
|
|
305
|
+
if (!plan.ok) {
|
|
306
|
+
throw new Error(`Development Companion plan gate: ${plan.reason}.`)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
let content: string
|
|
310
|
+
try {
|
|
311
|
+
content = readFileSync(plan.path, "utf8")
|
|
312
|
+
} catch {
|
|
313
|
+
throw new Error("Development Companion plan gate: the plan file cannot be read.")
|
|
314
|
+
}
|
|
315
|
+
if (!readPlanApproval(content).approved) {
|
|
316
|
+
throw new Error(
|
|
317
|
+
"Development Companion plan gate: the plan's `Aprobado:` is missing or not affirmative. " +
|
|
318
|
+
"Present the plan, get the user's approval, record it in the plan, and delegate again."
|
|
319
|
+
)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const validation = validatePlanContent(content)
|
|
323
|
+
if (!validation.ok) {
|
|
324
|
+
throw new Error(`Development Companion plan gate: ${validation.reason}.`)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const sessionID = typeof event?.sessionID === "string" ? event.sessionID : ""
|
|
328
|
+
const nextPlan = { path: plan.relative, hash: planContentHash(content) }
|
|
329
|
+
const revision = planRevisionDecision(
|
|
330
|
+
sessionID ? sessionPlans.get(sessionID) : undefined,
|
|
331
|
+
nextPlan,
|
|
332
|
+
sessionID ? approvals.has(sessionID) : false
|
|
333
|
+
)
|
|
334
|
+
if (revision.action === "changed") {
|
|
335
|
+
approvals.delete(sessionID)
|
|
336
|
+
sessionPlans.delete(sessionID)
|
|
337
|
+
throw new Error(
|
|
338
|
+
"Development Companion plan gate: the approved plan changed after approval. " +
|
|
339
|
+
"Ask the user for a new approval before delegating again."
|
|
340
|
+
)
|
|
341
|
+
}
|
|
342
|
+
if (revision.action === "different-plan") {
|
|
343
|
+
approvals.delete(sessionID)
|
|
344
|
+
sessionPlans.delete(sessionID)
|
|
345
|
+
throw new Error(
|
|
346
|
+
`Development Companion plan gate: this session approved a different plan ` +
|
|
347
|
+
`(${revision.previousPath}). Ask the user to approve ${plan.relative} before delegating.`
|
|
348
|
+
)
|
|
349
|
+
}
|
|
350
|
+
if (revision.action === "bind" && sessionID) {
|
|
351
|
+
sessionPlans.set(sessionID, nextPlan)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const planScope = planScopeFor(content, { step: delegation.step, agent: target })
|
|
355
|
+
if (planScope.error) {
|
|
356
|
+
throw new Error(`Development Companion plan gate: ${planScope.error}.`)
|
|
357
|
+
}
|
|
358
|
+
if (planScope.tokens.length === 0) {
|
|
359
|
+
throw new Error("Development Companion plan gate: the plan declares no `Scope:`.")
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const declared = validation.scope.declared
|
|
363
|
+
for (const token of planScope.tokens) {
|
|
364
|
+
if (!declared.some((allowed) => isScopeSubset(token, allowed))) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
`Development Companion plan gate: the plan step Scope (${planScope.tokens.join(", ")}) ` +
|
|
367
|
+
`exceeds the plan's own Scope (${declared.join(", ")}).`
|
|
368
|
+
)
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const outside = delegation.scope.filter((token) =>
|
|
372
|
+
!planScope.tokens.some((allowed) => isScopeSubset(token, allowed)))
|
|
373
|
+
if (outside.length > 0) {
|
|
374
|
+
throw new Error(
|
|
375
|
+
`Development Companion plan gate: delegation Scope ${outside.join(", ")} exceeds the ` +
|
|
376
|
+
`approved Scope (${planScope.tokens.join(", ")}). Narrow it to the plan or revise the plan.`
|
|
377
|
+
)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const now = Date.now()
|
|
381
|
+
prunePending(now)
|
|
382
|
+
pendingScopes.push({
|
|
383
|
+
agent: target,
|
|
384
|
+
parentSessionID: event?.sessionID ?? "",
|
|
385
|
+
callID: typeof event?.id === "string" ? event.id : undefined,
|
|
386
|
+
planPath: plan.relative,
|
|
387
|
+
scope: delegation.scope,
|
|
388
|
+
step: delegation.step,
|
|
389
|
+
createdAt: now
|
|
390
|
+
})
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function enforceScopeGate(ctx: any, companion: Companion, event: any, tool: string): Promise<void> {
|
|
394
|
+
const info = await sessionInfo(ctx, event?.sessionID)
|
|
395
|
+
const agent = typeof info?.agent === "string" ? info.agent : String(event?.agent ?? "")
|
|
396
|
+
|
|
397
|
+
// MF1/M4: read-only children own their report paths; they may not rewrite the bound plan.
|
|
398
|
+
if (READ_ONLY_AGENTS.has(agent)) {
|
|
399
|
+
const paths = extractToolPaths(tool, event?.input)
|
|
400
|
+
if (await isBoundPlanWrite(ctx, companion, info, paths)) {
|
|
401
|
+
throw new Error(
|
|
402
|
+
"Development Companion scope gate: a read-only role cannot modify the approved plan. " +
|
|
403
|
+
"Write a report under the planning directory instead."
|
|
404
|
+
)
|
|
405
|
+
}
|
|
406
|
+
return
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (!info) {
|
|
410
|
+
if (ROOT_AGENTS.has(agent)) return
|
|
411
|
+
throw new Error(scopeFailure("unverified"))
|
|
412
|
+
}
|
|
413
|
+
if (!info.parentID) return // direct sessions keep their agent's own permissions
|
|
414
|
+
|
|
415
|
+
const resolution = await scopeForSession(ctx, event.sessionID, agent)
|
|
416
|
+
if (resolution.status === "root") return
|
|
417
|
+
if (resolution.status !== "ok") throw new Error(scopeFailure(resolution.status))
|
|
418
|
+
const record = resolution.record
|
|
419
|
+
|
|
420
|
+
const paths = extractToolPaths(tool, event?.input)
|
|
421
|
+
if (paths.length === 0) {
|
|
422
|
+
throw new Error(
|
|
423
|
+
"Development Companion scope gate: the target path could not be determined. " +
|
|
424
|
+
"Use an edit/write input with `path`, a patch with file sections, or a multiedit with `edits`."
|
|
425
|
+
)
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const workspaceRoot = companion.root
|
|
429
|
+
const cwd = ctx.location?.directory ?? workspaceRoot
|
|
430
|
+
const outside = paths.filter((path) => !inScope(path, record.scope, { workspaceRoot, cwd }))
|
|
431
|
+
if (outside.length > 0) {
|
|
432
|
+
throw new Error(
|
|
433
|
+
`Development Companion scope gate: ${outside.join(", ")} is outside the approved Scope ` +
|
|
434
|
+
`(${record.scope.join(", ")}). Report it to the Coordinator instead of editing it.`
|
|
435
|
+
)
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async function enforceEditPermission(ctx: any, companion: Companion, event: any): Promise<void> {
|
|
440
|
+
const resources = Array.isArray(event?.resources) ? event.resources : [event?.resources]
|
|
441
|
+
const paths = resources.filter((resource: unknown) => typeof resource === "string") as string[]
|
|
442
|
+
if (paths.length === 0) return
|
|
443
|
+
|
|
444
|
+
const info = await sessionInfo(ctx, event?.sessionID)
|
|
445
|
+
const agent = typeof info?.agent === "string" ? info.agent : String(event?.agent ?? "")
|
|
446
|
+
|
|
447
|
+
// MF1: QA, architect, security and team-lead write under their binding's planning paths.
|
|
448
|
+
if (READ_ONLY_AGENTS.has(agent)) return
|
|
449
|
+
|
|
450
|
+
if (!info) {
|
|
451
|
+
if (ROOT_AGENTS.has(agent)) return
|
|
452
|
+
event.effect = "deny"
|
|
453
|
+
event.message = scopeFailure("unverified")
|
|
454
|
+
return
|
|
455
|
+
}
|
|
456
|
+
if (!info.parentID) return // coordinator, build and direct sessions are not scoped here
|
|
457
|
+
|
|
458
|
+
const resolution = await scopeForSession(ctx, event.sessionID, agent)
|
|
459
|
+
if (resolution.status === "root") return
|
|
460
|
+
if (resolution.status !== "ok") {
|
|
461
|
+
event.effect = "deny"
|
|
462
|
+
event.message = scopeFailure(resolution.status)
|
|
463
|
+
return
|
|
464
|
+
}
|
|
465
|
+
const record = resolution.record
|
|
466
|
+
|
|
467
|
+
const workspaceRoot = companion.root
|
|
468
|
+
const cwd = ctx.location?.directory ?? workspaceRoot
|
|
469
|
+
const outside = paths.filter((path) => !inScope(path, record.scope, { workspaceRoot, cwd }))
|
|
470
|
+
if (outside.length > 0) {
|
|
471
|
+
event.effect = "deny"
|
|
472
|
+
event.message =
|
|
473
|
+
`Development Companion scope gate: ${outside.join(", ")} is outside the approved Scope. ` +
|
|
474
|
+
"Report it to the Coordinator instead of editing it."
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export default Plugin.define({
|
|
479
|
+
id: "devcomp-runtime",
|
|
480
|
+
async setup(ctx) {
|
|
481
|
+
const companion = findCompanion(ctx.location.directory)
|
|
482
|
+
if (!companion) return
|
|
483
|
+
|
|
484
|
+
// H-new: only the global copy may no-op. The local copy must always register its gates,
|
|
485
|
+
// even when the project root is a symlink or the path case differs.
|
|
486
|
+
const localPlugin = join(companion.root, ".opencode", "plugins", "devcomp", "index.ts")
|
|
487
|
+
let selfPath = ""
|
|
488
|
+
try {
|
|
489
|
+
selfPath = fileURLToPath(import.meta.url)
|
|
490
|
+
} catch {
|
|
491
|
+
selfPath = ""
|
|
492
|
+
}
|
|
493
|
+
if (existsSync(localPlugin) && isGlobalPluginPath(selfPath, globalPluginRoots())) return
|
|
494
|
+
|
|
495
|
+
await ctx.session.hook("context", (event: any) => {
|
|
496
|
+
// devcomp:context-injection
|
|
497
|
+
const current = systemText(event)
|
|
498
|
+
const blocks = canonicalBlocks(companion, current)
|
|
499
|
+
const header = current.includes(MARKER) ? "" : banner(companion)
|
|
500
|
+
if (!header && blocks.length === 0) return
|
|
501
|
+
|
|
502
|
+
const text = [header, ...blocks].filter(Boolean).join("\n\n")
|
|
503
|
+
event.system.push({ type: "text", text })
|
|
504
|
+
})
|
|
505
|
+
|
|
506
|
+
await ctx.session.hook("prompt", async (event: any) => {
|
|
507
|
+
// devcomp:approval
|
|
508
|
+
const text = event?.prompt?.text
|
|
509
|
+
if (typeof text !== "string" || !text.trim()) return
|
|
510
|
+
if (!event?.sessionID) return
|
|
511
|
+
const info = await sessionInfo(ctx, event.sessionID)
|
|
512
|
+
if (info?.parentID) return // only the root conversation can approve or revoke
|
|
513
|
+
const change = approvalStateChange(text)
|
|
514
|
+
if (change === "set") {
|
|
515
|
+
approvals.set(event.sessionID, text.trim().slice(0, 200))
|
|
516
|
+
// The user approved the plan they just saw; bind the next delegation to that content.
|
|
517
|
+
sessionPlans.delete(event.sessionID)
|
|
518
|
+
} else if (change === "clear") {
|
|
519
|
+
approvals.delete(event.sessionID)
|
|
520
|
+
sessionPlans.delete(event.sessionID)
|
|
521
|
+
}
|
|
522
|
+
})
|
|
523
|
+
|
|
524
|
+
await ctx.permission.hook("evaluate", async (event: any) => {
|
|
525
|
+
// devcomp:destructive-guard
|
|
526
|
+
if (event.action === "shell") {
|
|
527
|
+
const commands = Array.isArray(event.resources) ? event.resources : [event.resources]
|
|
528
|
+
for (const command of commands) {
|
|
529
|
+
const result = isDestructiveCommand(String(command ?? ""))
|
|
530
|
+
if (!result.destructive) continue
|
|
531
|
+
event.effect = "ask"
|
|
532
|
+
event.message =
|
|
533
|
+
`Development Companion destructive guard: this command can cause ${result.reason}. ` +
|
|
534
|
+
"Known destructive patterns need the user's explicit authorization, even after an " +
|
|
535
|
+
"always approval. Shell writes remain a residual risk. " +
|
|
536
|
+
"Report it to the Coordinator instead of retrying with a broader permission."
|
|
537
|
+
return
|
|
538
|
+
}
|
|
539
|
+
return
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (event.action === "edit") {
|
|
543
|
+
// devcomp:scope-gate
|
|
544
|
+
await enforceEditPermission(ctx, companion, event)
|
|
545
|
+
return
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
if (event.action !== "subagent") return
|
|
549
|
+
// devcomp:plan-gate
|
|
550
|
+
const target = String(event.resources?.[0] ?? "")
|
|
551
|
+
if (!IMPLEMENTATION_AGENTS.has(target)) return
|
|
552
|
+
|
|
553
|
+
if (approvals.has(event.sessionID)) {
|
|
554
|
+
// The user approved the plan in this session. The tool hook still enforces Plan/Scope.
|
|
555
|
+
event.effect = "allow"
|
|
556
|
+
return
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// Native `subagent: ask` remains the fallback when no session approval was observed.
|
|
560
|
+
event.effect = "ask"
|
|
561
|
+
event.message =
|
|
562
|
+
"Development Companion: the plan is not approved in this session. " +
|
|
563
|
+
"Present the plan and get the user's approval before delegating implementation work."
|
|
564
|
+
})
|
|
565
|
+
|
|
566
|
+
await ctx.tool.hook("execute.after", (event: any) => {
|
|
567
|
+
if (event?.tool !== "subagent") return
|
|
568
|
+
const input = event?.input ?? {}
|
|
569
|
+
const target = implementationTarget(input)
|
|
570
|
+
if (!IMPLEMENTATION_AGENTS.has(target)) return
|
|
571
|
+
|
|
572
|
+
if (event?.status !== "completed") {
|
|
573
|
+
// A rejected or failed delegation must not leave an orphan scope behind.
|
|
574
|
+
const index = pendingScopes.findIndex((record) =>
|
|
575
|
+
typeof event.id === "string" && record.callID === event.id)
|
|
576
|
+
if (index !== -1) pendingScopes.splice(index, 1)
|
|
577
|
+
return
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const childSessionID = subagentSessionID(event.result)
|
|
581
|
+
if (!childSessionID) return
|
|
582
|
+
const record = pendingScopes.find((candidate) => {
|
|
583
|
+
if (candidate.childSessionID) return false
|
|
584
|
+
if (typeof event.id === "string" && candidate.callID === event.id) return true
|
|
585
|
+
return !candidate.callID &&
|
|
586
|
+
candidate.parentSessionID === event.sessionID &&
|
|
587
|
+
candidate.agent === target
|
|
588
|
+
})
|
|
589
|
+
if (record) record.childSessionID = childSessionID
|
|
590
|
+
})
|
|
591
|
+
|
|
592
|
+
await ctx.tool.hook("execute.before", async (event: any) => {
|
|
593
|
+
const tool = String(event?.tool ?? "")
|
|
594
|
+
if (tool === "subagent") {
|
|
595
|
+
await enforcePlanGate(ctx, companion, event)
|
|
596
|
+
return
|
|
597
|
+
}
|
|
598
|
+
if (!EDIT_TOOLS.has(tool)) return
|
|
599
|
+
// devcomp:plan-gate devcomp:scope-gate
|
|
600
|
+
await enforceScopeGate(ctx, companion, event, tool)
|
|
601
|
+
})
|
|
602
|
+
}
|
|
603
|
+
})
|