pi-braid 0.40.1 → 0.40.3

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 (105) hide show
  1. package/CONTRIBUTING.md +27 -3
  2. package/README.md +13 -13
  3. package/TOOLS.md +27 -3
  4. package/build-info.json +9 -0
  5. package/dist/extensions/cognitive/metacognition/handlers/claim-verification.js +7 -1
  6. package/dist/extensions/cognitive/metacognition/handlers/finalize.js +20 -0
  7. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.d.ts +9 -0
  8. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.js +13 -1
  9. package/dist/extensions/cognitive/metacognition/handlers/verify.js +35 -4
  10. package/dist/extensions/cognitive/topic-drift/index.js +19 -2
  11. package/dist/extensions/core/prompt-builder/inspect.js +9 -3
  12. package/dist/extensions/core/prompt-builder/top-level-extensions.d.ts +6 -5
  13. package/dist/extensions/core/prompt-builder/top-level-extensions.js +64 -29
  14. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.d.ts +1 -1
  15. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.js +1 -1
  16. package/dist/extensions/enforcement/handlers/turn-end-handler.js +1 -1
  17. package/dist/extensions/enforcement/self-state-claims.d.ts +1 -1
  18. package/dist/extensions/enforcement/self-state-claims.js +3 -2
  19. package/dist/extensions/manifest.js +2 -2
  20. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.d.ts +22 -5
  21. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.js +43 -11
  22. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +174 -50
  23. package/dist/extensions/memory/context-manager/handlers/tools/context-inspect.js +7 -1
  24. package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.js +4 -1
  25. package/dist/extensions/memory/memory-agent-bridge/explore-paths.d.ts +2 -24
  26. package/dist/extensions/memory/memory-agent-bridge/explore-paths.js +33 -2
  27. package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.js +16 -0
  28. package/dist/extensions/memory/memory-agent-bridge/memory-tool.js +21 -9
  29. package/dist/extensions/memory/scratchpad/format.js +8 -2
  30. package/dist/extensions/memory/scratchpad/index.js +11 -2
  31. package/dist/extensions/memory/session-recall/index.js +19 -6
  32. package/dist/extensions/memory/three-memory-stores/episodes.d.ts +1 -1
  33. package/dist/extensions/memory/three-memory-stores/episodes.js +2 -2
  34. package/dist/extensions/orchestrator/index.js +73 -8
  35. package/dist/extensions/scheduling/timer/index.js +9 -1
  36. package/dist/extensions/self/error-tracking/index.js +8 -1
  37. package/dist/extensions/self/health-maintenance/handlers/session-health-tool.js +9 -2
  38. package/dist/extensions/self/health-maintenance/index.js +112 -9
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +36 -0
  41. package/dist/lib/constants/session-thresholds.d.ts +2 -3
  42. package/dist/lib/constants/session-thresholds.js +2 -3
  43. package/dist/lib/enforcement/turn-dedup.d.ts +2 -2
  44. package/dist/lib/enforcement/turn-dedup.js +2 -2
  45. package/dist/lib/harness/index.d.ts +1 -1
  46. package/dist/lib/harness/index.js +1 -1
  47. package/dist/lib/harness/types.d.ts +1 -1
  48. package/dist/lib/harness/types.js +1 -1
  49. package/dist/lib/orchestrator/index.d.ts +2 -2
  50. package/dist/lib/orchestrator/index.js +1 -1
  51. package/dist/lib/orchestrator/workers.d.ts +184 -2
  52. package/dist/lib/orchestrator/workers.js +521 -6
  53. package/dist/lib/utils/injection-tracker.js +1 -1
  54. package/docs/CONTEXT-POLICY.md +13 -5
  55. package/docs/LOCAL_DEV.md +31 -5
  56. package/docs/ROADMAP.md +10 -7
  57. package/docs/SETUP.md +3 -2
  58. package/package.json +11 -8
  59. package/skills/braid-reference/SKILL.md +23 -23
  60. package/skills/release-pipeline/SKILL.md +46 -37
  61. package/skills/subagent-orchestration/SKILL.md +51 -1
  62. package/src/extensions/cognitive/metacognition/handlers/claim-verification.ts +8 -1
  63. package/src/extensions/cognitive/metacognition/handlers/finalize.ts +21 -0
  64. package/src/extensions/cognitive/metacognition/handlers/hypothesize.ts +14 -1
  65. package/src/extensions/cognitive/metacognition/handlers/verify.ts +39 -5
  66. package/src/extensions/cognitive/topic-drift/index.ts +20 -2
  67. package/src/extensions/core/prompt-builder/AGENTS.md +1 -1
  68. package/src/extensions/core/prompt-builder/inspect.ts +10 -3
  69. package/src/extensions/core/prompt-builder/top-level-extensions.ts +68 -29
  70. package/src/extensions/enforcement/AGENTS.md +25 -19
  71. package/src/extensions/enforcement/handlers/register-tool-result-formatting.ts +1 -1
  72. package/src/extensions/enforcement/handlers/turn-end-handler.ts +1 -1
  73. package/src/extensions/enforcement/self-state-claims.ts +3 -2
  74. package/src/extensions/heartbeat/heartbeat-scheduler/AGENTS.md +6 -3
  75. package/src/extensions/manifest.ts +2 -2
  76. package/src/extensions/memory/AGENTS.md +13 -5
  77. package/src/extensions/memory/context-manager/handlers/tool-batch-boundary.ts +45 -11
  78. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +202 -60
  79. package/src/extensions/memory/context-manager/handlers/tools/context-inspect.ts +8 -1
  80. package/src/extensions/memory/context-manager/handlers/tools/context-navigate.ts +4 -1
  81. package/src/extensions/memory/memory-agent-bridge/explore-paths.ts +37 -3
  82. package/src/extensions/memory/memory-agent-bridge/memory-store-tool.ts +16 -0
  83. package/src/extensions/memory/memory-agent-bridge/memory-tool.ts +22 -9
  84. package/src/extensions/memory/scratchpad/format.ts +8 -2
  85. package/src/extensions/memory/scratchpad/index.ts +12 -2
  86. package/src/extensions/memory/session-recall/index.ts +20 -8
  87. package/src/extensions/memory/three-memory-stores/episodes.ts +2 -2
  88. package/src/extensions/orchestrator/index.ts +100 -11
  89. package/src/extensions/scheduling/timer/AGENTS.md +7 -0
  90. package/src/extensions/scheduling/timer/index.ts +10 -1
  91. package/src/extensions/self/error-tracking/index.ts +9 -1
  92. package/src/extensions/self/health-maintenance/handlers/session-health-tool.ts +10 -2
  93. package/src/extensions/self/health-maintenance/index.ts +143 -14
  94. package/src/extensions/self/watchdog/AGENTS.md +1 -0
  95. package/src/lib/AGENTS.md +21 -21
  96. package/src/lib/config/braid-settings.ts +74 -0
  97. package/src/lib/constants/session-thresholds.ts +2 -3
  98. package/src/lib/enforcement/turn-dedup.ts +2 -2
  99. package/src/lib/harness/AGENTS.md +1 -1
  100. package/src/lib/harness/index.ts +1 -1
  101. package/src/lib/harness/types.ts +1 -1
  102. package/src/lib/orchestrator/index.ts +26 -0
  103. package/src/lib/orchestrator/workers.ts +705 -7
  104. package/src/lib/utils/AGENTS.md +1 -1
  105. package/src/lib/utils/injection-tracker.ts +1 -1
