pi-braid 0.44.0 → 0.44.5

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/CHANGELOG.md CHANGED
@@ -200,6 +200,89 @@ tarball did not have. All three move here, with the fixes they already hold:
200
200
  instead of throwing out of a timer and ending the process.
201
201
  - `pi-braid-contrib` 0.1.5: the git tool, argv-only and read-only by default.
202
202
 
203
+ ## Core 0.44.4, Telegram 0.2.0, Contrib 0.3.0 — a message names the process that sent it (2026-11-15)
204
+
205
+ Two agents writing through one bot were indistinguishable in the owner's chat, and a reply reaches whichever
206
+ process holds the poller. Every message the Telegram package sends now opens with one line rendered from what
207
+ the sending process can observe, `[braid · worker · pi-braid · session 01a1da43 · pid 98675]`: the role
208
+ marker, the working directory's name, the short session id and the pid. It is attached in `planOutbound`, the
209
+ boundary every owner-facing message already crosses, so a new send path cannot forget it and no caller can
210
+ label a message as another process's. An unobservable field says so and a marker the build does not know is
211
+ reported raw rather than upgraded to a role the code does not have; a body split into parts carries the line
212
+ once, in the first part.
213
+
214
+ The same gate closed a hole it had opened for itself: `rich:true` or a bare `parse_mode` exempted any body
215
+ from the 280-character rule, so a wall of prose could ship past it by asking for the format instead of using
216
+ it. Past the cap a sender-facing body must now carry structure a reader can see, and the refusal names the
217
+ length, the rule and the remedy. Automatic sources keep their delivery, because a refused crafted summary
218
+ has no sender to rewrite it.
219
+
220
+ Three smaller changes landed in the same window. The tracked ack is keyed by chat and resolves only when the
221
+ last holder ends, so two seats cannot both decide the chat has none; the adherence meter folds crossings
222
+ into at most one digest per hour and states how many it suppressed. A forwarded message carries its origin
223
+ now, read into the four kinds with the fields each actually carries, and two clocks are kept apart:
224
+ `forwardedAt` is arrival here, `originDate` is publication there, and `timeSource` says which one a consumer
225
+ holds, so a hand-copied message cannot inherit a forwarded timestamp. The `t.me` link is rebuilt from ids
226
+ only, with the `/c/` form for a channel-range id, and no link at all rather than a guess. And
227
+ `scripts/check-telegram-senders.mjs` walks the repository, the skills tree and the orchestrator's scripts,
228
+ comparing every file that can reach the Bot API with an allowlist where each row states why the file exists
229
+ and which gate it passes; an unlisted sender exits non-zero and names the file.
230
+
231
+ The journal checker stopped calling correct records fabrications: a supersedes target in a rotated sibling
232
+ was DANGLING and an evidence path recorded in another repository's coordinates was ABSENT. A seq now
233
+ resolves across the live file and its rotated siblings through one path helper the writer and the checker
234
+ both import, and a reference whose first component is not this tree's is UNRESOLVED and informational,
235
+ naming the root tried and the raw string given. Every run ends with one line counting findings by class, so
236
+ a checker that got quieter instead of more honest shows up as a shifted count.
237
+
238
+ Telegram moves a minor because a delivered body gains a line the caller did not author and the gate's answer
239
+ to a rich body over the cap flips from delivery to refusal. Contrib moves a minor for the same shape: its
240
+ network monitor's probe URL can no longer name a Bot API call or carry a bot token, since a configurable
241
+ endpoint is the one way a file that posts nothing can post, and the refusal is reported through the settings
242
+ error channel. Core stays a patch: the checker fix and the census script are not things a caller calls, and
243
+ `braid.schema.json` is regenerated with only its `x-source` line references moved.
244
+
245
+ Core ships at 0.44.4, and the three numbers before it are why. The 0.44.1 tag's own workflow never got past
246
+ its gates: the census sweeps three roots, two of which live under the operator's home, and it read a root a
247
+ runner does not have as a row that stopped being true, so both home rows came back stale on every CI machine
248
+ while passing on the machine that wrote them. Presence is now decided once per root, a row under an absent
249
+ root is reported as not checked rather than clean or stale, and `test-telegram-senders-census.mjs` holds both
250
+ halves: an absent root leaves its rows alone, while a root that IS present and holds a listed file that
251
+ reaches nothing still fails. That fixture also moved the suite's own census, which `LOCAL_DEV.md` states as
252
+ a number, so 0.44.2 was recorded and superseded before it could be published. Then 0.44.3's run died on that
253
+ same fixture's last arm, which asserted the operator's home instead of what every machine shares: the arm
254
+ now states the property it was meant to hold, that the shipped tree passes wherever the roots are. The tags
255
+ for 0.44.1 and 0.44.3 stay where they are, each with its failed run beside it.
256
+
257
+ ## Core 0.44.5, Telegram 0.2.1: a label names the session, and the digest reads as a sentence (2026-11-15)
258
+
259
+ The identity line said `session unknown` on every message a seat sent. pi DELETES `PI_SESSION_ID`
260
+ from the environment it hands an extension and re-injects it only into bash children, so the label's
261
+ `process.env` read could never succeed, while the adherence digest beside it printed the real id from
262
+ the extension context. The session now comes from that context: the Telegram factory registers a
263
+ getter (`setIdentitySessionSource`) bound to the live `ExtensionContext` it already keeps for
264
+ `isIdle`, and the label prefers it to the environment, which stays the fallback the standalone
265
+ `node src/lib/identity.ts` command still has. The memo is keyed on the id the getter answers with, so
266
+ one session reads one line, a label rendered before the first `session_start` corrects itself, and a
267
+ reload inside one process relabels to the session that now sends.
268
+
269
+ The adherence digest was nine labelled lines, and the owner read it as a field dump. It is now one
270
+ thing that happened: a bold subject naming the rung and how many rules are in it, one sentence
271
+ carrying the counts and quoting the rule in full with the internal source token after it in
272
+ parentheses rather than in front, and one time stamp. Two fields are gone. The truncated session id,
273
+ because the message already opens with a label that names the session. The report path, because the
274
+ reader receives this on a chat client and the report is where the counts live, not somewhere to
275
+ navigate to. A digest that folded several crossings now says so and names how many, and a rule is no
276
+ longer clipped to 64 characters: a fragment of a regex told the owner nothing, and above the plain
277
+ cap the body carries the format the outbound gate asks for.
278
+
279
+ Both changes are fixes to what the owner sees, so both move a patch: core 0.44.5 and Telegram 0.2.1.
280
+ The new function is internal wiring between the package's own modules, not a documented command. The
281
+ three digest shapes are frozen in `packages/telegram/test/fixtures/adherence-digest-bodies.json`
282
+ because the two packages cannot import each other: the producer's fixture asserts the renderer emits
283
+ those lines, and the Telegram fixture pushes the same bytes through the gate and Telegram's own
284
+ parser.
285
+
203
286
  ## Core 0.44.0, Contrib 0.2.0, Providers 1.0.8 — the ruler gains eyes, and refusals learn to speak (2026-11-12)
