pi-braid 0.43.60 → 0.44.4

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,7 +12,7 @@
12
12
 
13
13
  import * as path from "node:path";
14
14
  import * as os from "node:os";
15
- import { realpathSync } from "node:fs";
15
+ import { readdirSync, realpathSync } from "node:fs";
16
16
 
17
17
  // The module-load constants below are the PRECOMPUTED DEFAULT for the paths
18
18
  // declared from them. They are read-side compatibility, not a base to write
@@ -332,6 +332,39 @@ export function journalFilePath(projectSlug: string): string {
332
332
  return path.join(journalDir(), projectSlug, "journal.jsonl");
333
333
  }
334
334
 
335
+ /**
336
+ * Name of one rotated journal file: `journal-<year>.jsonl` beside the live file.
337
+ *
338
+ * Rotation moves a prefix of the live journal into a sibling, so the seq chain
339
+ * outlives the file that carries it. The name is stated here once because two
340
+ * programs must agree on which files are ONE journal: the writer, which reads
341
+ * the archived seqs so a rotated journal does not restart its chain at 1, and
342
+ * the checker, which reads them so a reference to a rotated entry is not
343
+ * called absent. A second spelling is how those two drift into disagreeing
344
+ * about the population.
345
+ */
346
+ export const ROTATED_JOURNAL_NAME = /^journal-\d{4}\.jsonl$/;
347
+
348
+ /**
349
+ * Absolute paths of the rotated siblings of one live journal, in name order so
350
+ * two readers list one chain in one order. A directory that does not exist yet
351
+ * has no siblings; a file that does not match ROTATED_JOURNAL_NAME is not part
352
+ * of the chain and is never read.
353
+ */
354
+ export function journalRotatedFiles(journalFile: string): string[] {
355
+ const dir = path.dirname(journalFile);
356
+ let names: string[];
357
+ try {
358
+ names = readdirSync(dir);
359
+ } catch {
360
+ return [];
361
+ }
362
+ return names
363
+ .filter((name) => ROTATED_JOURNAL_NAME.test(name))
364
+ .sort()
365
+ .map((name) => path.join(dir, name));
366
+ }
367
+
335
368
  /**
336
369
  * Get the lossless flush file path for one offloaded tool result.
337
370
  * Layout: <offload dir>/<sessionId>/<toolName>-<toolCallId>.txt.
@@ -7,10 +7,10 @@ need to participate in the enforcement layer (whisper cap, turn dedup).
7
7
 
8
8
  ## Files
9
9
 
10
- | File | Purpose |
11
- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
12
- | `turn-dedup.ts` | The whisper flood cap. Tracks per-turn whisper counts by priority tier (critical/high/medium/low) and source. Wired into `sendTrackedMessage` as a chokepoint so every extension benefits. |
13
- | `adherence-meter.ts` | The read-side adherence meter. Counts durable `braid_injection` entries per rule (deliveries, repeats, suppressions) from the active branch, defines the hold verdict (`repeats < K`), plans the bounded owner escalation (milestone ladder + per-session budget), and builds/writes the owner report under `~/.pi/agent/braid/adherence/`. Rule identity is data (`source` + normalized body), never a hardcoded rule name; owner-facing only, no judge. |
10
+ | File | Purpose |
11
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
12
+ | `turn-dedup.ts` | The whisper flood cap. Tracks per-turn whisper counts by priority tier (critical/high/medium/low) and source. Wired into `sendTrackedMessage` as a chokepoint so every extension benefits. |
13
+ | `adherence-meter.ts` | The read-side adherence meter. Counts durable `braid_injection` entries per rule (deliveries, repeats, suppressions) from the active branch, defines the hold verdict (`repeats < K`), plans the bounded owner escalation (milestone ladder + per-session budget) and buffers a crossing until the next digest window may open (`planDigest`/`commitDigest`: one message per window, the rest counted as suppressed), and builds/writes the owner report under `~/.pi/agent/braid/adherence/`. Rule identity is data (`source` + normalized body), never a hardcoded rule name; owner-facing only, no judge. |
14
14
 
15
15
  ## Local Contracts
16
16
 
@@ -308,12 +308,102 @@ export interface AdherenceEscalationState {
308
308
  total: number;
309
309
  /** Violation records observed in-process this session, by event `rule`. */
310
310
  violations: Record<string, number>;
311
+ /**
312
+ * Escalations recorded but NOT yet delivered: the owner gets one digest per
313
+ * window, so a crossing waits here instead of becoming its own message.
314
+ * A rule's rung is only spent when its entry is committed with a delivered
315
+ * digest (`planEscalation`/`markEscalated` stay the ladder).
316
+ */
317
+ pending?: PendingEscalation[];
318
+ /** Clock of the last digest the owner channel accepted. */
319
+ lastDigestAt?: number;
311
320
  }
312
321
 
322
+ /** One escalation waiting to be folded into the next digest. */
323
+ export interface PendingEscalation {
324
+ ruleKey: string;
325
+ /** Rung index the crossing advances to (1-based; the ladder stays pure). */
326
+ rung: number;
327
+ /** The milestone that was crossed (a value from the ladder). */
328
+ milestone: number;
329
+ source: string;
330
+ deliveries: number;
331
+ repeats: number;
332
+ sessionId: string;
333
+ at: number;
334
+ }
335
+
336
+ /** How often the owner may receive an adherence digest. */
337
+ export const ADHERENCE_DIGEST_WINDOW_MS = 60 * 60 * 1000;
338
+
313
339
  export function createEscalationState(): AdherenceEscalationState {
314
340
  return { rules: {}, total: 0, violations: {} };
315
341
  }
