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
@@ -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)}`);
@@ -50,6 +50,22 @@ export function createMemoryStoreTool(memory, initPromise, recordMemoryToolCall)
50
50
  recordMemoryToolCall(ctx, "memory_store");
51
51
  await initPromise;
52
52
  try {
53
+ // A blank string is not content. The store gate rejects short text as
54
+ // "Duplicate or low-utility content" for most types but exempts
55
+ // error/goal, so a blank landed as a real memory and every other type
56
+ // was refused under a misnamed cause. Refuse by name before the store
57
+ // call instead.
58
+ if (typeof params.content !== "string" || params.content.trim().length === 0) {
59
+ return {
60
+ content: [
61
+ {
62
+ type: "text",
63
+ text: "memory_store requires non-empty 'content' (got a blank string). Nothing was stored.",
64
+ },
65
+ ],
66
+ details: { stored: false },
67
+ };
68
+ }
53
69
  const related = [];
54
70
  if (params.linkedMemories) {
55
71
  for (const id of params.linkedMemories) {
@@ -20,6 +20,16 @@ import { textResult } from "../../../lib/utils/extension-utils.js";
20
20
  import { addEpisode, addHeuristicRule, createMemoryStoresState, evolveHeuristic, getApplicableHeuristics, getPrioritizedHeuristics, retrieveByRUMS, retrieveEpisodes, } from "../three-memory-stores/index.js";
21
21
  import { flushEpisodeAppends } from "../three-memory-stores/episodes-disk.js";
22
22
  const log = createLogger("memory-agent-bridge/memory-tool");
23
+ /**
24
+ * Read an optional limit selector. The framework's argument validation
25
+ * converts a blank string to 0 for `Type.Optional(Type.Number())` and the
26
+ * converted value passes validation, so the handler cannot tell a blank from a
27
+ * typed 0. 0 is never a usable limit (`slice(0, 0)`) so a non-positive or
28
+ * non-finite value is read as absent and the documented default applies.
29
+ */
30
+ function positiveLimit(value) {
31
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
32
+ }
23
33
  // Recency filtering helpers
24
34
  /** Parse a since/until value into a Unix timestamp (ms), or undefined if invalid. */
25
35
  function parseTimeFilter(value) {
@@ -161,6 +171,8 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
161
171
  // The action may be undefined if the caller sent a malformed request;
162
172
  // record as "memory:unknown" in that case so it's still counted.
163
173
  recordMemoryToolCall(ctx, `memory:${params?.action ?? "unknown"}`);
174
+ // One read at the boundary; every limit-consuming branch below uses it.
175
+ const limit = positiveLimit(params?.limit);
164
176
  try {
165
177
  switch (params?.action) {
166
178
  // recall_*
@@ -185,7 +197,7 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
185
197
  }
186
198
  const results = await memory.recall(params.query, {
187
199
  type,
188
- limit: params.limit,
200
+ limit,
189
201
  tags: params.tags,
190
202
  currentProject,
191
203
  projectScope: params.projectScope,
@@ -224,7 +236,7 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
224
236
  // project filtering and cross-project episodes rank into
225
237
  // results as if they were current-project memory.
226
238
  const effectiveScope = userProjectScope ?? "current";
227
- const episodes = retrieveByRUMS(threeMem, params.query, params.limit ?? 3, threeMem.currentSessionId, effectiveScope === "current" ? projectId : undefined, effectiveScope).filter((ep) => {
239
+ const episodes = retrieveByRUMS(threeMem, params.query, limit ?? 3, threeMem.currentSessionId, effectiveScope === "current" ? projectId : undefined, effectiveScope).filter((ep) => {
228
240
  if (since && ep.timestamp < since)
229
241
  return false;
230
242
  if (until && ep.timestamp > until)
@@ -260,7 +272,7 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
260
272
  const lines = [];
261
273
  if (annotatedResults.length > 0) {
262
274
  lines.push(`Found ${annotatedResults.length} semantic memories:`);
263
- for (const r of annotatedResults.slice(0, params.limit ?? 5)) {
275
+ for (const r of annotatedResults.slice(0, limit ?? 5)) {
264
276
  lines.push(` [${r.memory.type}] ${r.memory.content.slice(0, 300)}... (${r.relevanceReason}, id: ${r.memory.id})`);
265
277
  }
266
278
  }
@@ -289,7 +301,7 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
289
301
  details: {
290
302
  count: annotatedResults.length + episodeResults.length,
291
303
  relevanceReasons: annotatedResults
292
- .slice(0, params.limit ?? 5)
304
+ .slice(0, limit ?? 5)
293
305
  .map((r) => ({
294
306
  id: r.memory.id,
295
307
  reason: r.relevanceReason,
@@ -299,9 +311,9 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
299
311
  };
300
312
  }
301
313
  case "recall_list": {
302
- const limit = params.limit ?? 20;
314
+ const listLimit = limit ?? 20;
303
315
  const currentProject = ctx && typeof ctx.cwd === "string" ? deriveProjectIdFromCwd(ctx.cwd) : undefined;
304
- const allMemories = memory.getAll(limit);
316
+ const allMemories = memory.getAll(listLimit);
305
317
  // Filter to current-project entries (or legacy entries without a projectId).
306
318
  const memories = currentProject
307
319
  ? allMemories.filter((m) => !m.projectId || m.projectId === currentProject)
@@ -320,7 +332,7 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
320
332
  const recent = threeMem.episodes
321
333
  .slice()
322
334
  .sort((a, b) => b.timestamp - a.timestamp)
323
- .slice(0, Math.min(limit, 5));
335
+ .slice(0, Math.min(listLimit, 5));
324
336
  if (recent.length > 0) {
325
337
  if (lines.length > 0)
326
338
  lines.push("");
@@ -419,8 +431,8 @@ export function createMemoryTool(memory, initPromise, recordMemoryToolCall) {
419
431
  const state = getThreeMem(ctx);
420
432
  if (!state)
421
433
  return textResult("No episodes stored yet.");
422
- const limit = params.limit ?? 3;
423
- const episodes = retrieveEpisodes(state, params.query, limit, deriveProjectId(ctx?.cwd ?? ""));
434
+ const episodeLimit = limit ?? 3;
435
+ const episodes = retrieveEpisodes(state, params.query, episodeLimit, deriveProjectId(ctx?.cwd ?? ""));
424
436
  if (episodes.length === 0)
425
437
  return textResult("No relevant episodes found. Consider trying broader search.");
426
438
  const lines = [`Found ${episodes.length} relevant episodes:\n`];
@@ -17,8 +17,14 @@ export function formatScratchpad(pad, filter) {
17
17
  if (filter?.sinceTurn !== undefined) {
18
18
  out = out.filter((it) => (it.turn ?? 0) >= (filter.sinceTurn ?? 0));
19
19
  }
20
- if (filter?.untilTurn !== undefined) {
21
- out = out.filter((it) => (it.turn ?? 0) <= (filter.untilTurn ?? 0));
20
+ // A blank untilTurn arrives as 0 (argument validation converts "" before
21
+ // the handler runs) and `(it.turn ?? 0) <= 0` would drop every item that
22
+ // has a turn, answering a filter-less read with an almost-empty pad. Turn 0
23
+ // is never a real upper bound, so a non-positive bound is no filter - the
24
+ // same gate the limit branch below applies to its blank.
25
+ const untilTurn = filter?.untilTurn;
26
+ if (untilTurn !== undefined && untilTurn > 0) {
27
+ out = out.filter((it) => (it.turn ?? 0) <= untilTurn);
22
28
  }
23
29
  if (filter?.limit !== undefined && filter.limit > 0 && out.length > filter.limit) {
24
30
  out = out.slice(-filter.limit);
@@ -19,6 +19,15 @@ export { RECYCLE, scratchpadClean, capPush, generateLearningId, generateConstrai
19
19
  import { ACTION_DISPATCH } from "./handlers.js";
20
20
  export { ACTION_DISPATCH } from "./handlers.js";
21
21
  import { projectSlugFromCwd, createScratchpad, loadScratchpadFromDisk } from "./persistence.js";
22
+ /**
23
+ * A blank string is "not provided". A client that emits every schema key sends
24
+ * "" for the keys it does not use, and `??` alone keeps that "" as a real value
25
+ * (a blank id would then be looked up literally instead of falling back to the
26
+ * text). Whitespace-only counts as blank: the handlers refuse such text anyway.
27
+ */
28
+ function nonBlank(value) {
29
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
30
+ }
22
31
  function getCache(ctx) {
23
32
  if (!ctx)
24
33
  return { pad: null };
@@ -114,8 +123,8 @@ const scratchpadParams = Type.Object({
114
123
  // the result in the AgentToolResult envelope.
115
124
  async function scratchpadExecute(_toolCallId, params, _signal, _onUpdate, ctx) {
116
125
  const action = params.action;
117
- const text = params.text ?? "";
118
- const idOrText = params.id ?? text;
126
+ const text = nonBlank(params.text) ?? "";
127
+ const idOrText = nonBlank(params.id) ?? text;
119
128
  const pad = await getOrCreateScratchpad(ctx);
120
129
  if (!pad) {
121
130
  return {
@@ -79,8 +79,20 @@ const sessionSchema = Type.Object({
79
79
  })),
80
80
  since: Type.Optional(Type.String({ description: "Only include sessions since this date (YYYY-MM-DD). Optional." })),
81
81
  until: Type.Optional(Type.String({ description: "Only include sessions until this date (YYYY-MM-DD). Optional." })),
82
- limit: Type.Optional(Type.Number({ description: "Max sessions in output (default: 10). Use 0 for all." })),
82
+ limit: Type.Optional(Type.Number({ description: "Max sessions in output (default: 10)" })),
83
83
  });
84
+ /**
85
+ * Read an optional session limit. Argument validation converts a blank string
86
+ * to 0 for `Type.Optional(Type.Number())` and the converted value passes, so
87
+ * the handler cannot tell a blank from a typed 0. 0 used to select the
88
+ * documented "all sessions" mode, which a blank then triggered silently; a
89
+ * deliberate 0 is indistinguishable from a blank after conversion, so the
90
+ * documented default is the safe reading and the unbounded mode is no longer
91
+ * reachable through this selector.
92
+ */
93
+ function positiveLimit(value) {
94
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
95
+ }
84
96
  // Extension
85
97
  export default function sessionRecallExtension(pi) {
86
98
  let currentModel;
@@ -405,9 +417,10 @@ export default function sessionRecallExtension(pi) {
405
417
  }
406
418
  // Total matches
407
419
  const totalMatches = filtered.reduce((sum, m) => sum + m.count, 0);
408
- // Top N sessions
409
- const limit = params.limit ?? 10;
410
- const topSessions = limit > 0 ? filtered.slice(0, limit) : filtered;
420
+ // Top N sessions. A blank limit is read as absent (see positiveLimit),
421
+ // never as the old unbounded mode.
422
+ const limit = positiveLimit(params.limit) ?? 10;
423
+ const topSessions = filtered.slice(0, limit);
411
424
  const lines = [
412
425
  `## Batch: "${params.pattern}"`,