@@ -30,7 +30,7 @@ const inspectSchema = Type.Object({
30
30
  truncate: Type.Optional(
31
31
  Type.Number({
32
32
  description:
33
- "Max characters (0 = no limit, default 5000); applied after tool/skill exclusion.",
33
+ "Max characters before truncation (default 5000); applied after tool/skill exclusion. A blank or non-positive value applies the default.",
34
34
  default: 5000,
35
35
  }),
36
36
  ),
@@ -122,7 +122,14 @@ export function createPromptInspectTool() {
122
122
  ): Promise<any> => {
123
123
  const showTools = params.includeTools ?? true;
124
124
  const showSkills = params.includeSkills ?? true;
125
- const maxLen = params.truncate ?? 5000;
125
+ // Argument validation converts a blank truncate to 0, and the
126
+ // description used to define 0 as "no limit" - so a blank flipped the
127
+ // tool into dumping the whole assembled prompt. A deliberate 0 is
128
+ // indistinguishable from a blank after conversion, so the documented
129
+ // default wins and the old no-limit mode is no longer reachable through
130
+ // this selector (use `match` to read the full prompt).
131
+ const maxLen =
132
+ typeof params.truncate === "number" && params.truncate > 0 ? params.truncate : 5000;
126
133
 
127
134
  if (!ctx) {
128
135
  return {
@@ -202,7 +209,7 @@ export function createPromptInspectTool() {
202
209
  }
203
210
  } else {
204
211
  // Apply truncation only when no match filter is active
205
- if (maxLen > 0 && body.length > maxLen) {
212
+ if (body.length > maxLen) {
206
213
  didTruncate = true;
207
214
  body =
208
215
  body.slice(0, maxLen - 80) +
@@ -4,9 +4,10 @@
4
4
  * Discovers pi extension PACKAGES (package.json with a `pi` field)
5
5
  * from the settings `packages` field — never a walk over cwd/siblings.
6
6
  * Sources in pi-core precedence: project (<cwd>/.pi/settings.json)
7
- * then user (~/.pi/agent/settings.json); project scope wins for the
8
- * same identity. Entries: absolute local path, `npm:` (via `npm root
9
- * -g`), or `git:` (best-effort skip), tagged project / user-global.
7
+ * then user (<agentDir>/settings.json); project scope wins for the
8
+ * same identity. Entries: absolute local path, `npm:` (pi's managed
9
+ * install tree first, then the global npm root), or `git:`
10
+ * (best-effort skip), tagged project / user-global.
10
11
  * Best-effort: unreadable or missing packages are silently skipped —
11
12
  * no "failed to resolve" noise in the prompt.
12
13
  */
@@ -137,8 +138,9 @@ function basename(p: string): string {
137
138
  * source is unsupported or cannot be located on disk.
138
139
  *
139
140
  * Supported shapes:
140
- * - `npm:<spec>` (e.g. `npm:pi-web-access`) -- looks in the global
141
- * npm root (`npm root -g`), under each scoped directory.
141
+ * - `npm:<spec>` (e.g. `npm:pi-web-access`) -- looks in pi's
142
+ * managed install tree, then the global npm root, under each
143
+ * scoped directory.
142
144
  * - absolute local path (starts with `/`) -- used as-is.
143
145
  * - relative local path -- resolved relative to `cwd`.
144
146
  */
@@ -150,7 +152,7 @@ function resolveEntryToPackage(
150
152
  const trimmed = source.trim();
151
153
  if (!trimmed) return null;
152
154
 
153
- // npm:<spec> -- find in global node_modules.
155
+ // npm:<spec> -- find in the managed install tree, then global node_modules.
154
156
  if (trimmed.startsWith("npm:")) {
155
157
  const spec = trimmed.slice("npm:".length).trim();
156
158
  const at = spec.lastIndexOf("@");
@@ -195,34 +197,73 @@ function expandHome(p: string): string {
195
197
  }
196
198
 
197
199
  /**
198
- * Locate a globally-installed npm package by name. Walks the
199
- * scope directories under the global npm root (`npm root -g`).
200
- * Optional `version` filters to a directory whose `package.json`
201
- * version matches; if absent, the first matching directory wins.
200
+ * Resolve pi's agent directory. `PI_CODING_AGENT_DIR` relocates the whole
201
+ * agent home when set and non-empty; otherwise the default is `~/.pi/agent`.
202
+ * Both the user-global settings file and the managed npm install tree live
203
+ * under this one directory, so they are resolved from this one function.
204
+ */
205
+ function resolveAgentDir(): string {
206
+ const override = process.env.PI_CODING_AGENT_DIR?.trim();
207
+ if (override) return expandHome(override);
208
+ return join(process.env.HOME ?? "~", ".pi", "agent");
209
+ }
210
+
211
+ /**
212
+ * Locate an installed npm package by name, searching pi's managed install
213
+ * tree before the global npm root. Managed first because that is where pi
214
+ * installs a settings-declared `npm:` entry (`<agentDir>/npm/node_modules`)
215
+ * and it consults a legacy global install only when the managed copy is
216
+ * absent -- so the managed copy is the one pi actually loads. The global
217
+ * root stays as that same fallback, for packages installed by hand.
202
218
  *
203
- * Returns the absolute directory path, or null if not found.
219
+ * Optional `version` filters to a directory whose `package.json` version
220
+ * matches; if absent, the first matching directory wins. Returns the
221
+ * absolute directory path, or null if not found in any root.
204
222
  */
205
223
  function findNpmPackageDir(name: string, version: string | undefined): string | null {
224
+ for (const root of getNpmSearchRoots()) {
225
+ const dir = findPackageInNpmRoot(root, name, version);
226
+ if (dir) return dir;
227
+ }
228
+ return null;
229
+ }
230
+
231
+ /** The npm roots searched for an `npm:` entry, in precedence order. */
232
+ function getNpmSearchRoots(): string[] {
233
+ const roots = [join(resolveAgentDir(), "npm", "node_modules")];
206
234
  const globalRoot = getGlobalNpmRoot();
207
- if (!globalRoot) return null;
208
- if (!existsSync(globalRoot)) return null;
235
+ if (globalRoot) roots.push(globalRoot);
236
+ return roots;
237
+ }
238
+
239
+ /**
240
+ * Find the package directory for `name` inside one npm root.
241
+ *
242
+ * Scoped package: @scope/name -> look directly under `<root>/@scope/name`.
243
+ * Unscoped: scan the root's own directories for a package.json whose `name`
244
+ * matches -- npm installs both flat and nested layouts. A directory with no
245
+ * readable package.json is skipped, never fatal.
246
+ */
247
+ function findPackageInNpmRoot(
248
+ root: string,
249
+ name: string,
250
+ version: string | undefined,
251
+ ): string | null {
252
+ if (!existsSync(root)) return null;
209
253
 
210
- // Scoped package: @scope/name -> look under globalRoot/@scope/name.
211
254
  if (name.startsWith("@")) {
212
- const dir = join(globalRoot, name);
255
+ const dir = join(root, name);
213
256
  return packageDirMatches(dir, version) ? dir : null;
214
257
  }
215
258
 
216
- // Unscoped: scan globalRoot itself for a directory whose
217
- // package.json `name` matches. npm installs both flat and nested layouts.
218
259
  let entries: string[];
219
260
  try {
220
- entries = readdirSync(globalRoot);
261
+ entries = readdirSync(root);
221
262
  } catch {
222
263
  return null;
223
264
  }
224
265
  for (const entry of entries) {
225
- const dir = join(globalRoot, entry);
266
+ const dir = join(root, entry);
226
267
  let isDir: boolean;
227
268
  try {
228
269
  isDir = statSync(dir).isDirectory();
@@ -259,10 +300,11 @@ function packageDirMatches(dir: string, expectedVersion?: string, expectedName?:
259
300
 
260
301
  /**
261
302
  * Resolve the global npm root via `npm root -g`. Returns null if
262
- * the command fails or produces no output. Cached after first
263
- * successful call so the (slow) `npm root -g` invocation runs at
264
- * most once per process -- the value never changes inside one
265
- * pi session.
303
+ * the command fails or produces no output. This is the fallback root
304
+ * only -- pi's managed install tree is searched first (see
305
+ * `findNpmPackageDir`). Cached after first successful call so the
306
+ * (slow) `npm root -g` invocation runs at most once per process --
307
+ * the value never changes inside one pi session.
266
308
  *
267
309
  * Implemented as an IIFE-wrapped closure so the cache `let`
268
310
  * stays function-scoped (the project's no-module-level-let
@@ -297,8 +339,8 @@ const getGlobalNpmRoot = ((): (() => string | null) => {
297
339
  *
298
340
  * Settings-file paths:
299
341
  * - project: `<cwd>/.pi/settings.json`
300
- * - user-global: read from `PI_CODING_AGENT_DIR` env override,
301
- * falling back to `~/.pi/agent/settings.json`.
342
+ * - user-global: `<agentDir>/settings.json`, where the agent dir is
343
+ * `PI_CODING_AGENT_DIR` when set, else `~/.pi/agent`.
302
344
  */
303
345
  export function discoverTopLevelExtensions(
304
346
  cwd: string = process.cwd(),
@@ -308,10 +350,7 @@ export function discoverTopLevelExtensions(
308
350
  },
309
351
  ): TopLevelExtension[] {
310
352
  const projectPath = options?.projectSettingsPath ?? join(cwd, ".pi", "settings.json");
311
- const userPath =
312
- options?.userSettingsPath ??
313
- process.env.PI_CODING_AGENT_DIR ??
314
- join(process.env.HOME ?? "~", ".pi", "agent", "settings.json");
353
+ const userPath = options?.userSettingsPath ?? join(resolveAgentDir(), "settings.json");
315
354
 
316
355
  const seen = new Set<string>();
317
356
  const out: ResolvedPackage[] = [];
@@ -8,25 +8,25 @@ the wake-up policy.
8
8
 
9
9
  ## Files at this level
10
10
 
11
- | File | Purpose |
12
- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
13
- | `state.ts` | Composed session-scoped state. Re-exports `ENFORCEMENT_PARAMS` and `EnforcementState` from `enforcement-types.ts`. |
14
- | `enforcement-types.ts` | The shared `ENFORCEMENT_PARAMS` and `EnforcementState` definitions. **Lives outside `state.ts` to break the circular dep** that would otherwise form between `state.ts <-> session-state.ts <-> verification-judge-state.ts`. |
15
- | `session-state.ts` | Per-turn tracking, config, topic-drift detector. |
16
- | `whisper.ts` | The `sendTrackedMessage` wrapper with the whisper cap and metadata. |
17
- | `judge-utils.ts` | Helpers for the verification judge. |
18
- | `signals.ts` | The signal taxonomy (severity, source, priority). |
19
- | `validation.ts` | Validation of whisper payloads. |
20
- | `similarity.ts` | Cosine similarity for dedup. |
21
- | `nudge-manager.ts` | Manages nudge cooldowns and dedup. |
22
- | `verification-judge.ts` | The verification judge - runs in background. |
23
- | `self-state-claims.ts` | Deterministic self-state claim detector for the judge: scans the visible response for liveness/delivery/progress claims, suppresses them when the evidence window shows a probe call (session_health, health_maintenance, v2raytun_status, telegram_send); renders the judge's SELF-STATE CLAIMS section only when candidates survive (prompt byte-unchanged otherwise). |
24
- | `task-evidence.ts` | Task-wide evidence lines (since last real user message) rebuilt from the pi session store for the judge prompt; survives turn breaks (wake-retry redelivery). Logs over the cap are compacted into LLM chunk summaries (newest chunk raw), with drop-oldest truncation as the fallback. |
25
- | `verification-judge-state.ts` | Judge/calibration helpers. |
26
- | `handler-registry.ts` | Thin orchestrator that wires all handlers. |
27
- | `register-tool-result-formatting.ts` | MI-3 Structured Output Catalyst - wraps read/grep/find/ls outputs in structured header format (opt-in). |
28
- | `event-types.ts` | Types for events that flow through the enforcement layer. |
29
- | `*-state.ts` | Sub-state files (tool-tracking, error-tracking, memory-hygiene, context-hygiene, scratchpad, thought-chain). Each owns its slice of the composed state. |
11
+ | File | Purpose |
12
+ | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
13
+ | `state.ts` | Composed session-scoped state. Re-exports `ENFORCEMENT_PARAMS` and `EnforcementState` from `enforcement-types.ts`. |
14
+ | `enforcement-types.ts` | The shared `ENFORCEMENT_PARAMS` and `EnforcementState` definitions. **Lives outside `state.ts` to break the circular dep** that would otherwise form between `state.ts <-> session-state.ts <-> verification-judge-state.ts`. |
15
+ | `session-state.ts` | Per-turn tracking, config, topic-drift detector. |
16
+ | `whisper.ts` | The `sendTrackedMessage` wrapper with the whisper cap and metadata. |
17
+ | `judge-utils.ts` | Helpers for the verification judge. |
18
+ | `signals.ts` | The signal taxonomy (severity, source, priority). |
19
+ | `validation.ts` | Validation of whisper payloads. |
20
+ | `similarity.ts` | Cosine similarity for dedup. |
21
+ | `nudge-manager.ts` | Manages nudge cooldowns and dedup. |
22
+ | `verification-judge.ts` | The verification judge - runs in background. |
23
+ | `self-state-claims.ts` | Deterministic self-state claim detector for the judge: scans the visible response for liveness/delivery/progress claims, suppresses them when the evidence window shows a probe call (session_health, health_maintenance, tunnel_status, v2raytun_status, telegram_send); renders the judge's SELF-STATE CLAIMS section only when candidates survive (prompt byte-unchanged otherwise). |
24
+ | `task-evidence.ts` | Task-wide evidence lines (since last real user message) rebuilt from the pi session store for the judge prompt; survives turn breaks (wake-retry redelivery). Logs over the cap are compacted into LLM chunk summaries (newest chunk raw), with drop-oldest truncation as the fallback. |
25
+ | `verification-judge-state.ts` | Judge/calibration helpers. |
26
+ | `handler-registry.ts` | Thin orchestrator that wires all handlers. |
27
+ | `register-tool-result-formatting.ts` | Structured Output Catalyst - wraps read/grep/find/ls outputs in structured header format (opt-in). |
28
+ | `event-types.ts` | Types for events that flow through the enforcement layer. |
29
+ | `*-state.ts` | Sub-state files (tool-tracking, error-tracking, memory-hygiene, context-hygiene, scratchpad, thought-chain). Each owns its slice of the composed state. |
30
30
 
31
31
  ## Sub-directories
32
32
 
@@ -67,3 +67,9 @@ allow sub-state modules to be tested in isolation.
67
67
  for the agent's natural flow.
68
68
 
69
69
  See individual handler files in `handlers/` for the per-source policy.
70
+
71
+ ## Over-correction gate setting
72
+
73
+ | Setting | Default | Effect | Read cadence |
74
+ | ------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
75
+ | `braid.enforcement.overCorrectionGate.mode` | `"off"` | `off` leaves the gate inert; `shadow` logs and whispers without blocking; `on` blocks destructive `bash` and `write` calls while a recent accusation or hot acceptance signal is active. | Re-read at use time on each checked tool call. |
@@ -1,5 +1,5 @@
1
1
  /**
2
- * register-tool-result-formatting — Structured Output Catalyst (MI-3)
2
+ * register-tool-result-formatting — Structured Output Catalyst
3
3
  *
4
4
  * Wraps tool outputs for read/grep/find/ls in a consistent structured format
5
5
  * to improve transformer processing. Uses the tool_result event's middleware
@@ -193,7 +193,7 @@ export async function dispatchTurnEndLoop(
193
193
  const memoryUpdated = actualTools.some((t: string) => ["memory_store", "memory"].includes(t));
194
194
 
195
195
  // Truth-seeking trigger: verify_claim/conflict_qa usage
196
- // MI-2: When the agent uses verification tools, briefly surface TRUTH-SEEKING
196
+ // When the agent uses verification tools, briefly surface TRUTH-SEEKING
197
197
  // mode explicitly, confirming the correct epistemic stance.
198
198
  const truthTools = actualTools.filter((t: string) => ["verify_claim", "conflict_qa"].includes(t));
199
199
  if (truthTools.length > 0) {
@@ -29,6 +29,7 @@
29
29
  export const SELF_STATE_PROBE_TOOLS = [
30
30
  "session_health",
31
31
  "health_maintenance",
32
+ "tunnel_status",
32
33
  "v2raytun_status",
33
34
  "telegram_send",
34
35
  ] as const;
@@ -109,7 +110,7 @@ const NEGATION_HEDGE =
109
110
 
110
111
  /** Probe-tool names that, named in the claim clause itself, exempt it: citing the check ("I ran session_health: healthy") is probe awareness, not an ungrounded assertion. */
111
112
  const PROBE_NAME =
112
- /(?:session_health|health_maintenance|v2raytun_status|telegram_send|telegram_poller)/i;
113
+ /(?:session_health|health_maintenance|tunnel_status|v2raytun_status|telegram_send|telegram_poller)/i;
113
114
 
114
115
  /** Scan input: a subset of JudgeContext fields. */
115
116
  export interface SelfStateScanInput {
@@ -197,7 +198,7 @@ export function renderSelfStateClaimsSection(claims: SelfStateClaim[]): string {
197
198
  }
198
199
  lines.push(
199
200
  "",
200
- "These claims cannot be verified by build or test evidence: they need a decisive in-session probe call (session_health, health_maintenance, v2raytun_status, telegram_send), and the evidence window above shows none.",
201
+ "These claims cannot be verified by build or test evidence: they need a decisive in-session probe call (session_health, health_maintenance, tunnel_status, v2raytun_status, telegram_send), and the evidence window above shows none.",
201
202
  'Rule: flag each listed claim as an issue (category "claim") unless TASK EVIDENCE, TOOL EXECUTION LOG, or chunk summaries above show a probe call supporting it. Hedged or negative self-state ("poller not running", "reachability unverified") is honest and must NOT be flagged.',
202
203
  );
203
204
  return lines.join("\n");
@@ -73,9 +73,12 @@ per-source caps are enforced in `injection-tracker.ts`.
73
73
 
74
74
  - **Process-global**: state is per-session (via `getExtensionState(ctx, key, factory)`).
75
75
  The poller does not run when no session is active (gated by `SessionPhase`).
76
- - **Opt-in**: enable via `BRAID_MODULES=+heartbeat`. Off by default in
77
- core (timer) to avoid surprising users; on by default in
78
- `all,-heartbeat-scheduler` config.
76
+ - **Default-on**: the manifest entry carries no `disabledByDefault`, so the
77
+ scheduler loads like every other default extension. Turn it off per
78
+ extension (`braid.modules["heartbeat-scheduler"]: false`, or
79
+ `/modules-disable heartbeat-scheduler`) or by its module group
80
+ (`/modules-disable heartbeat`, which also covers `analytics`); the
81
+ in-process toggle changes the current session's set without a restart.
79
82
  - **First-tick timing**: the first heartbeat fires 5 turns after
80
83
  session_start, not on session_start itself. This avoids racing
81
84
  with the user's first message.
@@ -159,7 +159,7 @@ export const MANIFEST: ManifestEntry[] = [
159
159
  id: "session-recall",
160
160
  fn: sessionRecallFn,
161
161
  dependencies: ["three-memory-stores"],
162
- desc: "Session recall tools (session_search, session_query)",
162
+ desc: "Session recall tool (session)",
163
163
  module: "memory",
164
164
  },
165
165
  {
@@ -259,7 +259,7 @@ export const MANIFEST: ManifestEntry[] = [
259
259
  fn: errorCaptureFn,
260
260
  disabledByDefault: true,
261
261
  dependencies: ["agent-environment"],
262
- desc: "Error logging tools: error_list, error_get",
262
+ desc: "Error logging tool (error)",
263
263
  },
264
264
  ];
265
265
 
@@ -47,13 +47,21 @@ The `cancelTimersByTag` helper from `extensions/scheduling/timer/index.ts` is th
47
47
  ## Parallel-tool-call constraint
48
48
 
49
49
  `context_compress` returns its result immediately and defers the actual
50
- `ctx.compact()` to the agent-run settle point (batch-settle scheduler:
51
- armed on the compress tool's action, fired after `agent_settled` once the
52
- batch's tool-result messages have landed - see
53
- `context-manager/handlers/tools/context-compress.ts`). This removes the old
50
+ `ctx.compact()` to the next safe boundary (batch-settle scheduler in
51
+ `context-manager/handlers/tools/context-compress.ts`): the first `turn_end`
52
+ whose persisted `toolResults` account for every active tool call, or
53
+ `agent_settled`, whichever comes first. Active calls are tracked by
54
+ `toolCallId`, registered at `tool_execution_start` and released by its own
55
+ `tool_execution_end` or by a boundary event whose `toolResults` carry that
56
+ id; `agent_settled` clears whatever is left. The earlier in-flight COUNT was
57
+ decremented only by the exact end event it waited for, so one missed
58
+ `tool_execution_end` left it positive and every later boundary returned
59
+ before the armed compaction could drain; identity cannot drift that way, and
60
+ an id with no result stays protective. This removes the old
54
61
  mid-batch abort race: a still-executing parallel sibling's tool result is
55
62
  delivered BEFORE the aborting compact fires and is no longer discarded
56
- (pinned by `test/runtime/memory/test-compress-batch-settle.mjs`). The
63
+ (pinned by `test/runtime/memory/test-compress-batch-settle.mjs` and
64
+ `test/runtime/memory/test-compress-drain-boundaries.mjs`). The
57
65
  degraded path (batch-settle bookkeeping unavailable) uses a bounded
58
66
  `DEGRADED_DEFERRAL_MS` (150ms) deferral - never a raw `setTimeout(0)`.
59
67
 
@@ -19,6 +19,16 @@
19
19
  * at consumption (the armer may have read the branch before the batch's later
20
20
  * results landed).
21
21
  *
22
+ * A supplied index can land on a non-message entry (`label` from
23
+ * `context_navigate action=tag`, `custom`/`custom_message`, a model or
24
+ * thinking-level change, a context edit, a compaction): those entries carry no
25
+ * provider message, so the kept slice's opening message is the first `message`
26
+ * entry at or after the index. The leading-result check resolves that entry
27
+ * before judging the slice; judging the index itself let a tag placed between
28
+ * an assistant's tool call and its result pass, and the kept slice then opened
29
+ * with a bare tool result ("No tool call found for function call output with
30
+ * call_id ..." from Responses-style endpoints).
31
+ *
22
32
  * The readers take raw session entries (`readonly unknown[]`) because that is
23
33
  * what a live branch is at the boundaries; the shape is narrowed here rather
24
34
  * than asserted at every call site.
@@ -83,11 +93,25 @@ function toolCallIdsOf(entry: BoundaryEntry | undefined): string[] {
83
93
  return ids;
84
94
  }
85
95
 
96
+ /**
97
+ * Index of the first message entry at or after `fromIndex`; non-message
98
+ * session entries carry no provider message and are stepped over. Equals
99
+ * `entries.length` when no message remains.
100
+ */
101
+ function firstMessageIndex(entries: readonly unknown[], fromIndex: number): number {
102
+ let i = fromIndex;
103
+ while (i < entries.length && entryOf(entries[i])?.type !== "message") i++;
104
+ return i;
105
+ }
106
+
86
107
  /**
87
108
  * The structurally invalid shape of a kept slice [candidateIndex..end]:
88
- * either it begins with a tool result (its call fell outside the slice), or it
89
- * contains an assistant whose tool_calls are not fully answered inside it.
90
- * Returns null for a valid slice. Exported for tests and audit surfaces.
109
+ * either its first message is a tool result (its call fell outside the slice),
110
+ * or it contains an assistant whose tool_calls are not fully answered inside
111
+ * it. Non-message entries between the candidate and the first message are
112
+ * stepped over: they are not provider messages, so they neither open the
113
+ * slice nor hide a bare result behind them. Returns null for a valid slice.
114
+ * Exported for tests and audit surfaces.
91
115
  */
92
116
  export function findBoundaryViolation(
93
117
  entries: readonly unknown[],
@@ -95,16 +119,23 @@ export function findBoundaryViolation(
95
119
  ): {
96
120
  kind: "leading-tool-result" | "unanswered-tool-calls";
97
121
  entryId?: string;
122
+ /** Index of the offending tool-result entry (leading-tool-result). */
123
+ resultIndex?: number;
98
124
  /** Index of the offending assistant entry (unanswered-tool-calls). */
99
125
  assistantIndex?: number;
100
126
  } | null {
101
127
  if (!Array.isArray(entries) || candidateIndex < 0 || candidateIndex >= entries.length) {
102
128
  return null;
103
129
  }
104
- if (isToolResultEntry(entryOf(entries[candidateIndex]))) {
105
- return { kind: "leading-tool-result", entryId: entryOf(entries[candidateIndex])?.id };
130
+ const firstMessage = firstMessageIndex(entries, candidateIndex);
131
+ if (isToolResultEntry(entryOf(entries[firstMessage]))) {
132
+ return {
133
+ kind: "leading-tool-result",
134
+ entryId: entryOf(entries[firstMessage])?.id,
135
+ resultIndex: firstMessage,
136
+ };
106
137
  }
107
- for (let i = candidateIndex; i < entries.length; i++) {
138
+ for (let i = firstMessage; i < entries.length; i++) {
108
139
  for (const id of toolCallIdsOf(entryOf(entries[i]))) {
109
140
  let answered = false;
110
141
  for (let j = i + 1; j < entries.length; j++) {
@@ -160,8 +191,10 @@ function firstNonToolResultIndex(entries: readonly unknown[], fromIndex: number)
160
191
  /**
161
192
  * Snap a candidate first-kept index so the kept slice [result..end] cannot
162
193
  * split a tool batch:
163
- * - a candidate landing mid-batch snaps FORWARD to the first entry after
164
- * the batch's last tool result (parallel calls are one batch of N results);
194
+ * - a candidate landing mid-batch - including on a non-message entry whose
195
+ * first following message is mid-batch - snaps FORWARD to the first entry
196
+ * after the batch's last tool result (parallel calls are one batch of N
197
+ * results);
165
198
  * - when that would keep less than `MIN_KEPT_ENTRIES`, it snaps BACKWARD to
166
199
  * the batch's assistant message instead, keeping the whole batch live;
167
200
  * - a leading result whose call is no longer in the branch (summarized away)
@@ -182,12 +215,13 @@ export function snapBoundaryOutsideToolBatch(
182
215
  if (!violation) return index;
183
216
 
184
217
  if (violation.kind === "leading-tool-result") {
185
- const owner = findOwningAssistant(entries, index);
218
+ const resultIndex = violation.resultIndex ?? index;
219
+ const owner = findOwningAssistant(entries, resultIndex);
186
220
  if (owner < 0) {
187
221
  // The call is outside the branch: the only valid repair is dropping
188
222
  // the orphaned results.
189
- const after = firstNonToolResultIndex(entries, index);
190
- if (after > index && entries.length - after >= MIN_KEPT_ENTRIES) {
223
+ const after = firstNonToolResultIndex(entries, resultIndex);
224
+ if (after > resultIndex && entries.length - after >= MIN_KEPT_ENTRIES) {
191
225
  index = after;
192
226
  continue;
193
227
  }