@bonesofspring/ai-rules 0.2.68 → 0.2.70

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 (115) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +1 -1
  3. package/package.json +2 -2
  4. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +137 -2
  5. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +137 -2
  6. package/presets/claude/go/hooks/chain-team-phases.sh +137 -2
  7. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +137 -2
  8. package/presets/claude/java/hooks/chain-team-phases.sh +137 -2
  9. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +137 -2
  10. package/presets/claude/mol/hooks/chain-team-phases.sh +137 -2
  11. package/presets/claude/next/commands/README.md +5 -0
  12. package/presets/claude/next/commands/task-continue.md +17 -6
  13. package/presets/claude/next/commands/ui-start.md +54 -0
  14. package/presets/claude/next/commands/ui-stop.md +43 -0
  15. package/presets/claude/next/hooks/chain-team-phases.sh +137 -2
  16. package/presets/claude/nuxt/hooks/chain-team-phases.sh +137 -2
  17. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +137 -2
  18. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +137 -2
  19. package/presets/claude/svelte/hooks/chain-team-phases.sh +137 -2
  20. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +137 -2
  21. package/presets/cursor/go/hooks/chain-team-phases.sh +137 -2
  22. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +137 -2
  23. package/presets/cursor/java/hooks/chain-team-phases.sh +137 -2
  24. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +137 -2
  25. package/presets/cursor/mol/hooks/chain-team-phases.sh +137 -2
  26. package/presets/cursor/next/commands/README.md +5 -0
  27. package/presets/cursor/next/commands/task-continue.md +17 -6
  28. package/presets/cursor/next/commands/ui-start.md +54 -0
  29. package/presets/cursor/next/commands/ui-stop.md +43 -0
  30. package/presets/cursor/next/hooks/chain-team-phases.sh +137 -2
  31. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +137 -2
  32. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +137 -2
  33. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +137 -2
  34. package/presets/cursor/svelte/hooks/chain-team-phases.sh +137 -2
  35. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  36. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +137 -2
  37. package/presets/mavis/go/adapter-map.json +1 -1
  38. package/presets/mavis/go/hooks/chain-team-phases.sh +137 -2
  39. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  40. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +137 -2
  41. package/presets/mavis/java/adapter-map.json +1 -1
  42. package/presets/mavis/java/hooks/chain-team-phases.sh +137 -2
  43. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  44. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +137 -2
  45. package/presets/mavis/mol/adapter-map.json +1 -1
  46. package/presets/mavis/mol/hooks/chain-team-phases.sh +137 -2
  47. package/presets/mavis/next/adapter-map.json +17 -1
  48. package/presets/mavis/next/commands/README.md +5 -0
  49. package/presets/mavis/next/commands/task-continue.md +16 -5
  50. package/presets/mavis/next/commands/ui-start.md +49 -0
  51. package/presets/mavis/next/commands/ui-stop.md +38 -0
  52. package/presets/mavis/next/hooks/chain-team-phases.sh +137 -2
  53. package/presets/mavis/nuxt/adapter-map.json +1 -1
  54. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +137 -2
  55. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  56. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +137 -2
  57. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  58. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +137 -2
  59. package/presets/mavis/svelte/adapter-map.json +1 -1
  60. package/presets/mavis/svelte/hooks/chain-team-phases.sh +137 -2
  61. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  62. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +137 -2
  63. package/presets/opencode/go/adapter-map.json +1 -1
  64. package/presets/opencode/go/hooks/chain-team-phases.sh +137 -2
  65. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  66. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +137 -2
  67. package/presets/opencode/java/adapter-map.json +1 -1
  68. package/presets/opencode/java/hooks/chain-team-phases.sh +137 -2
  69. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  70. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +137 -2
  71. package/presets/opencode/mol/adapter-map.json +1 -1
  72. package/presets/opencode/mol/hooks/chain-team-phases.sh +137 -2
  73. package/presets/opencode/next/adapter-map.json +17 -1
  74. package/presets/opencode/next/commands/README.md +5 -0
  75. package/presets/opencode/next/commands/task-continue.md +17 -6
  76. package/presets/opencode/next/commands/ui-start.md +57 -0
  77. package/presets/opencode/next/commands/ui-stop.md +46 -0
  78. package/presets/opencode/next/hooks/chain-team-phases.sh +137 -2
  79. package/presets/opencode/nuxt/adapter-map.json +1 -1
  80. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +137 -2
  81. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  82. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +137 -2
  83. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  84. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +137 -2
  85. package/presets/opencode/plugins/output-guard/README.md +33 -0
  86. package/presets/opencode/plugins/output-guard/index.ts +225 -3
  87. package/presets/opencode/svelte/adapter-map.json +1 -1
  88. package/presets/opencode/svelte/hooks/chain-team-phases.sh +137 -2
  89. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  90. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +137 -2
  91. package/presets/zcode/go/adapter-map.json +1 -1
  92. package/presets/zcode/go/hooks/chain-team-phases.sh +137 -2
  93. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  94. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +137 -2
  95. package/presets/zcode/java/adapter-map.json +1 -1
  96. package/presets/zcode/java/hooks/chain-team-phases.sh +137 -2
  97. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  98. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +137 -2
  99. package/presets/zcode/mol/adapter-map.json +1 -1
  100. package/presets/zcode/mol/hooks/chain-team-phases.sh +137 -2
  101. package/presets/zcode/next/adapter-map.json +17 -1
  102. package/presets/zcode/next/commands/README.md +5 -0
  103. package/presets/zcode/next/commands/task-continue.md +17 -6
  104. package/presets/zcode/next/commands/ui-start.md +57 -0
  105. package/presets/zcode/next/commands/ui-stop.md +46 -0
  106. package/presets/zcode/next/hooks/chain-team-phases.sh +137 -2
  107. package/presets/zcode/nuxt/adapter-map.json +1 -1
  108. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +137 -2
  109. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  110. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +137 -2
  111. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  112. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +137 -2
  113. package/presets/zcode/svelte/adapter-map.json +1 -1
  114. package/presets/zcode/svelte/hooks/chain-team-phases.sh +137 -2
  115. package/scripts/report-context-cost.mjs +216 -5
