pi-braid 0.44.0 → 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.
- package/CHANGELOG.md +54 -0
- package/build-info.json +4 -4
- package/dist/extensions/enforcement/handlers/register-adherence-meter.d.ts +40 -9
- package/dist/extensions/enforcement/handlers/register-adherence-meter.js +120 -40
- package/dist/lib/config/braid-paths.d.ts +19 -0
- package/dist/lib/config/braid-paths.js +33 -1
- package/dist/lib/enforcement/adherence-meter.d.ts +49 -0
- package/dist/lib/enforcement/adherence-meter.js +49 -0
- package/dist/lib/state/global-state.d.ts +14 -1
- package/docs/LOCAL_DEV.md +1 -1
- package/package.json +1 -1
- package/src/extensions/enforcement/handlers/AGENTS.md +14 -14
- package/src/extensions/enforcement/handlers/register-adherence-meter.ts +163 -49
- package/src/lib/config/braid-paths.ts +34 -1
- package/src/lib/enforcement/AGENTS.md +4 -4
- package/src/lib/enforcement/adherence-meter.ts +90 -0
- package/src/lib/state/global-state.ts +18 -1
package/CHANGELOG.md
CHANGED
|
@@ -200,6 +200,60 @@ 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
|
+
|
|
203
257
|
## 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
258
|
|
|
205
259
|
`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.
|
|
4
|
-
"sha": "
|
|
5
|
-
"shaShort": "
|
|
3
|
+
"version": "0.44.4",
|
|
4
|
+
"sha": "867ae9adcf06547838bf83c7c8dcf43e290eda3f",
|
|
5
|
+
"shaShort": "867ae9ad",
|
|
6
6
|
"branch": "detached",
|
|
7
7
|
"dirty": false,
|
|
8
|
-
"packedAt": "2026-11-
|
|
8
|
+
"packedAt": "2026-11-15T15:38:22.037Z"
|
|
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
|
|
11
|
-
*
|
|
12
|
-
* (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses),
|
|
13
|
-
*
|
|
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
|
*
|
|
@@ -19,19 +22,47 @@
|
|
|
19
22
|
*/
|
|
20
23
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
21
24
|
import { type AdherenceWriteResult } 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?: () =>
|
|
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
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
54
|
+
* Aggregate the current branch and fold every crossing into the owner's
|
|
55
|
+
* hourly digest.
|
|
56
|
+
*
|
|
57
|
+
* What did NOT change: the ladder. `planEscalation` is asked exactly as before,
|
|
58
|
+
* and a rung is still spent only when the owner channel accepted the message
|
|
59
|
+
* that reported it, so the milestones, thresholds and detection are untouched.
|
|
60
|
+
*
|
|
61
|
+
* What changed: a crossing is buffered (`recordEscalation`) and delivered as
|
|
62
|
+
* ONE digest per window (`planDigest`), which states how many crossings it
|
|
63
|
+
* folded instead of sending each one as its own message. Two seats sharing a
|
|
64
|
+
* bot token no longer both write into the owner's chat: only the session that
|
|
65
|
+
* owns the inbound channel escalates.
|
|
35
66
|
*/
|
|
36
67
|
export declare function checkAdherence(ctx: ExtensionContext, deps?: AdherenceWiringDeps): Promise<{
|
|
37
68
|
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
|
|
11
|
-
*
|
|
12
|
-
* (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses),
|
|
13
|
-
*
|
|
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,
|
|
32
|
+
import { activeBranchEntries, adherenceReportPath, 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,121 @@ function branchEntries(ctx) {
|
|
|
42
55
|
return [];
|
|
43
56
|
}
|
|
44
57
|
}
|
|
45
|
-
/**
|
|
46
|
-
function
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
58
|
+
/** Escape the three characters Telegram's HTML parser reserves. */
|
|
59
|
+
function escapeHtml(text) {
|
|
60
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
61
|
+
}
|
|
62
|
+
function shorten(text, max) {
|
|
63
|
+
const trimmed = text.trim();
|
|
64
|
+
return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max - 3)}...`;
|
|
65
|
+
}
|
|
66
|
+
/** The rule's matched text (the key's `source::pattern` tail), shortened. */
|
|
67
|
+
function ruleLabel(entry) {
|
|
68
|
+
const tail = entry.ruleKey.includes("::")
|
|
69
|
+
? entry.ruleKey.split("::").slice(1).join("::")
|
|
70
|
+
: entry.ruleKey;
|
|
71
|
+
return shorten(`${entry.source}: ${tail}`, 64);
|
|
54
72
|
}
|
|
55
73
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
74
|
+
* The hourly digest: a bold subject naming the highest rung it reports, then
|
|
75
|
+
* labelled lines. Short enough to survive as plain text (the owner's
|
|
76
|
+
* tweet-length rule) and valid under `parse_mode: HTML` (the Telegram outbound
|
|
77
|
+
* gate validates it before any send).
|
|
78
|
+
*/
|
|
79
|
+
function renderDigest(digest, ctx, nowMs) {
|
|
80
|
+
// The subject is the highest rung in the digest; ties go to the latest.
|
|
81
|
+
const subject = digest.pending.reduce((best, entry) => entry.milestone >= best.milestone ? entry : best);
|
|
82
|
+
const lines = [
|
|
83
|
+
`<b>adherence · rung ${subject.milestone}</b>`,
|
|
84
|
+
`rule ${escapeHtml(ruleLabel(subject))}`,
|
|
85
|
+
...(digest.pending.length > 1 ? [`rules ${digest.pending.length}`] : []),
|
|
86
|
+
`deliveries ${subject.deliveries}`,
|
|
87
|
+
`repeats ${subject.repeats}`,
|
|
88
|
+
`suppressed ${digest.suppressed}`,
|
|
89
|
+
`session ${escapeHtml(shorten(getSessionIdSafe(ctx) || "unknown", 32))}`,
|
|
90
|
+
`at ${formatLocalTime(new Date(nowMs))}`,
|
|
91
|
+
// The next step is a pointer, not advice: the full signal text and the
|
|
92
|
+
// per-rule counts live in the session report.
|
|
93
|
+
`where ${escapeHtml(shorten(adherenceReportPath(), 72))}`,
|
|
94
|
+
];
|
|
95
|
+
return lines.join("\n");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Aggregate the current branch and fold every crossing into the owner's
|
|
99
|
+
* hourly digest.
|
|
100
|
+
*
|
|
101
|
+
* What did NOT change: the ladder. `planEscalation` is asked exactly as before,
|
|
102
|
+
* and a rung is still spent only when the owner channel accepted the message
|
|
103
|
+
* that reported it, so the milestones, thresholds and detection are untouched.
|
|
104
|
+
*
|
|
105
|
+
* What changed: a crossing is buffered (`recordEscalation`) and delivered as
|
|
106
|
+
* ONE digest per window (`planDigest`), which states how many crossings it
|
|
107
|
+
* folded instead of sending each one as its own message. Two seats sharing a
|
|
108
|
+
* bot token no longer both write into the owner's chat: only the session that
|
|
109
|
+
* owns the inbound channel escalates.
|
|
60
110
|
*/
|
|
61
111
|
export async function checkAdherence(ctx, deps = {}) {
|
|
62
112
|
const state = adherenceState(ctx);
|
|
63
113
|
const entries = branchEntries(ctx);
|
|
64
|
-
|
|
65
|
-
return { fired: [] };
|
|
66
|
-
const rules = aggregateRuleAdherence(activeBranchEntries(entries));
|
|
114
|
+
const rules = entries.length > 0 ? aggregateRuleAdherence(activeBranchEntries(entries)) : [];
|
|
67
115
|
const sender = (deps.sender ?? getWatchdogTgSignalSender)();
|
|
68
116
|
const nowMs = (deps.now ?? Date.now)();
|
|
69
|
-
const
|
|
117
|
+
const sessionId = getSessionIdSafe(ctx);
|
|
70
118
|
for (const rule of rules) {
|
|
71
119
|
const plan = planEscalation(state, rule.rule, rule.repeats);
|
|
72
120
|
if (!plan.fire)
|
|
73
121
|
continue;
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
|
|
122
|
+
recordEscalation(state, {
|
|
123
|
+
ruleKey: rule.rule,
|
|
124
|
+
rung: (state.rules[rule.rule]?.rung ?? 0) + 1,
|
|
125
|
+
milestone: plan.milestone,
|
|
126
|
+
source: rule.source,
|
|
127
|
+
deliveries: rule.deliveries,
|
|
128
|
+
repeats: rule.repeats,
|
|
129
|
+
sessionId,
|
|
130
|
+
at: nowMs,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
const buffered = state.pending ?? [];
|
|
134
|
+
if (buffered.length === 0)
|
|
135
|
+
return { fired: [] };
|
|
136
|
+
if (!sender) {
|
|
137
|
+
log.debug(`[adherence] ${buffered.length} escalation(s) buffered; no owner channel published`);
|
|
138
|
+
return { fired: [] };
|
|
139
|
+
}
|
|
140
|
+
if (!(deps.ownerSession ?? isOwnerChannelSession)()) {
|
|
141
|
+
log.debug(`[adherence] ${buffered.length} escalation(s) buffered; this session does not own the owner channel`);
|
|
142
|
+
return { fired: [] };
|
|
143
|
+
}
|
|
144
|
+
const digest = planDigest(state, nowMs, {
|
|
145
|
+
...(deps.digestWindowMs !== undefined ? { windowMs: deps.digestWindowMs } : {}),
|
|
146
|
+
});
|
|
147
|
+
if (!digest.send) {
|
|
148
|
+
log.debug(`[adherence] ${digest.pending.length} escalation(s) buffered; digest window closed (${digest.suppressed} suppressed so far)`);
|
|
149
|
+
return { fired: [] };
|
|
150
|
+
}
|
|
151
|
+
let ok = false;
|
|
152
|
+
try {
|
|
153
|
+
ok =
|
|
154
|
+
(await Promise.resolve(sender(renderDigest(digest, ctx, nowMs), {
|
|
155
|
+
parseMode: "HTML",
|
|
156
|
+
source: "adherence-digest",
|
|
157
|
+
suppressed: digest.suppressed,
|
|
158
|
+
}))) === true;
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
log.debug(`[adherence] digest send threw: ${e.message}`);
|
|
162
|
+
}
|
|
163
|
+
if (!ok) {
|
|
164
|
+
log.debug("[adherence] digest not delivered; crossings stay buffered, rungs unspent");
|
|
165
|
+
return { fired: [] };
|
|
92
166
|
}
|
|
167
|
+
const fired = digest.pending.map((entry) => ({
|
|
168
|
+
rule: entry.ruleKey,
|
|
169
|
+
milestone: entry.milestone,
|
|
170
|
+
}));
|
|
171
|
+
commitDigest(state, nowMs);
|
|
172
|
+
log.debug(`[adherence] digest delivered: ${fired.length} crossing(s), ${digest.suppressed} suppressed`);
|
|
93
173
|
return { fired };
|
|
94
174
|
}
|
|
95
175
|
/**
|
|
@@ -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 -
|
|
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.
|
|
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 -
|
|
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
|
|
11
|
-
*
|
|
12
|
-
* (`WATCHDOG_TG_SIGNAL_KEY`, the same route the watchdog page uses),
|
|
13
|
-
*
|
|
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,22 @@ 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,
|
|
43
|
+
adherenceReportPath,
|
|
39
44
|
aggregateRuleAdherence,
|
|
45
|
+
commitDigest,
|
|
40
46
|
createEscalationState,
|
|
41
|
-
|
|
47
|
+
planDigest,
|
|
42
48
|
planEscalation,
|
|
43
49
|
readSessionEntriesFromFile,
|
|
50
|
+
recordEscalation,
|
|
44
51
|
writeAdherenceReport,
|
|
45
52
|
type AdherenceEscalationState,
|
|
46
53
|
type AdherenceWriteResult,
|
|
47
|
-
type
|
|
54
|
+
type PendingEscalation,
|
|
48
55
|
} from "../../../lib/enforcement/adherence-meter.js";
|
|
49
56
|
|
|
50
57
|
const log = createLogger("adherence-meter");
|
|
@@ -52,15 +59,49 @@ const log = createLogger("adherence-meter");
|
|
|
52
59
|
/** Extension-state bucket key for the per-session meter state. */
|
|
53
60
|
const ADHERENCE_STATE_KEY = "adherence-meter";
|
|
54
61
|
|
|
62
|
+
/** What a crossing may ask the owner channel for. */
|
|
63
|
+
export interface AdherenceOwnerSender {
|
|
64
|
+
(
|
|
65
|
+
text: string,
|
|
66
|
+
opts?: {
|
|
67
|
+
parseMode?: "HTML" | "Markdown";
|
|
68
|
+
source?: string;
|
|
69
|
+
/** Escalations folded into this message instead of sent one by one. */
|
|
70
|
+
suppressed?: number;
|
|
71
|
+
},
|
|
72
|
+
): boolean | Promise<boolean>;
|
|
73
|
+
}
|
|
74
|
+
|
|
55
75
|
/** Injectables for fixtures; production callers pass nothing. */
|
|
56
76
|
export interface AdherenceWiringDeps {
|
|
57
77
|
now?: () => number;
|
|
58
78
|
/** Owner-channel factory; defaults to the published TG signal sender. */
|
|
59
|
-
sender?: () =>
|
|
79
|
+
sender?: () => AdherenceOwnerSender | null;
|
|
80
|
+
/**
|
|
81
|
+
* True when THIS session is the one that reads the owner's chat. Defaults to
|
|
82
|
+
* the Telegram poller's live state (the seat that owns the poller is the seat
|
|
83
|
+
* whose escalations the owner must hear). A second seat shares the bot token
|
|
84
|
+
* but not the conversation, and its escalations never become owner messages;
|
|
85
|
+
* a spawned seat registers no Telegram surface at all, so it publishes no
|
|
86
|
+
* sender either.
|
|
87
|
+
*/
|
|
88
|
+
ownerSession?: () => boolean;
|
|
89
|
+
/** How often the owner may receive a digest (default one hour). */
|
|
90
|
+
digestWindowMs?: number;
|
|
60
91
|
reportDir?: string;
|
|
61
92
|
k?: number;
|
|
62
93
|
}
|
|
63
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Owner-facing session predicate. The liveness probe is core's own registry
|
|
97
|
+
* (`telegram-poller-liveness.ts`): "running" or "unknown" means no other seat
|
|
98
|
+
* is holding the owner's inbound channel, "stopped" means this process loaded
|
|
99
|
+
* Telegram and its poller is not the one reading the chat.
|
|
100
|
+
*/
|
|
101
|
+
function isOwnerChannelSession(): boolean {
|
|
102
|
+
return readTelegramPollerLiveness() !== "stopped";
|
|
103
|
+
}
|
|
104
|
+
|
|
64
105
|
function adherenceState(ctx: ExtensionContext): AdherenceEscalationState {
|
|
65
106
|
return getExtensionState(ctx, ADHERENCE_STATE_KEY, createEscalationState);
|
|
66
107
|
}
|
|
@@ -75,30 +116,68 @@ function branchEntries(ctx: ExtensionContext): unknown[] {
|
|
|
75
116
|
}
|
|
76
117
|
}
|
|
77
118
|
|
|
78
|
-
/**
|
|
79
|
-
function
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
119
|
+
/** Escape the three characters Telegram's HTML parser reserves. */
|
|
120
|
+
function escapeHtml(text: string): string {
|
|
121
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function shorten(text: string, max: number): string {
|
|
125
|
+
const trimmed = text.trim();
|
|
126
|
+
return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max - 3)}...`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The rule's matched text (the key's `source::pattern` tail), shortened. */
|
|
130
|
+
function ruleLabel(entry: PendingEscalation): string {
|
|
131
|
+
const tail = entry.ruleKey.includes("::")
|
|
132
|
+
? entry.ruleKey.split("::").slice(1).join("::")
|
|
133
|
+
: entry.ruleKey;
|
|
134
|
+
return shorten(`${entry.source}: ${tail}`, 64);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The hourly digest: a bold subject naming the highest rung it reports, then
|
|
139
|
+
* labelled lines. Short enough to survive as plain text (the owner's
|
|
140
|
+
* tweet-length rule) and valid under `parse_mode: HTML` (the Telegram outbound
|
|
141
|
+
* gate validates it before any send).
|
|
142
|
+
*/
|
|
143
|
+
function renderDigest(
|
|
144
|
+
digest: { pending: PendingEscalation[]; suppressed: number },
|
|
83
145
|
ctx: ExtensionContext,
|
|
84
146
|
nowMs: number,
|
|
85
147
|
): string {
|
|
86
|
-
|
|
87
|
-
const
|
|
88
|
-
|
|
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))}`
|
|
148
|
+
// The subject is the highest rung in the digest; ties go to the latest.
|
|
149
|
+
const subject = digest.pending.reduce((best, entry) =>
|
|
150
|
+
entry.milestone >= best.milestone ? entry : best,
|
|
94
151
|
);
|
|
152
|
+
const lines = [
|
|
153
|
+
`<b>adherence · rung ${subject.milestone}</b>`,
|
|
154
|
+
`rule ${escapeHtml(ruleLabel(subject))}`,
|
|
155
|
+
...(digest.pending.length > 1 ? [`rules ${digest.pending.length}`] : []),
|
|
156
|
+
`deliveries ${subject.deliveries}`,
|
|
157
|
+
`repeats ${subject.repeats}`,
|
|
158
|
+
`suppressed ${digest.suppressed}`,
|
|
159
|
+
`session ${escapeHtml(shorten(getSessionIdSafe(ctx) || "unknown", 32))}`,
|
|
160
|
+
`at ${formatLocalTime(new Date(nowMs))}`,
|
|
161
|
+
// The next step is a pointer, not advice: the full signal text and the
|
|
162
|
+
// per-rule counts live in the session report.
|
|
163
|
+
`where ${escapeHtml(shorten(adherenceReportPath(), 72))}`,
|
|
164
|
+
];
|
|
165
|
+
return lines.join("\n");
|
|
95
166
|
}
|
|
96
167
|
|
|
97
168
|
/**
|
|
98
|
-
* Aggregate the current branch and
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
169
|
+
* Aggregate the current branch and fold every crossing into the owner's
|
|
170
|
+
* hourly digest.
|
|
171
|
+
*
|
|
172
|
+
* What did NOT change: the ladder. `planEscalation` is asked exactly as before,
|
|
173
|
+
* and a rung is still spent only when the owner channel accepted the message
|
|
174
|
+
* that reported it, so the milestones, thresholds and detection are untouched.
|
|
175
|
+
*
|
|
176
|
+
* What changed: a crossing is buffered (`recordEscalation`) and delivered as
|
|
177
|
+
* ONE digest per window (`planDigest`), which states how many crossings it
|
|
178
|
+
* folded instead of sending each one as its own message. Two seats sharing a
|
|
179
|
+
* bot token no longer both write into the owner's chat: only the session that
|
|
180
|
+
* owns the inbound channel escalates.
|
|
102
181
|
*/
|
|
103
182
|
export async function checkAdherence(
|
|
104
183
|
ctx: ExtensionContext,
|
|
@@ -106,38 +185,73 @@ export async function checkAdherence(
|
|
|
106
185
|
): Promise<{ fired: Array<{ rule: string; milestone: number }> }> {
|
|
107
186
|
const state = adherenceState(ctx);
|
|
108
187
|
const entries = branchEntries(ctx);
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const rules = aggregateRuleAdherence(activeBranchEntries(entries));
|
|
188
|
+
const rules = entries.length > 0 ? aggregateRuleAdherence(activeBranchEntries(entries)) : [];
|
|
112
189
|
const sender = (deps.sender ?? getWatchdogTgSignalSender)();
|
|
113
190
|
const nowMs = (deps.now ?? Date.now)();
|
|
114
|
-
const
|
|
191
|
+
const sessionId = getSessionIdSafe(ctx);
|
|
115
192
|
|
|
116
193
|
for (const rule of rules) {
|
|
117
194
|
const plan = planEscalation(state, rule.rule, rule.repeats);
|
|
118
195
|
if (!plan.fire) continue;
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
continue;
|
|
137
|
-
}
|
|
138
|
-
markEscalated(state, rule.rule);
|
|
139
|
-
fired.push({ rule: rule.rule, milestone: plan.milestone });
|
|
196
|
+
recordEscalation(state, {
|
|
197
|
+
ruleKey: rule.rule,
|
|
198
|
+
rung: (state.rules[rule.rule]?.rung ?? 0) + 1,
|
|
199
|
+
milestone: plan.milestone,
|
|
200
|
+
source: rule.source,
|
|
201
|
+
deliveries: rule.deliveries,
|
|
202
|
+
repeats: rule.repeats,
|
|
203
|
+
sessionId,
|
|
204
|
+
at: nowMs,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const buffered = state.pending ?? [];
|
|
209
|
+
if (buffered.length === 0) return { fired: [] };
|
|
210
|
+
if (!sender) {
|
|
211
|
+
log.debug(`[adherence] ${buffered.length} escalation(s) buffered; no owner channel published`);
|
|
212
|
+
return { fired: [] };
|
|
140
213
|
}
|
|
214
|
+
if (!(deps.ownerSession ?? isOwnerChannelSession)()) {
|
|
215
|
+
log.debug(
|
|
216
|
+
`[adherence] ${buffered.length} escalation(s) buffered; this session does not own the owner channel`,
|
|
217
|
+
);
|
|
218
|
+
return { fired: [] };
|
|
219
|
+
}
|
|
220
|
+
const digest = planDigest(state, nowMs, {
|
|
221
|
+
...(deps.digestWindowMs !== undefined ? { windowMs: deps.digestWindowMs } : {}),
|
|
222
|
+
});
|
|
223
|
+
if (!digest.send) {
|
|
224
|
+
log.debug(
|
|
225
|
+
`[adherence] ${digest.pending.length} escalation(s) buffered; digest window closed (${digest.suppressed} suppressed so far)`,
|
|
226
|
+
);
|
|
227
|
+
return { fired: [] };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
let ok = false;
|
|
231
|
+
try {
|
|
232
|
+
ok =
|
|
233
|
+
(await Promise.resolve(
|
|
234
|
+
sender(renderDigest(digest, ctx, nowMs), {
|
|
235
|
+
parseMode: "HTML",
|
|
236
|
+
source: "adherence-digest",
|
|
237
|
+
suppressed: digest.suppressed,
|
|
238
|
+
}),
|
|
239
|
+
)) === true;
|
|
240
|
+
} catch (e) {
|
|
241
|
+
log.debug(`[adherence] digest send threw: ${(e as Error).message}`);
|
|
242
|
+
}
|
|
243
|
+
if (!ok) {
|
|
244
|
+
log.debug("[adherence] digest not delivered; crossings stay buffered, rungs unspent");
|
|
245
|
+
return { fired: [] };
|
|
246
|
+
}
|
|
247
|
+
const fired = digest.pending.map((entry) => ({
|
|
248
|
+
rule: entry.ruleKey,
|
|
249
|
+
milestone: entry.milestone,
|
|
250
|
+
}));
|
|
251
|
+
commitDigest(state, nowMs);
|
|
252
|
+
log.debug(
|
|
253
|
+
`[adherence] digest delivered: ${fired.length} crossing(s), ${digest.suppressed} suppressed`,
|
|
254
|
+
);
|
|
141
255
|
return { fired };
|
|
142
256
|
}
|
|
143
257
|
|
|
@@ -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 = (
|
|
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 {
|