@bonesofspring/ai-rules 0.2.69 → 0.2.71

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.
@@ -12,8 +12,16 @@
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. Child
19
+ * discovery starts after the rewrite, is never awaited, and stops being waited
20
+ * for at AI_RULES_OUTPUT_GUARD_DISCOVERY_MS (default 250 ms); it cannot be
21
+ * cancelled.
15
22
  */
16
23
 
24
+ import { createHash } from "node:crypto"
17
25
  import fs from "node:fs"
18
26
  import path from "node:path"
19
27
  import { Plugin } from "@opencode/plugin"
@@ -27,6 +35,8 @@ const HEAD_BYTES = 2048
27
35
  const TAIL_BYTES = 1024
28
36
  const HEAD_LINES = 40
29
37
  const TAIL_LINES = 15
38
+ const MAX_TRACKED_SESSIONS = 12
39
+ const DEFAULT_DISCOVERY_MS = 250
30
40
  const ALLOWLIST = new Set(["shell", "bash", "read", "grep", "glob", "webfetch"])
31
41
 
32
42
  const findTeamRoot = (start: string): string | null => {
@@ -110,6 +120,86 @@ const readNumber = (name: string, fallback: number): number => {
110
120
  return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback
111
121
  }
112
122
 
123
+ const recordOf = (value: unknown): Record<string, unknown> =>
124
+ value !== null && typeof value === "object" ? (value as Record<string, unknown>) : {}
125
+
126
+ /** `session.list` answers `{ data }` over the client and a bare array in-process. */
127
+ const rowsOf = (value: unknown): unknown[] => {
128
+ if (Array.isArray(value)) return value
129
+ const data = recordOf(value).data
130
+ return Array.isArray(data) ? data : []
131
+ }
132
+
133
+ const utf8Bytes = (value: string): number => Buffer.byteLength(value, "utf8")
134
+
135
+ type ToolRow = { name: string; bytes: number; schema: string }
136
+ type ServerRow = { name: string; tools: number; bytes: number }
137
+
138
+ const toolRows = (tools: unknown): ToolRow[] => {
139
+ const rows: ToolRow[] = []
140
+ for (const [name, schema] of Object.entries(recordOf(tools)).sort(([left], [right]) =>
141
+ left.localeCompare(right),
142
+ )) {
143
+ const serialized = JSON.stringify(schema) ?? ""
144
+ rows.push({ name, bytes: utf8Bytes(serialized), schema: serialized })
145
+ }
146
+ return rows
147
+ }
148
+
149
+ const sumBytes = (rows: Array<{ bytes: number }>): number =>
150
+ rows.reduce((total, row) => total + row.bytes, 0)
151
+
152
+ const systemBytes = (system: unknown): number => {
153
+ if (!Array.isArray(system)) return 0
154
+ let total = 0
155
+ for (const part of system) {
156
+ const text = recordOf(part).text
157
+ if (typeof text === "string") total += utf8Bytes(text)
158
+ }
159
+ return total
160
+ }
161
+
162
+ /** MCP tools are named `<server>_<tool>`; a server with no dispatched schema is left out. */
163
+ const serverRows = (names: string[], tools: ToolRow[]): ServerRow[] => {
164
+ const rows: ServerRow[] = []
165
+ for (const name of names.sort((left, right) => left.localeCompare(right))) {
166
+ const matched = tools.filter((tool) => tool.name.startsWith(`${name}_`))
167
+ if (matched.length === 0) continue
168
+ rows.push({ name, tools: matched.length, bytes: sumBytes(matched) })
169
+ }
170
+ return rows
171
+ }
172
+
173
+ const toolsetHash = (rows: ToolRow[]): string =>
174
+ createHash("sha256")
175
+ .update(rows.map((row) => `${row.name}\n${row.schema}`).join("\n"))
176
+ .digest("hex")
177
+ .slice(0, 16)
178
+
179
+ /**
180
+ * `context.jsonl` is not rotated, so the keys already on disk seed the dedupe set:
181
+ * a plugin reload must not repeat a `(sessionID, toolset)` row.
182
+ */
183
+ const loadToolsets = (outputDir: string): Set<string> => {
184
+ const seen = new Set<string>()
185
+ try {
186
+ for (const line of fs.readFileSync(path.join(outputDir, "context.jsonl"), "utf8").split("\n")) {
187
+ if (line.trim() === "") continue
188
+ try {
189
+ const row = recordOf(JSON.parse(line))
190
+ if (typeof row.sessionID === "string" && typeof row.toolset === "string") {
191
+ seen.add(`${row.sessionID}|${row.toolset}`)
192
+ }
193
+ } catch {
194
+ /* a torn last line must not stop the plugin */
195
+ }
196
+ }
197
+ } catch {
198
+ /* no snapshot ledger yet */
199
+ }
200
+ return seen
201
+ }
202
+
113
203
  type ToolItem = {
114
204
  type?: string
115
205
  id?: string
@@ -186,6 +276,9 @@ export default Plugin.define({
186
276
  const outputDir = process.env.AI_RULES_OUTPUT_GUARD_DIR
187
277
  ? path.resolve(process.env.AI_RULES_OUTPUT_GUARD_DIR)
188
278
  : path.join(root, "output-guard")
279
+ // Wait bound for the detached discovery; the work bound is
280
+ // MAX_TRACKED_SESSIONS. Neither cancels an RPC already in flight.
281
+ const discoveryMs = readNumber("AI_RULES_OUTPUT_GUARD_DISCOVERY_MS", DEFAULT_DISCOVERY_MS)
189
282
  // Rotation is setup-only: the context hook must never stat or rename a ledger.
190
283
  const rotateBytes = parseRotateBytes(process.env[ROTATE_BYTES_ENV])
191
284
  rotateLedger(path.join(outputDir, "results.jsonl"), rotateBytes)
@@ -195,8 +288,81 @@ export default Plugin.define({
195
288
  const statsRecorded = new Set<string>()
196
289
  const resultsSeen = new Set<string>()
197
290
  const usageSeen = new Set<string>()
291
+ const toolsetsSeen = loadToolsets(outputDir)
292
+ const childrenByParent = new Map<string, Set<string>>()
198
293
 
199
- const recordUsage = async (sessionID: string) => {
294
+ const rememberChild = (parentID: string, childID: string) => {
295
+ const known = childrenByParent.get(parentID)
296
+ if (known) known.add(childID)
297
+ else childrenByParent.set(parentID, new Set([childID]))
298
+ }
299
+
300
+ // A session's own rows are tagged from its `parentID`, so a child that runs
301
+ // its own hook still lands as a child row. Parent-side discovery below is
302
+ // the backstop for a child whose hook never reached this plugin.
303
+ const parentOf = async (sessionID: string): Promise<string | undefined> => {
304
+ if (typeof ctx.session?.get !== "function") return undefined
305
+ try {
306
+ const parentID = recordOf(await ctx.session.get({ sessionID })).parentID
307
+ return typeof parentID === "string" && parentID !== sessionID ? parentID : undefined
308
+ } catch {
309
+ return undefined
310
+ }
311
+ }
312
+
313
+ // `session.created` covers children created after setup, `list({ parentID })`
314
+ // covers the ones that existed before it.
315
+ const watchChildren = () => {
316
+ try {
317
+ if (typeof ctx.event?.subscribe !== "function") return
318
+ const events = ctx.event.subscribe({ types: ["session.created"] })
319
+ void (async () => {
320
+ try {
321
+ for await (const event of events) {
322
+ // Payload sits under `data` in host v2 and under `properties` in v1.
323
+ const payload = recordOf(recordOf(event).data ?? recordOf(event).properties)
324
+ const parentID = payload.parentID
325
+ const childID = payload.sessionID
326
+ if (
327
+ typeof parentID === "string" &&
328
+ typeof childID === "string" &&
329
+ parentID !== childID
330
+ ) {
331
+ rememberChild(parentID, childID)
332
+ }
333
+ }
334
+ } catch {
335
+ /* the stream is an optimization; list() still finds the child */
336
+ }
337
+ })()
338
+ } catch {
339
+ /* a host without an event domain keeps the list path */
340
+ }
341
+ }
342
+
343
+ const childrenOf = async (parentID: string): Promise<string[]> => {
344
+ const known = new Set(childrenByParent.get(parentID) ?? [])
345
+ if (typeof ctx.session?.list !== "function") return [...known]
346
+ try {
347
+ const response = await ctx.session.list({
348
+ directory: ctx.location.directory,
349
+ parentID,
350
+ archived: false,
351
+ limit: MAX_TRACKED_SESSIONS,
352
+ })
353
+ for (const row of rowsOf(response)) {
354
+ const id = recordOf(row).id
355
+ if (typeof id !== "string" || id === parentID) continue
356
+ known.add(id)
357
+ rememberChild(parentID, id)
358
+ }
359
+ } catch {
360
+ /* the event path may still know the child */
361
+ }
362
+ return [...known].slice(0, MAX_TRACKED_SESSIONS)
363
+ }
364
+
365
+ const recordSession = async (sessionID: string, parentSessionID?: string) => {
200
366
  try {
201
367
  const messages = await ctx.session.context({ sessionID })
202
368
  if (!Array.isArray(messages)) return
@@ -219,7 +385,7 @@ export default Plugin.define({
219
385
  const key = `${sessionID}|${id}`
220
386
  if (usageSeen.has(key)) continue
221
387
  usageSeen.add(key)
222
- appendJsonl(outputDir, "usage.jsonl", {
388
+ const row: Record<string, unknown> = {
223
389
  at: new Date().toISOString(),
224
390
  sessionID,
225
391
  messageID: id,
@@ -232,17 +398,91 @@ export default Plugin.define({
232
398
  cacheWrite: typeof tokens.cache?.write === "number" ? tokens.cache.write : 0,
233
399
  cost: typeof message.cost === "number" ? message.cost : 0,
234
400
  finish: typeof message.finish === "string" ? message.finish : "",
235
- })
401
+ }
402
+ if (parentSessionID !== undefined) row.parentSessionID = parentSessionID
403
+ appendJsonl(outputDir, "usage.jsonl", row)
236
404
  }
237
405
  } catch {
238
406
  /* fail open: usage is an observation, not a guard input */
239
407
  }
240
408
  }
241
409
 
410
+ const recordUsage = async (sessionID: string) => {
411
+ const queue: Array<{ id: string; parentSessionID?: string }> = [
412
+ { id: sessionID, parentSessionID: await parentOf(sessionID) },
413
+ ]
414
+ const visited = new Set([sessionID])
415
+ for (let index = 0; index < queue.length && index < MAX_TRACKED_SESSIONS; index += 1) {
416
+ const current = queue[index]
417
+ await recordSession(current.id, current.parentSessionID)
418
+ for (const child of await childrenOf(current.id)) {
419
+ if (visited.has(child)) continue
420
+ visited.add(child)
421
+ queue.push({ id: child, parentSessionID: current.id })
422
+ }
423
+ }
424
+ }
425
+
426
+ // The hook hands discovery off instead of awaiting it: `recordUsage` is
427
+ // given the session id only, so the in-place rewrite of `event.messages`
428
+ // cannot reach it. One timer per task, `unref`'d so it holds nothing open,
429
+ // cleared when the race settles. The race bounds the wait, not the work:
430
+ // the walk keeps running and a late response still appends its row; rows
431
+ // are absent only when the host never answers.
432
+ const detachDiscovery = (sessionID: string) => {
433
+ let timer: ReturnType<typeof setTimeout> | undefined
434
+ const deadline = new Promise<void>((resolve) => {
435
+ timer = setTimeout(resolve, discoveryMs)
436
+ timer.unref()
437
+ })
438
+ void Promise.race([recordUsage(sessionID), deadline])
439
+ .catch(() => {
440
+ /* usage is an observation, not a guard input */
441
+ })
442
+ .finally(() => clearTimeout(timer))
443
+ }
444
+
445
+ const mcpServerNames = async (): Promise<string[] | null> => {
446
+ if (typeof ctx.mcp?.list !== "function") return null
447
+ try {
448
+ return rowsOf(await ctx.mcp.list({}))
449
+ .map((row) => recordOf(row).name)
450
+ .filter((name): name is string => typeof name === "string" && name !== "")
451
+ } catch {
452
+ return null
453
+ }
454
+ }
455
+
456
+ const recordToolset = async (sessionID: string, source: unknown) => {
457
+ const request = recordOf(source)
458
+ const tools = toolRows(request.tools)
459
+ if (tools.length === 0) return
460
+ const toolset = toolsetHash(tools)
461
+ const key = `${sessionID}|${toolset}`
462
+ if (toolsetsSeen.has(key)) return
463
+ toolsetsSeen.add(key)
464
+ const byTool = tools.map(({ name, bytes }) => ({ name, bytes }))
465
+ const row: Record<string, unknown> = {
466
+ at: new Date().toISOString(),
467
+ sessionID,
468
+ toolset,
469
+ tools: byTool.length,
470
+ toolSchemaBytes: sumBytes(byTool),
471
+ systemBytes: systemBytes(request.system),
472
+ byTool,
473
+ }
474
+ // No `mcpServers` key when the list call failed: an empty array would read
475
+ // as "measured zero" in the report.
476
+ const names = await mcpServerNames()
477
+ if (names !== null) row.mcpServers = serverRows(names, byTool)
478
+ appendJsonl(outputDir, "context.jsonl", row)
479
+ }
480
+
481
+ watchChildren()
482
+
242
483
  await ctx.session.hook("context", async (event) => {
243
484
  try {
244
485
  const sessionID = typeof event.sessionID === "string" ? event.sessionID : "session"
245
- await recordUsage(sessionID)
246
486
  const { calls, results } = collectToolActivity(event.messages)
247
487
  const save = ({ tool, id, text }: { tool: string; id: string; text: string }) => {
248
488
  const key = `${sessionID}|${id}|${tool}`
@@ -284,6 +524,16 @@ export default Plugin.define({
284
524
  path: changed?.path ?? "",
285
525
  })
286
526
  }
527
+ // Detached after the rewrite: the tool result must never depend on
528
+ // discovery, and the deadline keeps a hung host from holding a task.
529
+ detachDiscovery(sessionID)
530
+ // Last, and guarded on its own: a snapshot failure must not change the
531
+ // rewrite that already mutated `event.messages`.
532
+ try {
533
+ await recordToolset(sessionID, event)
534
+ } catch {
535
+ /* the snapshot is an observation, not a guard input */
536
+ }
287
537
  } catch (error) {
288
538
  if (process.env.AI_RULES_OUTPUT_GUARD_DEBUG === "1") {
289
539
  appendJsonl(outputDir, "debug.log", {
@@ -3,7 +3,7 @@
3
3
  "platform": "zcode",
4
4
  "stack": "next",
5
5
  "semanticSource": "cursor/next",
6
- "sourceRevision": "4cc832fcd394b5f68f4dd3008732965b197e4db0e161cf07adf5f8fbdd6228aa",
6
+ "sourceRevision": "633684ed117315d643a4af6bfcaa880093da59c22aef618fafc931d070330711",
7
7
  "entries": [
8
8
  {
9
9
  "source": "AGENTS.md",
@@ -527,6 +527,22 @@
527
527
  "loadMode": "native-skill",
528
528
  "reason": "Native slash commands under .zcode/commands; $ARGUMENTS kept (probe P-3)"
529
529
  },
530
+ {
531
+ "source": "commands/ui-start.md",
532
+ "target": "commands/ui-start.md",
533
+ "category": "commands",
534
+ "disposition": "transform",
535
+ "loadMode": "native-skill",
536
+ "reason": "Native slash commands under .zcode/commands; $ARGUMENTS kept (probe P-3)"
537
+ },
538
+ {
539
+ "source": "commands/ui-stop.md",
540
+ "target": "commands/ui-stop.md",
541
+ "category": "commands",
542
+ "disposition": "transform",
543
+ "loadMode": "native-skill",
544
+ "reason": "Native slash commands under .zcode/commands; $ARGUMENTS kept (probe P-3)"
545
+ },
530
546
  {
531
547
  "source": "commands/update.md",
532
548
  "target": "commands/update.md",
@@ -46,6 +46,11 @@ On OpenCode, `/task-evil` runs as the `task-evil` primary agent: the `question`
46
46
  → reviewer only
47
47
  ```
48
48
 
49
+ ## UI stack commands
50
+
51
+ - **`/ui-start`** — stop the running `team-tasks-ui` stack, run `team-db.mjs migrate-tasks`, then rebuild and start it.
52
+ - **`/ui-stop`** — stop the `team-tasks-ui` stack and the team-db API that `/ui-start` started.
53
+
49
54
  ## Related files
50
55
 
51
56
  - Subagents: `../agents/` (**24** roles, including `task-router.md`, `codebase-analyzer.md`)
@@ -0,0 +1,57 @@
1
+ ---
2
+ description: "Restart the team-tasks UI stack: stop it when running, refresh the task projection, then start."
3
+ ---
4
+
5
+ ## Invocation arguments
6
+
7
+ $ARGUMENTS
8
+
9
+ # Start the team-tasks UI
10
+
11
+ Bring up `apps/team-tasks-ui` through its own Docker Compose project, rebuilt
12
+ from the current source, and guarantee the host team-db API the UI reads from.
13
+
14
+ ## What to do
15
+
16
+ 1. If `apps/team-tasks-ui/scripts/stack.mjs` is absent, stop and report that this
17
+ repository has no team-tasks UI. Otherwise, from the repository root, run:
18
+
19
+ ```bash
20
+ node apps/team-tasks-ui/scripts/stack.mjs start
21
+ ```
22
+
23
+ 2. Quote the command's stdout verbatim: the `ui:` line and the `api:` line,
24
+ including the owner state. On success the script prints
25
+ `ui: http://127.0.0.1:4300` and
26
+ `api: http://127.0.0.1:4178 (owner: pre-existing|started-by-this-script)`.
27
+ 3. On a non-zero exit, quote the `error:` line verbatim and stop. Do not retry
28
+ with a different compose command and do not start the API by hand.
29
+ 4. The start is restart-safe: when the `team-tasks-ui` project is already
30
+ running, the script stops it first, runs `team-db.mjs migrate-tasks` against
31
+ the projection, then rebuilds the image from the current source and starts
32
+ again. A second start never binds a second stack or a second listener on the
33
+ published port.
34
+
35
+ ## What the script does
36
+
37
+ - Pins every project call to `apps/team-tasks-ui/docker-compose.yml` and the
38
+ `team-tasks-ui` project name.
39
+ - Stops a running `team-tasks-ui` project and the API this script started
40
+ before refreshing the projection.
41
+ - Runs `node .ai.local/scripts/team-db.mjs migrate-tasks --quiet --no-rebuild`
42
+ after that stop and before the rebuild, so the UI serves the current task
43
+ projection.
44
+ - Seeds `team/runner.json` from the default when it is absent.
45
+ - Starts the host API with `node .ai.local/scripts/team-db.mjs serve` only when
46
+ nothing answers on `127.0.0.1:4178`, and records that ownership in the
47
+ git-ignored `.ai.local/.ui/api.json` marker.
48
+ - Repairs a missing derived database once through `team-db.mjs sync`, and never
49
+ repairs an API this script did not start.
50
+
51
+ ## Do not
52
+
53
+ - Write `status.json`, `metrics.json`, or any task or lifecycle file.
54
+ - Run `docker stop`, `docker rm`, `docker kill`, or a bare `docker compose down`.
55
+ - Edit `apps/team-tasks-ui/docker-compose.yml`, the Dockerfile, the app source,
56
+ or the team-db API.
57
+ - Open a browser, tail container logs, or start a second copy of the app.
@@ -0,0 +1,46 @@
1
+ ---
2
+ description: "Stop the team-tasks UI compose project and the team-db API that /ui-start started."
3
+ ---
4
+
5
+ ## Invocation arguments
6
+
7
+ $ARGUMENTS
8
+
9
+ # Stop the team-tasks UI
10
+
11
+ Take down the `apps/team-tasks-ui` Docker Compose project and stop the host
12
+ team-db API only when `/ui-start` started it.
13
+
14
+ ## What to do
15
+
16
+ 1. If `apps/team-tasks-ui/scripts/stack.mjs` is absent, stop and report that this
17
+ repository has no team-tasks UI. Otherwise, from the repository root, run:
18
+
19
+ ```bash
20
+ node apps/team-tasks-ui/scripts/stack.mjs stop
21
+ ```
22
+
23
+ 2. Quote the command's stdout verbatim. On an already stopped stack it prints
24
+ `nothing running` and exits 0.
25
+ 3. On a non-zero exit, quote the `error:` line verbatim and stop.
26
+ 4. The stop is idempotent: a second stop exits 0 and changes nothing.
27
+
28
+ ## What the script does
29
+
30
+ - Pins every project call to `apps/team-tasks-ui/docker-compose.yml` and the
31
+ `team-tasks-ui` project name, and removes that project's containers and
32
+ network.
33
+ - Stops only the API process recorded in `.ai.local/.ui/api.json` whose live
34
+ command line is still `team-db.mjs serve`, then removes that marker.
35
+ - Leaves a foreign API alone: a process the marker does not prove is never
36
+ signalled.
37
+
38
+ ## Do not
39
+
40
+ - Write `status.json`, `metrics.json`, or any task or lifecycle file.
41
+ - Run `docker stop`, `docker rm`, `docker kill`, or a bare `docker compose down`.
42
+ - Stop a container outside the `team-tasks-ui` project.
43
+ - Edit `apps/team-tasks-ui/docker-compose.yml`, the Dockerfile, or the app
44
+ source.
45
+ - Kill a process on `127.0.0.1:4178` by port; only the ownership marker
46
+ authorizes a stop.