@bonesofspring/ai-rules 0.2.66 → 0.2.67

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 (183) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +2 -0
  3. package/bin/cli.js +9 -1
  4. package/bin/lib/engine-scripts.js +0 -4
  5. package/bin/lib/seed-ai-local-team.js +26 -0
  6. package/docs/OPENCODE-COMPATIBILITY.md +1 -0
  7. package/docs/OPENCODE.md +14 -1
  8. package/docs/TEAM-DB.md +2 -1
  9. package/docs/TOKEN-ECONOMY.md +32 -1
  10. package/docs/openapi/team-db.v1.json +5 -5
  11. package/package.json +10 -2
  12. package/presets/_shared/ai-local/scripts/dump-output.mjs +63 -12
  13. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +3 -3
  14. package/presets/_shared/ai-local/scripts/team-db-tracker.mjs +2 -0
  15. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +9 -2
  16. package/presets/_shared/hooks/list-ai-local.mjs +17 -0
  17. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +9 -2
  18. package/presets/claude/android-kotlin/hooks/list-ai-local.mjs +17 -0
  19. package/presets/claude/go/hooks/chain-team-phases.sh +9 -2
  20. package/presets/claude/go/hooks/list-ai-local.mjs +17 -0
  21. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +9 -2
  22. package/presets/claude/ios-swift/hooks/list-ai-local.mjs +17 -0
  23. package/presets/claude/java/hooks/chain-team-phases.sh +9 -2
  24. package/presets/claude/java/hooks/list-ai-local.mjs +17 -0
  25. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +9 -2
  26. package/presets/claude/mcp-ts/hooks/list-ai-local.mjs +17 -0
  27. package/presets/claude/mol/hooks/chain-team-phases.sh +9 -2
  28. package/presets/claude/mol/hooks/list-ai-local.mjs +17 -0
  29. package/presets/claude/next/agents/ci-investigator.md +5 -2
  30. package/presets/claude/next/agents/debugger.md +5 -2
  31. package/presets/claude/next/agents/feature-developer.md +5 -2
  32. package/presets/claude/next/hooks/chain-team-phases.sh +9 -2
  33. package/presets/claude/next/hooks/list-ai-local.mjs +17 -0
  34. package/presets/claude/next/rules/architecture/feature-delivery-workflow.md +4 -0
  35. package/presets/claude/nuxt/hooks/chain-team-phases.sh +9 -2
  36. package/presets/claude/nuxt/hooks/list-ai-local.mjs +17 -0
  37. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +9 -2
  38. package/presets/claude/php-hexagonal/hooks/list-ai-local.mjs +17 -0
  39. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +9 -2
  40. package/presets/claude/php-laravel/hooks/list-ai-local.mjs +17 -0
  41. package/presets/claude/svelte/hooks/chain-team-phases.sh +9 -2
  42. package/presets/claude/svelte/hooks/list-ai-local.mjs +17 -0
  43. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +9 -2
  44. package/presets/cursor/android-kotlin/hooks/list-ai-local.mjs +17 -0
  45. package/presets/cursor/go/hooks/chain-team-phases.sh +9 -2
  46. package/presets/cursor/go/hooks/list-ai-local.mjs +17 -0
  47. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +9 -2
  48. package/presets/cursor/ios-swift/hooks/list-ai-local.mjs +17 -0
  49. package/presets/cursor/java/hooks/chain-team-phases.sh +9 -2
  50. package/presets/cursor/java/hooks/list-ai-local.mjs +17 -0
  51. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +9 -2
  52. package/presets/cursor/mcp-ts/hooks/list-ai-local.mjs +17 -0
  53. package/presets/cursor/mol/hooks/chain-team-phases.sh +9 -2
  54. package/presets/cursor/mol/hooks/list-ai-local.mjs +17 -0
  55. package/presets/cursor/next/hooks/chain-team-phases.sh +9 -2
  56. package/presets/cursor/next/hooks/list-ai-local.mjs +17 -0
  57. package/presets/cursor/next/rules/feature-delivery-workflow.mdc +4 -0
  58. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +9 -2
  59. package/presets/cursor/nuxt/hooks/list-ai-local.mjs +17 -0
  60. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +9 -2
  61. package/presets/cursor/php-hexagonal/hooks/list-ai-local.mjs +17 -0
  62. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +9 -2
  63. package/presets/cursor/php-laravel/hooks/list-ai-local.mjs +17 -0
  64. package/presets/cursor/svelte/hooks/chain-team-phases.sh +9 -2
  65. package/presets/cursor/svelte/hooks/list-ai-local.mjs +17 -0
  66. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  67. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +9 -2
  68. package/presets/mavis/android-kotlin/hooks/list-ai-local.mjs +17 -0
  69. package/presets/mavis/go/adapter-map.json +1 -1
  70. package/presets/mavis/go/hooks/chain-team-phases.sh +9 -2
  71. package/presets/mavis/go/hooks/list-ai-local.mjs +17 -0
  72. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  73. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +9 -2
  74. package/presets/mavis/ios-swift/hooks/list-ai-local.mjs +17 -0
  75. package/presets/mavis/java/adapter-map.json +1 -1
  76. package/presets/mavis/java/hooks/chain-team-phases.sh +9 -2
  77. package/presets/mavis/java/hooks/list-ai-local.mjs +17 -0
  78. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  79. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +9 -2
  80. package/presets/mavis/mcp-ts/hooks/list-ai-local.mjs +17 -0
  81. package/presets/mavis/mol/adapter-map.json +1 -1
  82. package/presets/mavis/mol/hooks/chain-team-phases.sh +9 -2
  83. package/presets/mavis/mol/hooks/list-ai-local.mjs +17 -0
  84. package/presets/mavis/next/adapter-map.json +1 -1
  85. package/presets/mavis/next/agents/ci-investigator.md +5 -2
  86. package/presets/mavis/next/agents/debugger.md +5 -2
  87. package/presets/mavis/next/agents/feature-developer.md +5 -2
  88. package/presets/mavis/next/hooks/chain-team-phases.sh +9 -2
  89. package/presets/mavis/next/hooks/list-ai-local.mjs +17 -0
  90. package/presets/mavis/next/rules/feature-delivery-workflow.md +4 -0
  91. package/presets/mavis/nuxt/adapter-map.json +1 -1
  92. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +9 -2
  93. package/presets/mavis/nuxt/hooks/list-ai-local.mjs +17 -0
  94. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  95. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +9 -2
  96. package/presets/mavis/php-hexagonal/hooks/list-ai-local.mjs +17 -0
  97. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  98. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +9 -2
  99. package/presets/mavis/php-laravel/hooks/list-ai-local.mjs +17 -0
  100. package/presets/mavis/svelte/adapter-map.json +1 -1
  101. package/presets/mavis/svelte/hooks/chain-team-phases.sh +9 -2
  102. package/presets/mavis/svelte/hooks/list-ai-local.mjs +17 -0
  103. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  104. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +9 -2
  105. package/presets/opencode/android-kotlin/hooks/list-ai-local.mjs +17 -0
  106. package/presets/opencode/go/adapter-map.json +1 -1
  107. package/presets/opencode/go/hooks/chain-team-phases.sh +9 -2
  108. package/presets/opencode/go/hooks/list-ai-local.mjs +17 -0
  109. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  110. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +9 -2
  111. package/presets/opencode/ios-swift/hooks/list-ai-local.mjs +17 -0
  112. package/presets/opencode/java/adapter-map.json +1 -1
  113. package/presets/opencode/java/hooks/chain-team-phases.sh +9 -2
  114. package/presets/opencode/java/hooks/list-ai-local.mjs +17 -0
  115. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  116. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +9 -2
  117. package/presets/opencode/mcp-ts/hooks/list-ai-local.mjs +17 -0
  118. package/presets/opencode/mol/adapter-map.json +1 -1
  119. package/presets/opencode/mol/hooks/chain-team-phases.sh +9 -2
  120. package/presets/opencode/mol/hooks/list-ai-local.mjs +17 -0
  121. package/presets/opencode/next/adapter-map.json +1 -1
  122. package/presets/opencode/next/agents/ci-investigator.md +5 -2
  123. package/presets/opencode/next/agents/debugger.md +5 -2
  124. package/presets/opencode/next/agents/feature-developer.md +5 -2
  125. package/presets/opencode/next/hooks/chain-team-phases.sh +9 -2
  126. package/presets/opencode/next/hooks/list-ai-local.mjs +17 -0
  127. package/presets/opencode/next/rules/feature-delivery-workflow.md +4 -0
  128. package/presets/opencode/nuxt/adapter-map.json +1 -1
  129. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +9 -2
  130. package/presets/opencode/nuxt/hooks/list-ai-local.mjs +17 -0
  131. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  132. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +9 -2
  133. package/presets/opencode/php-hexagonal/hooks/list-ai-local.mjs +17 -0
  134. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  135. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +9 -2
  136. package/presets/opencode/php-laravel/hooks/list-ai-local.mjs +17 -0
  137. package/presets/opencode/plugins/output-guard/README.md +43 -0
  138. package/presets/opencode/plugins/output-guard/index.ts +300 -0
  139. package/presets/opencode/plugins/output-guard/package.json +9 -0
  140. package/presets/opencode/plugins/output-guard/rewrite.ts +149 -0
  141. package/presets/opencode/plugins/task-status/task-view.ts +58 -20
  142. package/presets/opencode/plugins/task-status/tui.tsx +5 -3
  143. package/presets/opencode/svelte/adapter-map.json +1 -1
  144. package/presets/opencode/svelte/hooks/chain-team-phases.sh +9 -2
  145. package/presets/opencode/svelte/hooks/list-ai-local.mjs +17 -0
  146. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  147. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +9 -2
  148. package/presets/zcode/android-kotlin/hooks/list-ai-local.mjs +17 -0
  149. package/presets/zcode/go/adapter-map.json +1 -1
  150. package/presets/zcode/go/hooks/chain-team-phases.sh +9 -2
  151. package/presets/zcode/go/hooks/list-ai-local.mjs +17 -0
  152. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  153. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +9 -2
  154. package/presets/zcode/ios-swift/hooks/list-ai-local.mjs +17 -0
  155. package/presets/zcode/java/adapter-map.json +1 -1
  156. package/presets/zcode/java/hooks/chain-team-phases.sh +9 -2
  157. package/presets/zcode/java/hooks/list-ai-local.mjs +17 -0
  158. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  159. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +9 -2
  160. package/presets/zcode/mcp-ts/hooks/list-ai-local.mjs +17 -0
  161. package/presets/zcode/mol/adapter-map.json +1 -1
  162. package/presets/zcode/mol/hooks/chain-team-phases.sh +9 -2
  163. package/presets/zcode/mol/hooks/list-ai-local.mjs +17 -0
  164. package/presets/zcode/next/adapter-map.json +1 -1
  165. package/presets/zcode/next/agents/ci-investigator.md +5 -2
  166. package/presets/zcode/next/agents/debugger.md +5 -2
  167. package/presets/zcode/next/agents/feature-developer.md +5 -2
  168. package/presets/zcode/next/hooks/chain-team-phases.sh +9 -2
  169. package/presets/zcode/next/hooks/list-ai-local.mjs +17 -0
  170. package/presets/zcode/next/rules/feature-delivery-workflow.md +4 -0
  171. package/presets/zcode/nuxt/adapter-map.json +1 -1
  172. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +9 -2
  173. package/presets/zcode/nuxt/hooks/list-ai-local.mjs +17 -0
  174. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  175. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +9 -2
  176. package/presets/zcode/php-hexagonal/hooks/list-ai-local.mjs +17 -0
  177. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  178. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +9 -2
  179. package/presets/zcode/php-laravel/hooks/list-ai-local.mjs +17 -0
  180. package/presets/zcode/svelte/adapter-map.json +1 -1
  181. package/presets/zcode/svelte/hooks/chain-team-phases.sh +9 -2
  182. package/presets/zcode/svelte/hooks/list-ai-local.mjs +17 -0
  183. package/scripts/report-context-cost.mjs +432 -0