413
426
  ``, //
@@ -618,7 +631,7 @@ export default function sessionRecallExtension(pi) {
618
631
  since: params.since,
619
632
  until: params.until,
620
633
  project: params.project === "all" ? null : (params.project ?? null),
621
- maxFiles: params.limit && params.limit > 0 ? params.limit : undefined,
634
+ maxFiles: positiveLimit(params.limit),
622
635
  });
623
636
  return {
624
637
  content: [{ type: "text", text: formatContextAggregate(aggregate) }],
@@ -681,7 +694,7 @@ export default function sessionRecallExtension(pi) {
681
694
  byMonth[month].count++;
682
695
  byMonth[month].size += s.size;
683
696
  }
684
- const limit = params.limit ?? 10;
697
+ const limit = positiveLimit(params.limit) ?? 10;
685
698
  const topSessions = [...sessionStats].sort((a, b) => b.size - a.size).slice(0, limit);
686
699
  function formatSize(bytes) {
687
700
  if (bytes < 1024)
@@ -9,7 +9,7 @@ import type { MemoryStoresState, Episode } from "./types.js";
9
9
  /**
10
10
  * Sanitize a string by decoding literal `\uXXXX` escape sequences that
11
11
  * may have been written by a previous code path that double-encoded
12
- * unicode (BUG-M3). The agent-facing `recall_search` and `episodes_search`
12
+ * unicode. The agent-facing `recall_search` and `episodes_search`
13
13
  * displays otherwise show literal `\u2192` instead of the real character
14
14
  * `->`. Applied at load time AND at write time (in `addEpisode`) so both
15
15
  * existing data files and new writes are healed.
@@ -13,7 +13,7 @@ const log = createLogger("three-memory-stores:episodes");
13
13
  /**
14
14
  * Sanitize a string by decoding literal `\uXXXX` escape sequences that
15
15
  * may have been written by a previous code path that double-encoded
16
- * unicode (BUG-M3). The agent-facing `recall_search` and `episodes_search`
16
+ * unicode. The agent-facing `recall_search` and `episodes_search`
17
17
  * displays otherwise show literal `\u2192` instead of the real character
18
18
  * `->`. Applied at load time AND at write time (in `addEpisode`) so both
19
19
  * existing data files and new writes are healed.
@@ -68,7 +68,7 @@ export function addEpisode(state, task, solution, outcome, toolSequence, tags =
68
68
  const quality = Math.round(outcomeScore * (toolDiversity * 0.4 + 0.6) * (reasoningDensity * 0.4 + 0.6) * 100) /
69
69
  100;
70
70
  // Sanitize string fields before storing so newly-added episodes
71
- // never reintroduce literal \uXXXX sequences (BUG-M3 hardening).
71
+ // never reintroduce literal \uXXXX sequences.
72
72
  // The load-time sanitizer in index.ts:loadPastEpisodes handles
73
73
  // already-stored entries.
74
74
  const episode = sanitizeEpisode({
@@ -17,7 +17,7 @@
17
17
  import { execFileSync } from "node:child_process";
18
18
  import { Type } from "typebox";
19
19
  import { createLogger } from "../../lib/core/logger.js";
20
- import { acquireLock, releaseLock, getConflicts, getAllLocks, createWorkerBranch, deleteWorkerBranch, getDiff, getCurrentBranch, findRepoRoot, branchExists, gitAvailable, worktreeForBranch, scanAddedLinesForSlop, registerWorker, updateWorker, closeWorker, recordWorkerMerge, readWorkers, checkWorker, parseWorkerStatus, parseWorkerOutcome, decideAdmission, recordAdmissionRefusal, resolveRequestId, computeWorkerStats, workerEffectEvidenceForEntry, WORKER_EFFECT_EVIDENCE_FLAG, WORKER_SPECS, WORKER_OUTCOMES, WORKER_STATUSES, WORKER_STATUS_LAYERS, } from "../../lib/orchestrator/index.js";
20
+ import { acquireLock, releaseLock, getConflicts, getAllLocks, createWorkerBranch, deleteWorkerBranch, getDiff, getCurrentBranch, findRepoRoot, branchExists, gitAvailable, worktreeForBranch, scanAddedLinesForSlop, registerWorker, updateWorker, closeWorker, recordWorkerMerge, readWorkers, checkWorker, parseWorkerStatus, parseWorkerOutcome, decideAdmission, recordAdmissionRefusal, resolveRequestId, computeWorkerStats, workerEffectEvidenceForEntry, locateResultSchema, readPopulationStamps, populationRefusalDetail, WORKER_EFFECT_EVIDENCE_FLAG, WORKER_SPECS, WORKER_OUTCOMES, WORKER_STATUSES, WORKER_STATUS_LAYERS, } from "../../lib/orchestrator/index.js";
21
21
  const log = createLogger("orchestrator");
22
22
  // Helpers
23
23
  /**
@@ -94,12 +94,42 @@ function isAncestor(ancestor, descendant, repoRoot) {
94
94
  function isSafeRef(ref) {
95
95
  return /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(ref);
96
96
  }
97
+ /**
98
+ * The commit census: how many entries the tree at `revision` holds. This is
99
+ * the index-independent equivalent of `git ls-files | wc -l` at that revision
100
+ * — it reads the named revision's tree rather than the caller's index, since
101
+ * the caller's worktree is not necessarily checked out where the gate scanned.
102
+ * Null when git cannot resolve the revision.
103
+ */
104
+ function censusAt(revision, repoRoot) {
105
+ if (!repoRoot)
106
+ return null;
107
+ const out = git(repoRoot, ["ls-tree", "-r", "--name-only", revision]);
108
+ if (out === undefined)
109
+ return null;
110
+ return out === "" ? 0 : out.split("\n").length;
111
+ }
112
+ /**
113
+ * The gate rows the merge path reads its population record from. A row that
114
+ * was already closed carries its recorded gates, and those win; the normal
115
+ * flow merges before close-worker, so the fallback is the worker's result
116
+ * block — the result contract's `gate_evidence`, located in the session the
117
+ * row names. No session and no gates is an empty read, not an error: the
118
+ * comparison is a reader, and a missing record prints as one.
119
+ */
120
+ function closeGateRows(entry) {
121
+ if (entry && Array.isArray(entry.gates) && entry.gates.length > 0)
122
+ return entry.gates;
123
+ const located = locateResultSchema(entry?.workerSession ?? null);
124
+ const rows = located?.schema.gate_evidence;
125
+ return Array.isArray(rows) ? rows : [];
126
+ }
97
127
  /**
98
128
  * Resolve the merge base explicitly, then merge the worker branch into it and
99
129
  * assert the base actually moved. Never infers the base from HEAD; never leaves
100
130
  * the worktree on a different branch; never claims a merge it did not perform.
101
131
  */
102
- function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
132
+ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot, population) {
103
133
  /** A refusal or no-op: nothing was merged, so nothing may be marked merged. */
104
134
  const nothingMerged = (report) => ({
105
135
  report,
@@ -126,6 +156,10 @@ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
126
156
  const short = (sha) => sha.slice(0, 12);
127
157
  const diff = getDiff(workerBranch, base, repoRoot);
128
158
  const scan = surfaceScanReport(diff);
159
+ // The population read rides directly under the outcome line: it is the
160
+ // reason a refusal happened, and on a merge it is the recorded-versus-git
161
+ // pair the merge claim is certified against.
162
+ const populationNote = population.lines.length > 0 ? `\n${population.lines.join("\n")}` : "";
129
163
  const finish = (lead, deletedLead, mergeSha, extraWorktreeNote = "") => {
130
164
  // Where the caller's tree sits is part of the merge result, not a detail:
131
165
  // this tool never switches the shared worktree's branch, so after a merge
@@ -146,7 +180,7 @@ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
146
180
  // what the registry now says.
147
181
  const audit = mergeAuditNote(workerId, mergeSha, repoRoot);
148
182
  return {
149
- report: `${lead}${audit}\nBranch: ${workerBranch} (${deleted ? "deleted" : onWorkerBranch ? "kept: this worktree is on it" : deletedLead})${worktreeNote}${settleBlock}\nDiff summary:\n${diff.slice(0, 2000)}\n${scan}`,
183
+ report: `${lead}${audit}${populationNote}\nBranch: ${workerBranch} (${deleted ? "deleted" : onWorkerBranch ? "kept: this worktree is on it" : deletedLead})${worktreeNote}${settleBlock}\nDiff summary:\n${diff.slice(0, 2000)}\n${scan}`,
150
184
  mergeSha,
151
185
  worktreeBranch: head,
152
186
  };
@@ -156,6 +190,14 @@ function verifyAndMergeBase(workerId, workerBranch, base, repoRoot) {
156
190
  if (isAncestor(tip, base, repoRoot)) {
157
191
  return finish(`Worker ${workerId} already contained in ${base}: ${short(tip)} is an ancestor of ${base} (${short(baseBefore)}). Nothing merged.`, "kept: still checked out", null);
158
192
  }
193
+ // A recorded population below the census at its own revision is the claim
194
+ // this read exists to test: the gate certified fewer tracked entries than
195
+ // that revision holds, so the merge waits for a re-run on the staged tree.
196
+ const standingDetail = populationRefusalDetail(population);
197
+ if (standingDetail) {
198
+ return nothingMerged(`NOT merged: ${standingDetail}\n` +
199
+ `Base unchanged at ${short(baseBefore)}. Locks and branch kept.\n${population.lines.join("\n")}`);
200
+ }
159
201
  // Set when the fast-forward happened in a worktree other than the caller's;
160
202
  // the report names where the base's tree moved, so a reader can act on it.
161
203
  let settleNote = "";
@@ -357,7 +399,7 @@ const orchestrateTool = {
357
399
  name: "orchestrate",
358
400
  label: "Orchestrate",
359
401
  promptSnippet: "Coordinate parallel agent workers (spawn/check/merge, locks)",
360
- description: "Coordinate parallel agent workers to prevent edit conflicts. Auto-detects the repo root (cwd overrides); without git, lock-only. verify-and-merge requires workerId, merges into an explicit base branch (default main), and claims success only when that base ref actually advanced. It never switches a worktree's branch: the caller's tree is left on the branch it was on, named in the report, and a branch is dropped only when it is actually gone. " +
402
+ description: "Coordinate parallel agent workers to prevent edit conflicts. Auto-detects the repo root (cwd overrides); without git, lock-only. verify-and-merge requires workerId, merges into an explicit base branch (default main), and claims success only when that base ref actually advanced. A close's stamped `files` row is compared against the census of the revision it names, and a number below that census refuses the merge before any ref moves. It never switches a worktree's branch: the caller's tree is left on the branch it was on, named in the report, and a branch is dropped only when it is actually gone. " +
361
403
  `Worker lifecycle speaks in four vocabularies: ${renderStatusLayers()}.`,
362
404
  parameters: Type.Object({
363
405
  action: Type.Union([
@@ -414,10 +456,28 @@ const orchestrateTool = {
414
456
  outcome: Type.Optional(Type.String({
415
457
  description: `Terminal outcome for close-worker (${WORKER_OUTCOMES.join("|")}).`,
416
458
  })),
417
- gates: Type.Optional(Type.Array(Type.Object({ cmd: Type.String(), exit: Type.Number() }), {
459
+ gates: Type.Optional(Type.Array(Type.Object({
460
+ cmd: Type.String(),
461
+ exit: Type.Number(),
462
+ stamp: Type.Optional(Type.String({
463
+ description: "Population record for a gate whose subject is a file or row population: " +
464
+ '"scanned <n> <unit> at <revision>" (n a non-negative integer, unit one ' +
465
+ "lowercase word, revision a 7-to-40-char hex sha or a ref name). " +
466
+ "verify-and-merge reads a stamped `files` row against that revision's " +
467
+ "tracked-entry census and refuses the merge when the recorded number sits " +
468
+ "below it.",
469
+ })),
470
+ }), {
418
471
  description: "Gate evidence for close-worker: command plus exit code, recorded with a timestamp. " +
419
472
  `A completed close whose entry carries none of a fresh output file, a branch advance or ` +
420
- `merge, and a passing gate is flagged "${WORKER_EFFECT_EVIDENCE_FLAG}" (advisory, non-blocking).`,
473
+ `merge, and a passing gate is flagged "${WORKER_EFFECT_EVIDENCE_FLAG}" (advisory, non-blocking). ` +
474
+ "Every row is also read for well-formedness at close time (parses under sh -n, first token " +
475
+ "resolves, no top-level decoration, exit 0 under a completed outcome); the read ships in " +
476
+ "shadow mode, so a failing row is logged and the close proceeds, until " +
477
+ 'braid.orchestrator.closeGateWellFormedness is set to "enforce". ' +
478
+ "Rows the seat's production-write class marks as writes are refused unless the close " +
479
+ "records every named preflight piece somewhere in its rows; the class data is the seat's, " +
480
+ "and no class data means no refusal.",
421
481
  })),
422
482
  includeClosed: Type.Optional(Type.Boolean({ description: "list-workers: include closed entries (default false)." })),
423
483
  includeStats: Type.Optional(Type.Boolean({
@@ -695,13 +755,18 @@ Register the worker (orchestrate action=register-worker) for a structured verdic
695
755
  // of the three yields one.
696
756
  const lockRows = getAllLocks(repoRoot);
697
757
  const lockBranch = Object.values(lockRows).find((row) => row.workerId === workerId)?.branch;
698
- const entryBranch = readWorkers(repoRoot).workers[workerId]?.branch ?? undefined;
758
+ const entry = readWorkers(repoRoot).workers[workerId];
759
+ const entryBranch = entry?.branch ?? undefined;
699
760
  const workerBranch = branch ?? entryBranch ?? lockBranch;
700
761
  if (!workerBranch) {
701
762
  return textResult(`Worker ${workerId} has no branch to verify: no branch argument, no branch on its ` +
702
763
  `registry entry, and no lock rows. Nothing to verify.`);
703
764
  }
704
- const outcome = verifyAndMergeBase(workerId, workerBranch, baseBranch ?? "main", repoRoot);
765
+ // The close's population record is read before the merge: the stamped
766
+ // rows are the reporter's own numbers, and the census they are compared
767
+ // against comes from git alone.
768
+ const population = readPopulationStamps(closeGateRows(entry), (revision) => censusAt(revision, repoRoot));
769
+ const outcome = verifyAndMergeBase(workerId, workerBranch, baseBranch ?? "main", repoRoot, population);
705
770
  // The merge sha travels in details as well as in the report, so a
706
771
  // parent can verify the claim it was handed without parsing prose; the
707
772
  // worktree branch travels with it, because a merge that leaves the
@@ -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,