opencode-agent-harness 0.0.0-stage → 0.3.14

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 (171) hide show
  1. package/CHANGELOG.md +217 -0
  2. package/LICENSE +21 -0
  3. package/README.md +636 -2
  4. package/bin/agent-harness.js +3182 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +86 -4
  8. package/templates/.agents/AGENTS.md +148 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1924 -0
  100. package/templates/scripts/board-service.sh +214 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +416 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +323 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +499 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +434 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +288 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +187 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/check-worktrees.js +93 -0
  124. package/templates/scripts/qa/ci-triage.js +346 -0
  125. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  126. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  127. package/templates/scripts/qa/command-classifier.js +552 -0
  128. package/templates/scripts/qa/context-guard-core.js +1618 -0
  129. package/templates/scripts/qa/diff.js +174 -0
  130. package/templates/scripts/qa/feature-scaffold.js +224 -0
  131. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  132. package/templates/scripts/qa/governance.js +174 -0
  133. package/templates/scripts/qa/hash-file.js +32 -0
  134. package/templates/scripts/qa/lease-lib.js +263 -0
  135. package/templates/scripts/qa/merge-backlog.js +324 -0
  136. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  137. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  138. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  139. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  140. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  141. package/templates/scripts/qa/mobile-e2e/check-flows.js +568 -0
  142. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  143. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  144. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  146. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  147. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  148. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  149. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  150. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  151. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  152. package/templates/scripts/qa/models.allowlist.txt +32 -0
  153. package/templates/scripts/qa/provider-stats.js +878 -0
  154. package/templates/scripts/qa/run-clean.js +83 -0
  155. package/templates/scripts/qa/run-gates.js +213 -0
  156. package/templates/scripts/qa/run-loop.js +220 -0
  157. package/templates/scripts/qa/session-recon.js +512 -0
  158. package/templates/scripts/qa/store-lib.js +324 -0
  159. package/templates/scripts/qa/tool-lib.js +134 -0
  160. package/templates/scripts/qa/where.js +214 -0
  161. package/templates/scripts/qa/worktree-hygiene.js +217 -0
  162. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  163. package/templates/scripts/serve.js +1328 -0
  164. package/templates/scripts/setup-nightly.sh +185 -0
  165. package/templates/scripts/setup-tmpfs.sh +374 -0
  166. package/templates/scripts/ship.js +586 -0
  167. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  168. package/templates/scripts/switch-reasoning-model.sh +104 -0
  169. package/templates/scripts/wait-for.js +342 -0
  170. package/templates/scripts/wsl-gpu.sh +180 -0
  171. package/templates/scripts/wsl-tune.sh +319 -0
