pi-braid 0.40.2 → 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 (23) hide show
  1. package/build-info.json +4 -4
  2. package/dist/extensions/cognitive/metacognition/handlers/claim-verification.js +7 -1
  3. package/dist/extensions/cognitive/metacognition/handlers/finalize.js +20 -0
  4. package/dist/extensions/cognitive/topic-drift/index.js +19 -2
  5. package/dist/extensions/core/prompt-builder/top-level-extensions.d.ts +6 -5
  6. package/dist/extensions/core/prompt-builder/top-level-extensions.js +64 -29
  7. package/dist/extensions/memory/context-manager/handlers/tools/context-inspect.js +7 -1
  8. package/dist/extensions/memory/memory-agent-bridge/explore-paths.d.ts +2 -24
  9. package/dist/extensions/memory/memory-agent-bridge/explore-paths.js +33 -2
  10. package/dist/extensions/scheduling/timer/index.js +9 -1
  11. package/dist/extensions/self/error-tracking/index.js +8 -1
  12. package/dist/extensions/self/health-maintenance/handlers/session-health-tool.js +9 -2
  13. package/package.json +1 -1
  14. package/src/extensions/cognitive/metacognition/handlers/claim-verification.ts +8 -1
  15. package/src/extensions/cognitive/metacognition/handlers/finalize.ts +21 -0
  16. package/src/extensions/cognitive/topic-drift/index.ts +20 -2
  17. package/src/extensions/core/prompt-builder/AGENTS.md +1 -1
  18. package/src/extensions/core/prompt-builder/top-level-extensions.ts +68 -29
  19. package/src/extensions/memory/context-manager/handlers/tools/context-inspect.ts +8 -1
  20. package/src/extensions/memory/memory-agent-bridge/explore-paths.ts +37 -3
  21. package/src/extensions/scheduling/timer/index.ts +10 -1
  22. package/src/extensions/self/error-tracking/index.ts +9 -1
  23. package/src/extensions/self/health-maintenance/handlers/session-health-tool.ts +10 -2
package/build-info.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.40.2",
4
- "sha": "752d2e6e9b45037a8ebcc17f3d6f90c905b2c71c",
5
- "shaShort": "752d2e6",
3
+ "version": "0.40.3",
4
+ "sha": "3f07ed16880eec5fea0c69493fff5cf59ac0cbf0",
5
+ "shaShort": "3f07ed1",
6
6
  "branch": "detached",
7
7
  "dirty": false,
8
- "packedAt": "2026-10-19T11:29:08.778Z"
8
+ "packedAt": "2026-10-20T11:41:36.856Z"
9
9
  }
@@ -19,6 +19,10 @@ import { classify } from "../../../../lib/ai/text-classifier.js";
19
19
  import { CRITICS } from "../../../../lib/ai/critic-registry.js";
20
20
  import { consolidatedClaimCritique } from "../../../../lib/ai/consolidated-claim-critic.js";
21
21
  const log = createLogger("metacognition:claim-verification");
22
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
23
+ function optionalString(v) {
24
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
25
+ }
22
26
  function truncate(text, maxLen) {
23
27
  return text.length > maxLen ? text.slice(0, maxLen) + "..." : text;
24
28
  }
@@ -116,7 +120,9 @@ export function createVerifyClaimTool() {
116
120
  if (!p.claim || !Array.isArray(p.context)) {
117
121
  throw new Error("verify_claim requires 'claim' (string) and 'context' (string array)");
118
122
  }
119
- const claimId = p.claimId ?? `claim-${Date.now()}`;
123
+ // A blank claimId is no id: it would become the tracking key of every
124
+ // such call for the rest of the session.
125
+ const claimId = optionalString(p.claimId) ?? `claim-${Date.now()}`;
120
126
  const issues = [];
121
127
  // PRIMARY PATH: consolidated single-LLM-call
122
128
  let consolidatedUsed = false;
@@ -453,6 +453,26 @@ finalize(completed=true, summary="Fixed the bug", tasksRemaining=["write tests"]
453
453
  details: { finalized: false, blocked: true, error: "missing_params" },
454
454
  };
455
455
  }
456
+ // A blank summary names nothing. The `=== undefined` check above lets it
457
+ // through, and the summary lands in the memory episode, the session label
458
+ // and the deliverables manifest -- an unfindable task recorded as done.
459
+ if (typeof params.summary !== "string" || params.summary.trim().length === 0) {
460
+ return {
461
+ content: [
462
+ {
463
+ type: "text",
464
+ text: `**FINALIZE REQUIRES A SUMMARY**
465
+
466
+ finalize was called with summary ${JSON.stringify(params.summary ?? null)}, which names nothing to record.
467
+ Provide the summary text: what was accomplished, or what is still open with completed: false.
468
+
469
+ Example:
470
+ finalize(completed=true, summary="Fixed the parser offset clamp", tasksRemaining=["add fixture"])`,
471
+ },
472
+ ],
473
+ details: { finalized: false, blocked: true, error: "missing_summary" },
474
+ };
475
+ }
456
476
  // Pre-flight check: verify must have passed
