pi-braid 0.40.3 → 0.40.6

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.
Files changed (85) hide show
  1. package/AGENTS.md +17 -18
  2. package/README.md +116 -130
  3. package/TOOLS.md +35 -35
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/agent-environment/index.js +4 -3
  6. package/dist/extensions/core/prompt-builder/index.js +12 -7
  7. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
  8. package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
  9. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
  10. package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
  11. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  12. package/dist/extensions/core/skills-tool/auto-inject.d.ts +178 -17
  13. package/dist/extensions/core/skills-tool/auto-inject.js +264 -23
  14. package/dist/extensions/core/skills-tool/index.d.ts +70 -2
  15. package/dist/extensions/core/skills-tool/index.js +149 -15
  16. package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
  17. package/dist/extensions/core/skills-tool/reach.js +213 -0
  18. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +74 -13
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +105 -24
  20. package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
  21. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
  22. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
  23. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
  24. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
  25. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
  26. package/dist/extensions/enforcement/resume-state.d.ts +76 -0
  27. package/dist/extensions/enforcement/resume-state.js +90 -0
  28. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
  29. package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
  30. package/dist/extensions/enforcement/whisper.d.ts +12 -0
  31. package/dist/extensions/enforcement/whisper.js +16 -1
  32. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
  33. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
  34. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
  35. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
  36. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
  37. package/dist/lib/config/braid-paths.d.ts +14 -0
  38. package/dist/lib/config/braid-paths.js +18 -0
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +16 -0
  41. package/dist/lib/detection/context-tiers.d.ts +47 -3
  42. package/dist/lib/detection/context-tiers.js +122 -13
  43. package/dist/lib/events/turn-boundary.d.ts +78 -0
  44. package/dist/lib/events/turn-boundary.js +91 -0
  45. package/dist/lib/orchestrator/workers.d.ts +3 -2
  46. package/dist/lib/orchestrator/workers.js +22 -4
  47. package/dist/lib/state/global-state.d.ts +1 -1
  48. package/docs/CONTEXT-POLICY.md +8 -0
  49. package/docs/LOCAL_DEV.md +0 -1
  50. package/docs/ROADMAP.md +5 -5
  51. package/docs/SETUP.md +19 -18
  52. package/package.json +2 -1
  53. package/skills/herdr-topology/SKILL.md +6 -1
  54. package/skills/research/SKILL.md +32 -0
  55. package/skills/subagent-orchestration/SKILL.md +2 -2
  56. package/src/extensions/core/agent-environment/index.ts +4 -3
  57. package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
  58. package/src/extensions/core/prompt-builder/index.ts +12 -7
  59. package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
  60. package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
  61. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  62. package/src/extensions/core/skills-tool/auto-inject.ts +350 -27
  63. package/src/extensions/core/skills-tool/index.ts +217 -15
  64. package/src/extensions/core/skills-tool/reach.ts +256 -0
  65. package/src/extensions/core/skills-tool/skill-triggers.ts +130 -23
  66. package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
  67. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
  68. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
  69. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
  70. package/src/extensions/enforcement/resume-state.ts +127 -0
  71. package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
  72. package/src/extensions/enforcement/whisper.ts +21 -1
  73. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
  74. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
  75. package/src/extensions/memory/AGENTS.md +25 -1
  76. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
  77. package/src/lib/config/braid-paths.ts +20 -0
  78. package/src/lib/config/braid-settings.ts +46 -0
  79. package/src/lib/detection/context-tiers.ts +186 -13
  80. package/src/lib/events/AGENTS.md +1 -0
  81. package/src/lib/events/turn-boundary.ts +115 -0
  82. package/src/lib/orchestrator/workers.ts +33 -12
  83. package/src/lib/state/global-state.ts +1 -0
  84. package/src/lib/utils/AGENTS.md +1 -1
  85. package/src/types/extension-context.d.ts +22 -79
@@ -25,6 +25,378 @@ export const VERIFICATION_TOOLS = new Set([
25
25
  ]);
26
26
  export const WEB_TOOLS = new Set(["fetch_content", "browser_navigate", "browser_content"]);
27
27
  export const CODE_TOOLS = new Set(["bash", "write", "edit"]);