@@ -0,0 +1,1164 @@
1
+ import type { Context } from "@opencode/plugin"
2
+ import fs from "node:fs"
3
+ import os from "node:os"
4
+ import path from "node:path"
5
+ import { execFileSync, spawn } from "node:child_process"
6
+ import guard from "../../scripts/qa/context-guard-core.js"
7
+ import capacity from "../../scripts/qa/capacity-lib.js"
8
+ import leases from "../../scripts/qa/lease-lib.js"
9
+ import toolLib from "../../scripts/qa/tool-lib.js"
10
+ import storeLib from "../../scripts/qa/store-lib.js"
11
+
12
+ // Mechanical half of the context budget: read the project-owned thresholds from
13
+ // `.agents/memory/orchestration.md` and nudge the PRIMARY orchestrator session as
14
+ // it crosses them. The nudge is injected into the conversation TAIL via the V2
15
+ // `context` session hook, never the system prompt: changing the
16
+ // system prefix on a band crossing evicts the provider's whole prompt cache and
17
+ // re-bills the entire transcript at full input price (measured: every full-price
18
+ // re-read landed on turn 50/60/80/100). Appending at the tail keeps the cached
19
+ // prefix byte-stable. Also counts identical tool+args calls (loop detector),
20
+ // whole turns with no material file/state change (no-state detector), and
21
+ // repeated failures sharing a signature (same-failure detector), and records
22
+ // crossings in `.agents/guard-events.jsonl` (local-only, excluded clone-locally)
23
+ // so telemetry exists before a full provider-stats pass does.
24
+ // It also hard-stops on provider funds/quota errors (see model-routing.md
25
+ // "Provider funds stop") so a failed dispatch can never silently degrade inline.
26
+ // Child sessions (subagent dispatches) are tracked to attribute their funds
27
+ // errors to the orchestrator *with the failing provider/model* — the top-up
28
+ // target comes from observed dispatch metadata (task `metadata.model` or the
29
+ // child assistant message `providerID/modelID`), never a guess.
30
+ // It also blocks a branch switch (`git checkout`/`git switch`) while another
31
+ // live primary session shares the same checkout — see the branch-switch guard
32
+ // on `tool.execute.before` (the 2026-09-18 direct-push-to-main incident) — and
33
+ // blocks any code change aimed at the shared MAIN checkout until the session
34
+ // isolates into its feature worktree (the F-278 stranded-work guard). Git ops
35
+ // are judged by the paths they actually move against the checkout they select
36
+ // (`-C` resolved), so docs maintenance on main — and only that — stays allowed.
37
+
38
+ const ORCHESTRATION_REL = path.join(".agents", "memory", "orchestration.md")
39
+ const GUARD_LOG_REL = path.join(".agents", "guard-events.jsonl")
40
+
41
+ /* Stable id for the synthetic tail message the guard injects. The transform is
42
+ * per-request (never persisted), so this only needs to be stable within one
43
+ * request-building pass — where it lets a re-request replace the message in
44
+ * place instead of stacking duplicates. */
45
+ const GUARD_MESSAGE_ID = "context-guard"
46
+
47
+
48
+ export default {
49
+ id: "context-guard",
50
+ async setup(ctx: Context) {
51
+ const directory = ctx.location.directory as string
52
+ // V2: plugin registrations live for the plugin's lifetime; this controller
53
+ // aborts the event subscription on unload.
54
+ const controller = new AbortController()
55
+ const sessions = new Map<string, any>()
56
+ const childSessions = new Set<string>()
57
+ const childParent = new Map<string, string>()
58
+ const sessionModel = new Map<string, string>()
59
+ let thresholds: any = null
60
+ let thresholdsMtime = -1
61
+ const ORCHESTRATION_ABS = path.join(directory, ORCHESTRATION_REL)
62
+
63
+ /* Root resolution. `directory` is the location this instance was loaded for;
64
+ * it is correct for a session in that location but NOT for a session in
65
+ * another (the V2 event stream is process-wide). `session.created` carries the
66
+ * session's own location, so it is recorded per session and preferred. */
67
+ const normDir = (p: unknown) => guard.normalizeRootPath(p)
68
+ const ourRoot = normDir(directory)
69
+ const sessionRoots = new Map<string, string>()
70
+ const rootOf = (sessionID: string) => sessionRoots.get(sessionID) || directory
71
+ /* Both sides known -> strict (normalized) comparison, with the Windows
72
+ * case-insensitive rule; `guard.ownsLocation` is the one home for that rule. */
73
+ const sameRoot = (a: string, b: string) => {
74
+ const x = normDir(a)
75
+ const y = normDir(b)
76
+ return x !== "" && y !== "" && guard.ownsLocation(x, y)
77
+ }
78
+ const sameLocation = (event: any) => {
79
+ // The session's own location (payload) is the most specific; the envelope
80
+ // carries the location for the other event types.
81
+ const loc = event?.data?.location?.directory ?? event?.location?.directory
82
+ return guard.ownsLocation(directory, loc)
83
+ }
84
+
85
+ /* Is this session ours? Tool hooks and the context/prompt hooks carry only a
86
+ * sessionID (no location), so they use this instead of the event envelope.
87
+ * Known sessions answer from the recorded root; an unseen session is resolved
88
+ * from the store once (authoritative), and an undeterminable one is treated as
89
+ * ours so a guard is never skipped. */
90
+ const storeDirs = new Map<string, string>()
91
+ const storeDir = (sessionID: string) => {
92
+ if (storeDirs.has(sessionID)) return storeDirs.get(sessionID) || ""
93
+ let dir = ""
94
+ try {
95
+ dir = storeLib.sessionDirectory(sessionID) || ""
96
+ } catch {
97
+ dir = ""
98
+ }
99
+ storeDirs.set(sessionID, dir)
100
+ return dir
101
+ }
102
+ const sessionOurs = (sessionID: unknown): boolean => {
103
+ const sid = typeof sessionID === "string" ? sessionID : ""
104
+ if (!sid) return true
105
+ const known = sessionRoots.get(sid)
106
+ if (known) return sameRoot(normDir(known), ourRoot)
107
+ const dir = storeDir(sid)
108
+ if (dir) return sameRoot(normDir(dir), ourRoot)
109
+ return true
110
+ }
111
+
112
+ const stateFor = (sessionID: string) => {
113
+ let state = sessions.get(sessionID)
114
+ if (!state) {
115
+ state = guard.createSessionState()
116
+ sessions.set(sessionID, state)
117
+ }
118
+ return state
119
+ }
120
+
121
+ /* Walk a subagent session up to the primary orchestrator it belongs to, so a
122
+ * child's funds error arms the stop on the session the user actually sees. */
123
+ const primaryRoot = (sessionID: string) => {
124
+ let cur = sessionID
125
+ for (let i = 0; i < 100 && childParent.has(cur); i++) cur = childParent.get(cur) as string
126
+ return cur
127
+ }
128
+
129
+ /* Arm the funds stop on the primary session, naming the failed provider/model
130
+ * (when observed) in the injected rule, the guard-event log, and the TUI log. */
131
+ const armFunds = async (sessionID: string, label: string | null, source: string) => {
132
+ const owner = primaryRoot(sessionID)
133
+ const state = stateFor(owner)
134
+ if (state.fundsPending) return
135
+ state.fundsPending = true
136
+ state.fundsNotice = guard.fundsText(label, source)
137
+ const [provider, model] = label
138
+ ? label.includes("/")
139
+ ? [label.slice(0, label.indexOf("/")), label.slice(label.indexOf("/") + 1)]
140
+ : [null, label]
141
+ : [null, null]
142
+ logEvent({
143
+ kind: "funds",
144
+ sessionID: owner,
145
+ failedSessionID: sessionID === owner ? null : sessionID,
146
+ provider,
147
+ model,
148
+ source,
149
+ })
150
+ await report(`${label || "unknown provider/model"} — provider funds/quota error (${source}) — pausing for top-up`)
151
+ }
152
+
153
+ const isPrimary = (sessionID: unknown): sessionID is string =>
154
+ typeof sessionID === "string" && sessionID.length > 0 && !childSessions.has(sessionID)
155
+
156
+ /* The V2 shell tool is named `shell`; V1 called it `bash`. Accept both so the
157
+ * pure core and any transitional caller keep working. */
158
+ const isShell = (tool: unknown): boolean => {
159
+ const n = String(tool || "").toLowerCase()
160
+ return n === "bash" || n === "shell"
161
+ }
162
+
163
+ /* Read `.agents/memory/orchestration.md` once and cache it, re-reading whenever
164
+ * the file's mtime changes. This replaces V1's `file.watcher.updated` branch
165
+ * (that event name does not exist in V2): a plain stat is cheaper than relying on
166
+ * an event we have not observed firing in 2.0.29, and it cannot go stale. */
167
+ const loadThresholds = () => {
168
+ let mtime = -1
169
+ try {
170
+ mtime = fs.statSync(ORCHESTRATION_ABS).mtimeMs
171
+ } catch {
172
+ /* missing/unreadable -> documented defaults from the core */
173
+ }
174
+ if (thresholds && mtime === thresholdsMtime) return thresholds
175
+ let text = ""
176
+ try {
177
+ text = fs.readFileSync(ORCHESTRATION_ABS, "utf8")
178
+ } catch {
179
+ /* missing/unreadable -> documented defaults from the core */
180
+ }
181
+ thresholds = guard.parseThresholds(text)
182
+ thresholdsMtime = mtime
183
+ return thresholds
184
+ }
185
+
186
+ const logEvent = (event: Record<string, unknown>) => {
187
+ try {
188
+ const file = path.join(rootOf(String(event.sessionID || "")), GUARD_LOG_REL)
189
+ fs.mkdirSync(path.dirname(file), { recursive: true })
190
+ // `root` makes a mis-attributed event self-evident in the log (the guard
191
+ // root must always be the session's own checkout).
192
+ fs.appendFileSync(file, guard.formatGuardEvent({ ...event, root: rootOf(String(event.sessionID || "")) }), "utf8")
193
+ } catch (err: any) {
194
+ // Best-effort telemetry, but never silent: a missing guard log left a real
195
+ // detection unattributable once (LibraryOS) — surface the write failure.
196
+ void report(`guard-event log write failed: ${err?.message || err}`)
197
+ }
198
+ }
199
+
200
+ // V2 plugins have no `client`; log to the opencode server log (stdout/stderr).
201
+ const report = async (message: string, level: "info" | "warn" = "warn") => {
202
+ try {
203
+ if (level === "info") console.log(`context-guard: ${message}`)
204
+ else console.warn(`context-guard: ${message}`)
205
+ } catch {
206
+ /* logging is best-effort */
207
+ }
208
+ }
209
+
210
+ /* Per-tree primary-session lease. `test:concurrency` reads `.serve/sessions/`
211
+ * to fail when two primary sessions share one checkout — a collision that
212
+ * exists even on a clean tree. The lease carries a process birth token
213
+ * (bootId + /proc starttime) and a heartbeat, both defined in lease-lib.js, so
214
+ * a recycled pid or a closed TUI can't masquerade as a live session.
215
+ * Best-effort (never throws into the hook). */
216
+ const writeLease = (sessionID: string) => {
217
+ try {
218
+ leases.writeLease(rootOf(sessionID), sessionID)
219
+ } catch {
220
+ /* lease is best-effort */
221
+ }
222
+ }
223
+ const clearLease = (sessionID: string) => {
224
+ try {
225
+ leases.clearLease(rootOf(sessionID), sessionID)
226
+ } catch {
227
+ /* lease is best-effort */
228
+ }
229
+ }
230
+ const touchLease = (sessionID: string) => {
231
+ try {
232
+ leases.touchLease(rootOf(sessionID), sessionID)
233
+ } catch {
234
+ /* lease is best-effort */
235
+ }
236
+ }
237
+
238
+ /* Classify the checkout that encloses a path WITHOUT invoking git (git is not
239
+ * guaranteed on the plugin process's PATH). A main worktree's `.git` is a
240
+ * DIRECTORY; a linked feature worktree's `.git` is a FILE (`gitdir: ...`), so
241
+ * walking up to the first `.git` and checking its type is enough. Returns
242
+ * "main" | "linked" | null (outside a repo). The path may not exist yet (a
243
+ * new file), so start from its nearest existing ancestor. */
244
+ const checkoutKind = (p: string): "main" | "linked" | null => {
245
+ let dir = path.resolve(p)
246
+ // A new file's parents may not exist yet: start from the nearest existing dir.
247
+ while (dir !== path.dirname(dir) && !fs.existsSync(dir)) dir = path.dirname(dir)
248
+ if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) dir = path.dirname(dir)
249
+ for (let i = 0; i < 64; i++) {
250
+ try {
251
+ return fs.statSync(path.join(dir, ".git")).isDirectory() ? "main" : "linked"
252
+ } catch {
253
+ /* no .git here — keep walking up */
254
+ }
255
+ const parent = path.dirname(dir)
256
+ if (parent === dir) return null
257
+ dir = parent
258
+ }
259
+ return null
260
+ }
261
+
262
+ /* The repo root enclosing a path (nearest ancestor holding a `.git`), or null.
263
+ * Lets the main-checkout refusal tell a SAME-repo edit (isolate here) from a
264
+ * CROSS-repo one (F-12: a project session editing the harness `templates/`),
265
+ * which worktree isolation cannot reach. */
266
+ const repoRootOf = (p: string): string | null => {
267
+ let dir = path.resolve(p)
268
+ while (dir !== path.dirname(dir) && !fs.existsSync(dir)) dir = path.dirname(dir)
269
+ if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) dir = path.dirname(dir)
270
+ for (let i = 0; i < 64; i++) {
271
+ if (fs.existsSync(path.join(dir, ".git"))) return dir
272
+ const parent = path.dirname(dir)
273
+ if (parent === dir) return null
274
+ dir = parent
275
+ }
276
+ return null
277
+ }
278
+
279
+ const expandHome = (p: string): string => {
280
+ const s = String(p || "")
281
+ if (s === "~") return os.homedir()
282
+ if (s.startsWith("~/")) return path.join(os.homedir(), s.slice(2))
283
+ return s
284
+ }
285
+
286
+ /* The tree a session's bash calls should default to: the recorded mid-session
287
+ * worktree pointer when this session (or its primary ancestor) created one,
288
+ * else null (fall back to the launch directory). Used to reroot `cd X && ...`
289
+ * into the bash `workdir` argument — opencode pins a session to the tree it
290
+ * launched in, and `--open` is rarely used, so agents otherwise `cd` by hand. */
291
+ const sessionBashRoot = (sessionID: string): string | null => {
292
+ try {
293
+ const root = primaryRoot(sessionID)
294
+ const ptr = leases.readWorktree(directory, root)
295
+ if (!ptr) return null
296
+ const abs = path.resolve(expandHome(ptr))
297
+ return fs.existsSync(abs) && fs.statSync(abs).isDirectory() ? abs : null
298
+ } catch {
299
+ return null
300
+ }
301
+ }
302
+
303
+ /* The feature id the session should isolate: the board's single In-progress
304
+ * row, or null. Best-effort and cached-ish (a fresh read per refusal only —
305
+ * refusals are rare). Used to hand back the exact `backlog worktree <id>`
306
+ * command in the main-checkout refusal, never a bare error. */
307
+ const inferBoardFeature = (sessionID: string): string | null => {
308
+ try {
309
+ const root = sessionBashRoot(sessionID) || directory
310
+ const out = gitOut(root, ["branch", "--show-current"])
311
+ const fromBranch = out && out.match(/^[fF]-\d+/)
312
+ if (fromBranch) return fromBranch[0].toUpperCase()
313
+ const backlog = path.join(root, "BACKLOG.md")
314
+ if (!fs.existsSync(backlog)) return null
315
+ const text = fs.readFileSync(backlog, "utf8")
316
+ const section = (text.split(/^##\s*In progress\s*$/m)[1] || "").split(/^##\s/m)[0]
317
+ const ids = [...section.matchAll(/^\|\s*([Ff]-\d+)\s*\|/gm)].map((m) => m[1].toUpperCase())
318
+ return ids.length === 1 ? ids[0] : null
319
+ } catch {
320
+ return null
321
+ }
322
+ }
323
+
324
+ /* Trimmed stdout of a git command run in `cwd`, or null on ANY failure (git
325
+ * absent, not a repo, bad ref). null is "unknown": the caller stays
326
+ * conservative and blocks, so a missing git binary can never open a hole. */
327
+ const gitOut = (cwd: string, args: string[]): string | null => {
328
+ try {
329
+ return execFileSync("git", args, {
330
+ cwd,
331
+ encoding: "utf8",
332
+ stdio: ["ignore", "pipe", "ignore"],
333
+ timeout: 5000,
334
+ }).trim()
335
+ } catch {
336
+ return null
337
+ }
338
+ }
339
+
340
+ /* Whether a PATHLESS git op would move a code path, resolved against the live
341
+ * checkout. `commit` inspects the index (or the `HEAD` diff for `-a`); `push`
342
+ * inspects the commits not yet on the upstream. Docs-only -> false; anything
343
+ * indeterminate (git unavailable, no upstream) -> null, which blocks. */
344
+ const gitOpTouchesCode = (checkout: string, op: any): boolean | null => {
345
+ const sub = String(op?.subcommand || "")
346
+ const args: string[] = Array.isArray(op?.args) ? op.args : []
347
+ const nameOnly = (spec: string[]): string | null => gitOut(checkout, [...spec, "--name-only"])
348
+ let files: string | null
349
+ if (sub === "commit") {
350
+ const all = args.some((a) => a === "--all" || (/^-[a-z]+$/i.test(a) && a.includes("a")))
351
+ if (args.includes("--amend")) {
352
+ const committed = gitOut(checkout, ["diff", "--name-only", "HEAD^", "HEAD"])
353
+ const staged = gitOut(checkout, ["diff", "--cached", "--name-only"])
354
+ if (committed == null || staged == null) return null // root commit / unborn HEAD
355
+ files = committed + "\n" + staged
356
+ } else {
357
+ files = all ? nameOnly(["diff", "HEAD"]) : nameOnly(["diff", "--cached"])
358
+ }
359
+ } else if (sub === "push") {
360
+ const upstream = gitOut(checkout, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
361
+ if (!upstream) return null
362
+ files = nameOnly(["diff", `${upstream}..HEAD`])
363
+ } else {
364
+ // merge/rebase/am/cherry-pick/revert/reset/clean/stash are not the docs
365
+ // maintenance carve-out — block them conservatively.
366
+ return null
367
+ }
368
+ if (files == null) return null
369
+ return files
370
+ .split(/\r?\n/)
371
+ .filter(Boolean)
372
+ .some((p) => guard.isCodePath(p))
373
+ }
374
+
375
+ /* Tools whose args name the file they write. `patch`/`apply_patch` may carry
376
+ * only a diff, in which case the target is unknown and the guard stands
377
+ * down — the edit/write paths still cover the F-278 shape. */
378
+ const EDIT_TOOLS = new Set(["edit", "write", "patch", "multiedit", "apply_patch"])
379
+
380
+ /* Best-effort board convergence at session start: the main checkout drifts
381
+ * behind `origin/main` while features land from their worktrees, so a stale
382
+ * BACKLOG.md can show a shipped row as Open. Fire-and-forget (never blocks
383
+ * session creation, never throws into the hook); a linked worktree no-ops in
384
+ * `backlog sync`. */
385
+ const syncBoard = () => {
386
+ try {
387
+ const script = path.join(directory, "scripts", "backlog.js")
388
+ if (!fs.existsSync(script)) return
389
+ const child = spawn(toolLib.nodeBin(), [script, "sync"], {
390
+ cwd: directory,
391
+ stdio: "ignore",
392
+ detached: true,
393
+ })
394
+ child.on("error", () => {})
395
+ child.unref()
396
+ } catch {
397
+ /* best-effort */
398
+ }
399
+ }
400
+
401
+ /* Session-start orientation injection. A resume/claim session otherwise spends
402
+ * its prologue re-deriving git/serve/capacity state and re-reading the
403
+ * session-start memory files (the 2026-10 LibraryOS recon measured a 24-call
404
+ * average prologue across 193 sessions and `serve.js list` 91×). Run the
405
+ * one-call `orient --brief` OFF the event loop (async — it spawns git/backlog)
406
+ * and stash its text on the session state; the transform injects it into the
407
+ * cache-safe tail until the first material action clears it. Best-effort:
408
+ * a missing script or a failed spawn injects nothing and never blocks. */
409
+ const collectOrient = async (sid: string, root: string) => {
410
+ try {
411
+ const script = path.join(root, "scripts", "orient.js")
412
+ if (!fs.existsSync(script)) return
413
+ const res = await toolLib.runScriptAsync(
414
+ { directory: root, sessionID: sid },
415
+ "scripts/orient.js",
416
+ ["--brief", "--root", root],
417
+ { label: "orient", timeout: 25000 }
418
+ )
419
+ const text = String(res.stdout || "").trim()
420
+ if (res.code !== 0 || !text) return
421
+ const state = stateFor(sid)
422
+ state.orientText = text
423
+ state.orientPending = true
424
+ logEvent({ kind: "orient", sessionID: sid, bytes: text.length })
425
+ } catch {
426
+ /* best-effort — orientation is an accelerator, never a gate */
427
+ }
428
+ }
429
+
430
+ // Sweep leases left by crashed/closed sessions so they can never block the
431
+ // concurrency gate. Runs once per plugin load (best-effort).
432
+ try {
433
+ const pruned = leases.pruneLeases(directory)
434
+ if (pruned.length) {
435
+ void report(`pruned ${pruned.length} stale session lease(s) in this tree`)
436
+ }
437
+ } catch {
438
+ /* best-effort */
439
+ }
440
+
441
+ /* V2 ModelRef ({ id, providerID, variant }) -> the shape `guard.modelLabel`
442
+ * reads ({ providerID, modelID }). Never invent a label. */
443
+ const modelFields = (m: any) =>
444
+ m && typeof m === "object" ? { providerID: m.providerID, modelID: m.id } : null
445
+
446
+ const hooks = {
447
+ event: async ({ event }: any) => {
448
+ try {
449
+ // V2 event envelope: { id, created, type, location, data }. The payload is
450
+ // `event.data` — V1's `properties` payload field does NOT exist in V2 — and
451
+ // several event NAMES changed (session.updated, message.updated,
452
+ // file.watcher.updated and session.error are gone). See
453
+ // docs/opencode-v2-event-remap-plan.md.
454
+ const type = event?.type
455
+ const d = event?.data || {}
456
+
457
+ /* A plugin instance is loaded per *location*, but V2's event stream is
458
+ * process-wide: every loaded instance receives EVERY session's events.
459
+ * Without this filter, a session in project A writes its leases and guard
460
+ * events into project B's checkout — measured 2026-10-16 on the same box:
461
+ * an agent-harness session held a lease in LibraryOS AND in the
462
+ * plugin-loader fixture, and logged guard events into both. That corrupts
463
+ * the live-session view `test:concurrency` and `worktree-prune` read
464
+ * ("in use by a live session") and mis-attributes a project's guard
465
+ * evidence. An event with no location is never dropped. */
466
+ if (!sameLocation(event)) return
467
+
468
+ if (type === "session.created") {
469
+ const sid = d.sessionID
470
+ if (typeof sid !== "string" || sid.length === 0) return
471
+ if (typeof d.location?.directory === "string" && d.location.directory) {
472
+ sessionRoots.set(sid, d.location.directory)
473
+ }
474
+ if (d.parentID) {
475
+ // A subagent dispatch. Track it so the guard never treats a persona
476
+ // session as the primary orchestrator (leases, tool blocks, and funds
477
+ // attribution all key off isPrimary/primaryRoot). A CHILD's
478
+ // session.created carries no `model`, so its funds label comes from
479
+ // `session.step.started` below.
480
+ childSessions.add(sid)
481
+ childParent.set(sid, d.parentID)
482
+ return
483
+ }
484
+ const label = guard.modelLabel(modelFields(d.model))
485
+ if (label) sessionModel.set(sid, label)
486
+ writeLease(sid)
487
+ syncBoard()
488
+ const root =
489
+ typeof d.location?.directory === "string" && d.location.directory
490
+ ? d.location.directory
491
+ : directory
492
+ void collectOrient(sid, root)
493
+ return
494
+ }
495
+
496
+ /* Per-step model capture. V1 stored the label from every assistant message
497
+ * (including children, which is what `armFunds`'s fallback needs); in V2 a
498
+ * child's `session.created` omits `model`, so `session.step.started` — which
499
+ * carries `{ agent, model }` for every session — is the reliable source. */
500
+ if (type === "session.step.started") {
501
+ const sid = d.sessionID
502
+ const label = guard.modelLabel(modelFields(d.model))
503
+ if (typeof sid === "string" && sid.length > 0 && label) sessionModel.set(sid, label)
504
+ return
505
+ }
506
+
507
+ // Keeps the funds-stop label current when the user switches model mid-session.
508
+ if (type === "session.model.selected") {
509
+ const sid = d.sessionID
510
+ const label = guard.modelLabel(modelFields(d.model))
511
+ if (typeof sid === "string" && sid.length > 0 && label) sessionModel.set(sid, label)
512
+ return
513
+ }
514
+
515
+ if (type === "session.deleted") {
516
+ const id = d.sessionID
517
+ if (id) {
518
+ clearLease(id)
519
+ childSessions.delete(id)
520
+ childParent.delete(id)
521
+ sessionModel.delete(id)
522
+ sessions.delete(id)
523
+ sessionRoots.delete(id)
524
+ // Auto-close this session's long-lived serves (dev server/emulator):
525
+ // the harness must not leave them orphaned after the session ends.
526
+ // Detached + best-effort; `reap` never touches a live owner's serve.
527
+ try {
528
+ const serve = path.join(rootOf(id), "scripts", "serve.js")
529
+ if (fs.existsSync(serve)) {
530
+ spawn(process.execPath, [serve, "reap"], {
531
+ cwd: directory,
532
+ detached: true,
533
+ stdio: "ignore",
534
+ }).unref()
535
+ }
536
+ } catch {
537
+ /* reaping is best-effort */
538
+ }
539
+ }
540
+ return
541
+ }
542
+
543
+ // One model call == one assistant message == one orchestrator turn. This is
544
+ // the V2 replacement for V1's `message.updated` (which no longer exists);
545
+ // `data.tokens` is the same TokenUsageInfo the pure core already reads.
546
+ if (type === "session.step.ended") {
547
+ const sid = d.sessionID
548
+ if (typeof sid !== "string" || sid.length === 0) return
549
+ if (!isPrimary(sid)) return
550
+ touchLease(sid)
551
+ const note = guard.noteAssistant(
552
+ stateFor(sid),
553
+ {
554
+ id: d.assistantMessageID,
555
+ sessionID: sid,
556
+ role: "assistant",
557
+ tokens: d.tokens,
558
+ },
559
+ loadThresholds()
560
+ )
561
+ // Not gated on `newTurn`: a token-band crossing must be logged whenever it
562
+ // actually changes.
563
+ if (note.bandChanged && note.band) {
564
+ logEvent({ kind: "band", sessionID: sid, band: note.band, turn: note.turns })
565
+ await report(`turn ${note.turns}: ${note.band} band`)
566
+ }
567
+ if (note.requestChanged && note.requestLevel) {
568
+ logEvent({
569
+ kind: "request",
570
+ sessionID: sid,
571
+ level: note.requestLevel,
572
+ tokens: note.requestTokens,
573
+ })
574
+ }
575
+ if (note.noStateChanged) {
576
+ logEvent({
577
+ kind: "no_state",
578
+ sessionID: sid,
579
+ turn: note.turns,
580
+ noStateTurns: note.noStateTurns,
581
+ })
582
+ await report(`turn ${note.turns}: no material state change across several turns`)
583
+ }
584
+ return
585
+ }
586
+
587
+ // V2 renamed `session.error`. The structured failure carries no
588
+ // provider/model (`SessionStructuredError` is `{ type, message, status?,
589
+ // response? }`), so the label comes from the per-session model observed
590
+ // on `session.step.started` (`sessionModel`), with `modelLabel` as a
591
+ // best-effort parse. Capture even for child sessions so the funds stop
592
+ // is armed on the session the user actually sees.
593
+ if (type === "session.execution.failed" || type === "session.step.failed") {
594
+ const sid = d.sessionID
595
+ if (typeof sid !== "string" || sid.length === 0) return
596
+ const text = JSON.stringify(d.error ?? d)
597
+ if (!guard.fundsError(text)) return
598
+ const label = guard.modelLabel(d.error) || sessionModel.get(sid) || null
599
+ await armFunds(sid, label, type)
600
+ return
601
+ }
602
+ } catch {
603
+ /* the guard must never break a session */
604
+ }
605
+ },
606
+
607
+ "tool.execute.before": async (input: any, output: any) => {
608
+ // Branch-switch guard. This MUST throw to abort the tool call, so it lives
609
+ // OUTSIDE the swallow-everything loop-guard try/catch below. It is armed
610
+ // only when another LIVE primary lease shares this checkout: a
611
+ // `git checkout`/`git switch` here would move HEAD under that session,
612
+ // which could then commit/push on the wrong branch (LibraryOS 2026-09-18).
613
+ if (isPrimary(input?.sessionID)) {
614
+ let target: any = null
615
+ try {
616
+ target = guard.branchSwitch(output?.args?.command)
617
+ } catch {
618
+ target = null
619
+ }
620
+ if (target) {
621
+ let others: any[] = []
622
+ try {
623
+ others = leases
624
+ .liveLeases(directory)
625
+ .filter((r: any) => r.sessionID !== input.sessionID)
626
+ } catch {
627
+ others = []
628
+ }
629
+ if (others.length > 0) {
630
+ const ids = others.map((r: any) => r.sessionID)
631
+ logEvent({ kind: "branch-switch", sessionID: input.sessionID, ref: target.ref, others: ids })
632
+ const message = guard.branchSwitchText(target.ref, ids)
633
+ await report(message)
634
+ throw new Error(message)
635
+ }
636
+ }
637
+ }
638
+ // `pkill -f` self-kill guard. A `-f` pattern that matches its own
639
+ // `bash -c` line SIGTERMs the shell running it — the turn dies mid-step and
640
+ // in-flight work is lost (and once it killed the shared opencode service).
641
+ // Block it and hand back the safe form. MUST throw to abort, so it lives
642
+ // OUTSIDE the swallow-everything loop-guard try/catch below.
643
+ if (isShell(input?.tool)) {
644
+ let selfKill: string | null = null
645
+ try {
646
+ selfKill = guard.shellSelfKill(output?.args?.command)
647
+ } catch {
648
+ selfKill = null
649
+ }
650
+ if (selfKill) {
651
+ logEvent({ kind: "self-kill", sessionID: input?.sessionID, pattern: selfKill })
652
+ const message = guard.SELFKILL_TEXT(selfKill)
653
+ await report(message)
654
+ throw new Error(message)
655
+ }
656
+ }
657
+ // Bash reroot (ALL sessions, best-effort, never blocks). A leading
658
+ // `cd X && rest` becomes workdir=X, command=rest, so the tree is carried by
659
+ // the tool's cwd parameter instead of a shell `cd` — the WSL `cd`-chaining
660
+ // habit (2,981 calls / 388 sessions). When the session owns a mid-session
661
+ // worktree pointer and the command carries no workdir/cd, the default cwd is
662
+ // rerooted into it, so bash matches the session's feature tree instead of the
663
+ // MAIN tree opencode pinned at launch. Runs BEFORE the main-checkout guard so
664
+ // that classifier sees the rewritten command.
665
+ if (isShell(input?.tool)) {
666
+ try {
667
+ const args = output?.args || {}
668
+ if (!args.workdir) {
669
+ const root = sessionBashRoot(String(input?.sessionID || ""))
670
+ const rerooted = guard.rerootBash(String(args.command || ""))
671
+ if (rerooted && (root || /^(?:~\/|\/)/.test(rerooted.workdir))) {
672
+ const target = path.resolve(expandHome(rerooted.workdir))
673
+ args.workdir = target
674
+ args.command = rerooted.command
675
+ logEvent({ kind: "reroot", sessionID: input?.sessionID, via: "cd", dir: target })
676
+ } else if (root) {
677
+ args.workdir = root
678
+ logEvent({ kind: "reroot", sessionID: input?.sessionID, via: "worktree", dir: root })
679
+ }
680
+ }
681
+ } catch {
682
+ /* best-effort — a reroot failure must never break the tool call */
683
+ }
684
+ }
685
+ // Main-checkout guard (ALL sessions, including subagents). A code change
686
+ // or code-carrying git mutation aimed at the shared MAIN checkout must
687
+ // isolate first (`backlog worktree <id>`), or the work is stranded exactly
688
+ // like F-278: `finalize` refuses on main and the branch switch is blocked
689
+ // while other sessions share the tree. Docs/board maintenance on main is
690
+ // allowed, so a git op is judged by the PATHS it actually moves — the
691
+ // explicit pathspecs when present, the live index/upstream diff for a
692
+ // whole-index `commit`/`push` — against the checkout the command selects
693
+ // (`git -C <main>` is resolved, not bypassed via an unrelated cwd).
694
+ //
695
+ // FRICTIONLESS RECOVERY (the 43 main-edit blocks / 24 sessions measured in
696
+ // the 2026-09 recon): when the session ALREADY owns a feature worktree, a
697
+ // code change aimed at main is silently REROOTED into that worktree
698
+ // (`workdir`/`-C` rewritten) and allowed — the isolation the agent should
699
+ // have done is done for it, so the common "meant to be in the worktree"
700
+ // case never strands work. Only when NO worktree exists does the guard
701
+ // still refuse, now with the exact `backlog worktree <id>` command to run
702
+ // (never a bare error). Auto-CREATING a worktree stays opt-in via
703
+ // `.harness.json` `autoIsolate` (default off) — the guard must not invent a
704
+ // branch/branch-name on its own. This MUST throw to abort when it refuses,
705
+ // so it lives OUTSIDE the swallow-everything loop-guard try/catch below.
706
+ let mainViolation: { kind: "edit" | "bash"; target: string } | null = null
707
+ // A dogfood install (the harness source checkout running its own guard) edits
708
+ // `templates/**` on main by design, so the main-checkout block is skipped
709
+ // there via the `.harness-dogfood` marker. Every other tree is unchanged.
710
+ const dogfood = !guard.mainEditGuardEnabled(
711
+ path.join(rootOf(String(input?.sessionID || "")), guard.DOGFOOD_MARKER),
712
+ fs.existsSync
713
+ )
714
+ if (!dogfood) {
715
+ try {
716
+ const tool = String(input?.tool || "").toLowerCase()
717
+ const args = output?.args || {}
718
+ const isEdit = EDIT_TOOLS.has(tool)
719
+ const isBash = isShell(tool)
720
+ if (isEdit) {
721
+ if (args.filePath && guard.isCodePath(args.filePath)) {
722
+ const base = path.resolve(String(args.workdir || directory))
723
+ const targetAbs = path.resolve(base, String(args.filePath))
724
+ if (checkoutKind(targetAbs) === "main") {
725
+ mainViolation = { kind: "edit", target: targetAbs }
726
+ }
727
+ }
728
+ } else if (isBash) {
729
+ const { contentCode, gitOps } = guard.classifyCommand(args.command)
730
+ const base = path.resolve(String(args.workdir || directory))
731
+ // Content mutators (`sed -i`/`tee`/redirect) name their own path in the
732
+ // command; the checkout is the command cwd.
733
+ if (contentCode && checkoutKind(base) === "main") {
734
+ mainViolation = { kind: "bash", target: base }
735
+ }
736
+ if (!mainViolation) {
737
+ for (const op of gitOps) {
738
+ const checkout = path.resolve(base, String(op.target || "."))
739
+ if (checkoutKind(checkout) !== "main") continue
740
+ const code = op.pathless
741
+ ? gitOpTouchesCode(checkout, op)
742
+ : op.paths.some((p: string) => guard.isCodePath(p))
743
+ if (code !== false) {
744
+ // true = code; null = indeterminate -> block conservatively.
745
+ mainViolation = { kind: "bash", target: checkout }
746
+ break
747
+ }
748
+ }
749
+ }
750
+ }
751
+ } catch {
752
+ mainViolation = null
753
+ }
754
+ }
755
+ if (mainViolation) {
756
+ // Recover by rerooting into the session's own feature worktree when it
757
+ // has one (see FRICTIONLESS RECOVERY above). A git `-C <main>` selector
758
+ // is rewritten to the worktree; an edit's `workdir` is set to it.
759
+ const reroot = sessionBashRoot(String(input?.sessionID || ""))
760
+ if (reroot && checkoutKind(reroot) === "linked") {
761
+ try {
762
+ const args = output?.args || {}
763
+ if (mainViolation.kind === "edit") {
764
+ args.workdir = reroot
765
+ } else {
766
+ args.workdir = reroot
767
+ // Rewrite an explicit `git -C <main>` to the worktree so the op
768
+ // applies to the isolated checkout, not the shared main tree.
769
+ args.command = String(args.command || "").replace(
770
+ /(git\s+(?:-C|--work-tree[= ])\s*)("[^"]*"|'[^']*'|\S+)/g,
771
+ (m, pre) => pre + JSON.stringify(reroot)
772
+ )
773
+ }
774
+ logEvent({
775
+ kind: "reroot",
776
+ sessionID: input?.sessionID,
777
+ via: "isolate",
778
+ dir: reroot,
779
+ })
780
+ } catch {
781
+ /* best-effort — if the reroot fails, fall through to the refusal */
782
+ }
783
+ return
784
+ }
785
+ // No worktree yet: refuse, but hand back the exact isolating command.
786
+ const feature = inferBoardFeature(String(input?.sessionID || ""))
787
+ logEvent({
788
+ kind: "main-edit",
789
+ sessionID: input?.sessionID,
790
+ tool: String(input?.tool || ""),
791
+ target: mainViolation.kind === "edit" ? mainViolation.target : null,
792
+ commandHash:
793
+ mainViolation.kind === "bash" ? guard.shortHash(String(output?.args?.command || "")) : null,
794
+ })
795
+ const targetRepo = repoRootOf(mainViolation.target)
796
+ const sessionRepo = repoRootOf(directory)
797
+ const crossRepo = !!targetRepo && !!sessionRepo && targetRepo !== sessionRepo
798
+ const message = guard.mainEditText(mainViolation.kind, mainViolation.target, feature, { crossRepo })
799
+ await report(message)
800
+ throw new Error(message)
801
+ }
802
+ // Capacity guard. WSL2 is one VM with no per-agent limits: an emulator +
803
+ // agents + `next dev` exhausts RAM and starves the host<->VM relay, which
804
+ // froze every terminal at once (2026-09-29). A heavy command is sampled
805
+ // against the project envelope and BLOCKED when it would exceed it
806
+ // (naming what is already up); `--force` / AGENT_CAPACITY_DISABLE are the
807
+ // deliberate overrides. This MUST throw to abort the tool call, so it
808
+ // lives outside the swallow-everything loop-guard try/catch; only the
809
+ // sampling is wrapped. A trivial command is never gated.
810
+ //
811
+ // Long-lived heavy commands (emulator/dev server/metro) add a concurrent
812
+ // tier; a ONE-SHOT heavy command (a build, a test tier, `maestro`) does
813
+ // not — it legitimately runs alongside the live device tier (the
814
+ // live-tier test pattern), so it is gated only by the free-RAM floor. The
815
+ // 2026-09-30 freeze was a one-shot `build-dev-apk.sh` (Gradle) that ran
816
+ // inline, uncapped and unclassified — the old code blocked only
817
+ // `serve.js start`, so it sailed through.
818
+ let capViolation: { label: string; ev: any; sample: any } | null = null
819
+ let capNotice: string | null = null
820
+ let capCommand = ""
821
+ try {
822
+ if (
823
+ isShell(input?.tool) &&
824
+ process.env.AGENT_CAPACITY_DISABLE !== "1"
825
+ ) {
826
+ capCommand = String(output?.args?.command || "")
827
+ const label = capacity.classifyHeavy(capCommand)
828
+ if (label) {
829
+ const sample = capacity.sample(directory)
830
+ const longLived = capacity.isLongLivedHeavy(capCommand)
831
+ const ev = capacity.evaluate(sample, {
832
+ pendingHeavy: longLived ? 1 : 0,
833
+ pendingLive: longLived ? 1 : 0,
834
+ })
835
+ const forced = /--force\b/.test(capCommand)
836
+ if (!ev.ok && !forced) capViolation = { label, ev, sample }
837
+ else if (!ev.ok) capNotice = capacity.notice(ev)
838
+ }
839
+ }
840
+ } catch {
841
+ /* capacity sampling is best-effort — never break a tool call */
842
+ }
843
+ if (capViolation) {
844
+ logEvent({
845
+ kind: "capacity",
846
+ sessionID: input?.sessionID,
847
+ label: capViolation.label,
848
+ reasons: capViolation.ev.reasons,
849
+ blocked: true,
850
+ })
851
+ const message = capacity.heavyBlockText(capViolation.label, capViolation.ev, capViolation.sample)
852
+ await report(message)
853
+ throw new Error(message)
854
+ }
855
+ if (isPrimary(input?.sessionID)) {
856
+ const state = stateFor(input.sessionID)
857
+ let blockMessage: string | null = null
858
+ const toolBlocking = guard.toolBlockEnabled(process.env)
859
+ if (capNotice) {
860
+ logEvent({
861
+ kind: "capacity",
862
+ sessionID: input.sessionID,
863
+ label: capacity.classifyHeavy(capCommand),
864
+ reasons: [],
865
+ blocked: false,
866
+ })
867
+ state.resourceNotice = capNotice
868
+ } else if (/serve\.js\s+(start|stop|stop-all)/.test(capCommand)) {
869
+ // A serve lifecycle op that did not trip the envelope clears the notice.
870
+ state.resourceNotice = null
871
+ }
872
+ // Tool-choice / whole-tree-dump / re-read hygiene (advisory, one-shot).
873
+ // Each kind is flagged once per session and rides the cache-safe tail; it
874
+ // is cleared after injection (`clearOneShot`), so it never nags.
875
+ try {
876
+ const tool = String(input?.tool || "").toLowerCase()
877
+ if (isShell(tool)) {
878
+ const command = String(output?.args?.command || "")
879
+ const inspect = guard.inspectCommand(command)
880
+ if (inspect) {
881
+ const rearm = guard.noteInspect(state, inspect, loadThresholds().stuck.inspect_rearm_every)
882
+ if (rearm.fire) {
883
+ logEvent({ kind: "tool-choice", sessionID: input.sessionID, tool: inspect, rearm: true, count: rearm.count })
884
+ }
885
+ // Structural escalation: block the first pure inspection of this
886
+ // head once, so the 0.1.104 advisory-only attempt cannot be ignored
887
+ // (measured: shell inspection stayed ~33% of bash two weeks later).
888
+ // A PURE single-path `cat`/`ls` is blocked on EVERY occurrence
889
+ // (H-23): Read/Glob is an exact substitute and the habit stayed
890
+ // flat across the re-measure window.
891
+ const repeat = toolBlocking ? guard.repeatInspectBlock(command) : null
892
+ if (repeat) {
893
+ blockMessage = guard.inspectBlockText(repeat)
894
+ } else if (toolBlocking && !state.blockedInspectHeads.has(inspect)) {
895
+ state.blockedInspectHeads.add(inspect)
896
+ blockMessage = guard.inspectBlockText(inspect)
897
+ }
898
+ }
899
+ const dump = guard.dumpCommand(command)
900
+ if (dump && !state.dumpFlagged) {
901
+ state.dumpFlagged = true
902
+ state.dumpPending = true
903
+ logEvent({ kind: "tool-choice", sessionID: input.sessionID, tool: dump, dump: true })
904
+ }
905
+ // Wait/poll advisory (B): `sleep N; grep log` / `gh run watch`.
906
+ const poll = guard.notePollCall(state, command)
907
+ if (poll.firstFlag) {
908
+ logEvent({ kind: "poll", sessionID: input.sessionID, mode: poll.kind })
909
+ }
910
+ if (poll.poll && toolBlocking && !state.blockedPollKinds.has(poll.kind)) {
911
+ state.blockedPollKinds.add(poll.kind)
912
+ blockMessage = blockMessage || guard.pollBlockText(poll.kind)
913
+ }
914
+ // Gate re-run advisory (F): same gate repeated with no edit between.
915
+ const gate = guard.noteGateRun(state, command, loadThresholds().stuck.gate_rerun_turns)
916
+ if (gate.fire) {
917
+ logEvent({ kind: "gate-rerun", sessionID: input.sessionID, gate: gate.key, count: gate.count })
918
+ }
919
+ } else if (tool === "read") {
920
+ const note = guard.noteReadBefore(state, output?.args?.filePath)
921
+ if (note.firstFlag) logEvent({ kind: "read", sessionID: input.sessionID, notice: "reread" })
922
+ }
923
+ } catch {
924
+ /* never break the tool call */
925
+ }
926
+ // The structural tool blocks throw OUTSIDE the swallow-everything block
927
+ // above (like the branch-switch/capacity guards), so the blocked call is
928
+ // aborted and the agent retries with the dedicated tool / bounded waiter.
929
+ if (blockMessage) {
930
+ logEvent({ kind: "tool-block", sessionID: input.sessionID, message: blockMessage.slice(0, 120) })
931
+ await report(blockMessage)
932
+ throw new Error(blockMessage)
933
+ }
934
+ }
935
+ try {
936
+ if (!isPrimary(input?.sessionID)) return
937
+ touchLease(input.sessionID)
938
+ const note = guard.noteToolCall(
939
+ stateFor(input.sessionID),
940
+ input?.tool,
941
+ output?.args,
942
+ loadThresholds().stuck
943
+ )
944
+ if (note.firstFlag) {
945
+ logEvent({
946
+ kind: "loop",
947
+ sessionID: input.sessionID,
948
+ tool: String(input?.tool || ""),
949
+ count: note.count,
950
+ keyHash: note.keyHash,
951
+ })
952
+ await report(`repeated identical ${input?.tool} call x${note.count}`)
953
+ }
954
+ } catch {
955
+ /* never break the tool call */
956
+ }
957
+ },
958
+
959
+ "tool.execute.after": async (input: any, output: any) => {
960
+ try {
961
+ if (!isPrimary(input?.sessionID)) return
962
+ touchLease(input.sessionID)
963
+ // Read-hygiene notice: a guessed (failed) read or a large whole-file read
964
+ // arms a one-shot nudge (whole-file re-reads are handled in `before`).
965
+ if (String(input?.tool || "").toLowerCase() === "read") {
966
+ const note = guard.noteReadAfter(stateFor(input.sessionID), output?.args, output)
967
+ if (note.firstFlag) logEvent({ kind: "read", sessionID: input.sessionID, notice: note.notice })
968
+ }
969
+ // Todo-list discipline: remember the last list the model wrote so the
970
+ // next request can tell whether the panel is missing, stale, invalid, or
971
+ // still open at a wrap-up boundary. Recording only; the nudge text rides
972
+ // the cache-safe tail via composeGuardText.
973
+ if (String(input?.tool || "").toLowerCase() === "todowrite") {
974
+ const note = guard.noteTodoWrite(stateFor(input.sessionID), output?.args)
975
+ if (note.recorded) {
976
+ logEvent({
977
+ kind: "todo",
978
+ sessionID: input.sessionID,
979
+ count: note.count,
980
+ inProgress: note.inProgress,
981
+ open: note.open,
982
+ })
983
+ }
984
+ }
985
+ // Edit-miss advisory (E): a failed edit/write/apply_patch is a guessed or
986
+ // stale path — point at the locations index once per session.
987
+ {
988
+ const t = String(input?.tool || "").toLowerCase()
989
+ if (EDIT_TOOLS.has(t)) {
990
+ const failed = !!output?.error || String(output?.status || "") === "error"
991
+ const note = guard.noteEditAfter(stateFor(input.sessionID), failed)
992
+ if (note.firstFlag) logEvent({ kind: "edit-miss", sessionID: input.sessionID, tool: t })
993
+ }
994
+ }
995
+ // Only structured failure evidence may arm the funds stop (core gate): a
996
+ // successful read/grep/dispatch returning the harness's own docs — which
997
+ // quote the trigger phrases — must never pause a healthy session.
998
+ const armed = guard.fundsArmText(input?.tool, output)
999
+ if (armed && guard.fundsError(armed)) {
1000
+ const meta = output?.metadata || {}
1001
+ const label =
1002
+ guard.modelLabel(meta.model) || sessionModel.get(String(meta.sessionId || "")) || null
1003
+ await armFunds(input.sessionID, label, `tool:${input?.tool}`)
1004
+ return
1005
+ }
1006
+ // Same-failure detector: a failed call (a thrown error, or a bash
1007
+ // non-zero exit) records a failure signature; any success clears it.
1008
+ // Distinct from the identical-call counter — the same failure can
1009
+ // repeat with different arguments.
1010
+ const tool = input?.tool
1011
+ const exit = output?.metadata?.exit
1012
+ const failed =
1013
+ !!output?.error || (isShell(tool) && Number.isFinite(exit) && exit !== 0)
1014
+ const failureText = output?.error
1015
+ ? String(output.error)
1016
+ : failed && typeof output?.output === "string"
1017
+ ? output.output
1018
+ : ""
1019
+ const note = guard.noteToolResult(
1020
+ stateFor(input.sessionID),
1021
+ tool,
1022
+ output?.args,
1023
+ !failed,
1024
+ failureText,
1025
+ loadThresholds().stuck
1026
+ )
1027
+ if (note.firstFlag) {
1028
+ logEvent({
1029
+ kind: "failure",
1030
+ sessionID: input.sessionID,
1031
+ tool: String(tool || ""),
1032
+ count: note.count,
1033
+ keyHash: note.keyHash,
1034
+ })
1035
+ await report(`same failure repeated x${note.count} (${tool})`)
1036
+ }
1037
+ } catch {
1038
+ /* never break the tool call */
1039
+ }
1040
+ },
1041
+
1042
+ // Cache-safe nudge injection is registered as the V2 `context` session hook
1043
+ // below (see `onContext`); the V1 `experimental.chat.messages.transform`
1044
+ // shape no longer exists.
1045
+ }
1046
+
1047
+ /* V1 tool-result shape adapter: the hook bodies above keep the V1
1048
+ * (input, output) contract; the V2 tool event carries a structured result. */
1049
+ const v1Result = (event: any) => {
1050
+ const completed = event?.status === "completed"
1051
+ const content = completed
1052
+ ? typeof event?.result?.content === "string"
1053
+ ? event.result.content
1054
+ : Array.isArray(event?.result?.content)
1055
+ ? event.result.content.map((p: any) => p?.text || "").join("")
1056
+ : ""
1057
+ : ""
1058
+ return {
1059
+ args: event?.input,
1060
+ status: event?.status,
1061
+ error: completed ? undefined : event?.error,
1062
+ output: content,
1063
+ metadata: completed ? event?.result?.metadata : event?.error?.metadata,
1064
+ }
1065
+ }
1066
+
1067
+ /* V2 replacement for the V1 messages transform: OpenCode hands the request
1068
+ * session and a structured Message[] directly, so we append a synthetic tail
1069
+ * message (role user) and never touch the cached leading prefix. */
1070
+ const onContext = (event: any) => {
1071
+ try {
1072
+ const sid = event?.sessionID
1073
+ if (!sessionOurs(sid)) return
1074
+ if (!isPrimary(sid)) return
1075
+ const messages = event?.messages
1076
+ if (!Array.isArray(messages)) return
1077
+ const state = stateFor(sid)
1078
+ // The capacity notice (set by the heavy-launch guard) rides the same
1079
+ // cache-safe tail message as the context-budget nudges; the session-start
1080
+ // orientation block rides it too until the first material action.
1081
+ const text = [
1082
+ guard.composeGuardText(state, loadThresholds()),
1083
+ state.orientPending ? state.orientText : null,
1084
+ state.resourceNotice,
1085
+ ]
1086
+ .filter(Boolean)
1087
+ .join("\n\n")
1088
+ if (!text) return
1089
+ // The tool-choice / read / dump notices are one-shot: once injected, clear
1090
+ // them so they never nag on later requests (bands/funds/loop persist).
1091
+ guard.clearOneShot(state)
1092
+ const last = messages[messages.length - 1]
1093
+ if (last?.id === GUARD_MESSAGE_ID) {
1094
+ // Same turn, re-request (e.g. a band advanced): update in place.
1095
+ const part = (last.content || []).find((p: any) => p?.type === "text")
1096
+ if (part && part.text !== text) part.text = text
1097
+ return
1098
+ }
1099
+ messages.push({
1100
+ id: GUARD_MESSAGE_ID,
1101
+ role: "user",
1102
+ content: [{ type: "text", text }],
1103
+ metadata: { synthetic: true },
1104
+ })
1105
+ } catch {
1106
+ /* never break a request */
1107
+ }
1108
+ }
1109
+
1110
+ // ---- V2 registration ----
1111
+ // The event stream replaces the V1 `event` hook; the tool hooks are driven
1112
+ // through the V1-shaped bodies above via thin adapters so the pure core
1113
+ // contract is unchanged. The V1 `permission.ask` hook is gone, but V2 does
1114
+ // expose `ctx.permission.hook("evaluate")`; only the built-in `doom_loop`
1115
+ // action was removed, so the core's loop guard is no longer mirrored onto the
1116
+ // permission layer. (Rebuild it on the `evaluate` hook if the runtime mirror
1117
+ // is wanted back — the evaluate hook is present in `permission.d.ts`.)
1118
+ void (async () => {
1119
+ try {
1120
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
1121
+ try {
1122
+ await hooks.event({ event })
1123
+ } catch {
1124
+ /* never break the stream */
1125
+ }
1126
+ }
1127
+ } catch {
1128
+ /* subscription unavailable/ended */
1129
+ }
1130
+ })()
1131
+ await ctx.tool.hook("execute.before", async (event: any) => {
1132
+ if (!sessionOurs(event?.sessionID)) return
1133
+ await hooks["tool.execute.before"](
1134
+ { tool: event?.tool, sessionID: event?.sessionID },
1135
+ { args: event?.input }
1136
+ )
1137
+ })
1138
+ await ctx.tool.hook("execute.after", async (event: any) => {
1139
+ if (!sessionOurs(event?.sessionID)) return
1140
+ await hooks["tool.execute.after"](
1141
+ { tool: event?.tool, sessionID: event?.sessionID },
1142
+ v1Result(event)
1143
+ )
1144
+ })
1145
+ await ctx.session.hook("context", onContext)
1146
+ await ctx.session.hook("prompt", (event: any) => {
1147
+ try {
1148
+ // A real user turn releases the provider funds stop (the top-up-complete
1149
+ // message). This is the V2 replacement for the dead `message.updated`
1150
+ // role==="user" branch. Synthetic/shell/compaction submissions do not fire
1151
+ // this hook, so the stop cannot be cleared by the harness's own traffic.
1152
+ const sid = event?.sessionID
1153
+ if (!sessionOurs(sid)) return
1154
+ if (!isPrimary(sid)) return
1155
+ const state = stateFor(sid as string)
1156
+ state.fundsPending = false
1157
+ state.fundsNotice = null
1158
+ } catch {
1159
+ /* never break a prompt */
1160
+ }
1161
+ })
1162
+ return () => controller.abort()
1163
+ },
1164
+ }