proactive-gate 0.2.2 → 0.2.3

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.
package/README.md CHANGED
@@ -132,7 +132,8 @@ Passing a single window is unchanged and remains the common case; a schedule who
132
132
  resolves to the same window behaves identically to that window.
133
133
 
134
134
  `weeklyBudget({ limit, bypassPriority })` is the same shape keyed on the user's local ISO
135
- week; `defaultChecks({ weeklyLimit })` places it just before the daily one. Budgets are
135
+ week; `defaultChecks({ weeklyLimit })` places it just before the daily one. It was contributed by
136
+ [@edwardsong08](https://github.com/edwardsong08) in [#9](https://github.com/Bubblegunn/proactive-gate/pull/9). Budgets are
136
137
  consumed in check order at commit, so when a weekly check passes and the daily one then
137
138
  refuses, that weekly unit is spent without a delivery. It only happens when two commits
138
139
  race after a shared evaluate.
@@ -374,11 +375,62 @@ if (decision.allowed && await gate.commit(decision, input)) { // INCR, returns
374
375
  counter is keyed on the user's local day, so a budget resets at the user's midnight,
375
376
  not at UTC.
376
377
 
378
+ ## One message per event, when the transport delivers twice
379
+
380
+ Message transports deliver at least once. A webhook that does not get its `200`
381
+ quickly enough is sent again; a queue hands the same event to two workers; a retry
382
+ after a timeout arrives after the first attempt already succeeded. The user sees the
383
+ same message twice and reads it as a broken assistant.
384
+
385
+ `dedupe` is the check for it, and it is off unless you ask for it:
386
+
387
+ ```ts
388
+ const gate = createGate({ checks: defaultChecks({ dedupe: true }), store });
389
+
390
+ await gate.evaluate({
391
+ user,
392
+ candidate: { id: crypto.randomUUID(), type: "shipping", dedupeKey: "order:42:shipped" },
393
+ });
394
+ ```
395
+
396
+ The key is yours because only you know what makes two attempts the same event.
397
+ Derive it from the event, `order:42:shipped`, not from a fresh identifier per attempt
398
+ and not from the message text, which usually carries a timestamp and so differs on
399
+ every retry. Without a `dedupeKey` the check skips and says so, rather than guessing a
400
+ key and silently doing nothing.
401
+
402
+ Three things about it are worth stating, because they are what a hand-rolled version
403
+ usually gets wrong.
404
+
405
+ **The claim is atomic and happens at commit.** Two workers holding the same event both
406
+ evaluate before either has recorded anything, so a check that only reads cannot tell
407
+ them apart. `dedupe` reads at evaluate and claims at commit with the same increment the
408
+ budgets use; only the caller that receives the first increment may send. A
409
+ read-then-write claim lets both through, and the spec calls that non-conforming.
410
+
411
+ **A suppressed duplicate does not cost a message.** `dedupe` consumes before the
412
+ budgets, so when it loses the race the gate stops there and the counter is never
413
+ incremented. The cost of that ordering, which is real: an event that clears `dedupe`
414
+ and is then refused by an exhausted budget has claimed its key for the rest of the
415
+ window.
416
+
417
+ **The window is fixed from the first claim, not sliding.** A stream of duplicates does
418
+ not push the expiry further out; every store here keeps the original expiry when a key
419
+ is incremented again.
420
+
421
+ The default window is 24 hours, which is the common retry horizon rather than a number
422
+ of ours: Stripe prunes an idempotency key ["after they're at least 24 hours
423
+ old"](https://docs.stripe.com/api/idempotent_requests), and Nylas gives the same figure
424
+ as the safe default for [webhook
425
+ deduplication](https://developer.nylas.com/docs/cookbook/agent-accounts/prevent-duplicate-replies/).
426
+ Set `windowSeconds` from your own transport's retry horizon.
427
+
377
428
  ## Stores
378
429
 
379
430
  `MemoryStore` keeps values in process memory and is useful for a single instance. `RedisStore`
380
431
  shares values across instances. `SqliteStore` persists values in a SQLite database without
381
- adding a package dependency. `SqliteStore` requires Node.js 22.5 or newer; the SQLite module
432
+ adding a package dependency. It was contributed by
433
+ [@aaqib-hafeez-khan-in](https://github.com/aaqib-hafeez-khan-in) in [#3](https://github.com/Bubblegunn/proactive-gate/pull/3). `SqliteStore` requires Node.js 22.5 or newer; the SQLite module
382
434
  is loaded only when the store is constructed so the package can still be used on Node.js 20. On Node 22 the module prints an ExperimentalWarning on first use; it is stable from Node 24.
383
435
 
384
436
  ## Fail open, on purpose
@@ -597,6 +649,15 @@ per-type switch and a priority floor that bypasses quiet time. Horvitz's work on
597
649
  initiative supplied the two optional checks. This package puts those ideas in one list with a
598
650
  trace, and adds the part they leave out: the budget consumed at send time.
599
651
 
652
+ ## Thanks
653
+
654
+ Two people sent pull requests on the day this was published, neither of whom I had spoken to
655
+ before. [@aaqib-hafeez-khan-in](https://github.com/aaqib-hafeez-khan-in) wrote `SqliteStore`
656
+ ([#3](https://github.com/Bubblegunn/proactive-gate/pull/3)) and
657
+ [@edwardsong08](https://github.com/edwardsong08) wrote the weekly budget
658
+ ([#9](https://github.com/Bubblegunn/proactive-gate/pull/9)). Both shipped in 0.1.2 and are in
659
+ every release since, including the one you install today.
660
+
600
661
  ## Development
601
662
 
602
663
  ```
package/README.tr.md CHANGED
@@ -342,6 +342,54 @@ if (decision.allowed && await gate.commit(decision, input)) { // INCR, returns
342
342
  `RedisStore`, `INCR` kullanır ve günün TTL'sini ilk artırmada ekler. Sayaç kullanıcının yerel
343
343
  gününe göre anahtarlanır, bu yüzden bütçe UTC'de değil kullanıcının gece yarısında sıfırlanır.
344
344
 
345
+ ## Taşıma iki kez ilettiğinde tek mesaj
346
+
347
+ Mesaj taşımaları en az bir kez iletir. `200` yanıtını yeterince hızlı alamayan bir
348
+ webhook yeniden gönderilir, bir kuyruk aynı olayı iki işçiye verir, zaman aşımından
349
+ sonraki bir deneme ilki çoktan başarılı olmuşken gelir. Kullanıcı aynı mesajı iki kez
350
+ görür ve bunu bozuk bir asistan diye okur.
351
+
352
+ `dedupe` bunun için, ve istemediğiniz sürece kapalıdır:
353
+
354
+ ```ts
355
+ const gate = createGate({ checks: defaultChecks({ dedupe: true }), store });
356
+
357
+ await gate.evaluate({
358
+ user,
359
+ candidate: { id: crypto.randomUUID(), type: "shipping", dedupeKey: "order:42:shipped" },
360
+ });
361
+ ```
362
+
363
+ Anahtar sizin, çünkü iki denemeyi aynı olay yapan şeyi yalnızca siz bilirsiniz. Onu
364
+ olaydan türetin, `order:42:shipped` gibi; her deneme için yeni üretilen bir kimlikten
365
+ ya da mesaj metninden değil, çünkü metin genellikle bir zaman damgası taşır ve her
366
+ denemede farklı olur. `dedupeKey` yoksa kontrol bunu söyleyerek kenara çekilir, bir
367
+ anahtar uydurup sessizce hiçbir şey yapmaz.
368
+
369
+ Elle yazılmış sürümlerin genellikle yanlış yaptığı üç nokta var.
370
+
371
+ **Talep atomiktir ve commit anında olur.** Aynı olayı tutan iki işçi, henüz hiçbir şey
372
+ kaydedilmeden değerlendirir; yalnızca okuyan bir kontrol onları ayıramaz. `dedupe`
373
+ evaluate'te okur, commit'te bütçelerin kullandığı artırmayla talep eder ve yalnızca ilk
374
+ artırmayı alan gönderebilir. Önce oku sonra yaz biçiminde bir talep ikisini de geçirir
375
+ ve şartname bunu uygunsuz sayar.
376
+
377
+ **Bastırılan bir kopya mesaj hakkı harcamaz.** `dedupe` bütçelerden önce tüketir, bu
378
+ yüzden yarışı kaybettiğinde kapı orada durur ve sayaç hiç artmaz. Bu sıralamanın bedeli
379
+ de gerçek: `dedupe`'u geçip ardından tükenmiş bir bütçeye takılan bir olay, pencerenin
380
+ kalanı için anahtarını yakmış olur.
381
+
382
+ **Pencere ilk talepten itibaren sabittir, kaymaz.** Arka arkaya gelen kopyalar bitiş
383
+ zamanını ileri itmez; buradaki her mağaza, bir anahtar yeniden artırıldığında ilk
384
+ bitiş zamanını korur.
385
+
386
+ Varsayılan pencere 24 saat, ve bu bizim seçtiğimiz bir sayı değil, yaygın yeniden
387
+ deneme ufku: Stripe bir idempotency anahtarını ["en az 24 saatlik olduktan
388
+ sonra"](https://docs.stripe.com/api/idempotent_requests) siliyor, Nylas da webhook
389
+ [tekilleştirmesi](https://developer.nylas.com/docs/cookbook/agent-accounts/prevent-duplicate-replies/)
390
+ için aynı rakamı güvenli varsayılan olarak veriyor. `windowSeconds` değerini kendi
391
+ taşımanızın yeniden deneme ufkundan seçin.
392
+
345
393
  ## Bilerek açık başarısız olur
346
394
 
347
395
  Depoya bağlı bir kontrol hata fırlattığında (Redis düştü), varsayılan adayı geçirir ve ize
@@ -127,6 +127,42 @@ export declare function dailyBudget(options?: BudgetOptions): BudgetCheck;
127
127
  export declare function weeklyBudget(options?: BudgetOptions): BudgetCheck;
128
128
  /** At most `limit` deliveries per user per local calendar month. */
129
129
  export declare function monthlyBudget(options?: BudgetOptions): BudgetCheck;
130
+ export declare const dedupeKeyFor: (userId: string, key: string) => string;
131
+ /**
132
+ * One delivery per event per window, claimed atomically at commit time.
133
+ *
134
+ * Message transports deliver at least once. A webhook that does not get its 200
135
+ * quickly enough arrives again, and two workers can pick up the same event at the
136
+ * same moment. Both attempts then evaluate against a store where nothing has been
137
+ * recorded yet, so a check that only reads cannot separate them: it has to claim.
138
+ * `consume()` claims with an atomic increment, the same primitive the budgets use,
139
+ * and only the caller that gets the first increment may send.
140
+ *
141
+ * Order matters and is the reason this check consumes before the budgets: when it
142
+ * loses the race the gate stops there, so the duplicate never spends one of the
143
+ * user's messages for the day. The cost of that ordering, stated rather than hidden:
144
+ * the key is claimed before a later budget check runs, so an event that clears
145
+ * dedupe and is then refused by an exhausted budget has burnt its key for the rest
146
+ * of the window.
147
+ *
148
+ * The window is fixed from the first claim rather than sliding; every store here
149
+ * keeps the original expiry when a key is incremented again.
150
+ *
151
+ * `candidate.dedupeKey` is the caller's, because only the caller knows what makes
152
+ * two attempts the same event. Without it the check skips rather than guessing: a
153
+ * dedupe keyed on something unique per attempt silently does nothing, which is
154
+ * worse than not running.
155
+ *
156
+ * The 24-hour default is the common convention for how long a retry may arrive:
157
+ * Stripe prunes an idempotency key "after they're at least 24 hours old"
158
+ * (https://docs.stripe.com/api/idempotent_requests), and Nylas gives the same
159
+ * figure as the safe default for webhook deduplication
160
+ * (https://developer.nylas.com/docs/cookbook/agent-accounts/prevent-duplicate-replies/).
161
+ * Pick your own from your transport's retry horizon.
162
+ */
163
+ export declare function dedupe(options?: {
164
+ windowSeconds?: number;
165
+ }): Check;
130
166
  /**
131
167
  * Expected-utility alerting: act only when the caller's estimate of acceptance
132
168
  * clears tau = cFA / (cFA + pNeed * cFN). That threshold is the classical Bayes
@@ -214,4 +250,11 @@ export declare function defaultChecks(options?: {
214
250
  dailyLimit?: number;
215
251
  weeklyLimit?: number;
216
252
  quietHoursFloor?: Priority;
253
+ /**
254
+ * Add `dedupe` before the budgets. Off by default because it adds an entry to
255
+ * every trace; on, it costs nothing until a candidate carries a `dedupeKey`.
256
+ */
257
+ dedupe?: boolean | {
258
+ windowSeconds?: number;
259
+ };
217
260
  }): Check[];
@@ -327,6 +327,67 @@ export function weeklyBudget(options = {}) {
327
327
  export function monthlyBudget(options = {}) {
328
328
  return budget({ id: "monthlyBudget", label: "monthly budget", defaultLimit: 60, keyFor: ({ user, now }) => monthlyBudgetKey(user.id, now, user.timezone), ttlSeconds: 32 * DAY_SECONDS }, options);
329
329
  }
330
+ export const dedupeKeyFor = (userId, key) => `dedupe:${userId}:${key}`;
331
+ const humanWindow = (seconds) => {
332
+ if (seconds % DAY_SECONDS === 0)
333
+ return `${seconds / DAY_SECONDS}d`;
334
+ if (seconds % 3600 === 0)
335
+ return `${seconds / 3600}h`;
336
+ if (seconds % 60 === 0)
337
+ return `${seconds / 60}m`;
338
+ return `${seconds}s`;
339
+ };
340
+ /**
341
+ * One delivery per event per window, claimed atomically at commit time.
342
+ *
343
+ * Message transports deliver at least once. A webhook that does not get its 200
344
+ * quickly enough arrives again, and two workers can pick up the same event at the
345
+ * same moment. Both attempts then evaluate against a store where nothing has been
346
+ * recorded yet, so a check that only reads cannot separate them: it has to claim.
347
+ * `consume()` claims with an atomic increment, the same primitive the budgets use,
348
+ * and only the caller that gets the first increment may send.
349
+ *
350
+ * Order matters and is the reason this check consumes before the budgets: when it
351
+ * loses the race the gate stops there, so the duplicate never spends one of the
352
+ * user's messages for the day. The cost of that ordering, stated rather than hidden:
353
+ * the key is claimed before a later budget check runs, so an event that clears
354
+ * dedupe and is then refused by an exhausted budget has burnt its key for the rest
355
+ * of the window.
356
+ *
357
+ * The window is fixed from the first claim rather than sliding; every store here
358
+ * keeps the original expiry when a key is incremented again.
359
+ *
360
+ * `candidate.dedupeKey` is the caller's, because only the caller knows what makes
361
+ * two attempts the same event. Without it the check skips rather than guessing: a
362
+ * dedupe keyed on something unique per attempt silently does nothing, which is
363
+ * worse than not running.
364
+ *
365
+ * The 24-hour default is the common convention for how long a retry may arrive:
366
+ * Stripe prunes an idempotency key "after they're at least 24 hours old"
367
+ * (https://docs.stripe.com/api/idempotent_requests), and Nylas gives the same
368
+ * figure as the safe default for webhook deduplication
369
+ * (https://developer.nylas.com/docs/cookbook/agent-accounts/prevent-duplicate-replies/).
370
+ * Pick your own from your transport's retry horizon.
371
+ */
372
+ export function dedupe(options = {}) {
373
+ const windowSeconds = options.windowSeconds ?? DAY_SECONDS;
374
+ const label = humanWindow(windowSeconds);
375
+ return {
376
+ id: "dedupe",
377
+ async run({ user, candidate, store }) {
378
+ if (!candidate.dedupeKey)
379
+ return skip("no dedupeKey on the candidate; deduplication cannot be evaluated");
380
+ const seen = await store.get(dedupeKeyFor(user.id, candidate.dedupeKey));
381
+ return seen === null ? pass : reject(`already delivered within the last ${label}`);
382
+ },
383
+ async consume({ user, candidate, store }) {
384
+ if (!candidate.dedupeKey)
385
+ return true;
386
+ const claims = await store.incr(dedupeKeyFor(user.id, candidate.dedupeKey), windowSeconds);
387
+ return claims === 1;
388
+ },
389
+ };
390
+ }
330
391
  /* ------------------------------------------------------------------------ */
331
392
  /* Optional, caller-fed checks. Off by default; the package ships no model. */
332
393
  /* ------------------------------------------------------------------------ */
@@ -480,6 +541,7 @@ export function defaultChecks(options = {}) {
480
541
  trustRamp(),
481
542
  dismissalCooldown(),
482
543
  adaptiveTiming(),
544
+ ...(options.dedupe ? [dedupe(typeof options.dedupe === "object" ? options.dedupe : {})] : []),
483
545
  ...(options.weeklyLimit === undefined ? [] : [weeklyBudget({ limit: options.weeklyLimit })]),
484
546
  dailyBudget({ limit: options.dailyLimit ?? 5 }),
485
547
  ];
@@ -20,6 +20,7 @@ export const KNOWN_CHECKS = {
20
20
  trustRamp: (o) => checks.trustRamp({ ...opt(num(o, "days"), "days"), ...opt(prio(o, "minPriority"), "minPriority") }),
21
21
  dismissalCooldown: (o) => checks.dismissalCooldown({ ...opt(num(o, "dismissals"), "dismissals"), ...opt(num(o, "withinDays"), "withinDays"), ...opt(num(o, "silenceDays"), "silenceDays") }),
22
22
  adaptiveTiming: () => checks.adaptiveTiming(),
23
+ dedupe: (o) => checks.dedupe({ ...opt(num(o, "windowSeconds"), "windowSeconds") }),
23
24
  dailyBudget: (o) => checks.dailyBudget(budgetOptions(o)),
24
25
  weeklyBudget: (o) => checks.weeklyBudget(budgetOptions(o)),
25
26
  monthlyBudget: (o) => checks.monthlyBudget(budgetOptions(o)),
@@ -89,6 +89,16 @@ export interface Candidate {
89
89
  pAccept?: number;
90
90
  /** Caller-estimated probability the user needs it; utilityFloor reads it, default 1. */
91
91
  pNeed?: number;
92
+ /**
93
+ * Identity of the underlying event, not of this attempt. `dedupe` claims it once
94
+ * per window, so a webhook redelivered by an at-least-once transport, or the same
95
+ * event picked up by two workers, produces one message rather than two.
96
+ *
97
+ * Derive it from what makes the event the same event: `order:42:shipped`, not a
98
+ * fresh UUID per attempt and not the message text, which usually carries a
99
+ * timestamp and so differs on every retry.
100
+ */
101
+ dedupeKey?: string;
92
102
  /** Free-form payload; the gate never reads it. */
93
103
  payload?: unknown;
94
104
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proactive-gate",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Decide whether a proactive AI agent may reach a user right now, and log why not. Ordered checks as code or JSON, a conformance spec, presets for platform and legal limits, adapters for AI SDK, Mastra, LangChain and OpenAI Agents, and a Python sibling.",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",
@@ -43,7 +43,7 @@
43
43
  "sideEffects": false,
44
44
  "scripts": {
45
45
  "build": "tsc -p tsconfig.json",
46
- "test": "npm run build && node test/spec-lint.mjs && node --test dist/test/gate.test.js dist/test/conformance.test.js dist/test/presets.test.js dist/test/adapters.test.js dist/test/init.test.js dist/test/properties.test.js test/release.test.mjs test/examples.test.mjs test/naive.test.mjs",
46
+ "test": "npm run build && node test/spec-lint.mjs && node --test dist/test/gate.test.js dist/test/conformance.test.js dist/test/presets.test.js dist/test/adapters.test.js dist/test/init.test.js dist/test/properties.test.js dist/test/dedupe.test.js test/release.test.mjs test/examples.test.mjs test/naive.test.mjs test/suite.test.mjs",
47
47
  "lint": "tsc -p tsconfig.json --noEmit",
48
48
  "spec-lint": "node test/spec-lint.mjs",
49
49
  "conformance": "npm run build && node dist/src/cli.js replay --fixtures spec/fixtures",