pi-braid 0.40.1 → 0.40.2

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 (84) 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/hypothesize.d.ts +9 -0
  6. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.js +13 -1
  7. package/dist/extensions/cognitive/metacognition/handlers/verify.js +35 -4
  8. package/dist/extensions/core/prompt-builder/inspect.js +9 -3
  9. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.d.ts +1 -1
  10. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.js +1 -1
  11. package/dist/extensions/enforcement/handlers/turn-end-handler.js +1 -1
  12. package/dist/extensions/enforcement/self-state-claims.d.ts +1 -1
  13. package/dist/extensions/enforcement/self-state-claims.js +3 -2
  14. package/dist/extensions/manifest.js +2 -2
  15. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.d.ts +22 -5
  16. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.js +43 -11
  17. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +174 -50
  18. package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.js +4 -1
  19. package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.js +16 -0
  20. package/dist/extensions/memory/memory-agent-bridge/memory-tool.js +21 -9
  21. package/dist/extensions/memory/scratchpad/format.js +8 -2
  22. package/dist/extensions/memory/scratchpad/index.js +11 -2
  23. package/dist/extensions/memory/session-recall/index.js +19 -6
  24. package/dist/extensions/memory/three-memory-stores/episodes.d.ts +1 -1
  25. package/dist/extensions/memory/three-memory-stores/episodes.js +2 -2
  26. package/dist/extensions/orchestrator/index.js +73 -8
  27. package/dist/extensions/self/health-maintenance/index.js +112 -9
  28. package/dist/lib/config/braid-settings.d.ts +21 -0
  29. package/dist/lib/config/braid-settings.js +36 -0
  30. package/dist/lib/constants/session-thresholds.d.ts +2 -3
  31. package/dist/lib/constants/session-thresholds.js +2 -3
  32. package/dist/lib/enforcement/turn-dedup.d.ts +2 -2
  33. package/dist/lib/enforcement/turn-dedup.js +2 -2
  34. package/dist/lib/harness/index.d.ts +1 -1
  35. package/dist/lib/harness/index.js +1 -1
  36. package/dist/lib/harness/types.d.ts +1 -1
  37. package/dist/lib/harness/types.js +1 -1
  38. package/dist/lib/orchestrator/index.d.ts +2 -2
  39. package/dist/lib/orchestrator/index.js +1 -1
  40. package/dist/lib/orchestrator/workers.d.ts +184 -2
  41. package/dist/lib/orchestrator/workers.js +521 -6
  42. package/dist/lib/utils/injection-tracker.js +1 -1
  43. package/docs/CONTEXT-POLICY.md +13 -5
  44. package/docs/LOCAL_DEV.md +31 -5
  45. package/docs/ROADMAP.md +10 -7
  46. package/docs/SETUP.md +3 -2
  47. package/package.json +11 -8
  48. package/skills/braid-reference/SKILL.md +23 -23
  49. package/skills/release-pipeline/SKILL.md +46 -37
  50. package/skills/subagent-orchestration/SKILL.md +51 -1
  51. package/src/extensions/cognitive/metacognition/handlers/hypothesize.ts +14 -1
  52. package/src/extensions/cognitive/metacognition/handlers/verify.ts +39 -5
  53. package/src/extensions/core/prompt-builder/inspect.ts +10 -3
  54. package/src/extensions/enforcement/AGENTS.md +25 -19
  55. package/src/extensions/enforcement/handlers/register-tool-result-formatting.ts +1 -1
  56. package/src/extensions/enforcement/handlers/turn-end-handler.ts +1 -1
  57. package/src/extensions/enforcement/self-state-claims.ts +3 -2
  58. package/src/extensions/heartbeat/heartbeat-scheduler/AGENTS.md +6 -3
  59. package/src/extensions/manifest.ts +2 -2
  60. package/src/extensions/memory/AGENTS.md +13 -5
  61. package/src/extensions/memory/context-manager/handlers/tool-batch-boundary.ts +45 -11
  62. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +202 -60
  63. package/src/extensions/memory/context-manager/handlers/tools/context-navigate.ts +4 -1
  64. package/src/extensions/memory/memory-agent-bridge/memory-store-tool.ts +16 -0
  65. package/src/extensions/memory/memory-agent-bridge/memory-tool.ts +22 -9
  66. package/src/extensions/memory/scratchpad/format.ts +8 -2
  67. package/src/extensions/memory/scratchpad/index.ts +12 -2
  68. package/src/extensions/memory/session-recall/index.ts +20 -8
  69. package/src/extensions/memory/three-memory-stores/episodes.ts +2 -2
  70. package/src/extensions/orchestrator/index.ts +100 -11
  71. package/src/extensions/scheduling/timer/AGENTS.md +7 -0
  72. package/src/extensions/self/health-maintenance/index.ts +143 -14
  73. package/src/extensions/self/watchdog/AGENTS.md +1 -0
  74. package/src/lib/AGENTS.md +21 -21
  75. package/src/lib/config/braid-settings.ts +74 -0
  76. package/src/lib/constants/session-thresholds.ts +2 -3
  77. package/src/lib/enforcement/turn-dedup.ts +2 -2
  78. package/src/lib/harness/AGENTS.md +1 -1
  79. package/src/lib/harness/index.ts +1 -1
  80. package/src/lib/harness/types.ts +1 -1
  81. package/src/lib/orchestrator/index.ts +26 -0
  82. package/src/lib/orchestrator/workers.ts +705 -7
  83. package/src/lib/utils/AGENTS.md +1 -1
  84. package/src/lib/utils/injection-tracker.ts +1 -1
@@ -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
  }