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
@@ -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;
@@ -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));
@@ -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({