316
342
 
343
+ /**
344
+ * Buffer one crossing. Idempotent per (rule, milestone): a pass that cannot
345
+ * deliver re-plans the same crossing on the next turn, and the second plan
346
+ * refreshes the counters instead of queueing a duplicate.
347
+ */
348
+ export function recordEscalation(state: AdherenceEscalationState, entry: PendingEscalation): void {
349
+ const pending = state.pending ?? (state.pending = []);
350
+ const existing = pending.find(
351
+ (p) => p.ruleKey === entry.ruleKey && p.milestone === entry.milestone,
352
+ );
353
+ if (existing) Object.assign(existing, entry);
354
+ else pending.push(entry);
355
+ }
356
+
357
+ export type DigestPlanReason = "empty" | "window-closed" | "window-open";
358
+
359
+ export interface DigestPlan {
360
+ send: boolean;
361
+ reason: DigestPlanReason;
362
+ /** Escalations the digest would report (the last one is its subject). */
363
+ pending: PendingEscalation[];
364
+ /** Crossings folded into this digest beyond its subject line. */
365
+ suppressed: number;
366
+ }
367
+
368
+ /**
369
+ * Decide whether the buffered crossings may go out now. One message per
370
+ * window: the first crossing after a quiet hour reports, everything inside the
371
+ * hour waits and is counted. Pure — the caller commits only after delivery.
372
+ */
373
+ export function planDigest(
374
+ state: AdherenceEscalationState,
375
+ nowMs: number,
376
+ opts: { windowMs?: number } = {},
377
+ ): DigestPlan {
378
+ const pending = state.pending ?? [];
379
+ const windowMs = opts.windowMs ?? ADHERENCE_DIGEST_WINDOW_MS;
380
+ if (pending.length === 0) {
381
+ return { send: false, reason: "empty", pending: [], suppressed: 0 };
382
+ }
383
+ const last = state.lastDigestAt;
384
+ if (last !== undefined && nowMs - last < windowMs) {
385
+ return {
386
+ send: false,
387
+ reason: "window-closed",
388
+ pending: [...pending],
389
+ suppressed: pending.length - 1,
390
+ };
391
+ }
392
+ return {
393
+ send: true,
394
+ reason: "window-open",
395
+ pending: [...pending],
396
+ suppressed: pending.length - 1,
397
+ };
398
+ }
399
+
400
+ /** Spend the rungs a delivered digest reported and open a fresh window. */
401
+ export function commitDigest(state: AdherenceEscalationState, nowMs: number): void {
402
+ for (const entry of state.pending ?? []) markEscalated(state, entry.ruleKey);
403
+ state.pending = [];
404
+ state.lastDigestAt = nowMs;
405
+ }
406
+
317
407
  export type EscalationPlanReason =
318
408
  | "crossing"
319
409
  | "below-threshold"
package/src/lib/public.ts CHANGED
@@ -13,7 +13,10 @@ export type {
13
13
  ClassificationResult,
14
14
  ClassifierOptions,
15
15
  } from "./ai/text-classifier.js";
16
- export { resolveVisionModel } from "./ai/model-resolver.js";
16
+ export { resolveVisionModel, searchVisionModel } from "./ai/model-resolver.js";
17
+ export type { VisionModelSearch } from "./ai/model-resolver.js";
18
+ export { callVision } from "./ai/llm-call.js";
19
+ export type { LlmCallOptions, LlmCallResult, LlmImagePart } from "./ai/llm-call.js";
17
20
 
18
21
  export { healthcheckDir, HEALTHCHECK_DIR } from "./config/braid-paths.js";
19
22
 
@@ -421,7 +421,24 @@ export function subscribeWatchdogTunnel(fn: (event: WatchdogTunnelEvent) => void
421
421
  export const WATCHDOG_TG_SIGNAL_KEY = "__braid_watchdog_tg_signal";
422
422
 
423
423
  /** Best-effort 1-line tg sender (must never throw). */
424
- export type WatchdogTgSignalSender = (text: string) => boolean | Promise<boolean>;
424
+ export type WatchdogTgSignalSender = (
425
+ text: string,
426
+ opts?: WatchdogTgSignalOptions,
427
+ ) => boolean | Promise<boolean>;
428
+
429
+ /**
430
+ * What a cross-package sender may ask for. Everything is optional: a caller
431
+ * that passes only `text` keeps the plain-text canary behaviour it always had.
432
+ */
433
+ export interface WatchdogTgSignalOptions {
434
+ /** `parse_mode` for the body (`HTML` for a structured owner message). */
435
+ parseMode?: "HTML" | "Markdown";
436
+ /** Metrics bucket (the telegram sender counts owner messages by it). */
437
+ source?: string;
438
+ /** Events the caller folded into this message instead of sending each one
439
+ * (the adherence meter reports how many escalations it suppressed). */
440
+ suppressed?: number;
441
+ }
425
442
 
426
443
  /** Read the optional tg-signal sender published by the telegram extension. */
427
444
  export function getWatchdogTgSignalSender(): WatchdogTgSignalSender | null {