@omercnet/paseo-omp 5.4.0-next.419.1 → 5.4.0-next.420.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,8 +4,10 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
4
4
  import { useState } from "react";
5
5
  import { Pressable, Switch, Text, View } from "react-native";
6
6
  import {
7
+ listOmpRuleFirings,
7
8
  listOmpRules,
8
9
  type OmpRule,
10
+ type OmpRuleFiring,
9
11
  type OmpRuleKind,
10
12
  setOmpRuleEnabled,
11
13
  } from "../shared/omp-rules";
@@ -25,6 +27,31 @@ const COPY_LABELS: Record<CopyState, string> = {
25
27
  };
26
28
 
27
29
  const RULES_KEY = ["paseo-omp", "rules"] as const;
30
+ const FIRINGS_KEY = ["paseo-omp", "rule-firings"] as const;
31
+ const MOST_FIRED = 3;
32
+
33
+ function firingText(firing: OmpRuleFiring): string {
34
+ const times = firing.count === 1 ? "1 time" : `${firing.count} times`;
35
+ return firing.lastFiredAt
36
+ ? `${times}, last ${new Date(firing.lastFiredAt).toLocaleString()}`
37
+ : times;
38
+ }
39
+
40
+ function firedSummary(counted: {
41
+ firings: readonly OmpRuleFiring[];
42
+ sessions: number;
43
+ partial: boolean;
44
+ }): string {
45
+ const top = counted.firings
46
+ .slice(0, MOST_FIRED)
47
+ .map((firing) => `${firing.name} (${firing.count})`)
48
+ .join(", ");
49
+ const sessions = `${counted.sessions} ${counted.sessions === 1 ? "session" : "sessions"}`;
50
+ const bound = counted.partial ? ", so some firings are not counted" : "";
51
+ return top
52
+ ? `Most fired: ${top}. Counted by rule name from ${sessions}${bound}.`
53
+ : `No rule fired in the ${sessions} counted${bound}.`;
54
+ }
28
55
 
