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.
@@ -42,6 +42,26 @@ export function normaliseRoleSetting(raw) {
42
42
  }
43
43
  return patterns;
44
44
  }
45
+ /**
46
+ * A model named the way a report names it: provider then id, the pair a reader
47
+ * can paste into a model flag.
48
+ */
49
+ function modelLabel(model) {
50
+ return `${model.provider ?? "unknown"}/${model.id}`;
51
+ }
52
+ /**
53
+ * Why a resolved model was not accepted for a role, in words, for a caller that
54
+ * has to explain an empty result. Null when the model is acceptable.
55
+ */
56
+ function rejectionReason(model, requireImage) {
57
+ if (!model)
58
+ return "no provider serves this pattern";
59
+ if (requireImage && !model.input?.includes("image")) {
60
+ const declared = model.input ?? [];
61
+ return `declares input [${declared.join(", ") || "text"}], no image input`;
62
+ }
63
+ return null;
64
+ }
45
65
  /**
46
66
  * Resolve a role setting to a single model.
47
67
  *
@@ -55,19 +75,40 @@ export function normaliseRoleSetting(raw) {
55
75
  *
56
76
  * @param requireImage - vision role only: entries must accept image input, so
57
77
  * a list may hold a text-only entry without an image being sent to it.
78
+ * @param trace - optional sink for one line per entry, in the order tried, so a
79
+ * caller that gets nothing back can print what was tried and why each entry
80
+ * was passed over. Passed in rather than returned because the successful path
81
+ * must stay allocation-free for the classification callers.
58
82
  */
