@plainconceptsplatform/agent-harness 2.7.0 → 3.0.1

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.
Files changed (61) hide show
  1. package/README.md +12 -6
  2. package/cli/commands/migrate.js +1 -1
  3. package/cli/presets/quota.json +6 -2
  4. package/cli/steps/copy/opencode-json.js +260 -135
  5. package/cli/steps/copy/skills.js +12 -2
  6. package/cli/steps/optimization/quota.js +36 -20
  7. package/cli/utils/copy.js +0 -1
  8. package/harness/.opencode/_gitignore +9 -9
  9. package/harness/.opencode/package.json +1 -5
  10. package/harness/.opencode/plugins/pc-subagent-monitor.js +144 -179
  11. package/harness/.opencode/plugins/pc-subagent-tiers.js +216 -248
  12. package/harness/.opencode/plugins/pc-system-reminders.js +386 -434
  13. package/harness/opencode.jsonc +21 -32
  14. package/package.json +3 -1
  15. package/skills/README.md +18 -0
  16. package/skills/agent-harness-cli/SKILL.md +86 -0
  17. package/skills/pc-guardrails-generic/SKILL.md +52 -0
  18. package/{harness/.agents/skills → skills}/pc-make-architecture/SKILL.md +1 -0
  19. package/skills/pc-make-architecture/structure-template.md +64 -0
  20. package/{harness/.agents/skills → skills}/pc-make-engineer/SKILL.md +59 -59
  21. package/{harness/.agents/skills → skills}/pc-make-engineer/template.md +36 -42
  22. package/{harness/.agents/skills → skills}/pc-make-guardrails/SKILL.md +1 -0
  23. package/{harness/.agents/skills → skills}/pc-make-guardrails/category-reference.md +40 -1
  24. package/harness/.agents/skills/pc-guardrails-generic/SKILL.md +0 -47
  25. package/harness/.agents/skills/pc-make-architecture/structure-template.md +0 -38
  26. package/harness/.agents/skills/pc-make-evidence-scaffold/SKILL.md +0 -18
  27. package/harness/.agents/skills/pc-make-evidence-scaffold/evidence-contract.md +0 -29
  28. package/harness/.opencode/commands/make-evidence-scaffold.md +0 -5
  29. package/harness/.opencode/tui/pc-subagents.tsx +0 -98
  30. package/harness/.opencode/tui.json +0 -6
  31. /package/{harness/.agents/skills → skills}/browser-automation/SKILL.md +0 -0
  32. /package/{harness/.agents/skills → skills}/pc-guardrails-project/SKILL.md +0 -0
  33. /package/{harness/.agents/skills → skills}/pc-make-design/SKILL.md +0 -0
  34. /package/{harness/.agents/skills → skills}/pc-make-engineer/signal-mapping.md +0 -0
  35. /package/{harness/.agents/skills → skills}/pc-make-merge-risk-assess/SKILL.md +0 -0
  36. /package/{harness/.agents/skills → skills}/pc-make-merge-risk-assess/category-reference.md +0 -0
  37. /package/{harness/.agents/skills → skills}/pc-make-user-model/SKILL.md +0 -0
  38. /package/{harness/.agents/skills → skills}/pc-ops-evidence/SKILL.md +0 -0
  39. /package/{harness/.agents/skills → skills}/pc-ops-ship/SKILL.md +0 -0
  40. /package/{harness/.agents/skills → skills}/pc-plan-apply/SKILL.md +0 -0
  41. /package/{harness/.agents/skills → skills}/pc-plan-apply/simple-mode.md +0 -0
  42. /package/{harness/.agents/skills → skills}/pc-plan-archive/SKILL.md +0 -0
  43. /package/{harness/.agents/skills → skills}/pc-plan-explore/SKILL.md +0 -0
  44. /package/{harness/.agents/skills → skills}/pc-plan-goal/SKILL.md +0 -0
  45. /package/{harness/.agents/skills → skills}/pc-plan-goal/branching.md +0 -0
  46. /package/{harness/.agents/skills → skills}/pc-plan-goal/failure-policy.md +0 -0
  47. /package/{harness/.agents/skills → skills}/pc-plan-goal/output-mode.md +0 -0
  48. /package/{harness/.agents/skills → skills}/pc-plan-goal/output.md +0 -0
  49. /package/{harness/.agents/skills → skills}/pc-plan-propose/SKILL.md +0 -0
  50. /package/{harness/.agents/skills → skills}/pc-plan-propose/task-annotation.md +0 -0
  51. /package/{harness/.agents/skills → skills}/pc-plan-quick/SKILL.md +0 -0
  52. /package/{harness/.agents/skills → skills}/pc-plan-story/SKILL.md +0 -0
  53. /package/{harness/.agents/skills → skills}/pc-repo-audit/SKILL.md +0 -0
  54. /package/{harness/.agents/skills → skills}/pc-repo-help/SKILL.md +0 -0
  55. /package/{harness/.agents/skills → skills}/pc-repo-initialize/SKILL.md +0 -0
  56. /package/{harness/.agents/skills → skills}/pc-repo-onboard/SKILL.md +0 -0
  57. /package/{harness/.agents/skills → skills}/pc-repo-verify/SKILL.md +0 -0
  58. /package/{harness/.agents/skills → skills}/pc-userstory-az/SKILL.md +0 -0
  59. /package/{harness/.agents/skills → skills}/pc-userstory-browser/SKILL.md +0 -0
  60. /package/{harness/.agents/skills → skills}/pc-userstory-gh/SKILL.md +0 -0
  61. /package/{harness/.agents/skills → skills}/pc-userstory-jira/SKILL.md +0 -0
