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
@@ -28,6 +28,7 @@
28
28
  export const SELF_STATE_PROBE_TOOLS = [
29
29
  "session_health",
30
30
  "health_maintenance",
31
+ "tunnel_status",
31
32
  "v2raytun_status",
32
33
  "telegram_send",
33
34
  ];
@@ -90,7 +91,7 @@ export const SELF_STATE_PATTERNS = [
90
91
  */
91
92
  const NEGATION_HEDGE = /\b(?:not|no|never|neither|nor|without|cannot|can't|won't|wouldn't|couldn't|shouldn't|isn't|aren't|wasn't|weren't|doesn't|didn't|stopped|stopping|offline|unavailable|unreachable|unverified|uncertain|unconfirmed|unknown|unsure|may|might|could|possibly|probably|presumably|perhaps|unlikely|doubtful|down|dead|crashed|died|flaky)\b/i;
92
93
  /** 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. */
93
- const PROBE_NAME = /(?:session_health|health_maintenance|v2raytun_status|telegram_send|telegram_poller)/i;
94
+ const PROBE_NAME = /(?:session_health|health_maintenance|tunnel_status|v2raytun_status|telegram_send|telegram_poller)/i;
94
95
  /**
95
96
  * Does the evidence window contain a probe call? toolsUsed matches by exact
96
97
  * tool name; evidence/log lines match by substring (tool names render inline,
@@ -161,7 +162,7 @@ export function renderSelfStateClaimsSection(claims) {
161
162
  if (claims.length > listed.length) {
162
163
  lines.push(`(${claims.length - listed.length} more matched claim(s) suppressed, cap ${MAX_SELF_STATE_CLAIMS_IN_PROMPT})`);
163
164
  }
164
- lines.push("", "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.", '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.');
165
+ lines.push("", "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.", '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.');
165
166
  return lines.join("\n");
166
167
  }
167
168
  //# sourceMappingURL=self-state-claims.js.map
@@ -126,7 +126,7 @@ export const MANIFEST = [
126
126
  id: "session-recall",
127
127
  fn: sessionRecallFn,
128
128
  dependencies: ["three-memory-stores"],
129
- desc: "Session recall tools (session_search, session_query)",
129
+ desc: "Session recall tool (session)",
130
130
  module: "memory",
131
131
  },
132
132
  {
@@ -220,7 +220,7 @@ export const MANIFEST = [
220
220
  fn: errorCaptureFn,
221
221
  disabledByDefault: true,
222
222
  dependencies: ["agent-environment"],
223
- desc: "Error logging tools: error_list, error_get",
223
+ desc: "Error logging tool (error)",
224
224
  },
225
225
  ];
226
226
  const _byId = new Map(MANIFEST.map((e) => [e.id, e]));
@@ -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.
@@ -27,21 +37,28 @@
27
37
  export declare const MIN_KEPT_ENTRIES = 1;
28
38
  /**
29
39
  * The structurally invalid shape of a kept slice [candidateIndex..end]:
30
- * either it begins with a tool result (its call fell outside the slice), or it
31
- * contains an assistant whose tool_calls are not fully answered inside it.
32
- * Returns null for a valid slice. Exported for tests and audit surfaces.
40
+ * either its first message is a tool result (its call fell outside the slice),
41
+ * or it contains an assistant whose tool_calls are not fully answered inside
42
+ * it. Non-message entries between the candidate and the first message are
43
+ * stepped over: they are not provider messages, so they neither open the
44
+ * slice nor hide a bare result behind them. Returns null for a valid slice.
45
+ * Exported for tests and audit surfaces.
33
46
  */
34
47
  export declare function findBoundaryViolation(entries: readonly unknown[], candidateIndex: number): {
35
48
  kind: "leading-tool-result" | "unanswered-tool-calls";
36
49
  entryId?: string;
50
+ /** Index of the offending tool-result entry (leading-tool-result). */
51
+ resultIndex?: number;
37
52
  /** Index of the offending assistant entry (unanswered-tool-calls). */
38
53
  assistantIndex?: number;
39
54
  } | null;
40
55
  /**
41
56
  * Snap a candidate first-kept index so the kept slice [result..end] cannot
42
57
  * split a tool batch:
43
- * - a candidate landing mid-batch snaps FORWARD to the first entry after
44
- * the batch's last tool result (parallel calls are one batch of N results);
58
+ * - a candidate landing mid-batch - including on a non-message entry whose
59
+ * first following message is mid-batch - snaps FORWARD to the first entry
60
+ * after the batch's last tool result (parallel calls are one batch of N
61
+ * results);
45
62
  * - when that would keep less than `MIN_KEPT_ENTRIES`, it snaps BACKWARD to
46
63
  * the batch's assistant message instead, keeping the whole batch live;
47
64
  * - a leading result whose call is no longer in the branch (summarized away)
@@ -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.
@@ -63,20 +73,39 @@ function toolCallIdsOf(entry) {
63
73
  }
64
74
  return ids;
65
75
  }
76
+ /**
77
+ * Index of the first message entry at or after `fromIndex`; non-message
78
+ * session entries carry no provider message and are stepped over. Equals
79
+ * `entries.length` when no message remains.
80
+ */
81
+ function firstMessageIndex(entries, fromIndex) {
82
+ let i = fromIndex;
83
+ while (i < entries.length && entryOf(entries[i])?.type !== "message")
84
+ i++;
85
+ return i;
86
+ }
66
87
  /**
67
88
  * The structurally invalid shape of a kept slice [candidateIndex..end]:
68
- * either it begins with a tool result (its call fell outside the slice), or it
69
- * contains an assistant whose tool_calls are not fully answered inside it.
70
- * Returns null for a valid slice. Exported for tests and audit surfaces.
89
+ * either its first message is a tool result (its call fell outside the slice),
90
+ * or it contains an assistant whose tool_calls are not fully answered inside
91
+ * it. Non-message entries between the candidate and the first message are
92
+ * stepped over: they are not provider messages, so they neither open the
93
+ * slice nor hide a bare result behind them. Returns null for a valid slice.
94
+ * Exported for tests and audit surfaces.
71
95
  */
72
96
  export function findBoundaryViolation(entries, candidateIndex) {
73
97
  if (!Array.isArray(entries) || candidateIndex < 0 || candidateIndex >= entries.length) {
74
98
  return null;
75
99
  }
76
- if (isToolResultEntry(entryOf(entries[candidateIndex]))) {
77
- return { kind: "leading-tool-result", entryId: entryOf(entries[candidateIndex])?.id };
100
+ const firstMessage = firstMessageIndex(entries, candidateIndex);
101
+ if (isToolResultEntry(entryOf(entries[firstMessage]))) {
102
+ return {
103
+ kind: "leading-tool-result",
104
+ entryId: entryOf(entries[firstMessage])?.id,
105
+ resultIndex: firstMessage,
106
+ };
78
107
  }
79
- for (let i = candidateIndex; i < entries.length; i++) {
108
+ for (let i = firstMessage; i < entries.length; i++) {
80
109
  for (const id of toolCallIdsOf(entryOf(entries[i]))) {
81
110
  let answered = false;
82
111
  for (let j = i + 1; j < entries.length; j++) {
@@ -133,8 +162,10 @@ function firstNonToolResultIndex(entries, fromIndex) {
133
162
  /**
134
163
  * Snap a candidate first-kept index so the kept slice [result..end] cannot
135
164
  * split a tool batch:
136
- * - a candidate landing mid-batch snaps FORWARD to the first entry after
137
- * the batch's last tool result (parallel calls are one batch of N results);
165
+ * - a candidate landing mid-batch - including on a non-message entry whose
166
+ * first following message is mid-batch - snaps FORWARD to the first entry
167
+ * after the batch's last tool result (parallel calls are one batch of N
168
+ * results);
138
169
  * - when that would keep less than `MIN_KEPT_ENTRIES`, it snaps BACKWARD to
139
170
  * the batch's assistant message instead, keeping the whole batch live;
140
171
  * - a leading result whose call is no longer in the branch (summarized away)
@@ -153,12 +184,13 @@ export function snapBoundaryOutsideToolBatch(entries, candidateIndex) {
153
184
  if (!violation)
154
185
  return index;
155
186
  if (violation.kind === "leading-tool-result") {
156
- const owner = findOwningAssistant(entries, index);
187
+ const resultIndex = violation.resultIndex ?? index;
188
+ const owner = findOwningAssistant(entries, resultIndex);
157
189
  if (owner < 0) {
158
190
  // The call is outside the branch: the only valid repair is dropping
159
191
  // the orphaned results.
160
- const after = firstNonToolResultIndex(entries, index);
161
- if (after > index && entries.length - after >= MIN_KEPT_ENTRIES) {
192
+ const after = firstNonToolResultIndex(entries, resultIndex);
193
+ if (after > resultIndex && entries.length - after >= MIN_KEPT_ENTRIES) {
162
194
  index = after;
163
195
  continue;
164
196
  }
@@ -58,6 +58,37 @@ function captureUsage(ctx) {
58
58
  return null;
59
59
  }
60
60
  }
61
+ // Blank optional selectors.
62
+ //
63
+ // Some clients emit every schema property and send "" for the ones they do
64
+ // not use. A blank string is "absent": a tag lookup or a percent parse on ""
65
+ // would otherwise reject a call that named nothing. Blank NUMERIC selectors
66
+ // are harder - the framework validates arguments before any handler runs and
67
+ // converts "" to 0 - so a numeric optional cannot tell a blank from a typed
68
+ // 0; the archive range guard reads the {0,0} index pair as the blank
69
+ // signature instead.
70
+ /** The non-blank string a selector names, or undefined when it names none. */
71
+ function optionalString(v) {
72
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
73
+ }
74
+ /** The finite number a selector names, or undefined when it names none. */
75
+ function optionalNumber(v) {
76
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
77
+ }
78
+ /**
79
+ * Marker for a tool_execution_start whose event carries no usable call id.
80
+ * A SYMBOL, never a string: every string is a possible call id and a marker
81
+ * that is one can be deleted by a persisted result that happens to name it,
82
+ * which drained the batch at a boundary the unidentifiable start had not
83
+ * reached. A symbol cannot equal any persisted id, so the marker keeps every
84
+ * boundary conservative and is released only by the AGENT_SETTLED backstop.
85
+ */
86
+ const UNIDENTIFIED_TOOL_CALL = Symbol("unidentified-tool-call-start");
87
+ /** The non-empty call id an event names, or undefined when it names none. */
88
+ function toolCallIdOf(event) {
89
+ const id = event?.toolCallId;
90
+ return typeof id === "string" && id.length > 0 ? id : undefined;
91
+ }
61
92
  /**
62
93
  * The pending list is bounded: one entry per armed action, capped so a
63
94
  * pathological re-arming loop cannot grow it without bound. Beyond the cap the
@@ -70,10 +101,25 @@ function captureUsage(ctx) {
70
101
  const PENDING_COMPACT_QUEUE_MAX = 8;
71
102
  function getBatchSettleState(ctx) {
72
103
  return getExtensionState(ctx, "context-manager/batch-settle", () => ({
73
- inFlight: 0,
104
+ activeToolCallIds: new Set(),
74
105
  pending: [],
75
106
  }));
76
107
  }
108
+ /**
109
+ * Release the call ids a turn's persisted tool results account for. A result
110
+ * with no usable id is ignored: an unmatched active id stays protective, so a
111
+ * malformed event can only delay a drain to a later boundary or the settle
112
+ * backstop, never release a sibling that is still executing.
113
+ */
114
+ function releaseSettledToolCallIds(st, toolResults) {
115
+ if (!Array.isArray(toolResults))
116
+ return;
117
+ for (const result of toolResults) {
118
+ const id = toolCallIdOf(result);
119
+ if (id)
120
+ st.activeToolCallIds.delete(id);
121
+ }
122
+ }
77
123
  /**
78
124
  * Read the pending queue without creating state (inspect surfaces it).
79
125
  * Exported so context_inspect and the heartbeat advisory can report
@@ -162,7 +208,7 @@ function coalesceIntoSlide(ctx, queue) {
162
208
  }
163
209
  }
164
210
  function firePendingCompactionsIfSettled(ctx, st) {
165
- if (st.pending.length === 0 || st.inFlight > 0)
211
+ if (st.pending.length === 0 || st.activeToolCallIds.size > 0)
166
212
  return;
167
213
  const queue = st.pending;
168
214
  st.pending = [];
@@ -440,26 +486,29 @@ export const contextCompressSchema = Type.Object({
440
486
  })),
441
487
  });
442
488
  export function registerContextCompress(pi) {
443
- // Batch-settle scheduling: track in-flight tool executions per session and
444
- // fire the deferred compaction ONLY at agent_settled — the moment the whole
445
- // agent run settles (session idle/promptable). Never mid-batch (would drop
446
- // a parallel sibling's result) and never at tool_execution_end (the run is
447
- // still live there — an aborting compact would surface a spurious
448
- // "This operation was aborted" error and tear the finishing turn).
449
- onEvent(pi, TOOL_EXECUTION_START, (_event, ctx) => {
489
+ // Batch-settle scheduling: track the ACTIVE tool calls of every running
490
+ // batch by call id and fire the deferred compaction only at a safe boundary
491
+ // (turn_end or agent_settled). Never mid-batch (would drop a parallel
492
+ // sibling's result) and never at tool_execution_end (the run is still live
493
+ // there — an aborting compact would surface a spurious "This operation was
494
+ // aborted" error and tear the finishing turn).
495
+ onEvent(pi, TOOL_EXECUTION_START, (event, ctx) => {
450
496
  try {
451
- getBatchSettleState(ctx).inFlight++;
497
+ const st = getBatchSettleState(ctx);
498
+ st.activeToolCallIds.add(toolCallIdOf(event) ?? UNIDENTIFIED_TOOL_CALL);
452
499
  }
453
500
  catch {
454
501
  // Settle tracking is unavailable — the pending compact then only fires
455
502
  // via AGENT_SETTLED below, which is the conservative path.
456
503
  }
457
504
  });
458
- onEvent(pi, TOOL_EXECUTION_END, (_event, ctx) => {
505
+ onEvent(pi, TOOL_EXECUTION_END, (event, ctx) => {
459
506
  try {
460
- const st = getBatchSettleState(ctx);
461
- if (st.inFlight > 0)
462
- st.inFlight--;
507
+ const id = toolCallIdOf(event);
508
+ // Only this call's id is released: a sibling's id survives its own end
509
+ // event, so the batch stays active until that sibling releases too.
510
+ if (id)
511
+ getBatchSettleState(ctx).activeToolCallIds.delete(id);
463
512
  // NOTE: do NOT fire here. The run is still active (the agent is
464
513
  // processing this tool's result and streaming its next response); an
465
514
  // aborting compact now would surface a spurious "This operation was
@@ -471,19 +520,24 @@ export function registerContextCompress(pi) {
471
520
  // AGENT_SETTLED handler remains the conservative trigger.
472
521
  }
473
522
  });
474
- onEvent(pi, TURN_END, (_event, ctx) => {
523
+ onEvent(pi, TURN_END, (event, ctx) => {
475
524
  // Between-turns boundary: the turn's assistant message and tool results
476
525
  // are already persisted when turn_end fires, so the abort inside
477
- // ctx.compact() cannot tear a live turn or drop a sibling result. A run
478
- // kept alive by continuous steers never reaches agent_settled — this
479
- // boundary keeps an armed compaction from stalling behind live work. A
480
- // steer queued at this moment survives: the loop appends it before the
481
- // aborted response stream, and its turn runs on the post-compaction
482
- // resume. inFlight is NOT reset here (only agent_settled owns that
483
- // backstop); a missed tool_execution_end keeps the boundary conservative.
526
+ // ctx.compact() cannot tear a live turn or drop a sibling result. The
527
+ // persisted results carry the toolCallIds of the calls they answer, which
528
+ // releases a call whose tool_execution_end never arrived; an active id
529
+ // with NO result in this event is kept (it may still be executing, and a
530
+ // count could not tell which sibling completed). A run kept alive by
531
+ // continuous steers never reaches agent_settled — this boundary keeps an
532
+ // armed compaction from stalling behind live work. A steer queued at this
533
+ // moment survives: the loop appends it before the aborted response stream,
534
+ // and its turn runs on the post-compaction resume. Ids are never blanket-
535
+ // reset here (only agent_settled owns that backstop, which is what keeps a
536
+ // missed end event from parking the queue forever).
484
537
  try {
485
538
  const st = getBatchSettleState(ctx);
486
- if (st.pending.length === 0 || st.inFlight > 0)
539
+ releaseSettledToolCallIds(st, event?.toolResults);
540
+ if (st.pending.length === 0 || st.activeToolCallIds.size > 0)
487
541
  return;
488
542
  if (isCompactionActive(ctx))
489
543
  return;
@@ -498,13 +552,14 @@ export function registerContextCompress(pi) {
498
552
  // Backstop boundary: the run has fully settled, so ctx.compact()'s
499
553
  // abort() is a clean no-op — no spurious abort error, no torn turn, and
500
554
  // the post-compaction resume wake lands when the session is
501
- // idle/promptable. The whole pending queue drains here (coalesced);
502
- // inFlight is reset so parked compactions always fire even if a
503
- // sibling's end event never arrived. Turn boundaries drain first when a
504
- // run stays alive; this handler catches everything they cannot reach.
555
+ // idle/promptable. The whole pending queue drains here (coalesced); the
556
+ // active set is cleared so parked compactions always fire even when a
557
+ // start never saw its end and no turn boundary ever accounted for it.
558
+ // Turn boundaries drain first when a run stays alive; this handler catches
559
+ // everything they cannot reach.
505
560
  try {
506
561
  const st = getBatchSettleState(ctx);
507
- st.inFlight = 0;
562
+ st.activeToolCallIds.clear();
508
563
  firePendingCompactionsIfSettled(ctx, st);
509
564
  }
510
565
  catch {
@@ -671,68 +726,122 @@ export function registerContextCompress(pi) {
671
726
  const usageBefore = captureUsage(ctx);
672
727
  const sessionLength = analyzeSession(ctx).branchLength;
673
728
  // Resolve range via priority: startTag/endTag > beforeTag > range > keepRecentTurns > startIndex/endIndex > auto
674
- let startIndex = params.startIndex;
675
- let endIndex = params.endIndex;
729
+ const startTag = optionalString(params.startTag);
730
+ const endTag = optionalString(params.endTag);
731
+ const beforeTag = optionalString(params.beforeTag);
732
+ const range = optionalString(params.range);
733
+ const keepRecentTurns = optionalNumber(params.keepRecentTurns);
734
+ const rawStartIndex = optionalNumber(params.startIndex);
735
+ const rawEndIndex = optionalNumber(params.endIndex);
736
+ let startIndex = rawStartIndex;
737
+ let endIndex = rawEndIndex;
738
+ const hasStringSelector = startTag !== undefined ||
739
+ endTag !== undefined ||
740
+ beforeTag !== undefined ||
741
+ range !== undefined;
742
+ // 0 turns is never a usable instruction (priority 3 refuses it), so a
743
+ // 0 here is a blank conversion too.
744
+ const keepRecentTurnsNamed = keepRecentTurns !== undefined && keepRecentTurns > 0;
745
+ // The blank numeric signature: a blank-filled call arrives as
746
+ // {startIndex: 0, endIndex: 0}, a pair that selects nothing a caller
747
+ // could have meant (a real 0 start bound travels with a non-zero
748
+ // end). Refuse before any state write when nothing else names a
749
+ // span; otherwise read the pair as absent and let the named selector
750
+ // decide.
751
+ if (rawStartIndex === 0 && rawEndIndex === 0) {
752
+ if (!hasStringSelector && !keepRecentTurnsNamed) {
753
+ return {
754
+ content: [
755
+ {
756
+ type: "text",
757
+ text: "context_compress archive: startIndex/endIndex both resolved to 0 and no " +
758
+ "tag/range/keepRecentTurns was given; blank numeric selectors cannot select " +
759
+ "a span. Name startTag/endTag/beforeTag/range/keepRecentTurns instead.",
760
+ },
761
+ ],
762
+ details: { action, error: "blank numeric selectors named no span" },
763
+ };
764
+ }
765
+ startIndex = undefined;
766
+ endIndex = undefined;
767
+ }
676
768
  // Priority 1: Tag-based range
677
- if (params.startTag !== undefined) {
678
- const idx = resolveTagToIndex(ctx, params.startTag);
769
+ if (startTag !== undefined) {
770
+ const idx = resolveTagToIndex(ctx, startTag);
679
771
  if (idx < 0) {
680
772
  return {
681
773
  content: [
682
774
  {
683
775
  type: "text",
684
- text: `Tag '${params.startTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
776
+ text: `Tag '${startTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
685
777
  },
686
778
  ],
687
- details: { action, error: `tag not found: ${params.startTag}` },
779
+ details: { action, error: `tag not found: ${startTag}` },
688
780
  };
689
781
  }
690
782
  startIndex = idx;
691
- if (params.endTag !== undefined) {
692
- const idxEnd = resolveTagToIndex(ctx, params.endTag);
783
+ if (endTag !== undefined) {
784
+ const idxEnd = resolveTagToIndex(ctx, endTag);
693
785
  if (idxEnd < 0) {
694
786
  return {
695
787
  content: [
696
788
  {
697
789
  type: "text",
698
- text: `Tag '${params.endTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
790
+ text: `Tag '${endTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
699
791
  },
700
792
  ],
701
- details: { action, error: `tag not found: ${params.endTag}` },
793
+ details: { action, error: `tag not found: ${endTag}` },
702
794
  };
703
795
  }
704
796
  endIndex = idxEnd;
705
797
  }
706
798
  }
799
+ // A start tag names where the archive begins, not where it ends:
800
+ // without a usable end bound the resolution below would either
801
+ // auto-clobber the resolved start index (endIndex absent) or die on
802
+ // the generic invalid-range sentence (endIndex 0 from a blank).
803
+ if (startTag !== undefined &&
804
+ endTag === undefined &&
805
+ (endIndex === undefined || endIndex <= 0)) {
806
+ return {
807
+ content: [
808
+ {
809
+ type: "text",
810
+ text: "startTag requires endTag or endIndex; use beforeTag to archive everything before a tag.",
811
+ },
812
+ ],
813
+ details: { action, error: "startTag without endTag or endIndex" },
814
+ };
815
+ }
707
816
  // Priority 1b: beforeTag convenience (archive everything before this tag)
708
- if (startIndex === undefined && params.beforeTag !== undefined) {
709
- const idx = resolveTagToIndex(ctx, params.beforeTag);
817
+ if (startIndex === undefined && beforeTag !== undefined) {
818
+ const idx = resolveTagToIndex(ctx, beforeTag);
710
819
  if (idx < 0) {
711
820
  return {
712
821
  content: [
713
822
  {
714
823
  type: "text",
715
- text: `Tag '${params.beforeTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
824
+ text: `Tag '${beforeTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
716
825
  },
717
826
  ],
718
- details: { action, error: `tag not found: ${params.beforeTag}` },
827
+ details: { action, error: `tag not found: ${beforeTag}` },
719
828
  };
720
829
  }
721
830
  startIndex = 0;
722
831
  endIndex = Math.max(0, idx - 1);
723
832
  }
724
833
  // Priority 2: Percentage-based range
725
- if (params.range !== undefined && (startIndex === undefined || endIndex === undefined)) {
726
- const match = String(params.range).match(/^(\d+)%$/);
834
+ if (range !== undefined && (startIndex === undefined || endIndex === undefined)) {
835
+ const match = range.match(/^(\d+)%$/);
727
836
  if (!match) {
728
837
  return {
729
838
  content: [
730
839
  {
731
840
  type: "text",
732
- text: `Invalid range format: '${params.range}'. Use 'N%' e.g. '80%'.`,
841
+ text: `Invalid range format: '${range}'. Use 'N%' e.g. '80%'.`,
733
842
  },
734
843
  ],
735
- details: { action, error: `invalid range: ${params.range}` },
844
+ details: { action, error: `invalid range: ${range}` },
736
845
  };
737
846
  }
738
847
  const pct = parseInt(match[1], 10);
@@ -752,9 +861,8 @@ export function registerContextCompress(pi) {
752
861
  endIndex = count - 1;
753
862
  }
754
863
  // Priority 3: Keep-recent-turns
755
- if ((startIndex === undefined || endIndex === undefined) &&
756
- params.keepRecentTurns !== undefined) {
757
- const keep = params.keepRecentTurns;
864
+ if ((startIndex === undefined || endIndex === undefined) && keepRecentTurns !== undefined) {
865
+ const keep = keepRecentTurns;
758
866
  if (keep <= 0) {
759
867
  return {
760
868
  content: [
@@ -794,6 +902,22 @@ export function registerContextCompress(pi) {
794
902
  endIndex = archiveCount - 1;
795
903
  }
796
904
  if (startIndex < 0 || endIndex < startIndex) {
905
+ // endIndex 0 under a positive startIndex is the blank-selector
906
+ // signature, not a number the caller typed: name the hypothesis.
907
+ // Genuinely invalid numbers keep the generic sentence.
908
+ if (endIndex === 0 && startIndex > 0) {
909
+ return {
910
+ content: [
911
+ {
912
+ type: "text",
913
+ text: `Invalid range: endIndex is 0 while startIndex is ${startIndex} - a blank ` +
914
+ `endIndex selector ("") is converted to 0 by argument validation; send a ` +
915
+ `real endIndex or name the span with beforeTag/range.`,
916
+ },
917
+ ],
918
+ details: { action, error: "endIndex 0 (blank selector) below startIndex" },
919
+ };
920
+ }
797
921
  return {
798
922
  content: [
799
923
  {
@@ -946,7 +1070,7 @@ export function registerContextCompress(pi) {
946
1070
  },
947
1071
  };
948
1072
  }
949
- const tagName = params.tagName ?? "before-cleanup";
1073
+ const tagName = optionalString(params.tagName) ?? "before-cleanup";
950
1074
  const usageBefore = captureUsage(ctx);
951
1075
  try {
952
1076
  const sm = ctx.sessionManager;
@@ -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));
@@ -34,7 +34,10 @@ export const contextNavigateSchema = Type.Object({
34
34
  });
35
35
  function formatLog(ctx, sm, params) {
36
36
  const verbose = params.verbose ?? false;
37
- const limit = params.limit ?? 50;
37
+ // Argument validation converts a blank limit to 0, and slice(-0) is
38
+ // slice(0): a blank limit would dump the whole visible history. A
39
+ // non-positive bound is read as absent and the documented default applies.
40
+ const limit = typeof params.limit === "number" && params.limit > 0 ? params.limit : 50;
38
41
  const branch = sm.getBranch();
39
42
  const currentLeafId = sm.getLeafId();
40
43
  const backboneIds = new Set(branch.map((e) => e.id));
@@ -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