457
477
  if (_ctx && !params.completed) {
458
478
  const lastVerification = getLastVerification(_ctx);
@@ -21,6 +21,10 @@ import { consolidatedTopicCritique } from "../../../lib/detection/consolidated-t
21
21
  import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
22
22
  import { BRAID_INJECTED, BRAID_SOURCE } from "../../../lib/constants/injection-details.js";
23
23
  const log = createLogger("topic-drift");
24
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
25
+ function optionalString(v) {
26
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
27
+ }
24
28
  const DRIFT_THRESHOLD = 0.5;
25
29
  // ANCHOR_TURNS_BEFORE_RESET comes from lib/constants/session-thresholds.ts —
26
30
  // the single source of truth.
@@ -263,7 +267,20 @@ export default function topicDriftExtension(pi) {
263
267
  switch (params?.action) {
264
268
  case "check": {
265
269
  const state = getExtensionState(ctx, "topic-drift", createDriftState);
266
- const output = params.output ?? "";
270
+ const output = optionalString(params.output);
271
+ if (output === undefined) {
272
+ // "" would be measured as an empty response and answered
273
+ // "No topic drift" -- a pass for a check that never ran.
274
+ return {
275
+ content: [
276
+ {
277
+ type: "text",
278
+ text: `topic_drift action=check requires a non-empty 'output': the response text to test against the anchored request.`,
279
+ },
280
+ ],
281
+ details: { error: "missing_output", action: "check" },
282
+ };
283
+ }
267
284
  let drifted = false;
268
285
  let similarity = 1.0;
269
286
  let missingAnchors = [];
@@ -313,7 +330,7 @@ export default function topicDriftExtension(pi) {
313
330
  }
314
331
  case "reset": {
315
332
  const state = getExtensionState(ctx, "topic-drift", createDriftState);
316
- const request = params.newRequest ?? state.originalRequest;
333
+ const request = optionalString(params.newRequest) ?? state.originalRequest;
317
334
  resetAnchors(state, request);
318
335
  return {
319
336
  content: [
@@ -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
  */
@@ -34,8 +35,8 @@ export interface TopLevelExtension {
34
35
  *
35
36
  * Settings-file paths:
36
37
  * - project: `<cwd>/.pi/settings.json`
37
- * - user-global: read from `PI_CODING_AGENT_DIR` env override,
38
- * falling back to `~/.pi/agent/settings.json`.
38
+ * - user-global: `<agentDir>/settings.json`, where the agent dir is
39
+ * `PI_CODING_AGENT_DIR` when set, else `~/.pi/agent`.
39
40
  */
40
41
  export declare function discoverTopLevelExtensions(cwd?: string, options?: {
41
42
  projectSettingsPath?: string;
@@ -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
  */
@@ -102,8 +103,9 @@ function basename(p) {
102
103
  * source is unsupported or cannot be located on disk.
103
104
  *
104
105
  * Supported shapes:
105
- * - `npm:<spec>` (e.g. `npm:pi-web-access`) -- looks in the global
106
- * npm root (`npm root -g`), under each scoped directory.
106
+ * - `npm:<spec>` (e.g. `npm:pi-web-access`) -- looks in pi's
107
+ * managed install tree, then the global npm root, under each
108
+ * scoped directory.
107
109
  * - absolute local path (starts with `/`) -- used as-is.
108
110
  * - relative local path -- resolved relative to `cwd`.
109
111
  */
@@ -111,7 +113,7 @@ function resolveEntryToPackage(source, scope, cwd) {
111
113
  const trimmed = source.trim();
112
114
  if (!trimmed)
113
115
  return null;
114
- // npm:<spec> -- find in global node_modules.
116
+ // npm:<spec> -- find in the managed install tree, then global node_modules.
115
117
  if (trimmed.startsWith("npm:")) {
116
118
  const spec = trimmed.slice("npm:".length).trim();
117
119
  const at = spec.lastIndexOf("@");
@@ -158,35 +160,69 @@ function expandHome(p) {
158
160
  return p;
159
161
  }
160
162
  /**
161
- * Locate a globally-installed npm package by name. Walks the
162
- * scope directories under the global npm root (`npm root -g`).
163
- * Optional `version` filters to a directory whose `package.json`
164
- * version matches; if absent, the first matching directory wins.
163
+ * Resolve pi's agent directory. `PI_CODING_AGENT_DIR` relocates the whole
164
+ * agent home when set and non-empty; otherwise the default is `~/.pi/agent`.
165
+ * Both the user-global settings file and the managed npm install tree live
166
+ * under this one directory, so they are resolved from this one function.
167
+ */
168
+ function resolveAgentDir() {
169
+ const override = process.env.PI_CODING_AGENT_DIR?.trim();
170
+ if (override)
171
+ return expandHome(override);
172
+ return join(process.env.HOME ?? "~", ".pi", "agent");
173
+ }
174
+ /**
175
+ * Locate an installed npm package by name, searching pi's managed install
176
+ * tree before the global npm root. Managed first because that is where pi
177
+ * installs a settings-declared `npm:` entry (`<agentDir>/npm/node_modules`)
178
+ * and it consults a legacy global install only when the managed copy is
179
+ * absent -- so the managed copy is the one pi actually loads. The global
180
+ * root stays as that same fallback, for packages installed by hand.
165
181
  *
166
- * Returns the absolute directory path, or null if not found.
182
+ * Optional `version` filters to a directory whose `package.json` version
183
+ * matches; if absent, the first matching directory wins. Returns the
184
+ * absolute directory path, or null if not found in any root.
167
185
  */
168
186
  function findNpmPackageDir(name, version) {
187
+ for (const root of getNpmSearchRoots()) {
188
+ const dir = findPackageInNpmRoot(root, name, version);
189
+ if (dir)
190
+ return dir;
191
+ }
192
+ return null;
193
+ }
194
+ /** The npm roots searched for an `npm:` entry, in precedence order. */
195
+ function getNpmSearchRoots() {
196
+ const roots = [join(resolveAgentDir(), "npm", "node_modules")];
169
197
  const globalRoot = getGlobalNpmRoot();
170
- if (!globalRoot)
171
- return null;
172
- if (!existsSync(globalRoot))
198
+ if (globalRoot)
199
+ roots.push(globalRoot);
200
+ return roots;
201
+ }
202
+ /**
203
+ * Find the package directory for `name` inside one npm root.
204
+ *
205
+ * Scoped package: @scope/name -> look directly under `<root>/@scope/name`.
206
+ * Unscoped: scan the root's own directories for a package.json whose `name`
207
+ * matches -- npm installs both flat and nested layouts. A directory with no
208
+ * readable package.json is skipped, never fatal.
209
+ */
210
+ function findPackageInNpmRoot(root, name, version) {
211
+ if (!existsSync(root))
173
212
  return null;
174
- // Scoped package: @scope/name -> look under globalRoot/@scope/name.
175
213
  if (name.startsWith("@")) {
176
- const dir = join(globalRoot, name);
214
+ const dir = join(root, name);
177
215
  return packageDirMatches(dir, version) ? dir : null;
178
216
  }
179
- // Unscoped: scan globalRoot itself for a directory whose
180
- // package.json `name` matches. npm installs both flat and nested layouts.
181
217
  let entries;
182
218
  try {
183
- entries = readdirSync(globalRoot);
219
+ entries = readdirSync(root);
184
220
  }
185
221
  catch {
186
222
  return null;
187
223
  }
188
224
  for (const entry of entries) {
189
- const dir = join(globalRoot, entry);
225
+ const dir = join(root, entry);
190
226
  let isDir;
191
227
  try {
192
228
  isDir = statSync(dir).isDirectory();
@@ -228,10 +264,11 @@ function packageDirMatches(dir, expectedVersion, expectedName) {
228
264
  }
229
265
  /**
230
266
  * Resolve the global npm root via `npm root -g`. Returns null if
231
- * the command fails or produces no output. Cached after first
232
- * successful call so the (slow) `npm root -g` invocation runs at
233
- * most once per process -- the value never changes inside one
234
- * pi session.
267
+ * the command fails or produces no output. This is the fallback root
268
+ * only -- pi's managed install tree is searched first (see
269
+ * `findNpmPackageDir`). Cached after first successful call so the
270
+ * (slow) `npm root -g` invocation runs at most once per process --
271
+ * the value never changes inside one pi session.
235
272
  *
236
273
  * Implemented as an IIFE-wrapped closure so the cache `let`
237
274
  * stays function-scoped (the project's no-module-level-let
@@ -267,14 +304,12 @@ const getGlobalNpmRoot = (() => {
267
304
  *
268
305
  * Settings-file paths:
269
306
  * - project: `<cwd>/.pi/settings.json`
270
- * - user-global: read from `PI_CODING_AGENT_DIR` env override,
271
- * falling back to `~/.pi/agent/settings.json`.
307
+ * - user-global: `<agentDir>/settings.json`, where the agent dir is
308
+ * `PI_CODING_AGENT_DIR` when set, else `~/.pi/agent`.
272
309
  */
273
310
  export function discoverTopLevelExtensions(cwd = process.cwd(), options) {
274
311
  const projectPath = options?.projectSettingsPath ?? join(cwd, ".pi", "settings.json");
275
- const userPath = options?.userSettingsPath ??
276
- process.env.PI_CODING_AGENT_DIR ??
277
- join(process.env.HOME ?? "~", ".pi", "agent", "settings.json");
312
+ const userPath = options?.userSettingsPath ?? join(resolveAgentDir(), "settings.json");
278
313
  const seen = new Set();
279
314
  const out = [];
280
315
  const add = (pkg, source) => {
@@ -12,6 +12,10 @@ import { CONTEXT_COMPACT_REFUSE_PERCENT } from "../../../../../lib/detection/con
12
12
  import { formatTokensK } from "../../../../../lib/detection/context-usage.js";
13
13
  import { readExtensionState } from "../../../../../lib/state/extension-state.js";
14
14
  import { formatPendingCompactionsLine, readPendingCompactions } from "./context-compress.js";
15
+ /** A numeric selector read as absent when it names no positive count. */
16
+ function positiveNumber(v) {
17
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
18
+ }
15
19
  export const contextInspectSchema = Type.Object({
16
20
  detail: Type.Optional(Type.String({
17
21
  enum: ["quick", "detailed", "full", "prune"],
@@ -226,7 +230,9 @@ export function registerContextInspect(pi) {
226
230
  }
227
231
  // PRUNE: Only prune candidates (like context_prune dry-run)
228
232
  if (detail === "prune") {
229
- const minAge = params.minAge ?? 5;
233
+ // "" converts to 0 before the handler, and `age >= 0` admits every
234
+ // candidate: the age filter disabled itself instead of applying 5.
235
+ const minAge = positiveNumber(params.minAge) ?? 5;
230
236
  let candidates = audit.candidates.filter((c) => c.age >= minAge);
231
237
  if (params.toolFilter?.length) {
232
238
  candidates = candidates.filter((c) => c.toolName && params.toolFilter.includes(c.toolName));
@@ -3,28 +3,6 @@
3
3
  *
4
4
  * Self-contained: file-finding helpers + the explore_paths tool.
5
5
  */
6
- import { Type } from "typebox";
7
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
- export declare function createExplorePathsTool(): {
9
- name: string;
10
- label: string;
11
- promptSnippet: string;
12
- description: string;
13
- parameters: Type.TObject<{
14
- hypothesis_1: Type.TString;
15
- hypothesis_2: Type.TString;
16
- hypothesis_3: Type.TOptional<Type.TString>;
17
- searchRoot: Type.TOptional<Type.TString>;
18
- }>;
19
- execute: (_toolCallId: string, params: unknown, _signal: unknown, _onUpdate: unknown, ctx: ExtensionContext) => Promise<{
20
- details: {
21
- hypotheses: number;
22
- projectRoot: string;
23
- };
24
- content: {
25
- type: "text";
26
- text: string;
27
- }[];
28
- }>;
29
- };
6
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
7
+ export declare function createExplorePathsTool(): ToolDefinition<any, any, any>;
30
8
  //# sourceMappingURL=explore-paths.d.ts.map
@@ -120,6 +120,9 @@ async function readFileHead(path, lines = 30) {
120
120
  return "(could not read)";
121
121
  }
122
122
  }
123
+ // The two result shapes (a named refusal and a report) carry different
124
+ // details, so the tool declares its own type rather than letting the first
125
+ // return statement narrow every other branch.
123
126
  export function createExplorePathsTool() {
124
127
  return {
125
128
  name: "explore_paths",
@@ -142,11 +145,39 @@ export function createExplorePathsTool() {
142
145
  }),
143
146
  execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
144
147
  const { hypothesis_1, hypothesis_2, hypothesis_3, searchRoot } = params;
148
+ // A blank hypothesis names nothing to search. Both are schema-legal
149
+ // (`Type.String()` accepts ""), and the report that followed came back
150
+ // with "No useful keywords found" -- read as "no evidence", not as an
151
+ // unusable call.
152
+ const requiredHypotheses = [
153
+ ["hypothesis_1", hypothesis_1],
154
+ ["hypothesis_2", hypothesis_2],
155
+ ];
156
+ const blankRequired = requiredHypotheses
157
+ .filter(([, value]) => typeof value !== "string" || value.trim().length === 0)
158
+ .map(([name]) => name);
159
+ if (blankRequired.length > 0) {
160
+ const named = blankRequired.map((name) => `'${name}'`).join(" and ");
161
+ return {
162
+ details: { error: "missing_hypothesis", blank: blankRequired },
163
+ content: [
164
+ {
165
+ type: "text",
166
+ text: `explore_paths requires a non-empty ${named}: name a file and a reason, e.g. "The bug might be in src/parser.ts because the offset is never clamped".`,
167
+ },
168
+ ],
169
+ };
170
+ }
145
171
  const searchDir = resolveSearchRoot(searchRoot, ctx?.cwd);
146
172
  const results = [];
147
173
  const hypotheses = [hypothesis_1, hypothesis_2];
148
- if (hypothesis_3)
149
- hypotheses.push(hypothesis_3);
174
+ // An optional third hypothesis is absent when blank; a blank one used to
175
+ // become a report section with an empty title and an empty search.
176
+ const third = typeof hypothesis_3 === "string" && hypothesis_3.trim().length > 0
177
+ ? hypothesis_3
178
+ : undefined;
179
+ if (third)
180
+ hypotheses.push(third);
150
181
  const explorations = hypotheses.map(async (hyp, i) => {
151
182
  const localResults = [];
152
183
  localResults.push(`### Hypothesis ${i + 1}: ${hyp.substring(0, 120)}`);
@@ -51,6 +51,10 @@ import { getTerminalBreakerConfig, getWakeDeliveryAlertConfig, } from "../../../
51
51
  import { getWatchdogWakeDeliveryFeed, setWatchdogWakeDueProvider, } from "../../../lib/state/global-state.js";
52
52
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
53
53
  import { describeFireTiming } from "./fire-timing.js";
54
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
55
+ function optionalString(v) {
56
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
57
+ }
54
58
  /** Get the timer file path for the current process CWD.
55
59
  * Each project CWD has its own timer file for independent timer pools. */
56
60
  function timerFilePath() {
@@ -720,7 +724,11 @@ function createTimerTool(sessionState) {
720
724
  }
721
725
  switch (params?.action) {
722
726
  case "set": {
723
- const { delay_seconds, reason, tag, interval_seconds, count, wake } = params;
727
+ const { delay_seconds, reason, interval_seconds, count, wake } = params;
728
+ // A blank tag is no tag: stored as "" it reads as [] in the list
729
+ // rendering instead of (untagged), and cancelTimersByTag("") would
730
+ // match every blank-tagged timer in the session.
731
+ const tag = optionalString(params.tag);
724
732
  if (tag && !/^[a-zA-Z0-9_-]+$/.test(tag)) {
725
733
  throw new Error(`Invalid tag "${tag}" - use alphanumeric + dash/underscore`);
726
734
  }
@@ -69,6 +69,10 @@ async function captureError(source, message, stack, context) {
69
69
  await saveError(entry);
70
70
  return entry;
71
71
  }
72
+ /** A numeric selector read as absent when it names no positive count. */
73
+ function positiveNumber(v) {
74
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
75
+ }
72
76
  const errorSchema = Type.Object({
73
77
  action: Type.Union([Type.Literal("list"), Type.Literal("get"), Type.Literal("clear"), Type.Literal("stats")], { description: "Action: list | get | clear | stats" }),
74
78
  // list-only
@@ -121,7 +125,10 @@ export default function errorCaptureExtension(pi) {
121
125
  switch (params.action) {
122
126
  case "list": {
123
127
  const entries = await loadErrors();
124
- const limit = params.limit ?? 10;
128
+ // The framework converts "" to 0 before the handler (no `minimum`
129
+ // on the schema), and slice(-0) is slice(0): a blank limit returned
130
+ // every captured error, the opposite of the documented cap.
131
+ const limit = positiveNumber(params.limit) ?? 10;
125
132
  const source = params.source;
126
133
  const unhandledOnly = params.unhandledOnly ?? false;
127
134
  let filtered = entries;
@@ -20,6 +20,10 @@
20
20
  */
21
21
  import { Type } from "typebox";
22
22
  import { getSessionHealth, setSessionHealthMode, } from "../../../enforcement/session-health.js";
23
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
24
+ function optionalString(v) {
25
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
26
+ }
23
27
  const sessionHealthSchema = Type.Object({
24
28
  action: Type.Union([Type.Literal("get"), Type.Literal("diagnose"), Type.Literal("recover")], {
25
29
  description: "Action: get, diagnose (with history), or recover (force reset)",
@@ -119,7 +123,10 @@ export function registerSessionHealthTool(pi) {
119
123
  details,
120
124
  };
121
125
  }
122
- setSessionHealthMode(ctx, "healthy", params.reason);
126
+ // A blank reason is no reason: stored (and echoed) as "" it reads as
127
+ // an audit note the operator never wrote.
128
+ const reason = optionalString(params.reason);
129
+ setSessionHealthMode(ctx, "healthy", reason);
123
130
  const after = getSessionHealth(ctx);
124
131
  const details = {
125
132
  mode: after.mode,
@@ -131,7 +138,7 @@ export function registerSessionHealthTool(pi) {
131
138
  content: [
132
139
  {
133
140
  type: "text",
134
- text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${params.reason ? `\n\nReason: ${params.reason}` : ""}`,
141
+ text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${reason ? `\n\nReason: ${reason}` : ""}`,
135
142
  },
136
143
  ],
137
144
  details,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.40.2",
3
+ "version": "0.40.3",
4
4
  "description": "Metacognitive extension suite for pi-coding-agent: enforcement, memory, reasoning, self-improvement, and structured cognitive signals.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,6 +27,11 @@ import { consolidatedClaimCritique } from "../../../../lib/ai/consolidated-claim
27
27
 
28
28
  const log = createLogger("metacognition:claim-verification");
29
29
 
30
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
31
+ function optionalString(v: unknown): string | undefined {
32
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
33
+ }
34
+
30
35
  function truncate(text: string, maxLen: number): string {
31
36
  return text.length > maxLen ? text.slice(0, maxLen) + "..." : text;
32
37
  }
@@ -166,7 +171,9 @@ export function createVerifyClaimTool(): ToolDefinition<any, any, any> {
166
171
  if (!p.claim || !Array.isArray(p.context)) {
167
172
  throw new Error("verify_claim requires 'claim' (string) and 'context' (string array)");
168
173
  }
169
- const claimId = p.claimId ?? `claim-${Date.now()}`;
174
+ // A blank claimId is no id: it would become the tracking key of every
175
+ // such call for the rest of the session.
176
+ const claimId = optionalString(p.claimId) ?? `claim-${Date.now()}`;
170
177
  const issues: Record<string, unknown>[] = [];
171
178
 
172
179
  // PRIMARY PATH: consolidated single-LLM-call
@@ -528,6 +528,27 @@ finalize(completed=true, summary="Fixed the bug", tasksRemaining=["write tests"]
528
528
  };
529
529
  }
530
530
 
531
+ // A blank summary names nothing. The `=== undefined` check above lets it
532
+ // through, and the summary lands in the memory episode, the session label
533
+ // and the deliverables manifest -- an unfindable task recorded as done.
534
+ if (typeof params.summary !== "string" || params.summary.trim().length === 0) {
535
+ return {
536
+ content: [
537
+ {
538
+ type: "text" as const,
539
+ text: `**FINALIZE REQUIRES A SUMMARY**
540
+
541
+ finalize was called with summary ${JSON.stringify(params.summary ?? null)}, which names nothing to record.
542
+ Provide the summary text: what was accomplished, or what is still open with completed: false.
543
+
544
+ Example:
545
+ finalize(completed=true, summary="Fixed the parser offset clamp", tasksRemaining=["add fixture"])`,
546
+ },
547
+ ],
548
+ details: { finalized: false, blocked: true, error: "missing_summary" },
549
+ };
550
+ }
551
+
531
552
  // Pre-flight check: verify must have passed
532
553
  if (_ctx && !params.completed) {
533
554
  const lastVerification = getLastVerification(_ctx);
@@ -29,6 +29,11 @@ import { BRAID_INJECTED, BRAID_SOURCE } from "../../../lib/constants/injection-d
29
29
 
30
30
  const log = createLogger("topic-drift");
31
31
 
32
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
33
+ function optionalString(v: unknown): string | undefined {
34
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
35
+ }
36
+
32
37
  interface DriftState {
33
38
  /** The original request text (used by critics directly - no token extraction needed). */
34
39
  originalRequest: string;
@@ -348,7 +353,20 @@ export default function topicDriftExtension(pi: ExtensionAPI) {
348
353
  switch (params?.action) {
349
354
  case "check": {
350
355
  const state = getExtensionState(ctx, "topic-drift", createDriftState);
351
- const output = params.output ?? "";
356
+ const output = optionalString(params.output);
357
+ if (output === undefined) {
358
+ // "" would be measured as an empty response and answered
359
+ // "No topic drift" -- a pass for a check that never ran.
360
+ return {
361
+ content: [
362
+ {
363
+ type: "text" as const,
364
+ text: `topic_drift action=check requires a non-empty 'output': the response text to test against the anchored request.`,
365
+ },
366
+ ],
367
+ details: { error: "missing_output", action: "check" },
368
+ };
369
+ }
352
370
  let drifted = false;
353
371
  let similarity = 1.0;
354
372
  let missingAnchors: string[] = [];
@@ -397,7 +415,7 @@ export default function topicDriftExtension(pi: ExtensionAPI) {
397
415
  }
398
416
  case "reset": {
399
417
  const state = getExtensionState(ctx, "topic-drift", createDriftState);
400
- const request = params.newRequest ?? state.originalRequest;
418
+ const request = optionalString(params.newRequest) ?? state.originalRequest;
401
419
  resetAnchors(state, request);
402
420
  return {
403
421
  content: [
@@ -25,7 +25,7 @@ Every file in this folder either:
25
25
  | `identity.ts` | Framing constants: `IDENTITY_INTRO` (generalist identity), `DISCOVERY` (D1 guarded exploration stance), `WORK_ETHIC` (methodical precision, signal-not-noise), `REPAIR_DISCIPLINE` (root cause named falsifiably before repair; re-derivation of claims that are not yours; weighted repair decisions), `SELF_MANAGEMENT` (memory workspace, evidence-carrying done items, known-open-check done gate), `COMMUNICATION` (conclusion-first, output style), `EPISTEMIC_STANCE` (identity-core: claim gate, self-state gate, retrieved-context preference), `SELF_AUDIT` (symmetric doubt; handoff ends with the unverified), `PHILOSOPHY` (character-level stance - silence, calm strategist, precise self-irony). |
26
26
  | `surface-discipline-section.ts` | `SURFACE_DISCIPLINE` (signal discipline across code, commits, tests, docs, reports, logs) + `surfaceDisciplineSection()` - its own section, rendered between the identity and identity-core blocks. Text pinned verbatim by test-prompt-budget.mjs. |
27
27
  | `instance-composition.ts` | **v3.8** Instance (consolidated): agent identity + pi-core version + root (pi-core npm package folder) + cwd + userland settings dir + os/pid + session (id + elapsed/last-event/turns/tool-avg) + top-level pi extension packages (settings-driven, scope-tagged `project` or `user-global`). Full block rendered on demand via the `system_info` tool; the prompt carries only the compact orientation line. |
28
- | `top-level-extensions.ts` | **v3.8** Discovery logic for top-level pi extension PACKAGES. Reads pi-core's `packages` field from `<cwd>/.pi/settings.json` (project) and `~/.pi/agent/settings.json` (user-global); project wins on collision. Resolves `npm:` specs via `npm root -g`; resolves local paths in place. Source tags: `project` / `user-global`. |
28
+ | `top-level-extensions.ts` | **v3.8** Discovery logic for top-level pi extension PACKAGES. Reads pi-core's `packages` field from `<cwd>/.pi/settings.json` (project) and `~/.pi/agent/settings.json` (user-global); project wins on collision. Resolves `npm:` specs in pi's managed install tree (`<agentDir>/npm/node_modules`) first, falling back to the global npm root (`npm root -g`); resolves local paths in place. Source tags: `project` / `user-global`. |
29
29
  | `project-docs-section.ts` | Project docs (AGENTS.md / CLAUDE.md) pointer-only rendering as plain-text bullets (`- <basename> at <path>`). Mirrors the skills discoverability model but uses plain text (no XML tags) so the system prompt stays prose. Includes fingerprint cache and `RESOURCES_DISCOVER` invalidation. |
30
30
  | `memory-section.ts` | Memory store pointer block (episodes + semantic + heuristics) as plain-text bullets (`- episodes at PATH`; count-free - per-store counts go stale at print time and are not rendered). Mirrors project-docs. Cached per session (static content, no fingerprint needed); invalidated on `RESOURCES_DISCOVER`. |
31
31
  | `context-section.ts` | **v3.6** body fragment for the unified context block: context %, session health, steps-since-checkpoint. Returns `""` when nothing to surface. Composer (`index.ts`) joins this with project-docs and memory bodies. No heading. (Memory stores render pointer-only: per-store entry counts are not rendered; the whisper carries token counts, not memory counts.) |
@@ -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[] = [];
@@ -21,6 +21,11 @@ import { formatTokensK } from "../../../../../lib/detection/context-usage.js";
21
21
  import { readExtensionState } from "../../../../../lib/state/extension-state.js";
22
22
  import { formatPendingCompactionsLine, readPendingCompactions } from "./context-compress.js";
23
23
 
24
+ /** A numeric selector read as absent when it names no positive count. */
25
+ function positiveNumber(v: unknown): number | undefined {
26
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
27
+ }
28
+
24
29
  export const contextInspectSchema = Type.Object({
25
30
  detail: Type.Optional(
26
31
  Type.String({
@@ -285,7 +290,9 @@ export function registerContextInspect(pi: ExtensionAPI): void {
285
290
 
286
291
  // PRUNE: Only prune candidates (like context_prune dry-run)
287
292
  if (detail === "prune") {
288
- const minAge = params.minAge ?? 5;
293
+ // "" converts to 0 before the handler, and `age >= 0` admits every
294
+ // candidate: the age filter disabled itself instead of applying 5.
295
+ const minAge = positiveNumber(params.minAge) ?? 5;
289
296
  let candidates = audit.candidates.filter((c: any) => c.age >= minAge);
290
297
  if (params.toolFilter?.length) {
291
298
  candidates = candidates.filter(
@@ -9,7 +9,7 @@ import { promisify } from "node:util";
9
9
  import * as path from "node:path";
10
10
  import * as url from "node:url";
11
11
  import { Type } from "typebox";
12
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import type { ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
13
13
  import { addEvidence } from "../../../lib/store/evidence-pool.js";
14
14
 
15
15
  const execFileAsync = promisify(execFile);
@@ -136,7 +136,10 @@ async function readFileHead(path: string, lines = 30): Promise<string> {
136
136
  }
137
137
  }
138
138
 
139
- export function createExplorePathsTool() {
139
+ // The two result shapes (a named refusal and a report) carry different
140
+ // details, so the tool declares its own type rather than letting the first
141
+ // return statement narrow every other branch.
142
+ export function createExplorePathsTool(): ToolDefinition<any, any, any> {
140
143
  return {
141
144
  name: "explore_paths",
142
145
  label: "Explore Paths",
@@ -178,11 +181,42 @@ export function createExplorePathsTool() {
178
181
  hypothesis_3?: string;
179
182
  searchRoot?: string;
180
183
  };
184
+
185
+ // A blank hypothesis names nothing to search. Both are schema-legal
186
+ // (`Type.String()` accepts ""), and the report that followed came back
187
+ // with "No useful keywords found" -- read as "no evidence", not as an
188
+ // unusable call.
189
+ const requiredHypotheses: Array<[string, unknown]> = [
190
+ ["hypothesis_1", hypothesis_1],
191
+ ["hypothesis_2", hypothesis_2],
192
+ ];
193
+ const blankRequired = requiredHypotheses
194
+ .filter(([, value]) => typeof value !== "string" || value.trim().length === 0)
195
+ .map(([name]) => name);
196
+ if (blankRequired.length > 0) {
197
+ const named = blankRequired.map((name) => `'${name}'`).join(" and ");
198
+ return {
199
+ details: { error: "missing_hypothesis", blank: blankRequired },
200
+ content: [
201
+ {
202
+ type: "text" as const,
203
+ text: `explore_paths requires a non-empty ${named}: name a file and a reason, e.g. "The bug might be in src/parser.ts because the offset is never clamped".`,
204
+ },
205
+ ],
206
+ };
207
+ }
208
+
181
209
  const searchDir = resolveSearchRoot(searchRoot, ctx?.cwd);
182
210
 
183
211
  const results: string[] = [];
184
212
  const hypotheses = [hypothesis_1, hypothesis_2];
185
- if (hypothesis_3) hypotheses.push(hypothesis_3);
213
+ // An optional third hypothesis is absent when blank; a blank one used to
214
+ // become a report section with an empty title and an empty search.
215
+ const third =
216
+ typeof hypothesis_3 === "string" && hypothesis_3.trim().length > 0
217
+ ? hypothesis_3
218
+ : undefined;
219
+ if (third) hypotheses.push(third);
186
220
 
187
221
  const explorations = hypotheses.map(async (hyp, i) => {
188
222
  const localResults: string[] = [];
@@ -63,6 +63,11 @@ import {
63
63
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
64
64
  import { describeFireTiming } from "./fire-timing.js";
65
65
 
66
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
67
+ function optionalString(v: unknown): string | undefined {
68
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
69
+ }
70
+
66
71
  type PersistedTimer = {
67
72
  id: string;
68
73
  sessionId: string;
@@ -880,7 +885,11 @@ function createTimerTool(sessionState: {
880
885
  }
881
886
  switch (params?.action) {
882
887
  case "set": {
883
- const { delay_seconds, reason, tag, interval_seconds, count, wake } = params;
888
+ const { delay_seconds, reason, interval_seconds, count, wake } = params;
889
+ // A blank tag is no tag: stored as "" it reads as [] in the list
890
+ // rendering instead of (untagged), and cancelTimersByTag("") would
891
+ // match every blank-tagged timer in the session.
892
+ const tag = optionalString(params.tag);
884
893
  if (tag && !/^[a-zA-Z0-9_-]+$/.test(tag)) {
885
894
  throw new Error(`Invalid tag "${tag}" - use alphanumeric + dash/underscore`);
886
895
  }
@@ -100,6 +100,11 @@ async function captureError(
100
100
  return entry;
101
101
  }
102
102
 
103
+ /** A numeric selector read as absent when it names no positive count. */
104
+ function positiveNumber(v: unknown): number | undefined {
105
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
106
+ }
107
+
103
108
  const errorSchema = Type.Object({
104
109
  action: Type.Union(
105
110
  [Type.Literal("list"), Type.Literal("get"), Type.Literal("clear"), Type.Literal("stats")],
@@ -161,7 +166,10 @@ export default function errorCaptureExtension(pi: ExtensionAPI): void {
161
166
  switch (params.action) {
162
167
  case "list": {
163
168
  const entries = await loadErrors();
164
- const limit = params.limit ?? 10;
169
+ // The framework converts "" to 0 before the handler (no `minimum`
170
+ // on the schema), and slice(-0) is slice(0): a blank limit returned
171
+ // every captured error, the opposite of the documented cap.
172
+ const limit = positiveNumber(params.limit) ?? 10;
165
173
  const source = params.source;
166
174
  const unhandledOnly = params.unhandledOnly ?? false;
167
175
 
@@ -28,6 +28,11 @@ import {
28
28
  type SessionHealthState,
29
29
  } from "../../../enforcement/session-health.js";
30
30
 
31
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
32
+ function optionalString(v: unknown): string | undefined {
33
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
34
+ }
35
+
31
36
  const sessionHealthSchema = Type.Object({
32
37
  action: Type.Union([Type.Literal("get"), Type.Literal("diagnose"), Type.Literal("recover")], {
33
38
  description: "Action: get, diagnose (with history), or recover (force reset)",
@@ -143,7 +148,10 @@ export function registerSessionHealthTool(pi: ExtensionAPI): void {
143
148
  details,
144
149
  };
145
150
  }
146
- setSessionHealthMode(ctx, "healthy", params.reason);
151
+ // A blank reason is no reason: stored (and echoed) as "" it reads as
152
+ // an audit note the operator never wrote.
153
+ const reason = optionalString(params.reason);
154
+ setSessionHealthMode(ctx, "healthy", reason);
147
155
  const after = getSessionHealth(ctx);
148
156
  const details: SessionHealthToolDetails = {
149
157
  mode: after.mode,
@@ -155,7 +163,7 @@ export function registerSessionHealthTool(pi: ExtensionAPI): void {
155
163
  content: [
156
164
  {
157
165
  type: "text" as const,
158
- text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${params.reason ? `\n\nReason: ${params.reason}` : ""}`,
166
+ text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${reason ? `\n\nReason: ${reason}` : ""}`,
159
167
  },
160
168
  ],
161
169
  details,