@@ -16,6 +16,7 @@ outgoing model call; persisted history is untouched.
16
16
  | Replacement | 40-line / 2 KB head + 15-line / 1 KB tail + path + hints |
17
17
  | Saved file | `.ai.local/team/output-guard/<sessionID>/outputs/<callID>-<tool>.txt`, 2 MiB cap |
18
18
  | Stats | `.ai.local/team/output-guard/stats.jsonl` (one row per replacement) |
19
+ | Ledgers | `results.jsonl`, `usage.jsonl`, `context.jsonl` — see [Ledgers](#ledgers) |
19
20
  | Kill switch | `AI_RULES_OUTPUT_GUARD=0` |
20
21
  | Debug | `AI_RULES_OUTPUT_GUARD_DEBUG=1` → `output-guard/debug.log` |
21
22
  | Host | OpenCode V2 with `ctx.session.hook`; a host without it no-ops |
@@ -24,6 +25,38 @@ The replacement keeps the first and last lines because a test log often carries
24
25
  the failure at the end. A JSON-looking result is still replaced, with a
25
26
  `[json: full document at the path]` note so the agent can `jq` the file.
26
27
 
28
+ ## Ledgers
29
+
30
+ All four files live in `.ai.local/team/output-guard/`. None but `results.jsonl`
31
+ and `usage.jsonl` rotate.
32
+
33
+ | File | Row | Written when |
34
+ |---|---|---|
35
+ | `stats.jsonl` | `sessionID`, `callID`, `tool`, `beforeBytes`, `afterBytes`, `path` | a result is replaced |
36
+ | `results.jsonl` | `sessionID`, `callID`, `tool`, `command`, `rawBytes`, `returnedBytes`, `replaced`, `path` | a tool result is seen |
37
+ | `usage.jsonl` | `sessionID`, `messageID`, `agent`, `model`, `input`, `output`, `reasoning`, `cacheRead`, `cacheWrite`, `cost`, `finish` | a message carries token counts |
38
+ | `context.jsonl` | `sessionID`, `toolset`, `tools`, `toolSchemaBytes`, `systemBytes`, `byTool[]`, `mcpServers[]` | a session's toolset changes |
39
+
40
+ `usage.jsonl` covers the session running the hook **and the child sessions it
41
+ discovers**. A child row adds `parentSessionID`; a root row, and every row
42
+ written before this field existed, has no such key — absence means "root or
43
+ unattributed". A session tags its own rows from `session.get({ sessionID })`
44
+ `parentID`, so a child that runs its own `context` hook still writes child rows.
45
+ Discovery is the backstop for a child whose hook never reaches this plugin:
46
+ `session.created` (host v2 `event.subscribe`, payload `data.parentID`) catches
47
+ children created after setup, and `session.list({ directory, parentID })`
48
+ catches children that already existed. A child is read with
49
+ `session.context({ sessionID })`, the same call the root uses.
50
+
51
+ `context.jsonl` keeps one row per distinct `(sessionID, toolset hash)`.
52
+ `toolSchemaBytes` is the summed UTF-8 size of every `{description, input}` tool
53
+ schema at dispatch; `byTool[]` is `{name, bytes}` per tool; `systemBytes` is the
54
+ summed size of the system part texts. `mcpServers[]` is `{name, tools, bytes}`
55
+ for configured MCP servers whose name prefixes at least one tool
56
+ (`<server>_<tool>`); the key is **omitted** when the MCP list call fails, so a
57
+ reader never mistakes a failed call for a measured zero. A session with no
58
+ tools writes no row.
59
+
27
60
  ## Why a hook, not a rule
28
61
 
29
62
  A prose line asks the agent to pipe output; context-mode measured that path at
@@ -12,8 +12,13 @@
12
12
  * AI_RULES_OUTPUT_GUARD_BYTES (default 8192). Debug:
13
13
  * AI_RULES_OUTPUT_GUARD_DEBUG=1. Ledger rotation: once in `setup()` at
14
14
  * AI_RULES_OUTPUT_GUARD_ROTATE_BYTES (default 8 MiB, 0 disables), two archives.
15
+ *
16
+ * Telemetry beside the guard: `usage.jsonl` reads the token rows of the session
17
+ * and of the child sessions it discovers, and `context.jsonl` keeps one row per
18
+ * `(sessionID, toolset)` for the MCP schema split. Neither rotates.
15
19
  */
16
20
 
21
+ import { createHash } from "node:crypto"
17
22
  import fs from "node:fs"
18
23
  import path from "node:path"
19
24
  import { Plugin } from "@opencode/plugin"
@@ -27,6 +32,7 @@ const HEAD_BYTES = 2048
27
32
  const TAIL_BYTES = 1024
28
33
  const HEAD_LINES = 40
29
34
  const TAIL_LINES = 15
35
+ const MAX_TRACKED_SESSIONS = 12
30
36
  const ALLOWLIST = new Set(["shell", "bash", "read", "grep", "glob", "webfetch"])
31
37
 
32
38
  const findTeamRoot = (start: string): string | null => {
@@ -110,6 +116,86 @@ const readNumber = (name: string, fallback: number): number => {
110
116
  return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback
111
117
  }
112
118
 
119
+ const recordOf = (value: unknown): Record<string, unknown> =>
120
+ value !== null && typeof value === "object" ? (value as Record<string, unknown>) : {}
121
+
122
+ /** `session.list` answers `{ data }` over the client and a bare array in-process. */
123
+ const rowsOf = (value: unknown): unknown[] => {
124
+ if (Array.isArray(value)) return value
125
+ const data = recordOf(value).data
126
+ return Array.isArray(data) ? data : []
127
+ }
128
+
129
+ const utf8Bytes = (value: string): number => Buffer.byteLength(value, "utf8")
130
+
131
+ type ToolRow = { name: string; bytes: number; schema: string }
132
+ type ServerRow = { name: string; tools: number; bytes: number }
133
+
134
+ const toolRows = (tools: unknown): ToolRow[] => {
135
+ const rows: ToolRow[] = []
136
+ for (const [name, schema] of Object.entries(recordOf(tools)).sort(([left], [right]) =>
137
+ left.localeCompare(right),
138
+ )) {
139
+ const serialized = JSON.stringify(schema) ?? ""
140
+ rows.push({ name, bytes: utf8Bytes(serialized), schema: serialized })
141
+ }
142
+ return rows
143
+ }
144
+
145
+ const sumBytes = (rows: Array<{ bytes: number }>): number =>
146
+ rows.reduce((total, row) => total + row.bytes, 0)
147
+
148
+ const systemBytes = (system: unknown): number => {
149
+ if (!Array.isArray(system)) return 0
150
+ let total = 0
151
+ for (const part of system) {
152
+ const text = recordOf(part).text
153
+ if (typeof text === "string") total += utf8Bytes(text)
154
+ }
155
+ return total
156
+ }
157
+
158
+ /** MCP tools are named `<server>_<tool>`; a server with no dispatched schema is left out. */
159
+ const serverRows = (names: string[], tools: ToolRow[]): ServerRow[] => {
160
+ const rows: ServerRow[] = []
161
+ for (const name of names.sort((left, right) => left.localeCompare(right))) {
162
+ const matched = tools.filter((tool) => tool.name.startsWith(`${name}_`))
163
+ if (matched.length === 0) continue
164
+ rows.push({ name, tools: matched.length, bytes: sumBytes(matched) })
165
+ }
166
+ return rows
167
+ }
168
+
169
+ const toolsetHash = (rows: ToolRow[]): string =>
170
+ createHash("sha256")
171
+ .update(rows.map((row) => `${row.name}\n${row.schema}`).join("\n"))
172
+ .digest("hex")
173
+ .slice(0, 16)
174
+
175
+ /**
176
+ * `context.jsonl` is not rotated, so the keys already on disk seed the dedupe set:
177
+ * a plugin reload must not repeat a `(sessionID, toolset)` row.
178
+ */
179
+ const loadToolsets = (outputDir: string): Set<string> => {
180
+ const seen = new Set<string>()
181
+ try {
182
+ for (const line of fs.readFileSync(path.join(outputDir, "context.jsonl"), "utf8").split("\n")) {
183
+ if (line.trim() === "") continue
184
+ try {
185
+ const row = recordOf(JSON.parse(line))
186
+ if (typeof row.sessionID === "string" && typeof row.toolset === "string") {
187
+ seen.add(`${row.sessionID}|${row.toolset}`)
188
+ }
189
+ } catch {
190
+ /* a torn last line must not stop the plugin */
191
+ }
192
+ }
193
+ } catch {
194
+ /* no snapshot ledger yet */
195
+ }
196
+ return seen
197
+ }
198
+
113
199
  type ToolItem = {
114
200
  type?: string
115
201
  id?: string
@@ -195,8 +281,81 @@ export default Plugin.define({
195
281
  const statsRecorded = new Set<string>()
196
282
  const resultsSeen = new Set<string>()
197
283
  const usageSeen = new Set<string>()
284
+ const toolsetsSeen = loadToolsets(outputDir)
285
+ const childrenByParent = new Map<string, Set<string>>()
198
286
 
199
- const recordUsage = async (sessionID: string) => {
287
+ const rememberChild = (parentID: string, childID: string) => {
288
+ const known = childrenByParent.get(parentID)
289
+ if (known) known.add(childID)
290
+ else childrenByParent.set(parentID, new Set([childID]))
291
+ }
292
+
293
+ // A session's own rows are tagged from its `parentID`, so a child that runs
294
+ // its own hook still lands as a child row. Parent-side discovery below is
295
+ // the backstop for a child whose hook never reached this plugin.
296
+ const parentOf = async (sessionID: string): Promise<string | undefined> => {
297
+ if (typeof ctx.session?.get !== "function") return undefined
298
+ try {
299
+ const parentID = recordOf(await ctx.session.get({ sessionID })).parentID
300
+ return typeof parentID === "string" && parentID !== sessionID ? parentID : undefined
301
+ } catch {
302
+ return undefined
303
+ }
304
+ }
305
+
306
+ // `session.created` covers children created after setup, `list({ parentID })`
307
+ // covers the ones that existed before it.
308
+ const watchChildren = () => {
309
+ try {
310
+ if (typeof ctx.event?.subscribe !== "function") return
311
+ const events = ctx.event.subscribe({ types: ["session.created"] })
312
+ void (async () => {
313
+ try {
314
+ for await (const event of events) {
315
+ // Payload sits under `data` in host v2 and under `properties` in v1.
316
+ const payload = recordOf(recordOf(event).data ?? recordOf(event).properties)
317
+ const parentID = payload.parentID
318
+ const childID = payload.sessionID
319
+ if (
320
+ typeof parentID === "string" &&
321
+ typeof childID === "string" &&
322
+ parentID !== childID
323
+ ) {
324
+ rememberChild(parentID, childID)
325
+ }
326
+ }
327
+ } catch {
328
+ /* the stream is an optimization; list() still finds the child */
329
+ }
330
+ })()
331
+ } catch {
332
+ /* a host without an event domain keeps the list path */
333
+ }
334
+ }
335
+
336
+ const childrenOf = async (parentID: string): Promise<string[]> => {
337
+ const known = new Set(childrenByParent.get(parentID) ?? [])
338
+ if (typeof ctx.session?.list !== "function") return [...known]
339
+ try {
340
+ const response = await ctx.session.list({
341
+ directory: ctx.location.directory,
342
+ parentID,
343
+ archived: false,
344
+ limit: MAX_TRACKED_SESSIONS,
345
+ })
346
+ for (const row of rowsOf(response)) {
347
+ const id = recordOf(row).id
348
+ if (typeof id !== "string" || id === parentID) continue
349
+ known.add(id)
350
+ rememberChild(parentID, id)
351
+ }
352
+ } catch {
353
+ /* the event path may still know the child */
354
+ }
355
+ return [...known].slice(0, MAX_TRACKED_SESSIONS)
356
+ }
357
+
358
+ const recordSession = async (sessionID: string, parentSessionID?: string) => {
200
359
  try {
201
360
  const messages = await ctx.session.context({ sessionID })
202
361
  if (!Array.isArray(messages)) return
@@ -219,7 +378,7 @@ export default Plugin.define({
219
378
  const key = `${sessionID}|${id}`
220
379
  if (usageSeen.has(key)) continue
221
380
  usageSeen.add(key)
222
- appendJsonl(outputDir, "usage.jsonl", {
381
+ const row: Record<string, unknown> = {
223
382
  at: new Date().toISOString(),
224
383
  sessionID,
225
384
  messageID: id,
@@ -232,13 +391,69 @@ export default Plugin.define({
232
391
  cacheWrite: typeof tokens.cache?.write === "number" ? tokens.cache.write : 0,
233
392
  cost: typeof message.cost === "number" ? message.cost : 0,
234
393
  finish: typeof message.finish === "string" ? message.finish : "",
235
- })
394
+ }
395
+ if (parentSessionID !== undefined) row.parentSessionID = parentSessionID
396
+ appendJsonl(outputDir, "usage.jsonl", row)
236
397
  }
237
398
  } catch {
238
399
  /* fail open: usage is an observation, not a guard input */
239
400
  }
240
401
  }
241
402
 
403
+ const recordUsage = async (sessionID: string) => {
404
+ const queue: Array<{ id: string; parentSessionID?: string }> = [
405
+ { id: sessionID, parentSessionID: await parentOf(sessionID) },
406
+ ]
407
+ const visited = new Set([sessionID])
408
+ for (let index = 0; index < queue.length && index < MAX_TRACKED_SESSIONS; index += 1) {
409
+ const current = queue[index]
410
+ await recordSession(current.id, current.parentSessionID)
411
+ for (const child of await childrenOf(current.id)) {
412
+ if (visited.has(child)) continue
413
+ visited.add(child)
414
+ queue.push({ id: child, parentSessionID: current.id })
415
+ }
416
+ }
417
+ }
418
+
419
+ const mcpServerNames = async (): Promise<string[] | null> => {
420
+ if (typeof ctx.mcp?.list !== "function") return null
421
+ try {
422
+ return rowsOf(await ctx.mcp.list({}))
423
+ .map((row) => recordOf(row).name)
424
+ .filter((name): name is string => typeof name === "string" && name !== "")
425
+ } catch {
426
+ return null
427
+ }
428
+ }
429
+
430
+ const recordToolset = async (sessionID: string, source: unknown) => {
431
+ const request = recordOf(source)
432
+ const tools = toolRows(request.tools)
433
+ if (tools.length === 0) return
434
+ const toolset = toolsetHash(tools)
435
+ const key = `${sessionID}|${toolset}`
436
+ if (toolsetsSeen.has(key)) return
437
+ toolsetsSeen.add(key)
438
+ const byTool = tools.map(({ name, bytes }) => ({ name, bytes }))
439
+ const row: Record<string, unknown> = {
440
+ at: new Date().toISOString(),
441
+ sessionID,
442
+ toolset,
443
+ tools: byTool.length,
444
+ toolSchemaBytes: sumBytes(byTool),
445
+ systemBytes: systemBytes(request.system),
446
+ byTool,
447
+ }
448
+ // No `mcpServers` key when the list call failed: an empty array would read
449
+ // as "measured zero" in the report.
450
+ const names = await mcpServerNames()
451
+ if (names !== null) row.mcpServers = serverRows(names, byTool)
452
+ appendJsonl(outputDir, "context.jsonl", row)
453
+ }
454
+
455
+ watchChildren()
456
+
242
457
  await ctx.session.hook("context", async (event) => {
243
458
  try {
244
459
  const sessionID = typeof event.sessionID === "string" ? event.sessionID : "session"
@@ -284,6 +499,13 @@ export default Plugin.define({
284
499
  path: changed?.path ?? "",
285
500
  })
286
501
  }
502
+ // Last, and guarded on its own: a snapshot failure must not change the
503
+ // rewrite that already mutated `event.messages`.
504
+ try {
505
+ await recordToolset(sessionID, event)
506
+ } catch {
507
+ /* the snapshot is an observation, not a guard input */
508
+ }
287
509
  } catch (error) {
288
510
  if (process.env.AI_RULES_OUTPUT_GUARD_DEBUG === "1") {
289
511
  appendJsonl(outputDir, "debug.log", {
@@ -3,7 +3,7 @@
3
3
  "platform": "opencode",
4
4
  "stack": "svelte",
5
5
  "semanticSource": "cursor/svelte",
6
- "sourceRevision": "5abc81e9f017c1fc9a379118d4dda448d4cde66e7fe2d088be6a0938b246a8bf",
6
+ "sourceRevision": "9aee30cc086e7efbe8493cb9f9b523c0e70f215590d027e5d0f43c8d4ec879d3",
7
7
  "entries": [
8
8
  {
9
9
  "source": "AGENTS.md",
@@ -23,8 +23,12 @@ try {
23
23
  }
24
24
 
25
25
  if (hookInput.status !== 'completed') {
26
- process.stdout.write('{}');
27
- process.exit(0);
26
+ // `resume_blocked` is a lifecycle repair, not a producer receipt: it runs
27
+ // with no `status`, and a `status` it carries is ignored.
28
+ if (hookInput.action !== 'resume_blocked') {
29
+ process.stdout.write('{}');
30
+ process.exit(0);
31
+ }
28
32
  }
29
33
 
30
34
  // Slug resolution, strongest first:
@@ -2095,6 +2099,137 @@ function syncMetricsProfile(pipeline) {
2095
2099
  });
2096
2100
  }
2097
2101
 
2102
+ function resumeBlockedRefuse(reason) {
2103
+ process.stdout.write(JSON.stringify({ ok: false, action: 'resume_blocked', reason }));
2104
+ }
2105
+
2106
+ /**
2107
+ * Arm attempt N+1 for one linear step. The ordinal read and the append share
2108
+ * one metrics critical section, like `completeTaskMetrics`: a second process
2109
+ * serializes on the lock and sees the first attempt instead of minting the
2110
+ * same ordinal.
2111
+ */
2112
+ function armResumedAttempt(step, stepIndex, agent) {
2113
+ let attemptId = null;
2114
+ mutateMetrics((metrics) => {
2115
+ const ledgerRunId = metrics.task && typeof metrics.task.runId === 'string' ? metrics.task.runId : '';
2116
+ const runId = ledgerRunId || status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
2117
+ metrics.task = { ...(metrics.task || {}), runId };
2118
+ status.metricsRunId = runId;
2119
+ const events = Array.isArray(metrics.events) ? metrics.events : (metrics.events = []);
2120
+ const attempt =
2121
+ events.reduce(
2122
+ (highest, event) =>
2123
+ event && event.type === 'attempt_started' && event.stepIndex === stepIndex && event.agent === agent
2124
+ ? Math.max(highest, Number(event.attempt) || 0)
2125
+ : highest,
2126
+ 0,
2127
+ ) + 1;
2128
+ attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
2129
+ status.activeAttempts = {
2130
+ ...(status.activeAttempts || {}),
2131
+ [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null },
2132
+ };
2133
+ events.push({
2134
+ eventId: `${runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
2135
+ type: 'attempt_started',
2136
+ at: now,
2137
+ attemptId,
2138
+ stepIndex,
2139
+ stepLabel: step.label || null,
2140
+ agent,
2141
+ role: roleFor(agent),
2142
+ attempt,
2143
+ parallelGroupId: null,
2144
+ waveId: null,
2145
+ source: 'hook',
2146
+ attributionConfidence: 'high',
2147
+ });
2148
+ });
2149
+ return attemptId;
2150
+ }
2151
+
2152
+ // Re-arm the step a producer left `blocked`. It arms the attempt only: a stop
2153
+ // that finds `awaitingHumanGate: true` returns before the stop tail, so an open
2154
+ // gate would swallow the retried receipt. Gate/advance stays receipt-driven.
2155
+ if (hookInput.action === 'resume_blocked') {
2156
+ if (pauseBlocksAdvance()) process.exit(0);
2157
+ const pipeline = readPipeline();
2158
+ if (!pipeline || !Array.isArray(pipeline.steps) || pipeline.steps.length === 0) {
2159
+ resumeBlockedRefuse(
2160
+ `pipeline.json is missing, unparseable, or has no steps for slug "${slug}"; no attempt was armed and status.json is unchanged.`,
2161
+ );
2162
+ process.exit(0);
2163
+ }
2164
+ const stepIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
2165
+ const step = pipeline.steps[stepIndex];
2166
+ const blockedSteps = Array.isArray(status.blockedSteps) ? status.blockedSteps : [];
2167
+ if (blockedSteps.length > 0 || pipeline.steps.some((entry) => entry && Array.isArray(entry.dependsOn))) {
2168
+ resumeBlockedRefuse(
2169
+ `graph mode is not supported by resume_blocked for slug "${slug}" (status.blockedSteps or a step.dependsOn): nothing was armed; resume the wave by hand.`,
2170
+ );
2171
+ process.exit(0);
2172
+ }
2173
+ const agents = step ? getStepAgents(step).filter((agent) => typeof agent === 'string' && agent.length > 0) : [];
2174
+ if (agents.length === 0) {
2175
+ resumeBlockedRefuse(
2176
+ `pipeline.json has no executable step at pipelineIndex ${stepIndex} for slug "${slug}"; nothing was armed.`,
2177
+ );
2178
+ process.exit(0);
2179
+ }
2180
+ // A parallel wave is not a single linear step: re-arming it would re-run the
2181
+ // agents that already succeeded. Refuse the shape instead of arming the wave.
2182
+ if (agents.length > 1) {
2183
+ resumeBlockedRefuse(
2184
+ `step ${stepIndex} is a parallel wave for slug "${slug}" (${agents.join(', ')}); resume_blocked arms one linear step, so nothing was armed.`,
2185
+ );
2186
+ process.exit(0);
2187
+ }
2188
+ if (status.state !== 'blocked') {
2189
+ resumeBlockedRefuse(
2190
+ `state "${status.state || 'unknown'}" is not blocked for slug "${slug}"; resume_blocked only re-arms the step a producer left blocked.`,
2191
+ );
2192
+ process.exit(0);
2193
+ }
2194
+ if (status.currentAgent === 'mockup-reviewer') {
2195
+ resumeBlockedRefuse(
2196
+ `the mockup-reviewer BLOCKED_MCP skip-forward owns this state for slug "${slug}": run {"action":"end_human_gate","activateNext":true} instead; resume_blocked armed nothing.`,
2197
+ );
2198
+ process.exit(0);
2199
+ }
2200
+ const activeForStep = Object.values(status.activeAttempts || {}).filter(
2201
+ (entry) => entry && entry.stepIndex === stepIndex,
2202
+ );
2203
+ if (activeForStep.length > 0) {
2204
+ resumeBlockedRefuse(
2205
+ `step ${stepIndex} already has an active attempt for slug "${slug}" (${activeForStep.map((entry) => entry.agent).join(', ')}); resume_blocked changed nothing.`,
2206
+ );
2207
+ process.exit(0);
2208
+ }
2209
+ const attemptId = armResumedAttempt(step, stepIndex, agents[0]);
2210
+ // `currentAgent` names the blocked producer; a pipeline blocked without one
2211
+ // (missing consumer artifacts) falls back to the step's agent.
2212
+ const resumedAgent = status.currentAgent || agents[0];
2213
+ writeStatus({
2214
+ pipelineIndex: stepIndex,
2215
+ currentAgent: resumedAgent,
2216
+ phase: 'executing',
2217
+ state: 'in_progress',
2218
+ awaitingHumanGate: false,
2219
+ });
2220
+ process.stdout.write(
2221
+ JSON.stringify({
2222
+ ok: true,
2223
+ action: 'resume_blocked',
2224
+ pipelineIndex: stepIndex,
2225
+ agents,
2226
+ attemptIds: [attemptId],
2227
+ followup_message: handoffForAgent(resumedAgent, step.scope, step),
2228
+ }),
2229
+ );
2230
+ process.exit(0);
2231
+ }
2232
+
2098
2233
  if (hookInput.action === 'bootstrap') {
2099
2234
  if (pauseBlocksAdvance()) process.exit(0);
2100
2235
  const pipeline = readPipeline();
@@ -3,7 +3,7 @@
3
3
  "platform": "zcode",
4
4
  "stack": "android-kotlin",
5
5
  "semanticSource": "cursor/android-kotlin",
6
- "sourceRevision": "72e82e08587bbbb355b0bba1714f89dfc67dbc8239b5130f8285cf49b480494c",
6
+ "sourceRevision": "b380f2539e876c45db733a02a9599adc7ce1aa47a10852407ed0970dddc71da4",
7
7
  "entries": [
8
8
  {
9
9
  "source": "AGENTS.md",
@@ -23,8 +23,12 @@ try {
23
23
  }
24
24
 
25
25
  if (hookInput.status !== 'completed') {
26
- process.stdout.write('{}');
27
- process.exit(0);
26
+ // `resume_blocked` is a lifecycle repair, not a producer receipt: it runs
27
+ // with no `status`, and a `status` it carries is ignored.
28
+ if (hookInput.action !== 'resume_blocked') {
29
+ process.stdout.write('{}');
30
+ process.exit(0);
31
+ }
28
32
  }
29
33
 
30
34
  // Slug resolution, strongest first:
@@ -2097,6 +2101,137 @@ function syncMetricsProfile(pipeline) {
2097
2101
  });
2098
2102
  }
2099
2103
 
2104
+ function resumeBlockedRefuse(reason) {
2105
+ process.stdout.write(JSON.stringify({ ok: false, action: 'resume_blocked', reason }));
2106
+ }
2107
+
2108
+ /**
2109
+ * Arm attempt N+1 for one linear step. The ordinal read and the append share
2110
+ * one metrics critical section, like `completeTaskMetrics`: a second process
2111
+ * serializes on the lock and sees the first attempt instead of minting the
2112
+ * same ordinal.
2113
+ */
2114
+ function armResumedAttempt(step, stepIndex, agent) {
2115
+ let attemptId = null;
2116
+ mutateMetrics((metrics) => {
2117
+ const ledgerRunId = metrics.task && typeof metrics.task.runId === 'string' ? metrics.task.runId : '';
2118
+ const runId = ledgerRunId || status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
2119
+ metrics.task = { ...(metrics.task || {}), runId };
2120
+ status.metricsRunId = runId;
2121
+ const events = Array.isArray(metrics.events) ? metrics.events : (metrics.events = []);
2122
+ const attempt =
2123
+ events.reduce(
2124
+ (highest, event) =>
2125
+ event && event.type === 'attempt_started' && event.stepIndex === stepIndex && event.agent === agent
2126
+ ? Math.max(highest, Number(event.attempt) || 0)
2127
+ : highest,
2128
+ 0,
2129
+ ) + 1;
2130
+ attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
2131
+ status.activeAttempts = {
2132
+ ...(status.activeAttempts || {}),
2133
+ [attemptId]: { agent, stepIndex, attempt, startedAt: now, parallelGroupId: null, waveId: null },
2134
+ };
2135
+ events.push({
2136
+ eventId: `${runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
2137
+ type: 'attempt_started',
2138
+ at: now,
2139
+ attemptId,
2140
+ stepIndex,
2141
+ stepLabel: step.label || null,
2142
+ agent,
2143
+ role: roleFor(agent),
2144
+ attempt,
2145
+ parallelGroupId: null,
2146
+ waveId: null,
2147
+ source: 'hook',
2148
+ attributionConfidence: 'high',
2149
+ });
2150
+ });
2151
+ return attemptId;
2152
+ }
2153
+
2154
+ // Re-arm the step a producer left `blocked`. It arms the attempt only: a stop
2155
+ // that finds `awaitingHumanGate: true` returns before the stop tail, so an open
2156
+ // gate would swallow the retried receipt. Gate/advance stays receipt-driven.
2157
+ if (hookInput.action === 'resume_blocked') {
2158
+ if (pauseBlocksAdvance()) process.exit(0);
2159
+ const pipeline = readPipeline();
2160
+ if (!pipeline || !Array.isArray(pipeline.steps) || pipeline.steps.length === 0) {
2161
+ resumeBlockedRefuse(
2162
+ `pipeline.json is missing, unparseable, or has no steps for slug "${slug}"; no attempt was armed and status.json is unchanged.`,
2163
+ );
2164
+ process.exit(0);
2165
+ }
2166
+ const stepIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
2167
+ const step = pipeline.steps[stepIndex];
2168
+ const blockedSteps = Array.isArray(status.blockedSteps) ? status.blockedSteps : [];
2169
+ if (blockedSteps.length > 0 || pipeline.steps.some((entry) => entry && Array.isArray(entry.dependsOn))) {
2170
+ resumeBlockedRefuse(
2171
+ `graph mode is not supported by resume_blocked for slug "${slug}" (status.blockedSteps or a step.dependsOn): nothing was armed; resume the wave by hand.`,
2172
+ );
2173
+ process.exit(0);
2174
+ }
2175
+ const agents = step ? getStepAgents(step).filter((agent) => typeof agent === 'string' && agent.length > 0) : [];
2176
+ if (agents.length === 0) {
2177
+ resumeBlockedRefuse(
2178
+ `pipeline.json has no executable step at pipelineIndex ${stepIndex} for slug "${slug}"; nothing was armed.`,
2179
+ );
2180
+ process.exit(0);
2181
+ }
2182
+ // A parallel wave is not a single linear step: re-arming it would re-run the
2183
+ // agents that already succeeded. Refuse the shape instead of arming the wave.
2184
+ if (agents.length > 1) {
2185
+ resumeBlockedRefuse(
2186
+ `step ${stepIndex} is a parallel wave for slug "${slug}" (${agents.join(', ')}); resume_blocked arms one linear step, so nothing was armed.`,
2187
+ );
2188
+ process.exit(0);
2189
+ }
2190
+ if (status.state !== 'blocked') {
2191
+ resumeBlockedRefuse(
2192
+ `state "${status.state || 'unknown'}" is not blocked for slug "${slug}"; resume_blocked only re-arms the step a producer left blocked.`,
2193
+ );
2194
+ process.exit(0);
2195
+ }
2196
+ if (status.currentAgent === 'mockup-reviewer') {
2197
+ resumeBlockedRefuse(
2198
+ `the mockup-reviewer BLOCKED_MCP skip-forward owns this state for slug "${slug}": run {"action":"end_human_gate","activateNext":true} instead; resume_blocked armed nothing.`,
2199
+ );
2200
+ process.exit(0);
2201
+ }
2202
+ const activeForStep = Object.values(status.activeAttempts || {}).filter(
2203
+ (entry) => entry && entry.stepIndex === stepIndex,
2204
+ );
2205
+ if (activeForStep.length > 0) {
2206
+ resumeBlockedRefuse(
2207
+ `step ${stepIndex} already has an active attempt for slug "${slug}" (${activeForStep.map((entry) => entry.agent).join(', ')}); resume_blocked changed nothing.`,
2208
+ );
2209
+ process.exit(0);
2210
+ }
2211
+ const attemptId = armResumedAttempt(step, stepIndex, agents[0]);
2212
+ // `currentAgent` names the blocked producer; a pipeline blocked without one
2213
+ // (missing consumer artifacts) falls back to the step's agent.
2214
+ const resumedAgent = status.currentAgent || agents[0];
2215
+ writeStatus({
2216
+ pipelineIndex: stepIndex,
2217
+ currentAgent: resumedAgent,
2218
+ phase: 'executing',
2219
+ state: 'in_progress',
2220
+ awaitingHumanGate: false,
2221
+ });
2222
+ process.stdout.write(
2223
+ JSON.stringify({
2224
+ ok: true,
2225
+ action: 'resume_blocked',
2226
+ pipelineIndex: stepIndex,
2227
+ agents,
2228
+ attemptIds: [attemptId],
2229
+ followup_message: handoffForAgent(resumedAgent, step.scope, step),
2230
+ }),
2231
+ );
2232
+ process.exit(0);
2233
+ }
2234
+
2100
2235
  if (hookInput.action === 'bootstrap') {
2101
2236
  if (pauseBlocksAdvance()) process.exit(0);
2102
2237
  const pipeline = readPipeline();
@@ -3,7 +3,7 @@
3
3
  "platform": "zcode",
4
4
  "stack": "go",
5
5
  "semanticSource": "cursor/go",
6
- "sourceRevision": "f3c2102b907ac4f5433862fbe9ca764759a197f79ddb63c4980e915f1dd1fea6",
6
+ "sourceRevision": "9168c02423559f6352aaa5e00e003b00f37e48b7aab3576b4a114515ea6afc2b",
7
7
  "entries": [
8
8
  {
9
9
  "source": "AGENTS.md",