204
287
 
205
288
  `design_audit` could measure a rendered page and say nothing about whether it looked cheap. The same
package/build-info.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.44.0",
4
- "sha": "f0165737cba18bd9ce624ec1a4bd13f47494b7aa",
5
- "shaShort": "f0165737",
3
+ "version": "0.44.5",
4
+ "sha": "130129cea9f9bb2c6adad598f0bdc456b778cdd5",
5
+ "shaShort": "130129ce",
6
6
  "branch": "detached",
7
7
  "dirty": false,
8
- "packedAt": "2026-11-12T23:32:20.399Z"
8
+ "packedAt": "2026-11-15T22:30:42.163Z"
9
9
  }
@@ -7,10 +7,13 @@
7
7
  * family `rule` but no whisper source; there is no durable per-rule
8
8
  * violation record, so this is the only honest count and it is
9
9
  * current-session only.
10
- * 2. On turn_end, aggregate the active branch and escalate a rule that
11
- * repeats past K to the owner over the existing TG signal seam
12
- * (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses),
13
- * bounded by the milestone ladder and the per-session budget.
10
+ * 2. On turn_end, aggregate the active branch and report a rule that repeats
11
+ * past K to the owner over the existing TG signal seam
12
+ * (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses), as at
13
+ * most ONE digest per hour that states how many crossings it folded. The
14
+ * milestone ladder and the per-session budget are unchanged: a crossing is
15
+ * still planned by `planEscalation` and its rung is still spent only when
16
+ * the digest was accepted.
14
17
  * 3. On session shutdown, append the owner report
15
18
  * (`~/.pi/agent/braid/adherence/report.jsonl`).
16
19
  *
@@ -18,20 +21,71 @@
18
21
  * report is read by nothing that composes the prompt.
19
22
  */
20
23
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
21
- import { type AdherenceWriteResult } from "../../../lib/enforcement/adherence-meter.js";
24
+ import { type AdherenceWriteResult, type PendingEscalation } from "../../../lib/enforcement/adherence-meter.js";
25
+ /** What a crossing may ask the owner channel for. */
26
+ export interface AdherenceOwnerSender {
27
+ (text: string, opts?: {
28
+ parseMode?: "HTML" | "Markdown";
29
+ source?: string;
30
+ /** Escalations folded into this message instead of sent one by one. */
31
+ suppressed?: number;
32
+ }): boolean | Promise<boolean>;
33
+ }
22
34
  /** Injectables for fixtures; production callers pass nothing. */
23
35
  export interface AdherenceWiringDeps {
24
36
  now?: () => number;
25
37
  /** Owner-channel factory; defaults to the published TG signal sender. */
26
- sender?: () => ((text: string) => boolean | Promise<boolean>) | null;
38
+ sender?: () => AdherenceOwnerSender | null;
39
+ /**
40
+ * True when THIS session is the one that reads the owner's chat. Defaults to
41
+ * the Telegram poller's live state (the seat that owns the poller is the seat
42
+ * whose escalations the owner must hear). A second seat shares the bot token
43
+ * but not the conversation, and its escalations never become owner messages;
44
+ * a spawned seat registers no Telegram surface at all, so it publishes no
45
+ * sender either.
46
+ */
47
+ ownerSession?: () => boolean;
48
+ /** How often the owner may receive a digest (default one hour). */
49
+ digestWindowMs?: number;
27
50
  reportDir?: string;
28
51
  k?: number;
29
52
  }