28
+ // ═══════════════════════════════════════════════════════════════════════════
29
+ // VERIFICATION-SHAPE RECOGNITION FOR BASH
30
+ // ═══════════════════════════════════════════════════════════════════════════
31
+ // VERIFICATION_TOOLS is a tool-NAME set, and the same work routinely runs
32
+ // through bash: `grep -rn "needle" src`, `git diff main...HEAD`, `node -e
33
+ // 'console.log(m.x)'`. The set cannot see it, so the verification counter
34
+ // stayed at zero while the agent verified and the hint below told the agent it
35
+ // had not verified in ten turns. Counting every bash call would swing the
36
+ // defect the other way — an edit, a build or a publish script is not
37
+ // verification, and a counter that accepts them silences the hint it exists to
38
+ // raise.
39
+ //
40
+ // The rule, in one sentence: a command counts when it puts an inspecting
41
+ // program at a program position and no mutating program anywhere.
42
+ // - program positions are the first word of each `;` `&&` `||` `|` `&`
43
+ // segment, tokenized quote-aware (`grep -n "a|b" f` is one segment);
44
+ // - inspecting: search/locate, read, compare/extract programs, git read
45
+ // subcommands, and an inline interpreter probe (`node -e`, `python -c`)
46
+ // whose script shows no write primitive;
47
+ // - mutating: rm/mv/cp/mkdir/tee/dd/chmod…, `sed -i`, `perl -i`, git write
48
+ // subcommands, and any unquoted redirect to a file other than /dev/null.
49
+ // Both directions matter: the two named holes are an interpreter script that
50
+ // writes through a primitive outside INLINE_WRITE_RE, and a mutating program
51
+ // behind `eval` or a heredoc body (both are read as inspection when the same
52
+ // command also inspects — they are listed here rather than guessed at).
53
+ /** Programs that inspect existing state: search, locate, read, compare, extract. */
54
+ const INSPECT_PROGRAMS = new Set([
55
+ "grep",
56
+ "egrep",
57
+ "fgrep",
58
+ "rg",
59
+ "ag",
60
+ "ack",
61
+ "ack-grep",
62
+ "ugrep",
63
+ "pcregrep",
64
+ "find",
65
+ "fd",
66
+ "fdfind",
67
+ "locate",
68
+ "cat",
69
+ "tac",
70
+ "head",
71
+ "tail",
72
+ "bat",
73
+ "less",
74
+ "more",
75
+ "wc",
76
+ "nl",
77
+ "od",
78
+ "xxd",
79
+ "strings",
80
+ "file",
81
+ "stat",
82
+ "ls",
83
+ "tree",
84
+ "realpath",
85
+ "readlink",
86
+ "jq",
87
+ "yq",
88
+ "diff",
89
+ "diff3",
90
+ "cmp",
91
+ "comm",
92
+ "cut",
93
+ "uniq",
94
+ "tr",
95
+ "column",
96
+ "awk",
97
+ "gawk",
98
+ "sed",
99
+ ]);
100
+ /** Programs that mutate the tree. Any one of them vetoes the call. */
101
+ const MUTATE_PROGRAMS = new Set([
102
+ "rm",
103
+ "rmdir",
104
+ "mv",
105
+ "cp",
106
+ "ln",
107
+ "touch",
108
+ "mkdir",
109
+ "install",
110
+ "truncate",
111
+ "dd",
112
+ "shred",
113
+ "tee",
114
+ "patch",
115
+ "chmod",
116
+ "chown",
117
+ "chgrp",
118
+ ]);
119
+ /**
120
+ * `git` subcommands that only read (the inspection side of the verbs the
121
+ * destructive gate covers separately).
122
+ */
123
+ const GIT_READ_SUBS = new Set([
124
+ "diff",
125
+ "diff-tree",
126
+ "diff-index",
127
+ "diff-files",
128
+ "show",
129
+ "log",
130
+ "status",
131
+ "grep",
132
+ "blame",
133
+ "shortlog",
134
+ "whatchanged",
135
+ "ls-files",
136
+ "ls-tree",
137
+ "cat-file",
138
+ "rev-parse",
139
+ "rev-list",
140
+ "show-ref",
141
+ "for-each-ref",
142
+ "describe",
143
+ "merge-base",
144
+ "name-rev",
145
+ "count-objects",
146
+ "fsck",
147
+ ]);
148
+ /** `git` subcommands that write. Conservative: a remote/config/branch/tag
149
+ * verb may mutate, so it vetoes rather than counts. */
150
+ const GIT_WRITE_SUBS = new Set([
151
+ "add",
152
+ "commit",
153
+ "push",
154
+ "pull",
155
+ "fetch",
156
+ "checkout",
157
+ "switch",
158
+ "restore",
159
+ "reset",
160
+ "revert",
161
+ "merge",
162
+ "rebase",
163
+ "cherry-pick",
164
+ "stash",
165
+ "apply",
166
+ "am",
167
+ "clean",
168
+ "rm",
169
+ "mv",
170
+ "tag",
171
+ "branch",
172
+ "init",
173
+ "clone",
174
+ "config",
175
+ "remote",
176
+ "submodule",
177
+ "worktree",
178
+ "update-index",
179
+ "update-ref",
180
+ "symbolic-ref",
181
+ "notes",
182
+ "gc",
183
+ "prune",
184
+ "reflog",
185
+ ]);
186
+ /** Interpreters whose inline-eval form can be a probe. */
187
+ const INLINE_INTERPRETERS = new Set(["node", "deno", "bun", "python", "python3", "ruby"]);
188
+ /** Write primitives inside an inline script (both JS/TS and Python spellings). */
189
+ const INLINE_WRITE_RE = /writeFileSync|writeFile\(|appendFileSync|createWriteStream|rmSync|unlinkSync|renameSync|mkdirSync|copyFileSync|truncateSync|chmodSync|openSync\([^)]*["'`][wa]|os\.remove|os\.rename|shutil\.|open\([^)]*["'`][wa]/;
190
+ /** Wrappers whose presence does not decide the kind of the segment. */
191
+ const WRAPPER_PROGRAMS = new Set(["sudo", "env", "time", "nice", "command", "nohup"]);
192
+ /** Tokens that end one command segment. */
193
+ const SEGMENT_SEPARATORS = new Set([";", "&&", "||", "|", "&", "\n"]);
194
+ /** The program name without its path (`/usr/bin/grep` → `grep`). */
195
+ function baseName(token) {
196
+ const parts = token.split("/");
197
+ return parts[parts.length - 1] ?? token;
198
+ }
199
+ /**
200
+ * Quote-aware tokenizer that keeps shell operators as their own tokens
201
+ * (`;` `&&` `||` `|` `&` newline `>` `>>`, and `&1`/`&2` as one token) and
202
+ * strips quote characters. An escaped character stays literal, so `find …
203
+ * -exec grep … \;` yields the word `;` rather than a separator.
204
+ */
205
+ function tokenizeCommand(command) {
206
+ const tokens = [];
207
+ let cur = "";
208
+ let quote = null;
209
+ const flush = () => {
210
+ if (cur) {
211
+ tokens.push(cur);
212
+ cur = "";
213
+ }
214
+ };
215
+ for (let i = 0; i < command.length; i++) {
216
+ const ch = command[i] ?? "";
217
+ if (quote) {
218
+ if (ch === "\\" && quote === '"') {
219
+ cur += command[i + 1] ?? "";
220
+ i++;
221
+ continue;
222
+ }
223
+ if (ch === quote) {
224
+ quote = null;
225
+ continue;
226
+ }
227
+ cur += ch;
228
+ continue;
229
+ }
230
+ if (ch === "\\") {
231
+ cur += command[i + 1] ?? "";
232
+ i++;
233
+ continue;
234
+ }
235
+ if (ch === '"' || ch === "'") {
236
+ quote = ch;
237
+ continue;
238
+ }
239
+ if (/\s/.test(ch)) {
240
+ flush();
241
+ if (ch === "\n")
242
+ tokens.push("\n");
243
+ continue;
244
+ }
245
+ if (ch === ";" || ch === "&") {
246
+ flush();
247
+ const next = command[i + 1] ?? "";
248
+ if (ch === "&" && /\d/.test(next)) {
249
+ tokens.push(`&${next}`);
250
+ i++;
251
+ continue;
252
+ }
253
+ if (ch === "&" && next === "&") {
254
+ tokens.push("&&");
255
+ i++;
256
+ continue;
257
+ }
258
+ tokens.push(ch);
259
+ continue;
260
+ }
261
+ if (ch === "|") {
262
+ flush();
263
+ if ((command[i + 1] ?? "") === "|") {
264
+ tokens.push("||");
265
+ i++;
266
+ continue;
267
+ }
268
+ tokens.push("|");
269
+ continue;
270
+ }
271
+ if (ch === ">") {
272
+ flush();
273
+ if ((command[i + 1] ?? "") === ">") {
274
+ tokens.push(">>");
275
+ i++;
276
+ continue;
277
+ }
278
+ tokens.push(">");
279
+ continue;
280
+ }
281
+ cur += ch;
282
+ }
283
+ flush();
284
+ return tokens;
285
+ }
286
+ /** Split tokenized commands into segments at the separators. */
287
+ function splitSegments(tokens) {
288
+ const out = [];
289
+ let cur = [];
290
+ for (const token of tokens) {
291
+ if (SEGMENT_SEPARATORS.has(token)) {
292
+ if (cur.length > 0)
293
+ out.push(cur);
294
+ cur = [];
295
+ continue;
296
+ }
297
+ cur.push(token);
298
+ }
299
+ if (cur.length > 0)
300
+ out.push(cur);
301
+ return out;
302
+ }
303
+ /**
304
+ * A redirect that writes a real file. `/dev/null` and fd duplications
305
+ * (`2>&1`) are the ordinary shapes of a silent inspection and stay benign — a
306
+ * redirect into a path is a write, whatever program it follows.
307
+ */
308
+ function writesFile(tokens) {
309
+ for (let i = 0; i < tokens.length; i++) {
310
+ const token = tokens[i];
311
+ if (token !== ">" && token !== ">>")
312
+ continue;
313
+ const target = tokens[i + 1];
314
+ if (!target || SEGMENT_SEPARATORS.has(target))
315
+ continue;
316
+ if (/^\/dev\/(?:null|stdout|stderr)$/.test(target))
317
+ continue;
318
+ if (/^&\d$/.test(target))
319
+ continue;
320
+ return true;
321
+ }
322
+ return false;
323
+ }
324
+ /** The first argument that is not a flag (`xargs -I{} rm` → `rm`). */
325
+ function firstArgument(args) {
326
+ for (const arg of args)
327
+ if (!arg.startsWith("-"))
328
+ return arg;
329
+ return null;
330
+ }
331
+ /** Classify one segment by the program in its program position. */
332
+ function classifySegment(tokens) {
333
+ let i = 0;
334
+ while (i < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i] ?? ""))
335
+ i++;
336
+ while (i < tokens.length && WRAPPER_PROGRAMS.has(baseName(tokens[i] ?? "")))
337
+ i++;
338
+ const program = tokens[i] ? baseName(tokens[i]) : "";
339
+ if (!program)
340
+ return "neutral";
341
+ const args = tokens.slice(i + 1);
342
+ if (MUTATE_PROGRAMS.has(program))
343
+ return "mutate";
344
+ // xargs runs its first non-flag argument: classify the thing it runs.
345
+ if (program === "xargs") {
346
+ const target = firstArgument(args);
347
+ return target ? classifySegment([target]) : "neutral";
348
+ }
349
+ if (program === "git") {
350
+ const sub = args.find((a) => GIT_READ_SUBS.has(a) || GIT_WRITE_SUBS.has(a));
351
+ if (!sub)
352
+ return "neutral";
353
+ return GIT_WRITE_SUBS.has(sub) ? "mutate" : "inspect";
354
+ }
355
+ const inPlace = args.some((a) => a === "--in-place" || /^-[A-Za-z]*i/.test(a) || /^--in-place=/.test(a));
356
+ if (program === "sed" || program === "perl") {
357
+ if (inPlace)
358
+ return "mutate";
359
+ return "inspect";
360
+ }
361
+ if (INLINE_INTERPRETERS.has(program)) {
362
+ const inline = args.some((a) => a === "-e" || a === "-p" || a === "--eval" || a === "-c");
363
+ if (!inline)
364
+ return "neutral";
365
+ return INLINE_WRITE_RE.test(args.join(" ")) ? "mutate" : "inspect";
366
+ }
367
+ if (INSPECT_PROGRAMS.has(program))
368
+ return "inspect";
369
+ return "neutral";
370
+ }
371
+ /** True when the command is inspection-shaped (see the rule above). */
372
+ export function bashCommandIsVerification(command) {
373
+ if (!command.trim())
374
+ return false;
375
+ const tokens = tokenizeCommand(command);
376
+ if (writesFile(tokens))
377
+ return false;
378
+ let inspected = false;
379
+ for (const segment of splitSegments(tokens)) {
380
+ const kind = classifySegment(segment);
381
+ if (kind === "mutate")
382
+ return false;
383
+ if (kind === "inspect")
384
+ inspected = true;
385
+ }
386
+ return inspected;
387
+ }
388
+ /**
389
+ * Does this tool call count as verification activity? The name set first, then
390
+ * bash by the command's shape. Every other tool is not verification.
391
+ */
392
+ export function isVerificationToolCall(toolName, input) {
393
+ if (VERIFICATION_TOOLS.has(toolName))
394
+ return true;
395
+ if (toolName !== "bash")
396
+ return false;
397
+ const command = input?.command;
398
+ return typeof command === "string" && bashCommandIsVerification(command);
399
+ }
28
400
  export function createDefaultPolicies(getToolTracking, onSignal, sendWhisper, sendSteerMessage) {
29
401
  return [
30
402
  {
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { Type } from "typebox";
15
15
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
+ import { type TurnBoundary } from "../../../../../lib/events/turn-boundary.js";
16
17
  /**
17
18
  * Read the pending queue without creating state (inspect surfaces it).
18
19
  * Exported so context_inspect and the heartbeat advisory can report
@@ -66,9 +67,14 @@ export declare function resolveAutoSlideKeep(branchLength: number): number;
66
67
  * settle, never mid-run.
67
68
  *
68
69
  * Called from the heartbeat tick — the only cadence that runs while a session
69
- * works. Returns what happened and why, so the caller can log it.
70
+ * works, and the only arm site that runs inside a turn boundary dispatch. It
71
+ * hands that boundary in, so the arm is judged by the same rule the drain
72
+ * applies: a "toolUse" boundary below the 0.90W backstop leaves the entry
73
+ * queued for the next loop-done boundary instead of aborting the request the
74
+ * loop is about to dispatch. Returns what happened and why, so the caller can
75
+ * log it.
70
76
  */
71
- export declare function maybeArmAutoCompaction(pi: ExtensionAPI, ctx: any): {
77
+ export declare function maybeArmAutoCompaction(pi: ExtensionAPI, ctx: any, boundary?: TurnBoundary): {
72
78
  armed: boolean;
73
79
  reason: string;
74
80
  };
@@ -19,6 +19,7 @@ import { analyzeSession } from "../../analysis.js";
19
19
  import * as timerMod from "../../../../scheduling/timer/index.js";
20
20
  import { getState } from "../../../../enforcement/state.js";
21
21
  import { CONTEXT_COMPACT_REFUSE_PERCENT } from "../../../../../lib/detection/context-thresholds.js";
22
+ import { turnBoundaryMayAbortRun, } from "../../../../../lib/events/turn-boundary.js";
22
23
  import { getCmState, isCompactionActive, log, recordNavigationAction } from "../shared.js";
23
24
  import { snapBoundaryOutsideToolBatch } from "../tool-batch-boundary.js";
24
25
  import { formatTokensK } from "../../../../../lib/detection/context-usage.js";
@@ -258,6 +259,19 @@ export const DEGRADED_DEFERRAL_MS = 150;
258
259
  export function scheduleDegradedCompact(trigger) {
259
260
  setTimeout(trigger, DEGRADED_DEFERRAL_MS);
260
261
  }
262
+ /**
263
+ * Whether an arm may fire its own entry. Firing a compact aborts whatever run
264
+ * is live, so an arm that happens inside a turn boundary dispatch hands that
265
+ * boundary in and is judged by the same rule the TURN_END handler applies
266
+ * (the rule lives in lib/events/turn-boundary.ts; it owns the "no boundary
267
+ * known" case, which fires). Every other arm site runs inside a tool call,
268
+ * where there is no boundary to read and the prior contract stands: the arm
269
+ * drains unless a batch is still active (the arm's own call id keeps it
270
+ * parked, so it does not fire there).
271
+ */
272
+ function armMayDrainNow(boundary, ctx) {
273
+ return turnBoundaryMayAbortRun(boundary, () => captureUsage(ctx));
274
+ }
261
275
  /**
262
276
  * Arm a one-shot compaction at a safe boundary (next turn end or run settle).
263
277
  * Returns "pending-exists" when an LLM-class compaction is already armed: the
@@ -271,7 +285,7 @@ export function scheduleDegradedCompact(trigger) {
271
285
  */
272
286
  function scheduleCompactionAtBatchSettle(pi, ctx, options, meta = {
273
287
  kind: "compact",
274
- }) {
288
+ }, boundary) {
275
289
  const trigger = () => {
276
290
  try {
277
291
  // Signal to session_compact handler that this is agent-initiated
@@ -301,7 +315,14 @@ function scheduleCompactionAtBatchSettle(pi, ctx, options, meta = {
301
315
  log.warn(`[context-compress] Pending queue overflow: dropped the newest armed ${dropped?.kind}` +
302
316
  ` (cap ${PENDING_COMPACT_QUEUE_MAX}); the first-armed entry still fires.`);
303
317
  }
304
- firePendingCompactionsIfSettled(ctx, st);
318
+ // Arming fires only where that is safe. Firing a compaction aborts whatever
319
+ // run is live, and an arm site is not in a position to tell: the tool path
320
+ // arms inside its own call (whose id parks the queue anyway), and the
321
+ // heartbeat's arm runs inside a turn_end dispatch, where whether the loop
322
+ // still has work to dispatch is a fact the event carries. That caller hands
323
+ // its boundary in; every other caller keeps the prior contract.
324
+ if (armMayDrainNow(boundary, ctx))
325
+ firePendingCompactionsIfSettled(ctx, st);
305
326
  return "queued";
306
327
  }
307
328
  catch {
@@ -326,7 +347,7 @@ function scheduleCompactionAtBatchSettle(pi, ctx, options, meta = {
326
347
  * trigger is queued for the next safe boundary. Returns null when the branch
327
348
  * is not longer than the keep window (nothing to slide).
328
349
  */
329
- function armSlideCompaction(pi, ctx, keepCount) {
350
+ function armSlideCompaction(pi, ctx, keepCount, boundary) {
330
351
  const sm = ctx.sessionManager;
331
352
  if (!sm || typeof sm.getBranch !== "function")
332
353
  return null;
@@ -374,7 +395,7 @@ function armSlideCompaction(pi, ctx, keepCount) {
374
395
  catch {
375
396
  // Non-fatal
376
397
  }
377
- scheduleCompactionAtBatchSettle(pi, ctx, { customInstructions: "SLIDE_MODE:true" }, { kind: "slide", cutEntryId });
398
+ scheduleCompactionAtBatchSettle(pi, ctx, { customInstructions: "SLIDE_MODE:true" }, { kind: "slide", cutEntryId }, boundary);
378
399
  return { cutEntryId, keptCount, droppedCount };
379
400
  }
380
401
  /**
@@ -401,9 +422,14 @@ function getAutoArmState(ctx) {
401
422
  * settle, never mid-run.
402
423
  *
403
424
  * Called from the heartbeat tick — the only cadence that runs while a session
404
- * works. Returns what happened and why, so the caller can log it.
425
+ * works, and the only arm site that runs inside a turn boundary dispatch. It
426
+ * hands that boundary in, so the arm is judged by the same rule the drain
427
+ * applies: a "toolUse" boundary below the 0.90W backstop leaves the entry
428
+ * queued for the next loop-done boundary instead of aborting the request the
429
+ * loop is about to dispatch. Returns what happened and why, so the caller can
430
+ * log it.
405
431
  */
406
- export function maybeArmAutoCompaction(pi, ctx) {
432
+ export function maybeArmAutoCompaction(pi, ctx, boundary) {
407
433
  const config = getAutoCompactConfig();
408
434
  if (!config.enabled)
409
435
  return { armed: false, reason: "disabled" };
@@ -426,7 +452,7 @@ export function maybeArmAutoCompaction(pi, ctx) {
426
452
  }
427
453
  const branchLength = ctx?.sessionManager?.getBranch?.().length ?? 0;
428
454
  const keep = resolveAutoSlideKeep(branchLength);
429
- const armed = armSlideCompaction(pi, ctx, keep);
455
+ const armed = armSlideCompaction(pi, ctx, keep, boundary);
430
456
  st.aboveCount = 0;
431
457
  if (!armed)
432
458
  return { armed: false, reason: "branch-too-short" };
@@ -488,10 +514,10 @@ export const contextCompressSchema = Type.Object({
488
514
  export function registerContextCompress(pi) {
489
515
  // Batch-settle scheduling: track the ACTIVE tool calls of every running
490
516
  // batch by call id and fire the deferred compaction only at a safe boundary
491
- // (turn_end or agent_settled). Never mid-batch (would drop a parallel
492
- // sibling's result) and never at tool_execution_end (the run is still live
493
- // there — an aborting compact would surface a spurious "This operation was
494
- // aborted" error and tear the finishing turn).
517
+ // (a loop-done turn_end or agent_settled). Never mid-batch (would drop a
518
+ // parallel sibling's result) and never at tool_execution_end (the run is
519
+ // still live there — an aborting compact would surface a spurious "This
520
+ // operation was aborted" error and tear the finishing turn).
495
521
  onEvent(pi, TOOL_EXECUTION_START, (event, ctx) => {
496
522
  try {
497
523
  const st = getBatchSettleState(ctx);
@@ -521,17 +547,22 @@ export function registerContextCompress(pi) {
521
547
  }
522
548
  });
523
549
  onEvent(pi, TURN_END, (event, ctx) => {
524
- // Between-turns boundary: the turn's assistant message and tool results
525
- // are already persisted when turn_end fires, so the abort inside
526
- // ctx.compact() cannot tear a live turn or drop a sibling result. The
527
- // persisted results carry the toolCallIds of the calls they answer, which
528
- // releases a call whose tool_execution_end never arrived; an active id
529
- // with NO result in this event is kept (it may still be executing, and a
530
- // count could not tell which sibling completed). A run kept alive by
550
+ // Turn boundary. The turn's assistant message and tool results are already
551
+ // persisted here, but that alone does not make the run safe to abort: a
552
+ // "toolUse" stop means the loop dispatches its next request the moment the
553
+ // handlers return, so the deferred ctx.compact() tears that request
554
+ // mid-stream and the compaction replaces the work it was about to do (the
555
+ // rule is lib/events/turn-boundary.ts, and its residual section lists the
556
+ // two cases a loop-done stop reason does not rule out). Only a loop-done
557
+ // boundary drains, except at the 0.90W hard backstop, which exists
558
+ // precisely to stop a runaway live loop before it overflows.
559
+ //
560
+ // The persisted results carry the toolCallIds of the calls they answer,
561
+ // which releases a call whose tool_execution_end never arrived; an active
562
+ // id with NO result in this event is kept (it may still be executing, and
563
+ // a count could not tell which sibling completed). A run kept alive by
531
564
  // continuous steers never reaches agent_settled — this boundary keeps an
532
- // armed compaction from stalling behind live work. A steer queued at this
533
- // moment survives: the loop appends it before the aborted response stream,
534
- // and its turn runs on the post-compaction resume. Ids are never blanket-
565
+ // armed compaction from stalling behind live work. Ids are never blanket-
535
566
  // reset here (only agent_settled owns that backstop, which is what keeps a
536
567
  // missed end event from parking the queue forever).
537
568
  try {
@@ -541,6 +572,8 @@ export function registerContextCompress(pi) {
541
572
  return;
542
573
  if (isCompactionActive(ctx))
543
574
  return;
575
+ if (!turnBoundaryMayAbortRun(event, () => captureUsage(ctx)))
576
+ return;
544
577
  firePendingCompactionsIfSettled(ctx, st);
545
578
  }
546
579
  catch {
@@ -55,6 +55,10 @@ export declare function checkpointDir(): string;
55
55
  export declare function errorDir(): string;
56
56
  /** Scratchpad root (one dir per project slug), resolved on every call. */
57
57
  export declare function scratchpadDir(): string;
58
+ /** Journal root (one dir per project slug), resolved on every call. Durable
59
+ * write state: the append-only record of what a seat decided, which a
60
+ * replacement seat reads before acting, so BRAID_HOME pinning must move it. */
61
+ export declare function journalDir(): string;
58
62
  /** Healthcheck scratch and report root, resolved on every call. Durable-write
59
63
  * state: the probes and the saved report must follow a pinned BRAID_HOME. */
60
64
  export declare function healthcheckDir(): string;
@@ -140,6 +144,16 @@ export declare const BRAID_CONFIG_FILE: string;
140
144
  * scratchpad/sessions convention), which matched nothing the writer ever
141
145
  * wrote and silently muted the `tags_prior` signal. */
142
146
  export declare function tagsSlugFromCwd(cwd?: string): string;
147
+ /**
148
+ * Append-only journal file for one project: `<journal root>/<slug>/journal.jsonl`.
149
+ *
150
+ * The slug is the scratchpad's `projectSlugFromCwd` form, passed in rather than
151
+ * re-derived here: the writer, the checker and the session-start pointer must
152
+ * name ONE file, and a second slug rule is how the tag file split into a writer
153
+ * and a reader that could never meet (see tagsSlugFromCwd). Resolved on every
154
+ * call, so a pinned BRAID_HOME writes and reads its own journal.
155
+ */
156
+ export declare function journalFilePath(projectSlug: string): string;
143
157
  /**
144
158
  * Get the lossless flush file path for one offloaded tool result.
145
159
  * Layout: <offload dir>/<sessionId>/<toolName>-<toolCallId>.txt.
@@ -107,6 +107,12 @@ export function errorDir() {
107
107
  export function scratchpadDir() {
108
108
  return path.join(braidDir(), "scratchpads");
109
109
  }
110
+ /** Journal root (one dir per project slug), resolved on every call. Durable
111
+ * write state: the append-only record of what a seat decided, which a
112
+ * replacement seat reads before acting, so BRAID_HOME pinning must move it. */
113
+ export function journalDir() {
114
+ return path.join(braidDir(), "journal");
115
+ }
110
116
  /** Healthcheck scratch and report root, resolved on every call. Durable-write
111
117
  * state: the probes and the saved report must follow a pinned BRAID_HOME. */
112
118
  export function healthcheckDir() {
@@ -257,6 +263,18 @@ export function tagsSlugFromCwd(cwd) {
257
263
  return "default";
258
264
  return cwd.split("/").filter(Boolean).join("-") || "default";
259
265
  }
266
+ /**
267
+ * Append-only journal file for one project: `<journal root>/<slug>/journal.jsonl`.
268
+ *
269
+ * The slug is the scratchpad's `projectSlugFromCwd` form, passed in rather than
270
+ * re-derived here: the writer, the checker and the session-start pointer must
271
+ * name ONE file, and a second slug rule is how the tag file split into a writer
272
+ * and a reader that could never meet (see tagsSlugFromCwd). Resolved on every
273
+ * call, so a pinned BRAID_HOME writes and reads its own journal.
274
+ */
275
+ export function journalFilePath(projectSlug) {
276
+ return path.join(journalDir(), projectSlug, "journal.jsonl");
277
+ }
260
278
  /**
261
279
  * Get the lossless flush file path for one offloaded tool result.
262
280
  * Layout: <offload dir>/<sessionId>/<toolName>-<toolCallId>.txt.
@@ -148,6 +148,27 @@ export declare function resolveMemoryWriteGateConfig(raw?: RawWriteGateBlock): M
148
148
  */
149
149
  export declare const DEFAULT_TIME_ZONE = "Europe/Moscow";
150
150
  export declare function getOwnerTimeZone(): string;
151
+ /**
152
+ * Which tier may answer the `list_skills` relevance ranking.
153
+ *
154
+ * keyword — the deterministic scorer answers (the only implemented value;
155
+ * the default).
156
+ * auto — reserved: the policy wrote down for a model tier that would
157
+ * answer only on an ambiguous deterministic verdict. Measured and
158
+ * not kept, so it currently evaluates to the keyword path.
159
+ * model — reserved: the model answers whenever a task text exists. Same
160
+ * status as "auto".
161
+ */
162
+ export type SkillsRankingMode = "auto" | "keyword" | "model";
163
+ export declare const SKILLS_RANKING_DEFAULT: SkillsRankingMode;
164
+ /**
165
+ * Resolve the ranking mode from a raw setting value. Unknown or malformed
166
+ * values fall back to the default rather than guessing: a typo must not turn a
167
+ * cheap catalog read into anything else. Pure.
168
+ */
169
+ export declare function resolveSkillsRankingMode(raw: unknown): SkillsRankingMode;
170
+ /** Read braid.skills.ranking from settings.json (default: "keyword"). */
171
+ export declare function getSkillsRankingMode(): SkillsRankingMode;
151
172
  /**
152
173
  * Sane defaults for the optional staleToolResultOffload params (defined next
153
174
  * to the schema per the design contract). Investigation suggests a size
@@ -197,6 +197,22 @@ export function getOwnerTimeZone() {
197
197
  const tz = settings.braid?.timezone;
198
198
  return typeof tz === "string" && tz.trim() ? tz.trim() : DEFAULT_TIME_ZONE;
199
199
  }
200
+ export const SKILLS_RANKING_DEFAULT = "keyword";
201
+ /**
202
+ * Resolve the ranking mode from a raw setting value. Unknown or malformed
203
+ * values fall back to the default rather than guessing: a typo must not turn a
204
+ * cheap catalog read into anything else. Pure.
205
+ */
206
+ export function resolveSkillsRankingMode(raw) {
207
+ const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
208
+ return value === "keyword" || value === "model" || value === "auto"
209
+ ? value
210
+ : SKILLS_RANKING_DEFAULT;
211
+ }
212
+ /** Read braid.skills.ranking from settings.json (default: "keyword"). */
213
+ export function getSkillsRankingMode() {
214
+ return resolveSkillsRankingMode(readSettings().braid?.skills?.ranking);
215
+ }
200
216
  // ── stale toolResult offload (braid.context.staleToolResultOffload) ────
201
217
  /**
202
218
  * Sane defaults for the optional staleToolResultOffload params (defined next