pi-braid 0.43.9 → 0.43.11

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.
@@ -44,6 +44,16 @@ export {
44
44
  parseStructuredContent,
45
45
  generateAutoTags,
46
46
  } from "./utils.js";
47
+ export {
48
+ classifyRulingBody,
49
+ deriveTopicTags,
50
+ QUOTE_LIMIT,
51
+ TAG_LIMIT,
52
+ type GrammarVocabulary,
53
+ type RulingClass,
54
+ type RulingShape,
55
+ type TagPopulation,
56
+ } from "./decision-grammar.js";
47
57
 
48
58
  // shouldStore, calculateUtility, pruneMemories, consolidate, and the
49
59
  // constants (MAX_ENTRIES, MIN_UTILITY_THRESHOLD, CATEGORY_BASE_UTILITY)
@@ -0,0 +1,286 @@
1
+ /**
2
+ * Owner speech: the braid half of the ruling write path.
3
+ *
4
+ * Two jobs, both of them specific to this deployment:
5
+ *
6
+ * - **Decide whether a turn is the owner speaking at all.** The corpus holds
7
+ * every user-role turn, and in this transcript tree that includes the
8
+ * system's own voice: dispatch prompts the seat writes to a running agent,
9
+ * and whisper envelopes from braid's subsystems. A directive-language
10
+ * classifier over that input files the seat's own brief text as an owner
11
+ * ruling, with a pointer into a worker session - a store that looks like
12
+ * provenance and is self-quotation. A telegram envelope is the exception:
13
+ * its body is the owner's message in a transport wrapper, so the wrapper is
14
+ * stripped and the body is what gets classified.
15
+ * - **File a ruling in braid's store.** The label stamped into `source`, the
16
+ * pointer shape, the duplicate key and the fixed tags are braid's filing
17
+ * convention, not English grammar, so they live here and the script that
18
+ * writes them carries no domain string of its own.
19
+ *
20
+ * The classification itself is `classifyRulingBody()` in the generic layer.
21
+ * This module supplies the vocabulary that layer cannot know - what a ruling
22
+ * can be about, and which words describe braid's own machinery - and removes
23
+ * the envelope before it ever reaches the grammar.
24
+ *
25
+ * Pure by construction: no I/O, no clock, no randomness.
26
+ */
27
+
28
+ import {
29
+ classifyRulingBody,
30
+ type GrammarVocabulary,
31
+ type RulingClass,
32
+ type RulingShape,
33
+ } from "../memory/decision-grammar.js";
34
+
35
+ /**
36
+ * One user turn, in the shape the corpus index stores it. Declared here rather
37
+ * than imported from `extensions/memory/session-recall/corpus-index.ts`: `lib/`
38
+ * does not import from `extensions/`, and the classifier needs six fields, not
39
+ * that module's build machinery.
40
+ */
41
+ export interface RulingTurn {
42
+ /** Absolute path of the session file the turn was read from. */
43
+ session: string;
44
+ /** pi's session id; with `line` it is the duplicate key. */
45
+ session_id: string;
46
+ /** Project label the session ran in. */
47
+ project: string;
48
+ /** Entry timestamp, ISO-8601. */
49
+ ts: string;
50
+ /** 1-based line number of the turn inside the session file. */
51
+ line: number;
52
+ /** The owner's words, verbatim. */
53
+ text: string;
54
+ }
55
+
56
+ /** A turn the classifier judged to carry an owner ruling. */
57
+ export interface OwnerRulingCandidate {
58
+ class: RulingClass;
59
+ /** The owner's words, contiguous and verbatim, capped with a trailing ellipsis. */
60
+ quote: string;
61
+ session: string;
62
+ session_id: string;
63
+ project: string;
64
+ ts: string;
65
+ line: number;
66
+ }
67
+
68
+ /**
69
+ * The label every filed ruling carries at the front of `source`, and the only
70
+ * handle a later run greps for. It is a constant here because the store's
71
+ * retention policy keys on the same prefix: a second spelling would be a class
72
+ * of entry the prune could not see.
73
+ */
74
+ export const OWNER_RULING_LABEL = "owner ruling";
75
+
76
+ /**
77
+ * A whisper envelope header. The transport line is not speech: for a telegram
78
+ * envelope the body beneath it is the owner's message, and for every other
79
+ * subsystem it is braid talking to itself.
80
+ */
81
+ const WHISPER_HEADER = /^\s*\[braid-whisper - ([a-z0-9-]+)(?: @ [^\]]*)?\](.*)$/i;
82
+
83
+ /** The envelope's closing marker. */
84
+ const WHISPER_END = /^\s*\[braid-whisper-end\]\s*$/i;
85
+
86
+ /**
87
+ * Transport lines inside a telegram envelope: the sender line, and the
88
+ * sub-header a coalesced batch puts above each message. Neither is the owner's
89
+ * words.
90
+ */
91
+ const TELEGRAM_TRANSPORT =
92
+ /^\s*(?:from @\S+ .*in chat \d+\S*|\[\d+\/\d+\s@ [^\]]*\](?:\s+from @\S+.*)?|-{3,})$/i;
93
+
94
+ /**
95
+ * How a dispatch prompt opens. These are turns the seat wrote to a running
96
+ * agent; they carry imperatives because that is what a dispatch is.
97
+ */
98
+ const SEAT_OPENER =
99
+ /^\s*(?:you are\b|your (?:branch|task|brief|report|cwd|job|pane|mission)\b|read your brief in full|read the brief\b|read (?:the )?(?:\/|~|[\w-]+\.md)|begin backlog item|your task:|mission:|task:|authori[sz]ed (?:execution )?brief|re-?read\b|acknowledge\b|this is a fresh session|first: )/i;
100
+
101
+ /**
102
+ * Words a dispatch prompt tends to carry: the seat's own shorthands, which the
103
+ * owner does not use when he states a ruling. One in a turn is enough, because
104
+ * none of them is owner vocabulary.
105
+ */
106
+ const SEAT_ANATOMY: ReadonlyArray<RegExp> = [
107
+ /\bAUTHORITATIVE BRIEF\b/i,
108
+ /\bAUTHORISED BRIEF\b/i,
109
+ /\bresult block\b/i,
110
+ /check-result\.mjs/,
111
+ /\bConfirm receipt\b/i,
112
+ /\bPI_SESSION_FILE\b/i,
113
+ /\bEnd it with the result block\b/i,
114
+ /\bDispatch facts\b/i,
115
+ /\bRead your brief\b/i,
116
+ ];
117
+
118
+ /** Pasted-brief structure: headings that only a dispatch prompt carries. */
119
+ const BRIEF_HEADINGS = /^\s*#{2,}\s/m;
120
+
121
+ /** Sends a turn from the seat to a running agent. */
122
+ const STEER_OPENER =
123
+ /^\s*(?:steer(?:,| from| to|:)|seat to |\[agent:|dispatch(?:ed)?:|correction to|status check|reminder:)/i;
124
+
125
+ /**
126
+ * Session machinery. A message about a timer, a poller, a pane or a
127
+ * predecessor's transcript is braid talking to a process; the owner states
128
+ * rules about how braid behaves, not about which lock file the previous
129
+ * occupant held.
130
+ */
131
+ const SESSION_MACHINERY =
132
+ /\b(?:timer|poller|polling|pane|worktree|predecessor|successor|lock (?:file|PID)|transcript|session file|placement section|check-result|result block|ci:check)\b/i;
133
+
134
+ /**
135
+ * What a ruling is about when it does not open with the owner's own voice: the
136
+ * system, its agents, its tools. A bare directive with none of this and no
137
+ * first person ("Do not read or write files.") is an instruction aimed at the
138
+ * reader, not a decision about braid.
139
+ */
140
+ const SYSTEM_SCOPE =
141
+ /\b(?:braid|agent|agents|worker|workers|writer|writers|reader|readers|seat|seats|system|prompt|memory|store|skill|skills|tool|tools|model|models|subscription|subscri\w*|session|sessions|orchestrator|identity|layer|layers|gate|gates|report|reports|brief|briefs|docs?|telegram|context|queue|pipeline|repo|repository|codebase|website|app|product)\b/i;
142
+
143
+ /**
144
+ * Explicit generalization. A rule aimed at any instance is a rule; one aimed
145
+ * at the agent reading it is a steer, and the escape hatch has to be stated.
146
+ */
147
+ const GENERALIZED =
148
+ /\b(?:any (?:instance|agent|worker|seat|one)|every (?:agent|instance|worker|seat)|generically?|whichever|regardless)\b/i;
149
+
150
+ /**
151
+ * The vocabulary this deployment hands the generic grammar. It is the only
152
+ * braid-specific input `classifyRulingBody()` takes, and it is a value rather
153
+ * than a parameter chain so a fixture can classify the same body with and
154
+ * without an envelope and compare.
155
+ */
156
+ export const BRAID_VOCABULARY: GrammarVocabulary = {
157
+ namesSubject: (text) => SYSTEM_SCOPE.test(text),
158
+ talksProcess: (text) => SESSION_MACHINERY.test(text),
159
+ generalizes: (text) => GENERALIZED.test(text),
160
+ };
161
+
162
+ /**
163
+ * The owner's words inside a turn, or `null` when the turn is not the owner's
164
+ * speech.
165
+ *
166
+ * Stripping happens line by line, and the kept lines are the original lines, so
167
+ * a quote later cut from the body is still a contiguous slice of the stored
168
+ * turn - the pointer resolves either way. A turn that carries any non-telegram
169
+ * envelope is refused whole: a subsystem whisper and an owner tail can share
170
+ * one turn, and no mechanical rule here can say which sentence is whose.
171
+ */
172
+ function ownerSpeech(body: string): string | null {
173
+ const lines = body.split("\n");
174
+ const headers = lines.map((line) => WHISPER_HEADER.exec(line)).filter(Boolean);
175
+ if (headers.length > 0) {
176
+ const foreign = headers.find((header) => header![1].toLowerCase() !== "telegram");
177
+ if (foreign) return null;
178
+ }
179
+ if (headers.length === 0) return body;
180
+
181
+ const kept: string[] = [];
182
+ let inside = false;
183
+ for (const line of lines) {
184
+ if (WHISPER_HEADER.test(line)) {
185
+ inside = true;
186
+ continue;
187
+ }
188
+ if (WHISPER_END.test(line)) {
189
+ inside = false;
190
+ continue;
191
+ }
192
+ if (inside && TELEGRAM_TRANSPORT.test(line)) continue;
193
+ if (inside) kept.push(line);
194
+ }
195
+ const stripped = kept.join("\n").trim();
196
+ return stripped || null;
197
+ }
198
+
199
+ /** Is this turn a dispatch prompt rather than the owner speaking? */
200
+ function looksLikeSeatPrompt(body: string): boolean {
201
+ const firstLine = body.split("\n").find((line) => line.trim()) ?? "";
202
+ if (SEAT_OPENER.test(firstLine)) return true;
203
+ if (STEER_OPENER.test(firstLine)) return true;
204
+ for (const pattern of SEAT_ANATOMY) if (pattern.test(body)) return true;
205
+ return BRIEF_HEADINGS.test(body) && /\bbrief\b/i.test(body);
206
+ }
207
+
208
+ /**
209
+ * Classify one user turn.
210
+ *
211
+ * Refuses everything that is not owner speech before the grammar runs, then
212
+ * hands the body to the generic classifier with this deployment's vocabulary,
213
+ * and stamps the provenance the pointer and the duplicate key are built from.
214
+ */
215
+ export function classifyOwnerRuling(turn: RulingTurn): OwnerRulingCandidate | null {
216
+ if (!turn || typeof turn.text !== "string") return null;
217
+ const raw = turn.text.trim();
218
+ if (!raw) return null;
219
+ const speech = ownerSpeech(raw);
220
+ if (!speech) return null;
221
+ if (looksLikeSeatPrompt(speech)) return null;
222
+ const shape: RulingShape | null = classifyRulingBody(speech, BRAID_VOCABULARY);
223
+ if (!shape) return null;
224
+ return {
225
+ class: shape.class,
226
+ quote: shape.quote,
227
+ session: turn.session,
228
+ session_id: turn.session_id,
229
+ project: turn.project,
230
+ ts: turn.ts,
231
+ line: turn.line,
232
+ };
233
+ }
234
+
235
+ /**
236
+ * The pointer the store carries in `source`, in one fixed shape:
237
+ * `owner ruling: <session path>:<line> (<iso ts>, <project>)`.
238
+ *
239
+ * Greppable by prefix, and it resolves: the path and line address the turn the
240
+ * quote came from, so `sed -n '<line>p' '<session path>'` prints the words.
241
+ */
242
+ export function rulingPointer(candidate: OwnerRulingCandidate): string {
243
+ return `${OWNER_RULING_LABEL}: ${candidate.session}:${candidate.line} (${candidate.ts}, ${candidate.project})`;
244
+ }
245
+
246
+ /**
247
+ * The pointer as a pattern, so a caller that scans a store for filed rulings
248
+ * reads the label from the same place it writes it instead of spelling it a
249
+ * second time. Groups: 1 the session path, 2 the line number.
250
+ */
251
+ export function rulingPointerPattern(): RegExp {
252
+ const escaped = OWNER_RULING_LABEL.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
253
+ return new RegExp(`^${escaped}: (.+):(\\d+) \\(`);
254
+ }
255
+
256
+ /**
257
+ * The duplicate key: one turn is one ruling, so `<session_id>:<line>` names it
258
+ * whether the entry was written by this script, by hand, or by a later run.
259
+ */
260
+ export function rulingDuplicateKey(candidate: OwnerRulingCandidate): string {
261
+ return `${candidate.session_id}:${candidate.line}`;
262
+ }
263
+
264
+ /**
265
+ * A project label as a tag token: lowercase alphanumerics, single hyphens, no
266
+ * leading/trailing hyphen. `projects/agents/pi-braid` becomes
267
+ * `projects-agents-pi-braid`, which is greppable and cannot collide with a
268
+ * different project's label through punctuation alone.
269
+ */
270
+ export function projectTag(label: string): string {
271
+ const slug = label
272
+ .toLowerCase()
273
+ .replace(/[^a-z0-9]+/g, "-")
274
+ .replace(/^-+|-+$/g, "");
275
+ return slug || "unknown-project";
276
+ }
277
+
278
+ /**
279
+ * The fixed handles every filed ruling carries: the class a reader filters on,
280
+ * and the project it came from. The quote's own words are added beside these by
281
+ * `deriveTopicTags()`, because a handle names the entry while a topic word is
282
+ * what a later question arrives through.
283
+ */
284
+ export function rulingBaseTags(candidate: OwnerRulingCandidate): string[] {
285
+ return ["owner-ruling", candidate.class, projectTag(candidate.project)];
286
+ }