30
53
  /**
31
- * Aggregate the current branch and escalate every rule that crosses its next
32
- * milestone. Returns what fired. The rung is marked only after the owner
33
- * channel accepted the message, so a missing/failing channel retries on the
34
- * next turn instead of silently spending the rung.
54
+ * The hourly digest: one thing that happened, not a field dump. A bold subject
55
+ * names the rung and how many rules the message is about; one sentence carries
56
+ * the counts and the rule it quotes; one stamp says when.
57
+ *
58
+ * Two fields the labelled body carried are deliberately gone:
59
+ * - the truncated session id, because the message already opens with the
60
+ * identity label, and the label names the session the send belongs to
61
+ * (`lib/identity.ts`, telegram);
62
+ * - the report path. The report is where the counts live, not somewhere a
63
+ * reader navigates to from a chat client, so an operator path on the last
64
+ * line was one of the labelled fields the owner read as a dump.
65
+ *
66
+ * The rule is quoted in FULL, never clipped: a fragment of a regex told the
67
+ * owner nothing, and the outbound gate carries a formatted body rather than
68
+ * asking a sender to pre-chew its subject. The quietest honest count of the
69
+ * crossings it folded is stated in its own sentence, so a digest that carries
70
+ * several never reads like a single one.
71
+ */
72
+ export declare function renderAdherenceDigest(digest: {
73
+ pending: PendingEscalation[];
74
+ suppressed: number;
75
+ }, nowMs: number): string;
76
+ /**
77
+ * Aggregate the current branch and fold every crossing into the owner's
78
+ * hourly digest.
79
+ *
80
+ * What did NOT change: the ladder. `planEscalation` is asked exactly as before,
81
+ * and a rung is still spent only when the owner channel accepted the message
82
+ * that reported it, so the milestones, thresholds and detection are untouched.
83
+ *
84
+ * What changed: a crossing is buffered (`recordEscalation`) and delivered as
85
+ * ONE digest per window (`planDigest`), which states how many crossings it
86
+ * folded instead of sending each one as its own message. Two seats sharing a
87
+ * bot token no longer both write into the owner's chat: only the session that
88
+ * owns the inbound channel escalates.
35
89
  */