29
56
  const GROUPS: readonly { kind: OmpRuleKind; title: string; empty: string }[] = [
30
57
  { kind: "watch", title: "Watch", empty: "No watch rules" },
@@ -62,6 +89,8 @@ function Detail({
62
89
  interface RuleSwitch {
63
90
  busy: boolean;
64
91
  toggle: (name: string, enabled: boolean) => void;
92
+ /** How often the rule fired in the counted sessions; null until they are counted. */
93
+ firingLabel: (name: string) => string | null;
65
94
  }
66
95
 
67
96
  function RuleRow({
@@ -90,6 +119,8 @@ function RuleRow({
90
119
  ["Files", rule.globs],
91
120
  ["Agents", rule.agents],
92
121
  ];
122
+ // Only watch rules fire; always-applied and rulebook rules sit in the prompt.
123
+ const fired = rule.kind === "watch" ? rules.firingLabel(rule.name) : null;
93
124
  return (
94
125
  <View style={styles.setting}>
95
126
  <View style={styles.settingHeader}>
@@ -105,6 +136,7 @@ function RuleRow({
105
136
  />
106
137
  </View>
107
138
  {rule.description ? <Text style={styles.settingDescription}>{rule.description}</Text> : null}
139
+ {fired ? <Detail styles={styles} label="Fired" value={fired} /> : null}
108
140
  {details.map(([label, values]) =>
109
141
  values.length > 0 ? (
110
142
  <Detail key={label} styles={styles} label={label} value={values.join(", ")} />
@@ -186,6 +218,22 @@ export function OmpRulesSection({
186
218
  queryKey: [...RULES_KEY, ompStoreKey(store), cwd ?? "global"],
187
219
  queryFn: () => loadRules({ store, ...(cwd ? { cwd } : {}) }),
188
220
  });
221
+ const loadFirings = useRpc(listOmpRuleFirings);
222
+ const firingsQuery = useQuery({
223
+ queryKey: [...FIRINGS_KEY, ompStoreKey(store), cwd ?? "global"],
224
+ queryFn: () => loadFirings({ store, ...(cwd ? { cwd } : {}) }),
225
+ staleTime: 30_000,
226
+ });
227
+ const counted = firingsQuery.data;
228
+ const firingByName = new Map((counted?.firings ?? []).map((firing) => [firing.name, firing]));
229
+ function firingLabel(name: string): string | null {
230
+ const firing = firingByName.get(name);
231
+ if (firing) return firingText(firing);
232
+ return counted && !counted.partial ? "Not fired in the sessions counted" : null;
233
+ }
234
+ function noisiestFirst(left: OmpRule, right: OmpRule): number {
235
+ return (firingByName.get(right.name)?.count ?? 0) - (firingByName.get(left.name)?.count ?? 0);
236
+ }
189
237
  const toggle = useMutation({
190
238
  mutationKey: [...RULES_KEY, "toggle"],
191
239
  mutationFn: (change: { name: string; enabled: boolean }) =>
@@ -199,6 +247,7 @@ export function OmpRulesSection({
199
247
  const rulesSwitch: RuleSwitch = {
200
248
  busy: toggle.isPending,
201
249
  toggle: (name, enabled) => toggle.mutate({ name, enabled }),
250
+ firingLabel,
202
251
  };
203
252
  const list = rules.data;
204
253
  const focused =
@@ -222,6 +271,7 @@ export function OmpRulesSection({
222
271
  </Text>
223
272
  <Text style={styles.muted}>Rule settings (ttsr.*) are in the Configuration tab.</Text>
224
273
  </View>
274
+ {counted ? <Text style={styles.muted}>{firedSummary(counted)}</Text> : null}
225
275
  {focusRule && list?.status === "ready" ? (
226
276
  <View style={styles.card}>
227
277
  <Text style={styles.cardTitle}>Rule named {focusRule}</Text>
@@ -252,8 +302,8 @@ export function OmpRulesSection({
252
302
  <>
253
303
  {GROUPS.map((group) => {
254
304
  const members = list.rules.filter((rule) => rule.kind === group.kind);
255
- const own = members.filter((rule) => rule.source !== "builtin");
256
- const builtin = members.filter((rule) => rule.source === "builtin");
305
+ const own = members.filter((rule) => rule.source !== "builtin").sort(noisiestFirst);
306
+ const builtin = members.filter((rule) => rule.source === "builtin").sort(noisiestFirst);
257
307
  return (
258
308
  <View key={group.kind} style={styles.card}>
259
309
  <Text style={styles.cardTitle}>{group.title}</Text>
package/index.server.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  resolveMutateOmpPluginConfig,
25
25
  } from "./server/omp-plugins";
26
26
  import { readHostAppendPrompt, readOmpPromptFiles } from "./server/omp-prompt-files";
27
+ import { resolveListOmpRuleFirings } from "./server/omp-rule-firings";
27
28
  import { resolveSetOmpRuleEnabled } from "./server/omp-rule-switch";
28
29
  import { resolveTestOmpRules } from "./server/omp-rule-test";
29
30
  import { resolveListOmpRules } from "./server/omp-rules";
@@ -99,7 +100,12 @@ import {
99
100
  mutateOmpPluginConfig,
100
101
  } from "./shared/omp-plugins";
101
102
  import { getOmpPromptFiles } from "./shared/omp-prompt-files";
102
- import { listOmpRules, setOmpRuleEnabled, testOmpRules } from "./shared/omp-rules";
103
+ import {
104
+ listOmpRuleFirings,
105
+ listOmpRules,
106
+ setOmpRuleEnabled,
107
+ testOmpRules,
108
+ } from "./shared/omp-rules";
103
109
  import { listOmpSecurity } from "./shared/omp-security";
104
110
  import { listOmpSettings, updateOmpSettings } from "./shared/omp-settings";
105
111
  import { deleteOmpManagedSkill, listOmpSkills, setOmpSkillEnabled } from "./shared/omp-skills";
@@ -229,6 +235,7 @@ export default function contribute(server: PluginServerContext) {
229
235
  server.handle(listOmpRules, scoped(resolveListOmpRules));
230
236
  server.handle(setOmpRuleEnabled, scoped(resolveSetOmpRuleEnabled));
231
237
  server.handle(testOmpRules, scoped(resolveTestOmpRules));
238
+ server.handle(listOmpRuleFirings, scoped(resolveListOmpRuleFirings));
232
239
  server.handle(listOmpExtensions, scoped(resolveListOmpExtensions));
233
240
  server.handle(setOmpExtensionEnabled, scoped(resolveSetOmpExtensionEnabled));
234
241
  server.handle(listOmpSecurity, scoped(resolveListOmpSecurity));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-omp",
3
- "version": "5.4.0-next.419.1",
3
+ "version": "5.4.0-next.420.1",
4
4
  "type": "module",
5
5
  "description": "Paseo integration for OMP, including its direct provider and workspace tooling.",
6
6
  "license": "MIT",
@@ -0,0 +1,211 @@
1
+ import { constants } from "node:fs";
2
+ import { type FileHandle, open, stat } from "node:fs/promises";
3
+ import { createInterface } from "node:readline";
4
+ import type { RpcInput } from "@getpaseo/plugin";
5
+ import { z } from "zod";
6
+ import type { listOmpRuleFirings, OmpRuleFiring } from "../shared/omp-rules";
7
+ import { currentOmpEnvironment } from "./paths";
8
+ import { listOmpSessionDescriptors } from "./provider/session-descriptors";
9
+
10
+ export interface FiringLimits {
11
+ /** Newest sessions to count. */
12
+ sessions: number;
13
+ /** Text read from one session file; the rest of a longer file is left uncounted. */
14
+ fileBytes: number;
15
+ /** Text read across all sessions of one request; sessions already counted cost nothing. */
16
+ totalBytes: number;
17
+ ms: number;
18
+ }
19
+
20
+ /** `sessions` plus the one extra session asked for must stay within the session listing's cap of 500. */
21
+ export const DEFAULT_FIRING_LIMITS: FiringLimits = {
22
+ sessions: 400,
23
+ fileBytes: 8 * 1024 * 1024,
24
+ totalBytes: 64 * 1024 * 1024,
25
+ ms: 8_000,
26
+ };
27
+ const MAX_RULES = 500;
28
+ const MAX_CACHED_FILES = 2_000;
29
+ const MAX_NAME_CHARS = 256;
30
+
31
+ /** One `ttsr_injection` line of an OMP session file: the rules injected after a match. */
32
+ const InjectionSchema = z.object({
33
+ type: z.literal("ttsr_injection"),
34
+ timestamp: z.string().optional(),
35
+ injectedRules: z.array(z.string()),
36
+ });
37
+
38
+ interface Tally {
39
+ count: number;
40
+ /** Epoch ms of the latest firing, or 0 when no entry had a readable time. */
41
+ last: number;
42
+ }
43
+
44
+ interface FileFirings {
45
+ mtimeMs: number;
46
+ size: number;
47
+ /** Bytes the counts cover: a larger bound than this one means the file must be read again. */
48
+ readBytes: number;
49
+ truncated: boolean;
50
+ rules: Map<string, Tally>;
51
+ }
52
+
53
+ /** Counts per session file, valid while its modification time and size are unchanged. */
54
+ const cache = new Map<string, FileFirings>();
55
+
56
+ function remember(path: string, firings: FileFirings): void {
57
+ cache.delete(path);
58
+ cache.set(path, firings);
59
+ if (cache.size > MAX_CACHED_FILES) {
60
+ const oldest = cache.keys().next().value;
61
+ if (oldest !== undefined) cache.delete(oldest);
62
+ }
63
+ }
64
+
65
+ function addTo(rules: Map<string, Tally>, name: string, at: number, count = 1): void {
66
+ const tally = rules.get(name) ?? { count: 0, last: 0 };
67
+ tally.count += count;
68
+ tally.last = Math.max(tally.last, at);
69
+ rules.set(name, tally);
70
+ }
71
+
72
+ const LINES_PER_TIME_CHECK = 1_000;
73
+
74
+ /** The counts of one file, or null when `expired` ended the read or the file could not be read. */
75
+ async function countFile(
76
+ path: string,
77
+ readBytes: number,
78
+ expired: () => boolean,
79
+ ): Promise<Map<string, Tally> | null> {
80
+ const rules = new Map<string, Tally>();
81
+ let lineCount = 0;
82
+ let handle: FileHandle;
83
+ try {
84
+ handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
85
+ } catch {
86
+ return null;
87
+ }
88
+ try {
89
+ const lines = createInterface({
90
+ input: handle.createReadStream({ encoding: "utf8", end: readBytes - 1 }),
91
+ crlfDelay: Number.POSITIVE_INFINITY,
92
+ });
93
+ for await (const line of lines) {
94
+ lineCount += 1;
95
+ if (lineCount % LINES_PER_TIME_CHECK === 0 && expired()) return null;
96
+ if (!line.includes('"ttsr_injection"')) continue;
97
+ let parsed: unknown;
98
+ try {
99
+ parsed = JSON.parse(line);
100
+ } catch {
101
+ continue;
102
+ }
103
+ const entry = InjectionSchema.safeParse(parsed);
104
+ if (!entry.success) continue;
105
+ const at = Date.parse(entry.data.timestamp ?? "");
106
+ for (const name of entry.data.injectedRules) {
107
+ if (name && name.length <= MAX_NAME_CHARS) addTo(rules, name, Number.isNaN(at) ? 0 : at);
108
+ }
109
+ }
110
+ } catch {
111
+ return null;
112
+ } finally {
113
+ await handle.close().catch(() => undefined);
114
+ }
115
+ return expired() ? null : rules;
116
+ }
117
+
118
+ /**
119
+ * How often each rule fired, from the `ttsr_injection` entries of OMP's session files: the
120
+ * sessions of `cwd` when given, else every session in the store. Newest sessions first, bounded
121
+ * by `limits`; files already counted are reused while their mtime and size are unchanged.
122
+ */
123
+ export async function readRuleFirings(
124
+ input: { cwd?: string; sessionDir?: string },
125
+ environment: NodeJS.ProcessEnv = currentOmpEnvironment(),
126
+ limits: FiringLimits = DEFAULT_FIRING_LIMITS,
127
+ now: () => number = Date.now,
128
+ ): Promise<{ firings: OmpRuleFiring[]; sessions: number; partial: boolean }> {
129
+ const started = now();
130
+ const expired = () => now() - started > limits.ms;
131
+ let partial = false;
132
+ const signal = AbortSignal.timeout(limits.ms);
133
+ let found: Awaited<ReturnType<typeof listOmpSessionDescriptors>>;
134
+ try {
135
+ found = await listOmpSessionDescriptors(
136
+ {
137
+ // One more than wanted, to learn whether older sessions exist.
138
+ limit: limits.sessions + 1,
139
+ signal,
140
+ onTruncated: () => {
141
+ partial = true;
142
+ },
143
+ ...(input.cwd ? { cwd: input.cwd } : {}),
144
+ ...(input.sessionDir ? { sessionDir: input.sessionDir } : {}),
145
+ },
146
+ environment,
147
+ );
148
+ } catch (error) {
149
+ if (signal.aborted) return { firings: [], sessions: 0, partial: true };
150
+ throw error;
151
+ }
152
+ if (found.length > limits.sessions) partial = true;
153
+ const sessions = found.slice(0, limits.sessions);
154
+ const totals = new Map<string, Tally>();
155
+ let counted = 0;
156
+ let bytes = 0;
157
+ for (const session of sessions) {
158
+ const file = session.transcriptFile;
159
+ if (!file) continue;
160
+ if (expired()) {
161
+ partial = true;
162
+ break;
163
+ }
164
+ const info = await stat(file).catch(() => null);
165
+ if (!info?.isFile()) continue;
166
+ const readBytes = Math.min(info.size, limits.fileBytes);
167
+ let firings = cache.get(file);
168
+ if (
169
+ firings?.mtimeMs !== info.mtimeMs ||
170
+ firings.size !== info.size ||
171
+ firings.readBytes !== readBytes
172
+ ) {
173
+ if (bytes + readBytes > limits.totalBytes) {
174
+ partial = true;
175
+ break;
176
+ }
177
+ bytes += readBytes;
178
+ const rules = await countFile(file, readBytes, expired);
179
+ if (!rules) {
180
+ // Not cached: a file that could not be read completely is read again next time.
181
+ partial = true;
182
+ continue;
183
+ }
184
+ firings = {
185
+ mtimeMs: info.mtimeMs,
186
+ size: info.size,
187
+ readBytes,
188
+ truncated: info.size > limits.fileBytes,
189
+ rules,
190
+ };
191
+ remember(file, firings);
192
+ }
193
+ if (firings.truncated) partial = true;
194
+ counted += 1;
195
+ for (const [name, tally] of firings.rules) addTo(totals, name, tally.last, tally.count);
196
+ }
197
+ if (totals.size > MAX_RULES) partial = true;
198
+ const firings = [...totals]
199
+ .map(([name, tally]) => ({
200
+ name,
201
+ count: tally.count,
202
+ lastFiredAt: tally.last > 0 ? new Date(tally.last).toISOString() : null,
203
+ }))
204
+ .sort((left, right) => right.count - left.count || left.name.localeCompare(right.name))
205
+ .slice(0, MAX_RULES);
206
+ return { firings, sessions: counted, partial };
207
+ }
208
+
209
+ export function resolveListOmpRuleFirings(input: RpcInput<typeof listOmpRuleFirings>) {
210
+ return readRuleFirings(input);
211
+ }
@@ -1,2 +1,2 @@
1
1
  /** Release Please keeps this bundle-safe constant aligned with package.json. */
2
- export const PASEO_OMP_PACKAGE_VERSION = "5.4.0-next.419.1"; // x-release-please-version
2
+ export const PASEO_OMP_PACKAGE_VERSION = "5.4.0-next.420.1"; // x-release-please-version
@@ -59,6 +59,8 @@ export interface OmpSessionListOptions {
59
59
  sessionId?: string;
60
60
  sessionDir?: string;
61
61
  signal?: AbortSignal;
62
+ /** Called when a scan bound ended the listing early, so the result may miss sessions. */
63
+ onTruncated?: () => void;
62
64
  }
63
65
 
64
66
  interface ScanBudget {
@@ -510,6 +512,7 @@ export async function listOmpSessionDescriptors(
510
512
  options.signal,
511
513
  );
512
514
  options.signal?.throwIfAborted();
515
+ if (budgetExceeded(budget)) options.onTruncated?.();
513
516
  return matches;
514
517
  }
515
518
 
@@ -109,3 +109,26 @@ export const testOmpRules = defineRpc({
109
109
  z.object({ status: z.literal("error"), message: z.string() }),
110
110
  ]),
111
111
  });
112
+
113
+ export const OmpRuleFiringSchema = z.object({
114
+ name: z.string(),
115
+ count: z.number().int().positive(),
116
+ /** ISO time of the most recent firing. */
117
+ lastFiredAt: z.string().nullable(),
118
+ });
119
+ export type OmpRuleFiring = z.infer<typeof OmpRuleFiringSchema>;
120
+
121
+ /** How often each rule fired, counted from OMP's session files for this workspace or every session. */
122
+ export const listOmpRuleFirings = defineRpc({
123
+ name: "paseo-omp.rule-firings",
124
+ input: z
125
+ .object({ store: OmpStoreSchema.optional(), cwd: OmpWorkspaceCwdSchema.optional() })
126
+ .strict(),
127
+ output: z.object({
128
+ firings: z.array(OmpRuleFiringSchema),
129
+ /** Sessions the counts cover. */
130
+ sessions: z.number().int().nonnegative(),
131
+ /** True when a size or time bound left some sessions or session text uncounted. */
132
+ partial: z.boolean(),
133
+ }),
134
+ });