59
- function resolveRoleModel(ctx, key, requireImage = false) {
83
+ function resolveRoleModel(ctx, key, requireImage = false, trace) {
60
84
  const raw = getCustomModelKey(key);
61
85
  const patterns = normaliseRoleSetting(raw);
62
- if (patterns.length === 0)
86
+ if (patterns.length === 0) {
87
+ trace?.push(`${key}: not configured`);
63
88
  return undefined;
89
+ }
64
90
  const acceptable = (model) => model && (!requireImage || model.input?.includes("image")) ? model : undefined;
65
- if (!Array.isArray(raw))
66
- return acceptable(resolveFromPattern(ctx, patterns[0]));
91
+ if (!Array.isArray(raw)) {
92
+ const resolved = resolveFromPattern(ctx, patterns[0]);
93
+ const model = acceptable(resolved);
94
+ if (!trace)
95
+ return model;
96
+ const reason = rejectionReason(resolved, requireImage);
97
+ trace.push(model && reason === null
98
+ ? `${key} "${patterns[0]}": using ${modelLabel(model)}, accepts image input`
99
+ : `${key} "${patterns[0]}": ${reason}`);
100
+ return model;
101
+ }
67
102
  for (const pattern of patterns) {
68
- const model = acceptable(resolveFromPattern(ctx, pattern));
69
- if (model && isModelRouteUsable(model))
103
+ const resolved = resolveFromPattern(ctx, pattern);
104
+ const model = acceptable(resolved);
105
+ if (model && isModelRouteUsable(model)) {
106
+ trace?.push(`${key} "${pattern}": using ${modelLabel(model)}, the provider reports the route usable`);
70
107
  return model;
108
+ }
109
+ trace?.push(model
110
+ ? `${key} "${pattern}": resolved ${modelLabel(model)}, but the provider reports the route unusable`
111
+ : `${key} "${pattern}": ${rejectionReason(resolved, requireImage)}`);
71
112
  }
72
113
  return undefined;
73
114
  }
@@ -83,7 +124,7 @@ export function resolveUtilityModels(ctx) {
83
124
  .filter((model) => model !== undefined);
84
125
  }
85
126
  /**
86
- * The model a vision call should use.
127
+ * The model a vision call should use, with the walk that produced it.
87
128
  *
88
129
  * Priority:
89
130
  * 1. The current model when it accepts images: the image stays in the call
@@ -94,18 +135,38 @@ export function resolveUtilityModels(ctx) {
94
135
  *
95
136
  * A text-only entry is never selected for an image call.
96
137
  */
97
- export function resolveVisionModel(ctx) {
138
+ export function searchVisionModel(ctx) {
139
+ const tried = [];
98
140
  // 1. Current model if vision-capable
99
- if (ctx.model?.input?.includes("image"))
100
- return ctx.model;
141
+ const current = ctx.model;
142
+ if (current?.input?.includes("image")) {
143
+ tried.push(`current model ${modelLabel(current)}: accepts image input`);
144
+ return { model: current, source: "current", tried };
145
+ }
146
+ tried.push(current
147
+ ? `current model ${modelLabel(current)}: ${rejectionReason(current, true)}`
148
+ : "current model: none selected");
101
149
  // 2. The merged role supplies an image-capable entry; a text-only entry in
102
150
  // the list is skipped rather than sent an image.
103
- const role = resolveRoleModel(ctx, UTILITY_MODEL_KEY, true);
151
+ const role = resolveRoleModel(ctx, UTILITY_MODEL_KEY, true, tried);
104
152
  if (role)
105
- return role;
153
+ return { model: role, source: "utilityModel", tried };
106
154
  // 3. First available vision model
107
155
  const available = ctx.modelRegistry.getAvailable();
108
- return available.find((m) => m?.input?.includes("image"));
156
+ const imageCapable = available.filter((m) => m?.input?.includes("image"));
157
+ tried.push(`available models: ${available.length}, ${imageCapable.length} accept image input`);
158
+ const fallback = imageCapable[0];
159
+ if (fallback) {
160
+ tried.push(`using ${modelLabel(fallback)}: first available model that accepts images`);
161
+ return { model: fallback, source: "available", tried };
162
+ }
163
+ return { source: null, tried };
164
+ }
165
+ /**
166
+ * The model a vision call should use: the `model` of the walk above.
167
+ */
168
+ export function resolveVisionModel(ctx) {
169
+ return searchVisionModel(ctx).model;
109
170
  }
110
171
  /**
111
172
  * Get the configured utility model for classification tasks.
@@ -158,6 +158,25 @@ export declare function tagsSlugFromCwd(cwd?: string): string;
158
158
  * call, so a pinned BRAID_HOME writes and reads its own journal.
159
159
  */
160
160
  export declare function journalFilePath(projectSlug: string): string;
161
+ /**
162
+ * Name of one rotated journal file: `journal-<year>.jsonl` beside the live file.
163
+ *
164
+ * Rotation moves a prefix of the live journal into a sibling, so the seq chain
165
+ * outlives the file that carries it. The name is stated here once because two
166
+ * programs must agree on which files are ONE journal: the writer, which reads
167
+ * the archived seqs so a rotated journal does not restart its chain at 1, and
168
+ * the checker, which reads them so a reference to a rotated entry is not
169
+ * called absent. A second spelling is how those two drift into disagreeing
170
+ * about the population.
171
+ */
172
+ export declare const ROTATED_JOURNAL_NAME: RegExp;
173
+ /**
174
+ * Absolute paths of the rotated siblings of one live journal, in name order so
175
+ * two readers list one chain in one order. A directory that does not exist yet
176
+ * has no siblings; a file that does not match ROTATED_JOURNAL_NAME is not part
177
+ * of the chain and is never read.
178
+ */
179
+ export declare function journalRotatedFiles(journalFile: string): string[];
161
180
  /**
162
181
  * Get the lossless flush file path for one offloaded tool result.
163
182
  * Layout: <offload dir>/<sessionId>/<toolName>-<toolCallId>.txt.
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import * as path from "node:path";
13
13
  import * as os from "node:os";
14
- import { realpathSync } from "node:fs";
14
+ import { readdirSync, realpathSync } from "node:fs";
15
15
  // The module-load constants below are the PRECOMPUTED DEFAULT for the paths
16
16
  // declared from them. They are read-side compatibility, not a base to write
17
17
  // from: `os.homedir()` is folded once, at import, so a home that is relative
@@ -281,6 +281,38 @@ export function tagsSlugFromCwd(cwd) {
281
281
  export function journalFilePath(projectSlug) {
282
282
  return path.join(journalDir(), projectSlug, "journal.jsonl");
283
283
  }
284
+ /**
285
+ * Name of one rotated journal file: `journal-<year>.jsonl` beside the live file.
286
+ *
287
+ * Rotation moves a prefix of the live journal into a sibling, so the seq chain
288
+ * outlives the file that carries it. The name is stated here once because two
289
+ * programs must agree on which files are ONE journal: the writer, which reads
290
+ * the archived seqs so a rotated journal does not restart its chain at 1, and
291
+ * the checker, which reads them so a reference to a rotated entry is not
292
+ * called absent. A second spelling is how those two drift into disagreeing
293
+ * about the population.
294
+ */
295
+ export const ROTATED_JOURNAL_NAME = /^journal-\d{4}\.jsonl$/;
296
+ /**
297
+ * Absolute paths of the rotated siblings of one live journal, in name order so
298
+ * two readers list one chain in one order. A directory that does not exist yet
299
+ * has no siblings; a file that does not match ROTATED_JOURNAL_NAME is not part
300
+ * of the chain and is never read.
301
+ */
302
+ export function journalRotatedFiles(journalFile) {
303
+ const dir = path.dirname(journalFile);
304
+ let names;
305
+ try {
306
+ names = readdirSync(dir);
307
+ }
308
+ catch {
309
+ return [];
310
+ }
311
+ return names
312
+ .filter((name) => ROTATED_JOURNAL_NAME.test(name))
313
+ .sort()
314
+ .map((name) => path.join(dir, name));
315
+ }
284
316
  /**
285
317
  * Get the lossless flush file path for one offloaded tool result.
286
318
  * Layout: <offload dir>/<sessionId>/<toolName>-<toolCallId>.txt.
@@ -131,8 +131,57 @@ export interface AdherenceEscalationState {
131
131
  total: number;
132
132
  /** Violation records observed in-process this session, by event `rule`. */
133
133
  violations: Record<string, number>;
134
+ /**
135
+ * Escalations recorded but NOT yet delivered: the owner gets one digest per
136
+ * window, so a crossing waits here instead of becoming its own message.
137
+ * A rule's rung is only spent when its entry is committed with a delivered
138
+ * digest (`planEscalation`/`markEscalated` stay the ladder).
139
+ */
140
+ pending?: PendingEscalation[];
141
+ /** Clock of the last digest the owner channel accepted. */
142
+ lastDigestAt?: number;
134
143
  }
144
+ /** One escalation waiting to be folded into the next digest. */
145
+ export interface PendingEscalation {
146
+ ruleKey: string;
147
+ /** Rung index the crossing advances to (1-based; the ladder stays pure). */
148
+ rung: number;
149
+ /** The milestone that was crossed (a value from the ladder). */
150
+ milestone: number;
151
+ source: string;
152
+ deliveries: number;
153
+ repeats: number;
154
+ sessionId: string;
155
+ at: number;
156
+ }
157
+ /** How often the owner may receive an adherence digest. */
158
+ export declare const ADHERENCE_DIGEST_WINDOW_MS: number;
135
159
  export declare function createEscalationState(): AdherenceEscalationState;
160
+ /**
161
+ * Buffer one crossing. Idempotent per (rule, milestone): a pass that cannot
162
+ * deliver re-plans the same crossing on the next turn, and the second plan
163
+ * refreshes the counters instead of queueing a duplicate.
164
+ */
165
+ export declare function recordEscalation(state: AdherenceEscalationState, entry: PendingEscalation): void;
166
+ export type DigestPlanReason = "empty" | "window-closed" | "window-open";
167
+ export interface DigestPlan {
168
+ send: boolean;
169
+ reason: DigestPlanReason;
170
+ /** Escalations the digest would report (the last one is its subject). */
171
+ pending: PendingEscalation[];
172
+ /** Crossings folded into this digest beyond its subject line. */
173
+ suppressed: number;
174
+ }
175
+ /**
176
+ * Decide whether the buffered crossings may go out now. One message per
177
+ * window: the first crossing after a quiet hour reports, everything inside the
178
+ * hour waits and is counted. Pure — the caller commits only after delivery.
179
+ */
180
+ export declare function planDigest(state: AdherenceEscalationState, nowMs: number, opts?: {
181
+ windowMs?: number;
182
+ }): DigestPlan;
183
+ /** Spend the rungs a delivered digest reported and open a fresh window. */
184
+ export declare function commitDigest(state: AdherenceEscalationState, nowMs: number): void;
136
185
  export type EscalationPlanReason = "crossing" | "below-threshold" | "rule-terminal" | "session-terminal";
137
186
  export interface EscalationPlan {
138
187
  fire: boolean;
@@ -253,9 +253,58 @@ export function aggregateRuleAdherence(entries) {
253
253
  export function ruleHolds(repeats, k = ADHERENCE_REPEAT_THRESHOLD_K) {
254
254
  return repeats < k;
255
255
  }
256
+ /** How often the owner may receive an adherence digest. */
257
+ export const ADHERENCE_DIGEST_WINDOW_MS = 60 * 60 * 1000;
256
258
  export function createEscalationState() {
257
259
  return { rules: {}, total: 0, violations: {} };
258
260
  }
261
+ /**
262
+ * Buffer one crossing. Idempotent per (rule, milestone): a pass that cannot
263
+ * deliver re-plans the same crossing on the next turn, and the second plan
264
+ * refreshes the counters instead of queueing a duplicate.
265
+ */
266
+ export function recordEscalation(state, entry) {
267
+ const pending = state.pending ?? (state.pending = []);
268
+ const existing = pending.find((p) => p.ruleKey === entry.ruleKey && p.milestone === entry.milestone);
269
+ if (existing)
270
+ Object.assign(existing, entry);
271
+ else
272
+ pending.push(entry);
273
+ }
274
+ /**
275
+ * Decide whether the buffered crossings may go out now. One message per
276
+ * window: the first crossing after a quiet hour reports, everything inside the
277
+ * hour waits and is counted. Pure — the caller commits only after delivery.
278
+ */
279
+ export function planDigest(state, nowMs, opts = {}) {
280
+ const pending = state.pending ?? [];
281
+ const windowMs = opts.windowMs ?? ADHERENCE_DIGEST_WINDOW_MS;
282
+ if (pending.length === 0) {
283
+ return { send: false, reason: "empty", pending: [], suppressed: 0 };
284
+ }
285
+ const last = state.lastDigestAt;
286
+ if (last !== undefined && nowMs - last < windowMs) {
287
+ return {
288
+ send: false,
289
+ reason: "window-closed",
290
+ pending: [...pending],
291
+ suppressed: pending.length - 1,
292
+ };
293
+ }
294
+ return {
295
+ send: true,
296
+ reason: "window-open",
297
+ pending: [...pending],
298
+ suppressed: pending.length - 1,
299
+ };
300
+ }
301
+ /** Spend the rungs a delivered digest reported and open a fresh window. */
302
+ export function commitDigest(state, nowMs) {
303
+ for (const entry of state.pending ?? [])
304
+ markEscalated(state, entry.ruleKey);
305
+ state.pending = [];
306
+ state.lastDigestAt = nowMs;
307
+ }
259
308
  /**
260
309
  * Decide whether `ruleKey` should escalate at `repeats`. Pure: the caller
261
310
  * marks the rung with `markEscalated` only after the owner channel accepted
@@ -8,7 +8,10 @@
8
8
  */
9
9
  export { classify } from "./ai/text-classifier.js";
10
10
  export type { ClassifierCriteria, ClassificationResult, ClassifierOptions, } from "./ai/text-classifier.js";
11
- export { resolveVisionModel } from "./ai/model-resolver.js";
11
+ export { resolveVisionModel, searchVisionModel } from "./ai/model-resolver.js";
12
+ export type { VisionModelSearch } from "./ai/model-resolver.js";
13
+ export { callVision } from "./ai/llm-call.js";
14
+ export type { LlmCallOptions, LlmCallResult, LlmImagePart } from "./ai/llm-call.js";
12
15
  export { healthcheckDir, HEALTHCHECK_DIR } from "./config/braid-paths.js";
13
16
  export { onEvent } from "./events/event-types.js";
14
17
  export { getExtensionState } from "./state/extension-state.js";
@@ -7,7 +7,8 @@
7
7
  * `./lib`.
8
8
  */
9
9
  export { classify } from "./ai/text-classifier.js";
10
- export { resolveVisionModel } from "./ai/model-resolver.js";
10
+ export { resolveVisionModel, searchVisionModel } from "./ai/model-resolver.js";
11
+ export { callVision } from "./ai/llm-call.js";
11
12
  export { healthcheckDir, HEALTHCHECK_DIR } from "./config/braid-paths.js";
12
13
  export { onEvent } from "./events/event-types.js";
13
14
  export { getExtensionState } from "./state/extension-state.js";
@@ -161,7 +161,20 @@ export declare function getWatchdogTunnelStatus(): WatchdogTunnelStatus;
161
161
  export declare function subscribeWatchdogTunnel(fn: (event: WatchdogTunnelEvent) => void): () => void;
162
162
  export declare const WATCHDOG_TG_SIGNAL_KEY = "__braid_watchdog_tg_signal";
163
163
  /** Best-effort 1-line tg sender (must never throw). */
164
- export type WatchdogTgSignalSender = (text: string) => boolean | Promise<boolean>;
164
+ export type WatchdogTgSignalSender = (text: string, opts?: WatchdogTgSignalOptions) => boolean | Promise<boolean>;
165
+ /**
166
+ * What a cross-package sender may ask for. Everything is optional: a caller
167
+ * that passes only `text` keeps the plain-text canary behaviour it always had.
168
+ */
169
+ export interface WatchdogTgSignalOptions {
170
+ /** `parse_mode` for the body (`HTML` for a structured owner message). */
171
+ parseMode?: "HTML" | "Markdown";
172
+ /** Metrics bucket (the telegram sender counts owner messages by it). */
173
+ source?: string;
174
+ /** Events the caller folded into this message instead of sending each one
175
+ * (the adherence meter reports how many escalations it suppressed). */
176
+ suppressed?: number;
177
+ }
165
178
  /** Read the optional tg-signal sender published by the telegram extension. */
166
179
  export declare function getWatchdogTgSignalSender(): WatchdogTgSignalSender | null;
167
180
  export declare const WATCHDOG_WAKE_DELIVERY_FEED_KEY = "__braid_watchdog_wake_delivery_feed";
package/docs/LOCAL_DEV.md CHANGED
@@ -138,7 +138,7 @@ before and after a full run. A non-zero delta is the leak this rule prevents.
138
138
  ### New fixtures: use `node:test`
139
139
 
140
140
  A new fixture is written on `node:test`. The runner does not care which style a
141
- file uses - 121 of the core suite's 357 fixtures already use `node:test` - so the
141
+ file uses - 124 of the core suite's 361 fixtures already use `node:test` - so the
142
142
  reason is the failure the other style produces. A hand-rolled helper that calls
143
143
  `fn()` without awaiting it discards the case's promise, so an `async` case runs
144
144
  detached and the file can print its green tally before that case settles, with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.43.60",
3
+ "version": "0.44.4",
4
4
  "description": "🥨 Braid - Metacognitive extension suite for pi coding agent: Adds memory, plan tracking, structured cognitive signals and completion checks on top of pi core loop, so long sessions keep their context and stop claiming unfinished work.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -22,20 +22,20 @@ in a pipeline." It's the broadest use of the term in the codebase.
22
22
  These are the entry points for enforcement. They register with pi core
23
23
  and delegate to the actual enforcement logic.
24
24
 
25
- | File | Event |
26
- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
27
- | `register-session-start.ts` | `session_start` |
28
- | `register-session-start-discoverability.ts` | `session_start` (Background phase, via `registerSessionStartHandler`) - surfaces disk-backed prior state (scratchpad, memory, sessions, resume file, tags, journal) before the first turn. Per-signal dedup with per-project disk persistence; the journal pointer is exempt and carries what is open. |
29
- | `register-session-compact.ts` | `session_compact` |
30
- | `register-session-shutdown.ts` | `session_shutdown` |
31
- | `register-session-shutdown-resumption.ts` | (read by discoverability handler) - resume file creation on shutdown. |
32
- | `register-input-handler.ts` | `input` |
33
- | `register-message-end.ts` | `message_end` |
34
- | `register-tool-call.ts` | `tool_call` |
35
- | `register-tool-result.ts` | `tool_execution_end` |
36
- | `register-agent-end-api-error.ts` | `agent_end` (classifies a terminal assistant API error into guidance) |
37
- | `register-post-cycle-hygiene.ts` | `turn_end` (priority 1 - auto-tag + inspect + advise on text-only yield after work) |
38
- | `register-adherence-meter.ts` | `session_start` (Background - counts `enforcement_violation` events per session), `turn_end` (priority 40 - escalates a rule repeating past K to the owner, bounded), `session_shutdown` (writes the owner report). Owner-facing only: never sends a tracked message and never registers a tool. |
25
+ | File | Event |
26
+ | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
+ | `register-session-start.ts` | `session_start` |
28
+ | `register-session-start-discoverability.ts` | `session_start` (Background phase, via `registerSessionStartHandler`) - surfaces disk-backed prior state (scratchpad, memory, sessions, resume file, tags, journal) before the first turn. Per-signal dedup with per-project disk persistence; the journal pointer is exempt and carries what is open. |
29
+ | `register-session-compact.ts` | `session_compact` |
30
+ | `register-session-shutdown.ts` | `session_shutdown` |
31
+ | `register-session-shutdown-resumption.ts` | (read by discoverability handler) - resume file creation on shutdown. |
32
+ | `register-input-handler.ts` | `input` |
33
+ | `register-message-end.ts` | `message_end` |
34
+ | `register-tool-call.ts` | `tool_call` |
35
+ | `register-tool-result.ts` | `tool_execution_end` |
36
+ | `register-agent-end-api-error.ts` | `agent_end` (classifies a terminal assistant API error into guidance) |
37
+ | `register-post-cycle-hygiene.ts` | `turn_end` (priority 1 - auto-tag + inspect + advise on text-only yield after work) |
38
+ | `register-adherence-meter.ts` | `session_start` (Background - counts `enforcement_violation` events per session), `turn_end` (priority 40 - folds a rule repeating past K into at most one owner digest per hour, which states how many crossings it suppressed; only the session that owns the Telegram poller escalates), `session_shutdown` (writes the owner report). Owner-facing only: never sends a tracked message and never registers a tool. |
39
39
 
40
40
  ### Orchestrators (not `register-*`, but invoked at turn end)
41
41