36
90
  export declare function checkAdherence(ctx: ExtensionContext, deps?: AdherenceWiringDeps): Promise<{
37
91
  fired: Array<{
@@ -7,10 +7,13 @@
7
7
  * family `rule` but no whisper source; there is no durable per-rule
8
8
  * violation record, so this is the only honest count and it is
9
9
  * current-session only.
10
- * 2. On turn_end, aggregate the active branch and escalate a rule that
11
- * repeats past K to the owner over the existing TG signal seam
12
- * (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses),
13
- * bounded by the milestone ladder and the per-session budget.
10
+ * 2. On turn_end, aggregate the active branch and report a rule that repeats
11
+ * past K to the owner over the existing TG signal seam
12
+ * (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses), as at
13
+ * most ONE digest per hour that states how many crossings it folded. The
14
+ * milestone ladder and the per-session budget are unchanged: a crossing is
15
+ * still planned by `planEscalation` and its rung is still spent only when
16
+ * the digest was accepted.
14
17
  * 3. On session shutdown, append the owner report
15
18
  * (`~/.pi/agent/braid/adherence/report.jsonl`).
16
19
  *
@@ -24,11 +27,21 @@ import { registerTurnEndHandler } from "../../../lib/events/turn-end-coordinator
24
27
  import { registerSessionStartHandler, SessionPhase, } from "../../../lib/state/session-start-queue.js";
25
28
  import { getExtensionState, getSessionIdSafe, safeSessionManagerTyped, } from "../../../lib/state/extension-state.js";
26
29
  import { getWatchdogTgSignalSender } from "../../../lib/state/global-state.js";
30
+ import { readTelegramPollerLiveness } from "../../../lib/state/telegram-poller-liveness.js";
27
31
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
28
- import { activeBranchEntries, aggregateRuleAdherence, createEscalationState, markEscalated, planEscalation, readSessionEntriesFromFile, writeAdherenceReport, } from "../../../lib/enforcement/adherence-meter.js";
32
+ import { activeBranchEntries, aggregateRuleAdherence, commitDigest, createEscalationState, planDigest, planEscalation, readSessionEntriesFromFile, recordEscalation, writeAdherenceReport, } from "../../../lib/enforcement/adherence-meter.js";
29
33
  const log = createLogger("adherence-meter");
30
34
  /** Extension-state bucket key for the per-session meter state. */
31
35
  const ADHERENCE_STATE_KEY = "adherence-meter";
36
+ /**
37
+ * Owner-facing session predicate. The liveness probe is core's own registry
38
+ * (`telegram-poller-liveness.ts`): "running" or "unknown" means no other seat
39
+ * is holding the owner's inbound channel, "stopped" means this process loaded
40
+ * Telegram and its poller is not the one reading the chat.
41
+ */
42
+ function isOwnerChannelSession() {
43
+ return readTelegramPollerLiveness() !== "stopped";
44
+ }
32
45
  function adherenceState(ctx) {
33
46
  return getExtensionState(ctx, ADHERENCE_STATE_KEY, createEscalationState);
34
47
  }
@@ -42,54 +55,177 @@ function branchEntries(ctx) {
42
55
  return [];
43
56
  }
44
57
  }
45
- /** Compact owner ping: headline rung, source + signal, counters, provenance. */
46
- function renderEscalation(rule, milestone, state, ctx, nowMs) {
47
- const signal = rule.signal.length > 140 ? `${rule.signal.slice(0, 137)}...` : rule.signal;
48
- const sessionId = getSessionIdSafe(ctx);
49
- return (`[adherence] rule repeating · rung ${milestone}\n` +
50
- `${rule.source}: "${signal}"\n` +
51
- `\n` +
52
- `deliveries ${rule.deliveries} · repeats ${rule.repeats} · suppressed ${rule.suppressions} · escalation ${state.total + 1}\n` +
53
- `session ${sessionId} · ${formatLocalTime(new Date(nowMs))}`);
58
+ /** Escape the three characters Telegram's HTML parser reserves. */
59
+ function escapeHtml(text) {
60
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
61
+ }
62
+ /** The rule's own text: the key is `source::body`, and the body is the rule. */
63
+ function ruleText(entry) {
64
+ const body = entry.ruleKey.includes("::")
65
+ ? entry.ruleKey.split("::").slice(1).join("::")
66
+ : entry.ruleKey;
67
+ return body.trim();
68
+ }
69
+ /** Counts up to twenty in words; past that the numeral is the honest form. */
70
+ const COUNT_WORDS = [
71
+ "zero",
72
+ "one",
73
+ "two",
74
+ "three",
75
+ "four",
76
+ "five",
77
+ "six",
78
+ "seven",
79
+ "eight",
80
+ "nine",
81
+ "ten",
82
+ "eleven",
83
+ "twelve",
84
+ "thirteen",
85
+ "fourteen",
86
+ "fifteen",
87
+ "sixteen",
88
+ "seventeen",
89
+ "eighteen",
90
+ "nineteen",
91
+ "twenty",
92
+ ];
93
+ function countWord(n) {
94
+ return Number.isInteger(n) && n >= 0 && n < COUNT_WORDS.length ? COUNT_WORDS[n] : String(n);
95
+ }
96
+ /** The same word, as the opening of a sentence. */
97
+ function sentenceCase(text) {
98
+ return text.length > 0 ? `${text[0].toUpperCase()}${text.slice(1)}` : text;
99
+ }
100
+ /**
101
+ * A rule body that already carries its own quoting is not quoted twice: the
102
+ * whisper bodies the meter counts open and close with quotation marks of their
103
+ * own.
104
+ */
105
+ function quoted(text) {
106
+ const opens = /^["'“«]/.test(text);
107
+ const closes = /["'”»]$/.test(text);
108
+ return opens && closes ? text : `"${text}"`;
54
109
  }
55
110
  /**
56
- * Aggregate the current branch and escalate every rule that crosses its next
57
- * milestone. Returns what fired. The rung is marked only after the owner
58
- * channel accepted the message, so a missing/failing channel retries on the
59
- * next turn instead of silently spending the rung.
111
+ * The hourly digest: one thing that happened, not a field dump. A bold subject
112
+ * names the rung and how many rules the message is about; one sentence carries
113
+ * the counts and the rule it quotes; one stamp says when.
114
+ *
115
+ * Two fields the labelled body carried are deliberately gone:
116
+ * - the truncated session id, because the message already opens with the
117
+ * identity label, and the label names the session the send belongs to
118
+ * (`lib/identity.ts`, telegram);
119
+ * - the report path. The report is where the counts live, not somewhere a
120
+ * reader navigates to from a chat client, so an operator path on the last
121
+ * line was one of the labelled fields the owner read as a dump.
122
+ *
123
+ * The rule is quoted in FULL, never clipped: a fragment of a regex told the
124
+ * owner nothing, and the outbound gate carries a formatted body rather than
125
+ * asking a sender to pre-chew its subject. The quietest honest count of the
126
+ * crossings it folded is stated in its own sentence, so a digest that carries
127
+ * several never reads like a single one.
128
+ */
129
+ export function renderAdherenceDigest(digest, nowMs) {
130
+ // The subject is the rule at the highest rung in the digest. Among rules the
131
+ // ladder put on the same rung (it advances one rung per pass, so a tie is the
132
+ // ordinary case for a folded digest), the one with the most deliveries is the
133
+ // informative quote.
134
+ const subject = digest.pending.reduce((best, entry) => entry.milestone > best.milestone ||
135
+ (entry.milestone === best.milestone && entry.deliveries >= best.deliveries)
136
+ ? entry
137
+ : best);
138
+ const crossings = digest.pending.length;
139
+ const ruleCount = new Set(digest.pending.map((entry) => entry.ruleKey)).size;
140
+ const rules = ruleCount === 1 ? "rule" : "rules";
141
+ const folded = crossings > 1
142
+ ? sentenceCase(`${countWord(crossings)} crossings, from ${countWord(ruleCount)} ${rules}, ` +
143
+ `are reported together in this message. `)
144
+ : "";
145
+ return [
146
+ `<b>Adherence · rung ${subject.milestone} · ${countWord(ruleCount)} ${rules}</b>`,
147
+ `${folded}The rule ${escapeHtml(quoted(ruleText(subject)))} ` +
148
+ `(${escapeHtml(subject.source)}) has repeated ${subject.repeats} ` +
149
+ `times across ${subject.deliveries} deliveries.`,
150
+ `at ${formatLocalTime(new Date(nowMs))}`,
151
+ ].join("\n");
152
+ }
153
+ /**
154
+ * Aggregate the current branch and fold every crossing into the owner's
155
+ * hourly digest.
156
+ *
157
+ * What did NOT change: the ladder. `planEscalation` is asked exactly as before,
158
+ * and a rung is still spent only when the owner channel accepted the message
159
+ * that reported it, so the milestones, thresholds and detection are untouched.
160
+ *
161
+ * What changed: a crossing is buffered (`recordEscalation`) and delivered as
162
+ * ONE digest per window (`planDigest`), which states how many crossings it
163
+ * folded instead of sending each one as its own message. Two seats sharing a
164
+ * bot token no longer both write into the owner's chat: only the session that
165
+ * owns the inbound channel escalates.
60
166
  */
61
167
  export async function checkAdherence(ctx, deps = {}) {
62
168
  const state = adherenceState(ctx);
63
169
  const entries = branchEntries(ctx);
64
- if (entries.length === 0)
65
- return { fired: [] };
66
- const rules = aggregateRuleAdherence(activeBranchEntries(entries));
170
+ const rules = entries.length > 0 ? aggregateRuleAdherence(activeBranchEntries(entries)) : [];
67
171
  const sender = (deps.sender ?? getWatchdogTgSignalSender)();
68
172
  const nowMs = (deps.now ?? Date.now)();
69
- const fired = [];
173
+ const sessionId = getSessionIdSafe(ctx);
70
174
  for (const rule of rules) {
71
175
  const plan = planEscalation(state, rule.rule, rule.repeats);
72
176
  if (!plan.fire)
73
177
  continue;
74
- if (!sender) {
75
- log.debug(`[adherence] ${rule.rule} crossed rung ${plan.milestone}; no owner channel published`);
76
- continue;
77
- }
78
- let ok = false;
79
- try {
80
- ok =
81
- (await Promise.resolve(sender(renderEscalation(rule, plan.milestone, state, ctx, nowMs)))) === true;
82
- }
83
- catch (e) {
84
- log.debug(`[adherence] escalation send threw for ${rule.rule}: ${e.message}`);
85
- }
86
- if (!ok) {
87
- log.debug(`[adherence] escalation not delivered for ${rule.rule}; rung stays unspent`);
88
- continue;
89
- }
90
- markEscalated(state, rule.rule);
91
- fired.push({ rule: rule.rule, milestone: plan.milestone });
178
+ recordEscalation(state, {
179
+ ruleKey: rule.rule,
180
+ rung: (state.rules[rule.rule]?.rung ?? 0) + 1,
181
+ milestone: plan.milestone,
182
+ source: rule.source,
183
+ deliveries: rule.deliveries,
184
+ repeats: rule.repeats,
185
+ sessionId,
186
+ at: nowMs,
187
+ });
188
+ }
189
+ const buffered = state.pending ?? [];
190
+ if (buffered.length === 0)
191
+ return { fired: [] };
192
+ if (!sender) {
193
+ log.debug(`[adherence] ${buffered.length} escalation(s) buffered; no owner channel published`);
194
+ return { fired: [] };
195
+ }
196
+ if (!(deps.ownerSession ?? isOwnerChannelSession)()) {
197
+ log.debug(`[adherence] ${buffered.length} escalation(s) buffered; this session does not own the owner channel`);
198
+ return { fired: [] };
199
+ }
200
+ const digest = planDigest(state, nowMs, {
201
+ ...(deps.digestWindowMs !== undefined ? { windowMs: deps.digestWindowMs } : {}),
202
+ });
203
+ if (!digest.send) {
204
+ log.debug(`[adherence] ${digest.pending.length} escalation(s) buffered; digest window closed (${digest.suppressed} suppressed so far)`);
205
+ return { fired: [] };
206
+ }
207
+ let ok = false;
208
+ try {
209
+ ok =
210
+ (await Promise.resolve(sender(renderAdherenceDigest(digest, nowMs), {
211
+ parseMode: "HTML",
212
+ source: "adherence-digest",
213
+ suppressed: digest.suppressed,
214
+ }))) === true;
215
+ }
216
+ catch (e) {
217
+ log.debug(`[adherence] digest send threw: ${e.message}`);
218
+ }
219
+ if (!ok) {
220
+ log.debug("[adherence] digest not delivered; crossings stay buffered, rungs unspent");
221
+ return { fired: [] };
92
222
  }
223
+ const fired = digest.pending.map((entry) => ({
224
+ rule: entry.ruleKey,
225
+ milestone: entry.milestone,
226
+ }));
227
+ commitDigest(state, nowMs);
228
+ log.debug(`[adherence] digest delivered: ${fired.length} crossing(s), ${digest.suppressed} suppressed`);
93
229
  return { fired };
94
230
  }
95
231
  /**
@@ -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
@@ -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 - 122 of the core suite's 358 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.44.0",
3
+ "version": "0.44.5",
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
 
@@ -7,10 +7,13 @@
7
7
  * family `rule` but no whisper source; there is no durable per-rule
8
8
  * violation record, so this is the only honest count and it is
9
9
  * current-session only.
10
- * 2. On turn_end, aggregate the active branch and escalate a rule that
11
- * repeats past K to the owner over the existing TG signal seam
12
- * (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses),
13
- * bounded by the milestone ladder and the per-session budget.
10
+ * 2. On turn_end, aggregate the active branch and report a rule that repeats
11
+ * past K to the owner over the existing TG signal seam
12
+ * (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses), as at
13
+ * most ONE digest per hour that states how many crossings it folded. The
14
+ * milestone ladder and the per-session budget are unchanged: a crossing is
15
+ * still planned by `planEscalation` and its rung is still spent only when
16
+ * the digest was accepted.
14
17
  * 3. On session shutdown, append the owner report
15
18
  * (`~/.pi/agent/braid/adherence/report.jsonl`).
16
19
  *
@@ -33,18 +36,21 @@ import {
33
36
  safeSessionManagerTyped,
34
37
  } from "../../../lib/state/extension-state.js";
35
38
  import { getWatchdogTgSignalSender } from "../../../lib/state/global-state.js";
39
+ import { readTelegramPollerLiveness } from "../../../lib/state/telegram-poller-liveness.js";
36
40
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
37
41
  import {
38
42
  activeBranchEntries,
39
43
  aggregateRuleAdherence,
44
+ commitDigest,
40
45
  createEscalationState,
41
- markEscalated,
46
+ planDigest,
42
47
  planEscalation,
43
48
  readSessionEntriesFromFile,
49
+ recordEscalation,
44
50
  writeAdherenceReport,
45
51
  type AdherenceEscalationState,
46
52
  type AdherenceWriteResult,
47
- type RuleAdherence,
53
+ type PendingEscalation,
48
54
  } from "../../../lib/enforcement/adherence-meter.js";
49
55
 
50
56
  const log = createLogger("adherence-meter");
@@ -52,15 +58,49 @@ const log = createLogger("adherence-meter");
52
58
  /** Extension-state bucket key for the per-session meter state. */
53
59
  const ADHERENCE_STATE_KEY = "adherence-meter";
54
60
 
61
+ /** What a crossing may ask the owner channel for. */
62
+ export interface AdherenceOwnerSender {
63
+ (
64
+ text: string,
65
+ opts?: {
66
+ parseMode?: "HTML" | "Markdown";
67
+ source?: string;
68
+ /** Escalations folded into this message instead of sent one by one. */
69
+ suppressed?: number;
70
+ },
71
+ ): boolean | Promise<boolean>;
72
+ }
73
+
55
74
  /** Injectables for fixtures; production callers pass nothing. */
56
75
  export interface AdherenceWiringDeps {
57
76
  now?: () => number;
58
77
  /** Owner-channel factory; defaults to the published TG signal sender. */
59
- sender?: () => ((text: string) => boolean | Promise<boolean>) | null;
78
+ sender?: () => AdherenceOwnerSender | null;
79
+ /**
80
+ * True when THIS session is the one that reads the owner's chat. Defaults to
81
+ * the Telegram poller's live state (the seat that owns the poller is the seat
82
+ * whose escalations the owner must hear). A second seat shares the bot token
83
+ * but not the conversation, and its escalations never become owner messages;
84
+ * a spawned seat registers no Telegram surface at all, so it publishes no
85
+ * sender either.
86
+ */
87
+ ownerSession?: () => boolean;
88
+ /** How often the owner may receive a digest (default one hour). */
89
+ digestWindowMs?: number;
60
90
  reportDir?: string;
61
91
  k?: number;
62
92
  }
63
93
 
94
+ /**
95
+ * Owner-facing session predicate. The liveness probe is core's own registry
96
+ * (`telegram-poller-liveness.ts`): "running" or "unknown" means no other seat
97
+ * is holding the owner's inbound channel, "stopped" means this process loaded
98
+ * Telegram and its poller is not the one reading the chat.
99
+ */
100
+ function isOwnerChannelSession(): boolean {
101
+ return readTelegramPollerLiveness() !== "stopped";
102
+ }
103
+
64
104
  function adherenceState(ctx: ExtensionContext): AdherenceEscalationState {
65
105
  return getExtensionState(ctx, ADHERENCE_STATE_KEY, createEscalationState);
66
106
  }
@@ -75,30 +115,129 @@ function branchEntries(ctx: ExtensionContext): unknown[] {
75
115
  }
76
116
  }
77
117
 
78
- /** Compact owner ping: headline rung, source + signal, counters, provenance. */
79
- function renderEscalation(
80
- rule: RuleAdherence,
81
- milestone: number,
82
- state: AdherenceEscalationState,
83
- ctx: ExtensionContext,
118
+ /** Escape the three characters Telegram's HTML parser reserves. */
119
+ function escapeHtml(text: string): string {
120
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
121
+ }
122
+
123
+ /** The rule's own text: the key is `source::body`, and the body is the rule. */
124
+ function ruleText(entry: PendingEscalation): string {
125
+ const body = entry.ruleKey.includes("::")
126
+ ? entry.ruleKey.split("::").slice(1).join("::")
127
+ : entry.ruleKey;
128
+ return body.trim();
129
+ }
130
+
131
+ /** Counts up to twenty in words; past that the numeral is the honest form. */
132
+ const COUNT_WORDS = [
133
+ "zero",
134
+ "one",
135
+ "two",
136
+ "three",
137
+ "four",
138
+ "five",
139
+ "six",
140
+ "seven",
141
+ "eight",
142
+ "nine",
143
+ "ten",
144
+ "eleven",
145
+ "twelve",
146
+ "thirteen",
147
+ "fourteen",
148
+ "fifteen",
149
+ "sixteen",
150
+ "seventeen",
151
+ "eighteen",
152
+ "nineteen",
153
+ "twenty",
154
+ ];
155
+
156
+ function countWord(n: number): string {
157
+ return Number.isInteger(n) && n >= 0 && n < COUNT_WORDS.length ? COUNT_WORDS[n] : String(n);
158
+ }
159
+
160
+ /** The same word, as the opening of a sentence. */
161
+ function sentenceCase(text: string): string {
162
+ return text.length > 0 ? `${text[0].toUpperCase()}${text.slice(1)}` : text;
163
+ }
164
+
165
+ /**
166
+ * A rule body that already carries its own quoting is not quoted twice: the
167
+ * whisper bodies the meter counts open and close with quotation marks of their
168
+ * own.
169
+ */
170
+ function quoted(text: string): string {
171
+ const opens = /^["'“«]/.test(text);
172
+ const closes = /["'”»]$/.test(text);
173
+ return opens && closes ? text : `"${text}"`;
174
+ }
175
+
176
+ /**
177
+ * The hourly digest: one thing that happened, not a field dump. A bold subject
178
+ * names the rung and how many rules the message is about; one sentence carries
179
+ * the counts and the rule it quotes; one stamp says when.
180
+ *
181
+ * Two fields the labelled body carried are deliberately gone:
182
+ * - the truncated session id, because the message already opens with the
183
+ * identity label, and the label names the session the send belongs to
184
+ * (`lib/identity.ts`, telegram);
185
+ * - the report path. The report is where the counts live, not somewhere a
186
+ * reader navigates to from a chat client, so an operator path on the last
187
+ * line was one of the labelled fields the owner read as a dump.
188
+ *
189
+ * The rule is quoted in FULL, never clipped: a fragment of a regex told the
190
+ * owner nothing, and the outbound gate carries a formatted body rather than
191
+ * asking a sender to pre-chew its subject. The quietest honest count of the
192
+ * crossings it folded is stated in its own sentence, so a digest that carries
193
+ * several never reads like a single one.
194
+ */
195
+ export function renderAdherenceDigest(
196
+ digest: { pending: PendingEscalation[]; suppressed: number },
84
197
  nowMs: number,
85
198
  ): string {
86
- const signal = rule.signal.length > 140 ? `${rule.signal.slice(0, 137)}...` : rule.signal;
87
- const sessionId = getSessionIdSafe(ctx);
88
- return (
89
- `[adherence] rule repeating · rung ${milestone}\n` +
90
- `${rule.source}: "${signal}"\n` +
91
- `\n` +
92
- `deliveries ${rule.deliveries} · repeats ${rule.repeats} · suppressed ${rule.suppressions} · escalation ${state.total + 1}\n` +
93
- `session ${sessionId} · ${formatLocalTime(new Date(nowMs))}`
199
+ // The subject is the rule at the highest rung in the digest. Among rules the
200
+ // ladder put on the same rung (it advances one rung per pass, so a tie is the
201
+ // ordinary case for a folded digest), the one with the most deliveries is the
202
+ // informative quote.
203
+ const subject = digest.pending.reduce((best, entry) =>
204
+ entry.milestone > best.milestone ||
205
+ (entry.milestone === best.milestone && entry.deliveries >= best.deliveries)
206
+ ? entry
207
+ : best,
94
208
  );
209
+ const crossings = digest.pending.length;
210
+ const ruleCount = new Set(digest.pending.map((entry) => entry.ruleKey)).size;
211
+ const rules = ruleCount === 1 ? "rule" : "rules";
212
+ const folded =
213
+ crossings > 1
214
+ ? sentenceCase(
215
+ `${countWord(crossings)} crossings, from ${countWord(ruleCount)} ${rules}, ` +
216
+ `are reported together in this message. `,
217
+ )
218
+ : "";
219
+ return [
220
+ `<b>Adherence · rung ${subject.milestone} · ${countWord(ruleCount)} ${rules}</b>`,
221
+ `${folded}The rule ${escapeHtml(quoted(ruleText(subject)))} ` +
222
+ `(${escapeHtml(subject.source)}) has repeated ${subject.repeats} ` +
223
+ `times across ${subject.deliveries} deliveries.`,
224
+ `at ${formatLocalTime(new Date(nowMs))}`,
225
+ ].join("\n");
95
226
  }
96
227
 
97
228
  /**
98
- * Aggregate the current branch and escalate every rule that crosses its next
99
- * milestone. Returns what fired. The rung is marked only after the owner
100
- * channel accepted the message, so a missing/failing channel retries on the
101
- * next turn instead of silently spending the rung.
229
+ * Aggregate the current branch and fold every crossing into the owner's
230
+ * hourly digest.
231
+ *
232
+ * What did NOT change: the ladder. `planEscalation` is asked exactly as before,
233
+ * and a rung is still spent only when the owner channel accepted the message
234
+ * that reported it, so the milestones, thresholds and detection are untouched.
235
+ *
236
+ * What changed: a crossing is buffered (`recordEscalation`) and delivered as
237
+ * ONE digest per window (`planDigest`), which states how many crossings it
238
+ * folded instead of sending each one as its own message. Two seats sharing a
239
+ * bot token no longer both write into the owner's chat: only the session that
240
+ * owns the inbound channel escalates.
102
241
  */
103
242
  export async function checkAdherence(
104
243
  ctx: ExtensionContext,
@@ -106,38 +245,73 @@ export async function checkAdherence(
106
245
  ): Promise<{ fired: Array<{ rule: string; milestone: number }> }> {
107
246
  const state = adherenceState(ctx);
108
247
  const entries = branchEntries(ctx);
109
- if (entries.length === 0) return { fired: [] };
110
-
111
- const rules = aggregateRuleAdherence(activeBranchEntries(entries));
248
+ const rules = entries.length > 0 ? aggregateRuleAdherence(activeBranchEntries(entries)) : [];
112
249
  const sender = (deps.sender ?? getWatchdogTgSignalSender)();
113
250
  const nowMs = (deps.now ?? Date.now)();
114
- const fired: Array<{ rule: string; milestone: number }> = [];
251
+ const sessionId = getSessionIdSafe(ctx);
115
252
 
116
253
  for (const rule of rules) {
117
254
  const plan = planEscalation(state, rule.rule, rule.repeats);
118
255
  if (!plan.fire) continue;
119
- if (!sender) {
120
- log.debug(
121
- `[adherence] ${rule.rule} crossed rung ${plan.milestone}; no owner channel published`,
122
- );
123
- continue;
124
- }
125
- let ok = false;
126
- try {
127
- ok =
128
- (await Promise.resolve(
129
- sender(renderEscalation(rule, plan.milestone, state, ctx, nowMs)),
130
- )) === true;
131
- } catch (e) {
132
- log.debug(`[adherence] escalation send threw for ${rule.rule}: ${(e as Error).message}`);
133
- }
134
- if (!ok) {
135
- log.debug(`[adherence] escalation not delivered for ${rule.rule}; rung stays unspent`);
136
- continue;
137
- }
138
- markEscalated(state, rule.rule);
139
- fired.push({ rule: rule.rule, milestone: plan.milestone });
256
+ recordEscalation(state, {
257
+ ruleKey: rule.rule,
258
+ rung: (state.rules[rule.rule]?.rung ?? 0) + 1,
259
+ milestone: plan.milestone,
260
+ source: rule.source,
261
+ deliveries: rule.deliveries,
262
+ repeats: rule.repeats,
263
+ sessionId,
264
+ at: nowMs,
265
+ });
266
+ }
267
+
268
+ const buffered = state.pending ?? [];
269
+ if (buffered.length === 0) return { fired: [] };
270
+ if (!sender) {
271
+ log.debug(`[adherence] ${buffered.length} escalation(s) buffered; no owner channel published`);
272
+ return { fired: [] };
273
+ }
274
+ if (!(deps.ownerSession ?? isOwnerChannelSession)()) {
275
+ log.debug(
276
+ `[adherence] ${buffered.length} escalation(s) buffered; this session does not own the owner channel`,
277
+ );
278
+ return { fired: [] };
279
+ }
280
+ const digest = planDigest(state, nowMs, {
281
+ ...(deps.digestWindowMs !== undefined ? { windowMs: deps.digestWindowMs } : {}),
282
+ });
283
+ if (!digest.send) {
284
+ log.debug(
285
+ `[adherence] ${digest.pending.length} escalation(s) buffered; digest window closed (${digest.suppressed} suppressed so far)`,
286
+ );
287
+ return { fired: [] };
140
288
  }
289
+
290
+ let ok = false;
291
+ try {
292
+ ok =
293
+ (await Promise.resolve(
294
+ sender(renderAdherenceDigest(digest, nowMs), {
295
+ parseMode: "HTML",
296
+ source: "adherence-digest",
297
+ suppressed: digest.suppressed,
298
+ }),
299
+ )) === true;
300
+ } catch (e) {
301
+ log.debug(`[adherence] digest send threw: ${(e as Error).message}`);
302
+ }
303
+ if (!ok) {
304
+ log.debug("[adherence] digest not delivered; crossings stay buffered, rungs unspent");
305
+ return { fired: [] };
306
+ }
307
+ const fired = digest.pending.map((entry) => ({
308
+ rule: entry.ruleKey,
309
+ milestone: entry.milestone,
310
+ }));
311
+ commitDigest(state, nowMs);
312
+ log.debug(
313
+ `[adherence] digest delivered: ${fired.length} crossing(s), ${digest.suppressed} suppressed`,
314
+ );
141
315
  return { fired };
142
316
  }
143
317
 
@@ -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"
@@ -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 {