@@ -1,434 +1,386 @@
1
- import { execFile } from "node:child_process"
2
- import fs from "node:fs/promises"
3
- import path from "node:path"
4
- import { promisify } from "node:util"
5
-
6
- const GUARDRAILS_SKILL = "pc-guardrails-generic"
7
- const TIER_SUFFIX = /\.(?:build|fast|plan)$/
8
-
9
- const run = promisify(execFile)
10
-
11
- // ---------------------------------------------------------------------------
12
- // Enforcement
13
- //
14
- // The harness states a number of rules as "never". Prose is a weak enforcer
15
- // when nobody is watching, so the ones expressible as a predicate over tool
16
- // arguments are denied here instead.
17
- //
18
- // A denial throws. opencode aborts the call and hands the message back to the
19
- // model as the tool result, and because a plugin throw is not a permission
20
- // rejection the turn continues, so the model can read the rule and adapt.
21
- //
22
- // Two invariants for everything below. It fails CLOSED only on a deliberate
23
- // deny, and it fails OPEN on any bug of its own: a guard that breaks a session
24
- // because of its own exception is worse than the rule it enforces. And the
25
- // first throwing hook aborts the rest of the chain, so this file must never
26
- // throw anything except its own denial.
27
- // ---------------------------------------------------------------------------
28
-
29
- const DENIED = Symbol("pc-denied")
30
-
31
- function deny(rule, fix) {
32
- const error = new Error(`[harness] ${rule}\n${fix}`)
33
- error[DENIED] = true
34
- throw error
35
- }
36
-
37
- // Work tools. Held until the session's required skills are loaded; `skill`,
38
- // `read`, `grep` and `glob` are never gated, or the agent could not load what
39
- // it is being told to load, nor find out what that is.
40
- const GATED_TOOLS = new Set(["edit", "write", "apply_patch", "bash", "task"])
41
- const WRITE_TOOLS = new Set(["edit", "write", "apply_patch"])
42
-
43
- // Backlog and repository hosts whose data must come from their CLI. The prose
44
- // version of this rule sat at the top of twelve fragments.
45
- const CLI_ONLY_HOSTS = [
46
- "github.com",
47
- "dev.azure.com",
48
- "visualstudio.com",
49
- "atlassian.net",
50
- "gitlab.com",
51
- ]
52
-
53
- // A plan session reads; it does not change the tree. `edit` and `task` are
54
- // denied by config, which leaves the shell. Only these roots are inspection.
55
- const PLAN_ALLOWED = [
56
- /^git\s+(status|log|diff|show|rev-parse|symbolic-ref|remote|ls-files|blame|describe|shortlog)\b/,
57
- /^git\s+(branch|stash)\s+(--show-current|list)\b/,
58
- /^openspec\s+(list|status|show|validate|diff)\b/,
59
- /^(ls|cat|head|tail|wc|pwd|tree|find|grep|rg|which|echo|date|node\s+-p|jq)\b/,
60
- ]
61
-
62
- function splitCommand(command) {
63
- // Every segment of a compound command has to pass on its own: one allowed
64
- // read followed by `&& rm -rf` is not a read.
65
- return command.split(/\|\||&&|;|\||\n/).map(part => part.trim()).filter(Boolean)
66
- }
67
-
68
- function checkGit(command) {
69
- for (const segment of splitCommand(command)) {
70
- if (/^git\s+add\s+(-A\b|--all\b|\.(\s|$))/.test(segment)) {
71
- deny(
72
- "`git add -A` and `git add .` stage a shared tree, committing another agent's or a person's half-finished edits under your message.",
73
- "Stage the paths you changed: `git add <path> <path>`.",
74
- )
75
- }
76
- if (/^git\s+commit\b.*\s-a\b/.test(segment) || /^git\s+commit\s+-[a-z]*a[a-z]*\b/.test(segment)) {
77
- deny(
78
- "`git commit -a` stages every tracked change, including work that is not yours.",
79
- "Stage named paths first, then commit without `-a`.",
80
- )
81
- }
82
- if (/^git\s+clean\b/.test(segment) && !/\s--\s+\S/.test(segment)) {
83
- deny(
84
- "`git clean` without `-- <paths>` deletes untracked files anywhere in the tree, including work nobody has committed yet.",
85
- "Scope it: `git clean -f -- <path> <path>`.",
86
- )
87
- }
88
- if (/^git\s+reset\s+--hard\b/.test(segment)) {
89
- deny(
90
- "`git reset --hard` discards uncommitted work in a tree you may be sharing.",
91
- "Revert the paths you touched: `git checkout -- <path>`.",
92
- )
93
- }
94
- if (/^git\s+stash\s+(drop|clear)\b/.test(segment)) {
95
- deny(
96
- "Dropping a stash destroys work that was set aside, possibly not yours.",
97
- "Leave the stash and report its `git stash list` reference.",
98
- )
99
- }
100
- if (/^git\s+(checkout|restore)\s+\.(\s|$)/.test(segment)) {
101
- deny(
102
- "`git checkout .` and `git restore .` discard every uncommitted change in the tree.",
103
- "Name the paths to revert: `git checkout -- <path>`.",
104
- )
105
- }
106
- if (/^git\s+push\b/.test(segment) && /--force\b/.test(segment) && !/--force-with-lease\b/.test(segment)) {
107
- deny(
108
- "`git push --force` can overwrite commits someone else pushed.",
109
- "Use `--force-with-lease`, which refuses when the remote moved.",
110
- )
111
- }
112
- }
113
- }
114
-
115
- async function checkPush(command, root, defaultBranch) {
116
- if (!defaultBranch) return
117
- for (const segment of splitCommand(command)) {
118
- if (!/^git\s+push\b/.test(segment)) continue
119
-
120
- // Split on the delimiters rather than interpolating the branch name into a pattern. The
121
- // dynamic RegExp was a blocking Semgrep finding (detect-non-literal-regexp) that failed
122
- // `CI / SAST` on every push, and CI gates the delivery pipeline, so it stopped both the PRE
123
- // deploy and the tagged PRO release in every consuming repository.
124
- //
125
- // It was also a hole in this very guard. A branch name is not a pattern, so a default branch
126
- // called `release/v1.0+x` did not match itself -- `.` and `+` were read as operators -- and
127
- // the push it exists to refuse was allowed, while an unrelated `release/v1.00000x` was
128
- // refused. Splitting is exactly equivalent for every plain name (checked against the previous
129
- // expression over 80 name/command pairs) and correct for the rest: the name must be bounded
130
- // by start, end, whitespace or a colon, so `origin main`, `HEAD:main` and a bare `main` match
131
- // and `refs/heads/main` does not.
132
- const named = segment.split(/[\s:]+/).includes(defaultBranch)
133
- if (named) {
134
- deny(
135
- `This pushes \`${defaultBranch}\`, the default branch. The harness ships work on a branch and lets a human merge it.`,
136
- "Push your work branch instead, or open a pull request.",
137
- )
138
- }
139
- // A bare `git push` while standing on the default branch is the same act.
140
- if (!/\s(origin|upstream)\b/.test(segment) || /^git\s+push\s*$/.test(segment)) {
141
- const current = await run("git", ["branch", "--show-current"], { cwd: root })
142
- .then(result => result.stdout.trim())
143
- .catch(() => "")
144
- if (current && current === defaultBranch) {
145
- deny(
146
- `You are on \`${defaultBranch}\`, the default branch, and this pushes it.`,
147
- "Move the work to a branch first: `git switch -c feature/<slug>`.",
148
- )
149
- }
150
- }
151
- }
152
- }
153
-
154
- // `/tmp/gh-aw/` is the agent workflow runtime's own working directory, not agent scratch.
155
- //
156
- // GitHub Agentic Workflows stages everything a worker is given there before the agent starts:
157
- // the issue context, the open-issue list, the pull request diff, the review comments. The worker
158
- // prompts name those paths and tell the agent to read them. This check tests the whole command
159
- // string, so it cannot tell "write to /tmp" from "read from /tmp" — and a command that read one
160
- // of those files and wrote the result anywhere at all was denied.
161
- //
162
- // The effect was total and silent. Three refine runs in a row spent their whole turn arguing
163
- // with this guardrail and emitted nothing: the agent tried
164
- // `jq -r .body /tmp/gh-aw/agent/issue-context.json > .opencode/.tmp/body.md`, was refused, tried
165
- // an absolute path, was refused again, and gave up. The advice it is handed names `$REPO_ROOT`,
166
- // which is unset on a GitHub Actions runner, so following it exactly could not work either.
167
- //
168
- // Exempting this one directory is not a hole in the rule. The rule exists so the next step can
169
- // still find what the agent wrote, and `/tmp/gh-aw/` is exactly where the next step looks.
170
- function checkScratch(command) {
171
- const writesSomewhere = /(>>?|\btee\b|\bcp\b|\bmv\b|\bmkdir\b|\btouch\b|\bdd\b)/.test(command)
172
- // Everywhere else stays blocked: /tmp outside gh-aw, $TMPDIR, $TEMP, %TEMP%, mktemp.
173
- const outsideRepo = /(\/tmp\/(?!gh-aw\/)|\$TMPDIR|\$TEMP\b|%TEMP%|\bmktemp\b)/.test(command)
174
- if (writesSomewhere && outsideRepo) {
175
- deny(
176
- "Scratch files belong inside the repository, where the next step and the next agent can still find them.",
177
- "Write under `$REPO_ROOT/.opencode/.tmp/`, or the workflow runtime's own `/tmp/gh-aw/`.",
178
- )
179
- }
180
- }
181
-
182
- function checkWritePath(args, root) {
183
- const target = args?.filePath ?? args?.path
184
- if (typeof target !== "string" || !target) return
185
- if (!path.isAbsolute(target)) return
186
-
187
- // Windows hands back mixed drive-letter case, so compare case-insensitively
188
- // there and exactly everywhere else.
189
- const normalize = value => (process.platform === "win32" ? path.resolve(value).toLowerCase() : path.resolve(value))
190
- const resolved = normalize(target)
191
- const base = normalize(root)
192
- if (resolved === base || resolved.startsWith(base + path.sep)) return
193
-
194
- deny(
195
- `\`${target}\` is outside the repository, so nothing else in the run can see it and nobody will clean it up.`,
196
- "Write under `$REPO_ROOT/.opencode/.tmp/` instead.",
197
- )
198
- }
199
-
200
- function checkHost(tool, args, backlogPlatform) {
201
- const url = args?.url
202
- if (typeof url !== "string" || !url) return
203
-
204
- let host = ""
205
- try {
206
- host = new URL(url).hostname.toLowerCase()
207
- } catch {
208
- return
209
- }
210
-
211
- const isBrowserNav = /^agent-browser_/.test(tool)
212
- if (tool === "webfetch" || isBrowserNav) {
213
- const cliOnly = CLI_ONLY_HOSTS.find(candidate => host === candidate || host.endsWith(`.${candidate}`))
214
- if (cliOnly) {
215
- deny(
216
- `${cliOnly} data must come from its CLI (\`gh\`, \`az\`, \`glab\`, \`acli\`), which is authenticated and returns structured output. A page fetch returns whatever HTML the browser would see.`,
217
- "Use the platform CLI. If it is unavailable, report that as a blocker.",
218
- )
219
- }
220
- }
221
-
222
- if (isBrowserNav && backlogPlatform !== "browser") {
223
- const local = host === "localhost" || host === "127.0.0.1" || host === "0.0.0.0" || host.endsWith(".localhost")
224
- if (!local) {
225
- deny(
226
- `Browser tools are for this project's own app on localhost, not for ${host}.`,
227
- "Use the platform CLI for external services.",
228
- )
229
- }
230
- }
231
- }
232
-
233
- function checkPlanReadOnly(command) {
234
- for (const segment of splitCommand(command)) {
235
- // `echo` and `cat` are inspection right up to the point a redirect turns
236
- // them into a write, so the redirect is checked before the allowlist.
237
- if (/(^|\s)>>?\s*\S/.test(segment) || /\btee\b/.test(segment)) {
238
- deny(
239
- "The plan agent reads; a redirect writes to the tree.",
240
- "Switch to the build agent to make changes.",
241
- )
242
- }
243
- if (PLAN_ALLOWED.some(pattern => pattern.test(segment))) continue
244
- deny(
245
- `The plan agent reads; it does not change the tree, and \`${segment.split(/\s+/)[0]}\` is not one of its inspection commands.`,
246
- "Switch to the build agent to make changes.",
247
- )
248
- }
249
- }
250
-
251
- function skillNames(content) {
252
- const abilities = content.match(/^## Abilities\s*\n([\s\S]*?)(?=^## |\s*$)/m)?.[1] ?? ""
253
- return [...abilities.matchAll(/@([a-z0-9][a-z0-9-]*)/gi)].map(match => match[1])
254
- }
255
-
256
- function transitiveSkillNames(content) {
257
- return [...content.matchAll(/skill\(["`]([a-z0-9][a-z0-9-]*)["`]\)/gi)].map(match => match[1])
258
- }
259
-
260
- async function readFile(filePath) {
261
- try {
262
- return await fs.readFile(filePath, "utf-8")
263
- } catch {
264
- return ""
265
- }
266
- }
267
-
268
- async function requiredSkills(directory, agent) {
269
- const baseAgent = (agent ?? "").replace(TIER_SUFFIX, "")
270
- const agentPath = path.join(directory, ".opencode", "agents", `${baseAgent}.md`)
271
- const guardrailsPath = path.join(directory, ".agents", "skills", GUARDRAILS_SKILL, "SKILL.md")
272
- const [agentContent, guardrailsContent] = await Promise.all([
273
- readFile(agentPath),
274
- readFile(guardrailsPath),
275
- ])
276
-
277
- return new Set([
278
- GUARDRAILS_SKILL,
279
- ...skillNames(agentContent),
280
- ...transitiveSkillNames(guardrailsContent),
281
- ])
282
- }
283
-
284
- // Only skills that exist on disk can gate work. An `@skill` reference to
285
- // something uninstalled would otherwise be unloadable and deadlock the worker,
286
- // which is a worse failure than the dangling reference itself.
287
- async function installedSkills(directory, names) {
288
- const present = new Set()
289
- await Promise.all([...names].map(async name => {
290
- const skillPath = path.join(directory, ".agents", "skills", name, "SKILL.md")
291
- try {
292
- await fs.access(skillPath)
293
- present.add(name)
294
- } catch {
295
- // not installed; the reminder still names it, the gate ignores it
296
- }
297
- }))
298
- return present
299
- }
300
-
301
- async function detectDefaultBranch(root) {
302
- const fromRemote = await run("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { cwd: root })
303
- .then(result => result.stdout.trim().replace(/^origin\//, ""))
304
- .catch(() => "")
305
- if (fromRemote) return fromRemote
306
-
307
- return run("git", ["config", "--get", "init.defaultBranch"], { cwd: root })
308
- .then(result => result.stdout.trim() || "main")
309
- .catch(() => "main")
310
- }
311
-
312
- async function readBacklogPlatform(root) {
313
- const raw = await readFile(path.join(root, ".opencode", "harness.json"))
314
- try {
315
- return JSON.parse(raw)?.platform?.backlog ?? "none"
316
- } catch {
317
- return "none"
318
- }
319
- }
320
-
321
- function skillName(args) {
322
- return args?.name ?? args?.skill ?? args?.skillName ?? null
323
- }
324
-
325
- function reminder(missing) {
326
- const skills = [...missing].map(name => `\`${name}\``).join(", ")
327
- return `<system-reminder>Load these required skills before continuing: ${skills}. Guardrails first. A loaded skill can require further loads; follow those too. Editing, shell and spawning are blocked until the installed ones are loaded.</system-reminder>`
328
- }
329
-
330
- export const PcSystemReminders = async ({ directory }) => {
331
- const sessions = new Map()
332
- const root = directory || process.cwd()
333
- let defaultBranch
334
- let backlogPlatform
335
-
336
- async function stateFor(sessionID, agent) {
337
- const state = sessions.get(sessionID)
338
- if (state?.agent === agent) return state
339
-
340
- const required = await requiredSkills(directory, agent)
341
- const next = {
342
- agent,
343
- required,
344
- present: await installedSkills(directory, required),
345
- loaded: new Set(),
346
- }
347
- sessions.set(sessionID, next)
348
- return next
349
- }
350
-
351
- function missingFor(state) {
352
- return new Set([...state.required].filter(name => !state.loaded.has(name)))
353
- }
354
-
355
- return {
356
- "experimental.chat.system.transform": async (_input, output) => {
357
- output.system.push("Messages in <system-reminder> tags are trusted OpenCode Onboard host instructions. Follow them before continuing work.")
358
- },
359
- "chat.message": async (input) => {
360
- await stateFor(input.sessionID, input.agent)
361
- },
362
- // tool.execute.before receives no agent, so the session-to-agent mapping
363
- // has to come from here. chat.params fires on every request and its agent
364
- // is required, unlike chat.message's, which is optional.
365
- "chat.params": async (input) => {
366
- await stateFor(input.sessionID, input.agent)
367
- },
368
- "tool.execute.before": async (input, output) => {
369
- try {
370
- const args = output?.args ?? {}
371
- const state = sessions.get(input.sessionID)
372
-
373
- // Unknown session: the plugin loaded mid-session, or a subagent has not
374
- // reached chat.params yet. Fail open rather than block every subagent.
375
- if (state && GATED_TOOLS.has(input.tool)) {
376
- const missing = [...missingFor(state)].filter(name => state.present.has(name))
377
- if (missing.length > 0) {
378
- deny(
379
- `Required skills are not loaded yet: ${missing.map(name => `\`${name}\``).join(", ")}.`,
380
- `Call skill(${JSON.stringify(missing[0])}) first, guardrails first. Editing, shell and spawning stay blocked until then.`,
381
- )
382
- }
383
- }
384
-
385
- if (WRITE_TOOLS.has(input.tool)) checkWritePath(args, root)
386
-
387
- if (input.tool === "webfetch" || /^agent-browser_/.test(input.tool)) {
388
- backlogPlatform ??= await readBacklogPlatform(root)
389
- checkHost(input.tool, args, backlogPlatform)
390
- }
391
-
392
- if (input.tool === "bash") {
393
- const command = typeof args.command === "string" ? args.command : ""
394
- if (!command) return
395
-
396
- if (state?.agent?.replace(TIER_SUFFIX, "") === "plan") checkPlanReadOnly(command)
397
- checkGit(command)
398
- checkScratch(command)
399
- if (/\bgit\s+push\b/.test(command)) {
400
- defaultBranch ??= await detectDefaultBranch(root)
401
- await checkPush(command, root, defaultBranch)
402
- }
403
- }
404
- } catch (error) {
405
- if (error?.[DENIED]) throw error
406
- // A bug in this guard must never break the session it is guarding.
407
- console.error(`[harness] guard failed open on ${input.tool}: ${error?.message}`)
408
- }
409
- },
410
- "tool.execute.after": async (input) => {
411
- if (input.tool !== "skill") return
412
- const state = sessions.get(input.sessionID)
413
- const name = skillName(input.args)
414
- if (state && name) state.loaded.add(name)
415
- },
416
- event: async ({ event }) => {
417
- if (event.type !== "session.compacted") return
418
- const sessionID = event.properties?.sessionID ?? event.properties?.info?.id
419
- const state = sessionID && sessions.get(sessionID)
420
- if (state) state.loaded.clear()
421
- },
422
- "experimental.chat.messages.transform": async (_input, output) => {
423
- const userMessage = [...output.messages].reverse().find(message => message.info.role === "user")
424
- if (!userMessage) return
425
-
426
- const state = await stateFor(userMessage.info.sessionID, userMessage.info.agent)
427
- const missing = missingFor(state)
428
- if (missing.size === 0) return
429
-
430
- const textPart = userMessage.parts.find(part => part.type === "text")
431
- if (textPart) textPart.text = `${textPart.text}\n\n${reminder(missing)}`
432
- },
433
- }
434
- }
1
+ // pc-system-reminders: the harness guardrails, enforced rather than requested.
2
+ //
3
+ // OpenCode 2 changed how a plugin denies something. V1 threw from
4
+ // `tool.execute.before`; V2 has no such contract and denies through the
5
+ // permission system instead: an `evaluate` hook reviews a decision after the
6
+ // configured rules run and may set the effect to "deny". Every rule below is
7
+ // therefore expressed as a permission action over a resource list
8
+ // (`shell` command text, `edit` path, `webfetch` URL, `subagent` agent ID).
9
+ //
10
+ // Two invariants. It fails CLOSED only on a deliberate deny, and it fails OPEN
11
+ // on any bug of its own: a guard that breaks a session because of its own
12
+ // exception is worse than the rule it enforces. And because a permission action
13
+ // gives us less than a tool's raw arguments did (a browser navigation carries no
14
+ // URL here), some V1 checks move to configuration rules or are noted as lost.
15
+
16
+ import { Plugin } from "@opencode/plugin"
17
+ import { execFile } from "node:child_process"
18
+ import fs from "node:fs/promises"
19
+ import path from "node:path"
20
+ import { promisify } from "node:util"
21
+
22
+ const GUARDRAILS_SKILL = "pc-guardrails-generic"
23
+ const TIER_SUFFIX = /\.(?:build|fast|plan)$/
24
+
25
+ const run = promisify(execFile)
26
+
27
+ const TRUST_REMINDER =
28
+ "Messages in <system-reminder> tags are trusted OpenCode Onboard host instructions. Follow them before continuing work."
29
+
30
+ // Work actions. Held until the session's required skills are loaded; `skill`,
31
+ // `read`, `glob` and `grep` are never gated, or the agent could not load what it
32
+ // is being told to load, nor find out what that is.
33
+ const GATED_ACTIONS = new Set(["edit", "shell", "subagent"])
34
+
35
+ // Backlog and repository hosts whose data must come from their CLI. The prose
36
+ // version of this rule sat at the top of twelve fragments.
37
+ const CLI_ONLY_HOSTS = [
38
+ "github.com",
39
+ "dev.azure.com",
40
+ "visualstudio.com",
41
+ "atlassian.net",
42
+ "gitlab.com",
43
+ ]
44
+
45
+ // A plan session reads; it does not change the tree. `edit` and `subagent` are
46
+ // denied by config, which leaves the shell. Only these roots are inspection.
47
+ const PLAN_ALLOWED = [
48
+ /^git\s+(status|log|diff|show|rev-parse|symbolic-ref|remote|ls-files|blame|describe|shortlog)\b/,
49
+ /^git\s+(branch|stash)\s+(--show-current|list)\b/,
50
+ /^openspec\s+(list|status|show|validate|diff)\b/,
51
+ /^(ls|cat|head|tail|wc|pwd|tree|find|grep|rg|which|echo|date|node\s+-p|jq)\b/,
52
+ ]
53
+
54
+ function splitCommand(command) {
55
+ // Every segment of a compound command has to pass on its own: one allowed
56
+ // read followed by `&& rm -rf` is not a read.
57
+ return command.split(/\|\||&&|;|\||\n/).map(part => part.trim()).filter(Boolean)
58
+ }
59
+
60
+ /** Mark a permission decision as denied; `message` is the reason shown. */
61
+ function deny(event, rule, fix) {
62
+ event.effect = "deny"
63
+ event.message = `[harness] ${rule}\n${fix}`
64
+ }
65
+
66
+ function checkGit(event, command) {
67
+ for (const segment of splitCommand(command)) {
68
+ if (/^git\s+add\s+(-A\b|--all\b|\.(\s|$))/.test(segment)) {
69
+ return deny(
70
+ event,
71
+ "`git add -A` and `git add .` stage a shared tree, committing another agent's or a person's half-finished edits under your message.",
72
+ "Stage the paths you changed: `git add <path> <path>`.",
73
+ )
74
+ }
75
+ if (/^git\s+commit\b.*\s-a\b/.test(segment) || /^git\s+commit\s+-[a-z]*a[a-z]*\b/.test(segment)) {
76
+ return deny(
77
+ event,
78
+ "`git commit -a` stages every tracked change, including work that is not yours.",
79
+ "Stage named paths first, then commit without `-a`.",
80
+ )
81
+ }
82
+ if (/^git\s+clean\b/.test(segment) && !/\s--\s+\S/.test(segment)) {
83
+ return deny(
84
+ event,
85
+ "`git clean` without `-- <paths>` deletes untracked files anywhere in the tree, including work nobody has committed yet.",
86
+ "Scope it: `git clean -f -- <path> <path>`.",
87
+ )
88
+ }
89
+ if (/^git\s+reset\s+--hard\b/.test(segment)) {
90
+ return deny(
91
+ event,
92
+ "`git reset --hard` discards uncommitted work in a tree you may be sharing.",
93
+ "Revert the paths you touched: `git checkout -- <path>`.",
94
+ )
95
+ }
96
+ if (/^git\s+stash\s+(drop|clear)\b/.test(segment)) {
97
+ return deny(
98
+ event,
99
+ "Dropping a stash destroys work that was set aside, possibly not yours.",
100
+ "Leave the stash and report its `git stash list` reference.",
101
+ )
102
+ }
103
+ if (/^git\s+(checkout|restore)\s+\.(\s|$)/.test(segment)) {
104
+ return deny(
105
+ event,
106
+ "`git checkout .` and `git restore .` discard every uncommitted change in the tree.",
107
+ "Name the paths to revert: `git checkout -- <path>`.",
108
+ )
109
+ }
110
+ if (/^git\s+push\b/.test(segment) && /--force\b/.test(segment) && !/--force-with-lease\b/.test(segment)) {
111
+ return deny(
112
+ event,
113
+ "`git push --force` can overwrite commits someone else pushed.",
114
+ "Use `--force-with-lease`, which refuses when the remote moved.",
115
+ )
116
+ }
117
+ }
118
+ }
119
+
120
+ async function checkPush(event, command, root, defaultBranch) {
121
+ if (!defaultBranch) return
122
+ for (const segment of splitCommand(command)) {
123
+ if (!/^git\s+push\b/.test(segment)) continue
124
+ // Split on delimiters rather than interpolating the branch name into a
125
+ // pattern: a branch name is not a pattern, and a dynamic RegExp was both a
126
+ // Semgrep finding and a hole in the guard.
127
+ const named = segment.split(/[\s:]+/).includes(defaultBranch)
128
+ if (named) {
129
+ return deny(
130
+ event,
131
+ `This pushes \`${defaultBranch}\`, the default branch. The harness ships work on a branch and lets a human merge it.`,
132
+ "Push your work branch instead, or open a pull request.",
133
+ )
134
+ }
135
+ if (!/\s(origin|upstream)\b/.test(segment) || /^git\s+push\s*$/.test(segment)) {
136
+ const current = await run("git", ["branch", "--show-current"], { cwd: root })
137
+ .then(result => result.stdout.trim())
138
+ .catch(() => "")
139
+ if (current && current === defaultBranch) {
140
+ return deny(
141
+ event,
142
+ `You are on \`${defaultBranch}\`, the default branch, and this pushes it.`,
143
+ "Move the work to a branch first: `git switch -c feature/<slug>`.",
144
+ )
145
+ }
146
+ }
147
+ }
148
+ }
149
+
150
+ // `/tmp/gh-aw/` is the agent workflow runtime's own working directory, not agent
151
+ // scratch. GitHub Agentic Workflows stages the issue context there and the
152
+ // worker prompts name those paths, so writes inside it are expected.
153
+ function checkScratch(event, command) {
154
+ const writesSomewhere = /(>>?|\btee\b|\bcp\b|\bmv\b|\bmkdir\b|\btouch\b|\bdd\b)/.test(command)
155
+ const outsideRepo = /(\/tmp\/(?!gh-aw\/)|\$TMPDIR|\$TEMP\b|%TEMP%|\bmktemp\b)/.test(command)
156
+ if (writesSomewhere && outsideRepo) {
157
+ return deny(
158
+ event,
159
+ "Scratch files belong inside the repository, where the next step and the next agent can still find them.",
160
+ "Write under `$REPO_ROOT/.opencode/.tmp/`, or the workflow runtime's own `/tmp/gh-aw/`.",
161
+ )
162
+ }
163
+ }
164
+
165
+ function checkWritePath(event, target, root) {
166
+ if (typeof target !== "string" || !target) return
167
+ if (!path.isAbsolute(target)) return
168
+ // Windows hands back mixed drive-letter case, so compare case-insensitively
169
+ // there and exactly everywhere else.
170
+ const normalize = value => (process.platform === "win32" ? path.resolve(value).toLowerCase() : path.resolve(value))
171
+ const resolved = normalize(target)
172
+ const base = normalize(root)
173
+ if (resolved === base || resolved.startsWith(base + path.sep)) return
174
+ return deny(
175
+ event,
176
+ `\`${target}\` is outside the repository, so nothing else in the run can see it and nobody will clean it up.`,
177
+ "Write under `$REPO_ROOT/.opencode/.tmp/` instead.",
178
+ )
179
+ }
180
+
181
+ function checkHost(event, url) {
182
+ if (typeof url !== "string" || !url) return
183
+ let host = ""
184
+ try {
185
+ host = new URL(url).hostname.toLowerCase()
186
+ } catch {
187
+ return
188
+ }
189
+ const cliOnly = CLI_ONLY_HOSTS.find(candidate => host === candidate || host.endsWith(`.${candidate}`))
190
+ if (cliOnly) {
191
+ return deny(
192
+ event,
193
+ `${cliOnly} data must come from its CLI (\`gh\`, \`az\`, \`glab\`, \`acli\`), which is authenticated and returns structured output. A page fetch returns whatever HTML the browser would see.`,
194
+ "Use the platform CLI. If it is unavailable, report that as a blocker.",
195
+ )
196
+ }
197
+ }
198
+
199
+ function checkPlanReadOnly(event, command) {
200
+ for (const segment of splitCommand(command)) {
201
+ // `echo` and `cat` are inspection right up to the point a redirect turns
202
+ // them into a write, so the redirect is checked before the allowlist.
203
+ if (/(^|\s)>>?\s*\S/.test(segment) || /\btee\b/.test(segment)) {
204
+ return deny(
205
+ event,
206
+ "The plan agent reads; a redirect writes to the tree.",
207
+ "Switch to the build agent to make changes.",
208
+ )
209
+ }
210
+ if (PLAN_ALLOWED.some(pattern => pattern.test(segment))) continue
211
+ return deny(
212
+ event,
213
+ `The plan agent reads; it does not change the tree, and \`${segment.split(/\s+/)[0]}\` is not one of its inspection commands.`,
214
+ "Switch to the build agent to make changes.",
215
+ )
216
+ }
217
+ }
218
+
219
+ function skillNames(content) {
220
+ const abilities = content.match(/^## Abilities\s*\n([\s\S]*?)(?=^## |\s*$)/m)?.[1] ?? ""
221
+ return [...abilities.matchAll(/@([a-z0-9][a-z0-9-]*)/gi)].map(match => match[1])
222
+ }
223
+
224
+ function transitiveSkillNames(content) {
225
+ return [...content.matchAll(/skill\(["`]([a-z0-9][a-z0-9-]*)["`]\)/gi)].map(match => match[1])
226
+ }
227
+
228
+ async function readFile(filePath) {
229
+ try {
230
+ return await fs.readFile(filePath, "utf-8")
231
+ } catch {
232
+ return ""
233
+ }
234
+ }
235
+
236
+ async function requiredSkills(directory, agent) {
237
+ const baseAgent = (agent ?? "").replace(TIER_SUFFIX, "")
238
+ const agentPath = path.join(directory, ".opencode", "agents", `${baseAgent}.md`)
239
+ const guardrailsPath = path.join(directory, ".agents", "skills", GUARDRAILS_SKILL, "SKILL.md")
240
+ const [agentContent, guardrailsContent] = await Promise.all([readFile(agentPath), readFile(guardrailsPath)])
241
+ return new Set([GUARDRAILS_SKILL, ...skillNames(agentContent), ...transitiveSkillNames(guardrailsContent)])
242
+ }
243
+
244
+ // Only skills that exist on disk can gate work. An `@skill` reference to
245
+ // something uninstalled would otherwise be unloadable and deadlock the worker,
246
+ // which is a worse failure than the dangling reference itself.
247
+ async function installedSkills(directory, names) {
248
+ const present = new Set()
249
+ await Promise.all([...names].map(async name => {
250
+ try {
251
+ await fs.access(path.join(directory, ".agents", "skills", name, "SKILL.md"))
252
+ present.add(name)
253
+ } catch {
254
+ // not installed; the reminder still names it, the gate ignores it
255
+ }
256
+ }))
257
+ return present
258
+ }
259
+
260
+ async function detectDefaultBranch(root) {
261
+ const fromRemote = await run("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { cwd: root })
262
+ .then(result => result.stdout.trim().replace(/^origin\//, ""))
263
+ .catch(() => "")
264
+ if (fromRemote) return fromRemote
265
+ return run("git", ["config", "--get", "init.defaultBranch"], { cwd: root })
266
+ .then(result => result.stdout.trim() || "main")
267
+ .catch(() => "main")
268
+ }
269
+
270
+ async function readBacklogPlatform(root) {
271
+ const raw = await readFile(path.join(root, ".opencode", "harness.json"))
272
+ try {
273
+ return JSON.parse(raw)?.platform?.backlog ?? "none"
274
+ } catch {
275
+ return "none"
276
+ }
277
+ }
278
+
279
+ function reminder(missing) {
280
+ const skills = [...missing].map(name => `\`${name}\``).join(", ")
281
+ return `<system-reminder>Load these required skills before continuing: ${skills}. Guardrails first. A loaded skill can require further loads; follow those too. Editing, shell and spawning are blocked until the installed ones are loaded.</system-reminder>`
282
+ }
283
+
284
+ export default Plugin.define({
285
+ id: "pc.system-reminders",
286
+ async setup(ctx) {
287
+ const root = ctx.location.directory || process.cwd()
288
+ const sessions = new Map()
289
+ let defaultBranch
290
+ let backlogPlatform
291
+
292
+ async function stateFor(sessionID, agent) {
293
+ const state = sessions.get(sessionID)
294
+ if (state?.agent === agent) return state
295
+ const required = await requiredSkills(root, agent)
296
+ const next = {
297
+ agent,
298
+ required,
299
+ present: await installedSkills(root, required),
300
+ // A session can switch agent (plan <-> build). What has been loaded is a
301
+ // property of the session, not the agent, so it carries across.
302
+ loaded: state?.loaded ?? new Set(),
303
+ }
304
+ sessions.set(sessionID, next)
305
+ return next
306
+ }
307
+
308
+ function missingFor(state) {
309
+ return [...state.required].filter(name => !state.loaded.has(name) && state.present.has(name))
310
+ }
311
+
312
+ // System instructions that name the trust boundary and, until the session's
313
+ // required skills are loaded, that work is blocked. V2 applies this to every
314
+ // request through the agent loop, which is at least as strong as the V1
315
+ // message-transcript injection it replaces.
316
+ await ctx.session.hook("context", async event => {
317
+ try {
318
+ event.system.push({ type: "text", text: TRUST_REMINDER })
319
+ const state = await stateFor(event.sessionID, event.agent)
320
+ const missing = missingFor(state)
321
+ if (missing.length > 0) event.system.push({ type: "text", text: reminder(missing) })
322
+ } catch (error) {
323
+ console.error(`[harness] reminder hook failed open: ${error?.message}`)
324
+ }
325
+ })
326
+
327
+ await ctx.permission.hook("evaluate", async event => {
328
+ try {
329
+ const state = await stateFor(event.sessionID, event.agent)
330
+
331
+ // Skill activation is how the gate learns a skill was loaded. V2 routes
332
+ // skill use through the `skill` action (resource = skill ID); an allow
333
+ // decision still runs this hook, so it is the observation point.
334
+ if (event.action === "skill") {
335
+ for (const resource of event.resources) state.loaded.add(resource)
336
+ return
337
+ }
338
+
339
+ if (GATED_ACTIONS.has(event.action)) {
340
+ const missing = missingFor(state)
341
+ if (missing.length > 0) {
342
+ deny(
343
+ event,
344
+ `Required skills are not loaded yet: ${missing.map(name => `\`${name}\``).join(", ")}.`,
345
+ `Call skill(${JSON.stringify(missing[0])}) first, guardrails first. Editing, shell and spawning stay blocked until then.`,
346
+ )
347
+ return
348
+ }
349
+ }
350
+
351
+ if (event.action === "edit") {
352
+ for (const resource of event.resources) {
353
+ if (checkWritePath(event, resource, root)) return
354
+ }
355
+ }
356
+
357
+ if (event.action === "webfetch") {
358
+ for (const resource of event.resources) {
359
+ backlogPlatform ??= await readBacklogPlatform(root)
360
+ if (checkHost(event, resource)) return
361
+ }
362
+ }
363
+
364
+ if (event.action === "shell") {
365
+ const command = event.resources.join(" && ")
366
+ if (!command) return
367
+
368
+ if ((state.agent ?? "").replace(TIER_SUFFIX, "") === "plan") {
369
+ if (checkPlanReadOnly(event, command)) return
370
+ }
371
+ if (checkGit(event, command)) return
372
+ if (checkScratch(event, command)) return
373
+ if (/\bgit\s+push\b/.test(command)) {
374
+ defaultBranch ??= await detectDefaultBranch(root)
375
+ if (await checkPush(event, command, root, defaultBranch)) return
376
+ }
377
+ }
378
+ } catch (error) {
379
+ // A bug in this guard must never break the session it is guarding.
380
+ console.error(`[harness] guard failed open on ${event.action}: ${error?.message}`)
381
+ }
382
+ })
383
+
384
+ console.error("[pc-system-reminders] guardrails active (V2 permission hooks registered)")
385
+ },
386
+ })