@@ -0,0 +1,300 @@
1
+ /**
2
+ * OpenCode output guard: keeps a large tool result out of the context window.
3
+ *
4
+ * The `context` hook receives the assembled model messages before dispatch.
5
+ * A `tool-result` over the threshold is written to
6
+ * `.ai.local/team/output-guard/<session>/outputs/` and replaced with a bounded
7
+ * head + tail plus the path and one search hint. Nothing is persisted: the
8
+ * mutation affects only the outgoing call, so the next request rebuilds from
9
+ * the stored history.
10
+ *
11
+ * Kill switch: AI_RULES_OUTPUT_GUARD=0. Threshold:
12
+ * AI_RULES_OUTPUT_GUARD_BYTES (default 8192). Debug:
13
+ * AI_RULES_OUTPUT_GUARD_DEBUG=1.
14
+ */
15
+
16
+ import fs from "node:fs"
17
+ import path from "node:path"
18
+ import { Plugin } from "@opencode/plugin"
19
+ import { rewriteMessages } from "./rewrite.ts"
20
+
21
+ const MARKER = "[ai-rules output-guard]"
22
+ const DEFAULT_THRESHOLD_BYTES = 8192
23
+ const MAX_SAVED_BYTES = 2 * 1024 * 1024
24
+ const HEAD_BYTES = 2048
25
+ const TAIL_BYTES = 1024
26
+ const HEAD_LINES = 40
27
+ const TAIL_LINES = 15
28
+ const ALLOWLIST = new Set(["shell", "bash", "read", "grep", "glob", "webfetch"])
29
+
30
+ const findTeamRoot = (start: string): string | null => {
31
+ let dir = path.resolve(start)
32
+ for (;;) {
33
+ const candidate = path.join(dir, ".ai.local", "team")
34
+ try {
35
+ if (fs.statSync(candidate).isDirectory()) return candidate
36
+ } catch {
37
+ /* keep walking up */
38
+ }
39
+ const parent = path.dirname(dir)
40
+ if (parent === dir) return null
41
+ dir = parent
42
+ }
43
+ }
44
+
45
+ const safeSegment = (value: string, fallback: string): string => {
46
+ const cleaned = value
47
+ .toLowerCase()
48
+ .replace(/[^a-z0-9]+/g, "-")
49
+ .replace(/^-+|-+$/g, "")
50
+ return cleaned.slice(0, 48) || fallback
51
+ }
52
+
53
+ const writeOutput = ({
54
+ outputDir,
55
+ projectRoot,
56
+ sessionID,
57
+ tool,
58
+ id,
59
+ text,
60
+ }: {
61
+ outputDir: string
62
+ projectRoot: string
63
+ sessionID: string
64
+ tool: string
65
+ id: string
66
+ text: string
67
+ }): string | null => {
68
+ const session = safeSegment(sessionID, "session")
69
+ const dir = path.join(outputDir, session, "outputs")
70
+ fs.mkdirSync(dir, { recursive: true })
71
+
72
+ const base = `${safeSegment(id, "result")}-${safeSegment(tool, "tool")}`
73
+ const file = path.join(dir, `${base}.txt`)
74
+ const relative = path.relative(dir, file)
75
+ if (relative.startsWith("..") || path.isAbsolute(relative)) return null
76
+
77
+ const buffer = Buffer.from(text, "utf8").subarray(0, MAX_SAVED_BYTES)
78
+ const tmp = path.join(dir, `.${base}.tmp-${process.pid}-${Date.now()}`)
79
+ try {
80
+ fs.writeFileSync(tmp, buffer)
81
+ fs.renameSync(tmp, file)
82
+ } finally {
83
+ try {
84
+ fs.rmSync(tmp, { force: true })
85
+ } catch {
86
+ /* best effort */
87
+ }
88
+ }
89
+
90
+ const shown = path.relative(projectRoot, file)
91
+ const inside = shown !== "" && !shown.startsWith("..") && !path.isAbsolute(shown)
92
+ return (inside ? shown : file).split(path.sep).join("/")
93
+ }
94
+
95
+ const appendJsonl = (dir: string, name: string, row: unknown) => {
96
+ try {
97
+ fs.mkdirSync(dir, { recursive: true })
98
+ fs.appendFileSync(path.join(dir, name), `${JSON.stringify(row)}\n`)
99
+ } catch {
100
+ /* the guard must never break the session */
101
+ }
102
+ }
103
+
104
+ const readNumber = (name: string, fallback: number): number => {
105
+ const raw = process.env[name]
106
+ if (!raw) return fallback
107
+ const value = Number(raw)
108
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback
109
+ }
110
+
111
+ type ToolItem = {
112
+ type?: string
113
+ id?: string
114
+ name?: string
115
+ input?: unknown
116
+ result?: { type?: string; value?: unknown }
117
+ }
118
+
119
+ const commandOf = (input: unknown): string => {
120
+ if (!input || typeof input !== "object") return ""
121
+ const record = input as Record<string, unknown>
122
+ for (const key of ["command", "filePath", "path", "pattern", "url", "query"]) {
123
+ const value = record[key]
124
+ if (typeof value === "string" && value !== "") return value.slice(0, 200)
125
+ }
126
+ return ""
127
+ }
128
+
129
+ /**
130
+ * Pair tool calls with their results once per assembled request. The pair gives
131
+ * the command for the category report; the raw bytes are the stored output, not
132
+ * the bounded replacement from a previous request.
133
+ */
134
+ const collectToolActivity = (messages: unknown) => {
135
+ const calls = new Map<string, { tool: string; command: string }>()
136
+ const results: Array<{ id: string; tool: string; rawBytes: number }> = []
137
+ if (!Array.isArray(messages)) return { calls, results }
138
+ for (const message of messages as Array<{ content?: unknown }>) {
139
+ const content = message?.content
140
+ if (!Array.isArray(content)) continue
141
+ for (const item of content as ToolItem[]) {
142
+ if (item?.type === "tool-call" && typeof item.id === "string") {
143
+ calls.set(item.id, {
144
+ tool: typeof item.name === "string" ? item.name : "",
145
+ command: commandOf(item.input),
146
+ })
147
+ }
148
+ if (
149
+ item?.type === "tool-result" &&
150
+ typeof item.id === "string" &&
151
+ item.result?.type === "text" &&
152
+ typeof item.result.value === "string"
153
+ ) {
154
+ const call = calls.get(item.id)
155
+ results.push({
156
+ id: item.id,
157
+ tool: call?.tool ?? (typeof item.name === "string" ? item.name : ""),
158
+ rawBytes: Buffer.byteLength(item.result.value, "utf8"),
159
+ })
160
+ }
161
+ }
162
+ }
163
+ return { calls, results }
164
+ }
165
+
166
+ export default Plugin.define({
167
+ id: "ai-rules.output-guard",
168
+ async setup(ctx) {
169
+ try {
170
+ if (process.env.AI_RULES_OUTPUT_GUARD === "0") return
171
+ if (typeof ctx.session?.hook !== "function") return
172
+ const root = findTeamRoot(ctx.location.directory)
173
+ if (!root) return
174
+
175
+ const options = {
176
+ thresholdBytes: readNumber("AI_RULES_OUTPUT_GUARD_BYTES", DEFAULT_THRESHOLD_BYTES),
177
+ headBytes: HEAD_BYTES,
178
+ tailBytes: TAIL_BYTES,
179
+ headLines: HEAD_LINES,
180
+ tailLines: TAIL_LINES,
181
+ allowlist: ALLOWLIST,
182
+ marker: MARKER,
183
+ }
184
+ const outputDir = process.env.AI_RULES_OUTPUT_GUARD_DIR
185
+ ? path.resolve(process.env.AI_RULES_OUTPUT_GUARD_DIR)
186
+ : path.join(root, "output-guard")
187
+ const projectRoot = path.resolve(root, "..", "..")
188
+ const savedPaths = new Map<string, string>()
189
+ const statsRecorded = new Set<string>()
190
+ const resultsSeen = new Set<string>()
191
+ const usageSeen = new Set<string>()
192
+
193
+ const recordUsage = async (sessionID: string) => {
194
+ try {
195
+ const messages = await ctx.session.context({ sessionID })
196
+ if (!Array.isArray(messages)) return
197
+ for (const message of messages as Array<{
198
+ id?: unknown
199
+ agent?: unknown
200
+ model?: unknown
201
+ tokens?: {
202
+ input?: unknown
203
+ output?: unknown
204
+ reasoning?: unknown
205
+ cache?: { read?: unknown; write?: unknown }
206
+ }
207
+ cost?: unknown
208
+ finish?: unknown
209
+ }>) {
210
+ const id = typeof message?.id === "string" ? message.id : ""
211
+ const tokens = message?.tokens
212
+ if (id === "" || !tokens || typeof tokens.input !== "number") continue
213
+ const key = `${sessionID}|${id}`
214
+ if (usageSeen.has(key)) continue
215
+ usageSeen.add(key)
216
+ appendJsonl(outputDir, "usage.jsonl", {
217
+ at: new Date().toISOString(),
218
+ sessionID,
219
+ messageID: id,
220
+ agent: typeof message.agent === "string" ? message.agent : "",
221
+ model: message.model ?? null,
222
+ input: tokens.input,
223
+ output: typeof tokens.output === "number" ? tokens.output : 0,
224
+ reasoning: typeof tokens.reasoning === "number" ? tokens.reasoning : 0,
225
+ cacheRead: typeof tokens.cache?.read === "number" ? tokens.cache.read : 0,
226
+ cacheWrite: typeof tokens.cache?.write === "number" ? tokens.cache.write : 0,
227
+ cost: typeof message.cost === "number" ? message.cost : 0,
228
+ finish: typeof message.finish === "string" ? message.finish : "",
229
+ })
230
+ }
231
+ } catch {
232
+ /* fail open: usage is an observation, not a guard input */
233
+ }
234
+ }
235
+
236
+ await ctx.session.hook("context", async (event) => {
237
+ try {
238
+ const sessionID = typeof event.sessionID === "string" ? event.sessionID : "session"
239
+ await recordUsage(sessionID)
240
+ const { calls, results } = collectToolActivity(event.messages)
241
+ const save = ({ tool, id, text }: { tool: string; id: string; text: string }) => {
242
+ const key = `${sessionID}|${id}|${tool}`
243
+ const existing = savedPaths.get(key)
244
+ if (existing) return existing
245
+ const file = writeOutput({ outputDir, projectRoot, sessionID, tool, id, text })
246
+ if (file) savedPaths.set(key, file)
247
+ return file
248
+ }
249
+ const result = rewriteMessages(event.messages, options, save)
250
+ const changedById = new Map(result.changed.map((stat) => [stat.id, stat]))
251
+ for (const stat of result.changed) {
252
+ if (statsRecorded.has(stat.path)) continue
253
+ statsRecorded.add(stat.path)
254
+ appendJsonl(outputDir, "stats.jsonl", {
255
+ at: new Date().toISOString(),
256
+ sessionID,
257
+ callID: stat.id,
258
+ tool: stat.tool,
259
+ beforeBytes: stat.beforeBytes,
260
+ afterBytes: stat.afterBytes,
261
+ path: stat.path,
262
+ })
263
+ }
264
+ for (const item of results) {
265
+ const key = `${sessionID}|${item.id}`
266
+ if (resultsSeen.has(key)) continue
267
+ resultsSeen.add(key)
268
+ const changed = changedById.get(item.id)
269
+ appendJsonl(outputDir, "results.jsonl", {
270
+ at: new Date().toISOString(),
271
+ sessionID,
272
+ callID: item.id,
273
+ tool: item.tool,
274
+ command: calls.get(item.id)?.command ?? "",
275
+ rawBytes: item.rawBytes,
276
+ returnedBytes: changed ? changed.afterBytes : item.rawBytes,
277
+ replaced: changed !== undefined,
278
+ path: changed?.path ?? "",
279
+ })
280
+ }
281
+ } catch (error) {
282
+ if (process.env.AI_RULES_OUTPUT_GUARD_DEBUG === "1") {
283
+ appendJsonl(outputDir, "debug.log", {
284
+ at: new Date().toISOString(),
285
+ message: error instanceof Error ? error.message : String(error),
286
+ })
287
+ }
288
+ }
289
+ })
290
+ } catch (error) {
291
+ if (process.env.AI_RULES_OUTPUT_GUARD_DEBUG === "1") {
292
+ appendJsonl(
293
+ path.join(ctx.location.directory, ".ai.local", "team", "output-guard"),
294
+ "debug.log",
295
+ { at: new Date().toISOString(), message: error instanceof Error ? error.message : String(error) },
296
+ )
297
+ }
298
+ }
299
+ },
300
+ })
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "ai-rules-output-guard",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./index.ts"
8
+ }
9
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Pure replacement logic for the OpenCode output guard. No host imports: the
3
+ * adapter in `index.ts` supplies the writer, and the fixture test imports this
4
+ * module directly.
5
+ */
6
+
7
+ export type OutputGuardOptions = {
8
+ thresholdBytes: number
9
+ headBytes: number
10
+ tailBytes: number
11
+ headLines: number
12
+ tailLines: number
13
+ allowlist: ReadonlySet<string>
14
+ marker: string
15
+ }
16
+
17
+ export type SaveOutputInput = { tool: string; id: string; text: string }
18
+
19
+ export type SaveOutput = (input: SaveOutputInput) => string | null
20
+
21
+ export type OutputGuardStats = {
22
+ id: string
23
+ tool: string
24
+ beforeBytes: number
25
+ afterBytes: number
26
+ path: string
27
+ }
28
+
29
+ export type RewriteResult = { changed: OutputGuardStats[] }
30
+
31
+ type ToolResult = {
32
+ type?: string
33
+ name?: string
34
+ id?: string
35
+ result?: { type?: string; value?: unknown }
36
+ }
37
+
38
+ type Message = { role?: string; content?: unknown }
39
+
40
+ const DEFAULT_MARKER = "[ai-rules output-guard]"
41
+
42
+ export const isOutputGuardText = (value: string, marker = DEFAULT_MARKER): boolean =>
43
+ value.startsWith(marker)
44
+
45
+ const bytes = (value: string): number => Buffer.byteLength(value, "utf8")
46
+
47
+ const takeHead = (value: string, maxBytes: number, maxLines: number): string => {
48
+ const lines = value.split("\n").slice(0, maxLines)
49
+ let text = lines.join("\n")
50
+ if (bytes(text) > maxBytes) {
51
+ text = Buffer.from(text, "utf8").subarray(0, maxBytes).toString("utf8")
52
+ }
53
+ return text
54
+ }
55
+
56
+ const takeTail = (value: string, maxBytes: number, maxLines: number): string => {
57
+ const lines = value.split("\n")
58
+ let text = lines.slice(Math.max(0, lines.length - maxLines)).join("\n")
59
+ if (bytes(text) > maxBytes) {
60
+ const buffer = Buffer.from(text, "utf8")
61
+ text = buffer.subarray(Math.max(0, buffer.length - maxBytes)).toString("utf8")
62
+ }
63
+ return text
64
+ }
65
+
66
+ /** A search term a shell can carry inside single quotes. */
67
+ const SEARCH_TERM = /^[\p{L}\p{N}][\p{L}\p{N}_-]*$/u
68
+
69
+ const searchTerm = (head: string, fallback: string): string => {
70
+ for (const line of head.split("\n")) {
71
+ for (const token of line.split(/\s+/)) {
72
+ if (token.length >= 2 && SEARCH_TERM.test(token)) return token.slice(0, 64)
73
+ }
74
+ }
75
+ return fallback
76
+ }
77
+
78
+ const looksJson = (value: string): boolean => /^[\s]*[{[]/.test(value)
79
+
80
+ export const renderReplacement = (
81
+ value: string,
82
+ file: string,
83
+ options: OutputGuardOptions,
84
+ ): string => {
85
+ const head = takeHead(value, options.headBytes, options.headLines)
86
+ const tail = takeTail(value, options.tailBytes, options.tailLines)
87
+ const term = searchTerm(head, "error")
88
+ const total = bytes(value)
89
+ const json = looksJson(value) ? " [json: full document at the path]" : ""
90
+ return [
91
+ `${options.marker} ${total} B -> bounded head+tail${json}`,
92
+ head,
93
+ "... (truncated)",
94
+ tail,
95
+ `${options.marker} full output: ${file} (${total} B)`,
96
+ `${options.marker} search: grep -n '${term}' ${file}`,
97
+ `${options.marker} read more: sed -n '${options.headLines + 1},${options.headLines + 80}p' ${file}`,
98
+ ].join("\n")
99
+ }
100
+
101
+ /**
102
+ * Replace every large, allow-listed `tool-result` text in the assembled model
103
+ * messages. Mutates the result objects in place (the host assembles them per
104
+ * request) and returns the stats the adapter records.
105
+ */
106
+ export function rewriteMessages(
107
+ messages: unknown,
108
+ options: OutputGuardOptions,
109
+ save: SaveOutput,
110
+ ): RewriteResult {
111
+ const changed: OutputGuardStats[] = []
112
+ if (!Array.isArray(messages)) return { changed }
113
+
114
+ for (const message of messages as Message[]) {
115
+ const content = message?.content
116
+ if (!Array.isArray(content)) continue
117
+ for (const item of content as ToolResult[]) {
118
+ if (item?.type !== "tool-result") continue
119
+ const tool = typeof item.name === "string" ? item.name : ""
120
+ if (tool === "" || !options.allowlist.has(tool)) continue
121
+ const result = item.result
122
+ if (result?.type !== "text" || typeof result.value !== "string") continue
123
+ const value = result.value
124
+ if (isOutputGuardText(value, options.marker)) continue
125
+ const beforeBytes = bytes(value)
126
+ if (beforeBytes <= options.thresholdBytes) continue
127
+
128
+ let file: string | null = null
129
+ try {
130
+ file = save({ tool, id: typeof item.id === "string" ? item.id : "", text: value })
131
+ } catch {
132
+ continue
133
+ }
134
+ if (file === null || file === "") continue
135
+
136
+ const replacement = renderReplacement(value, file, options)
137
+ result.value = replacement
138
+ changed.push({
139
+ id: typeof item.id === "string" ? item.id : "",
140
+ tool,
141
+ beforeBytes,
142
+ afterBytes: bytes(replacement),
143
+ path: file,
144
+ })
145
+ }
146
+ }
147
+
148
+ return { changed }
149
+ }
@@ -146,33 +146,54 @@ export const pauseState = (root: string, slug?: string): PauseScope | null => {
146
146
  const pausePayload = (scope: PauseScope) =>
147
147
  JSON.stringify({ reason: "soft stop requested from the task sidebar", scope })
148
148
 
149
- export const engagePause = (root: string, slug?: string): boolean => {
149
+ /** The scope actually written, or `null` when no sentinel could be written. */
150
+ export const engagePause = (root: string, slug?: string): PauseScope | null => {
150
151
  if (slug) {
151
152
  try {
152
153
  fs.writeFileSync(taskSentinel(root, slug), pausePayload("task"), "utf8")
153
- return true
154
+ return "task"
154
155
  } catch {
155
156
  // A task directory can disappear under a stale view; fall back to the repo sentinel.
156
157
  }
157
158
  }
158
159
  const overlay = overlayDir(root)
159
- if (!overlay) return false
160
+ if (!overlay) return null
160
161
  try {
161
162
  fs.writeFileSync(path.join(overlay, "STOP"), pausePayload("repo"), "utf8")
162
- return true
163
+ return "repo"
163
164
  } catch {
164
- return false
165
+ return null
165
166
  }
166
167
  }
167
168
 
168
- export const clearPause = (root: string, slug?: string): boolean => {
169
- let cleared = false
169
+ /**
170
+ * What a sidebar affordance or a resume word may lift: a task sentinel or a
171
+ * repo `STOP`. A repo `ESTOP` alone is emergency-stop semantics — it is
172
+ * displayed as a repo pause, but nothing automatic clears it.
173
+ */
174
+ export const resumableScope = (root: string, slug?: string): PauseScope | null => {
175
+ if (slug && isPresent(taskSentinel(root, slug))) return "task"
170
176
  const overlay = overlayDir(root)
171
- const files = [
172
- ...(slug ? [taskSentinel(root, slug)] : []),
173
- ...(overlay ? [path.join(overlay, "STOP"), path.join(overlay, "ESTOP")] : []),
174
- ]
175
- for (const file of files) {
177
+ if (!overlay) return null
178
+ return isPresent(path.join(overlay, "STOP")) ? "repo" : null
179
+ }
180
+
181
+ /**
182
+ * Clear exactly the named scope's sentinel. A repo resume lifts the operator
183
+ * `STOP` only: an `ESTOP` is removed by hand alone, never by a resume word or
184
+ * a sidebar button.
185
+ */
186
+ export const clearPause = (root: string, slug: string | undefined, scope: PauseScope): boolean => {
187
+ let cleared = false
188
+ const targets: string[] = []
189
+ if (scope === "task") {
190
+ if (!slug) return false
191
+ targets.push(taskSentinel(root, slug))
192
+ } else {
193
+ const overlay = overlayDir(root)
194
+ if (overlay) targets.push(path.join(overlay, "STOP"))
195
+ }
196
+ for (const file of targets) {
176
197
  if (!fs.existsSync(file)) continue
177
198
  try {
178
199
  fs.rmSync(file, { force: true })
@@ -242,11 +263,19 @@ const buildPromptIndex = (root: string): PromptEntry[] => {
242
263
  return index
243
264
  }
244
265
 
245
- /** Exact > prompt-contained-in-message > message-contained-in-prompt. */
266
+ /**
267
+ * Tier-monotonic: a stronger tier always outscores a weaker one, so a longer
268
+ * substring can never outrank a shorter match from a better tier, and an
269
+ * exact match (handled outright in `computeMatch`) always wins.
270
+ */
246
271
  const scoreFor = (message: string, prompt: string): number => {
247
- if (message === prompt) return 1000 + prompt.length
248
- if (prompt.length >= MIN_PARTIAL && message.includes(prompt)) return 500 + prompt.length
249
- if (message.length >= MIN_PARTIAL && prompt.includes(message)) return 100 + message.length
272
+ if (message === prompt) return 3000 + prompt.length
273
+ if (prompt.length >= MIN_PARTIAL && message.includes(prompt)) {
274
+ return 2000 + Math.min(prompt.length, 999)
275
+ }
276
+ if (message.length >= MIN_PARTIAL && prompt.includes(message)) {
277
+ return 1000 + Math.min(message.length, 999)
278
+ }
250
279
  return 0
251
280
  }
252
281
 
@@ -260,6 +289,15 @@ const computeMatch = (index: PromptEntry[], messages: string[]): string | undefi
260
289
  }
261
290
  if (continued) return continued
262
291
 
292
+ // An exact prompt match wins outright whatever the lengths involved; the
293
+ // substring tiers only rank the remaining candidates. Newest exact wins.
294
+ let exact: PromptEntry | undefined
295
+ for (const entry of index) {
296
+ if (!entry.texts.some((prompt) => messages.includes(prompt))) continue
297
+ if (!exact || entry.updatedAt > exact.updatedAt) exact = entry
298
+ }
299
+ if (exact) return exact.slug
300
+
263
301
  let best: PromptEntry | undefined
264
302
  let bestScore = 0
265
303
  for (const entry of index) {
@@ -270,7 +308,7 @@ const computeMatch = (index: PromptEntry[], messages: string[]): string | undefi
270
308
  }
271
309
  }
272
310
  if (score === 0) continue
273
- // An exact match outranks a newer, weaker substring match; recency breaks ties.
311
+ // Recency breaks ties inside a tier; `scoreFor` keeps the tiers monotonic.
274
312
  if (!best || score > bestScore || (score === bestScore && entry.updatedAt > best.updatedAt)) {
275
313
  best = entry
276
314
  bestScore = score
@@ -477,7 +515,7 @@ const buildTaskView = (
477
515
  slug,
478
516
  root,
479
517
  stoppable: !done && !paused && !blocked && !status.awaitingHumanGate && state !== "awaiting_approval",
480
- resumable: pauseScope !== null,
518
+ resumable: resumableScope(root, slug) !== null,
481
519
  pausedScope: pauseScope ?? undefined,
482
520
  offline,
483
521
  }
@@ -618,8 +656,8 @@ export const createTaskWatcher = (storage: MemoryStorage, options: TaskWatcherOp
618
656
  const key = `${current.texts.length}:${latest}`
619
657
  if (!latest || current.resumeFor === key || !resumeIntent(latest)) return
620
658
  current.resumeFor = key
621
- const scope = pauseState(root, slug)
622
- if (scope && clearPause(root, slug)) {
659
+ const scope = resumableScope(root, slug)
660
+ if (scope && clearPause(root, slug, scope)) {
623
661
  logTaskDebug(`resume intent cleared ${scope} pause for ${slug}`)
624
662
  }
625
663
  }
@@ -45,11 +45,13 @@ const TaskSidebar = () => {
45
45
  label: { confirm: "Stop", cancel: "Cancel" },
46
46
  })
47
47
  if (!confirmed) return
48
- if (!engagePause(view.root, view.slug)) {
48
+ const written = engagePause(view.root, view.slug)
49
+ if (!written) {
49
50
  context.ui.toast.show({ title: "Task", message: "Cannot write .ai.local/STOP", variant: "error" })
50
51
  return
51
52
  }
52
- context.ui.toast.show({ title: "Task", message: `Soft stop engaged for ${view.slug}`, variant: "warning" })
53
+ const where = written === "repo" ? `repository-wide (the ${view.slug} task dir was unwritable)` : `for ${view.slug}`
54
+ context.ui.toast.show({ title: "Task", message: `Soft stop engaged ${where}`, variant: "warning" })
53
55
  }
54
56
 
55
57
  const confirmResume = async () => {
@@ -62,7 +64,7 @@ const TaskSidebar = () => {
62
64
  label: { confirm: "Resume", cancel: "Cancel" },
63
65
  })
64
66
  if (!confirmed) return
65
- if (!clearPause(view.root, view.slug)) {
67
+ if (!clearPause(view.root, view.slug, view.pausedScope === "task" ? "task" : "repo")) {
66
68
  context.ui.toast.show({ title: "Task", message: "No stop sentinel to clear", variant: "error" })
67
69
  return
68
70
  }
@@ -3,7 +3,7 @@
3
3
  "platform": "opencode",
4
4
  "stack": "svelte",
5
5
  "semanticSource": "cursor/svelte",
6
- "sourceRevision": "9d456ee183d392a7bef006558ae785f04a37c02fa5258cb764b955267d637607",
6
+ "sourceRevision": "e38ba765bb0c5bb6d7d8054db0f7089e6512d6cb8d2eb2d7525a164bfd673828",
7
7
  "entries": [
8
8
  {
9
9
  "source": "AGENTS.md",
@@ -1283,11 +1283,15 @@ function focusDigestMarkdown(dir, statusSnapshot) {
1283
1283
  }
1284
1284
  } catch {}
1285
1285
  }
1286
+ // Five entries is enough to resume; a longer list is a status dump, not a
1287
+ // pointer. The line budget below still bounds a single entry with many paths.
1288
+ const MAX_FOCUS_ENTRIES = 5;
1289
+ const shownIncomplete = incomplete.slice(0, MAX_FOCUS_ENTRIES);
1286
1290
  const pathLines = [];
1287
1291
  if (incomplete.length === 0) pathLines.push(' - (none)');
1288
1292
  else {
1289
- for (let index = 0; index < incomplete.length; index += 1) {
1290
- const item = incomplete[index];
1293
+ for (let index = 0; index < shownIncomplete.length; index += 1) {
1294
+ const item = shownIncomplete[index];
1291
1295
  if (item.paths.length === 0) pathLines.push(' - ' + item.id + ': (none)');
1292
1296
  else {
1293
1297
  for (let pathIndex = 0; pathIndex < item.paths.length; pathIndex += 1) {
@@ -1295,6 +1299,9 @@ function focusDigestMarkdown(dir, statusSnapshot) {
1295
1299
  }
1296
1300
  }
1297
1301
  }
1302
+ if (incomplete.length > shownIncomplete.length) {
1303
+ pathLines.push(' - (+' + String(incomplete.length - shownIncomplete.length) + ' more incomplete entries)');
1304
+ }
1298
1305
  }
1299
1306
  let readyLine = '- decomposition ready set: (none)';
1300
1307
  try {