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.
- package/CONTRIBUTING.md +27 -3
- package/README.md +13 -13
- package/TOOLS.md +27 -3
- package/build-info.json +9 -0
- package/dist/extensions/cognitive/metacognition/handlers/hypothesize.d.ts +9 -0
- package/dist/extensions/cognitive/metacognition/handlers/hypothesize.js +13 -1
- package/dist/extensions/cognitive/metacognition/handlers/verify.js +35 -4
- package/dist/extensions/core/prompt-builder/inspect.js +9 -3
- package/dist/extensions/enforcement/handlers/register-tool-result-formatting.d.ts +1 -1
- package/dist/extensions/enforcement/handlers/register-tool-result-formatting.js +1 -1
- package/dist/extensions/enforcement/handlers/turn-end-handler.js +1 -1
- package/dist/extensions/enforcement/self-state-claims.d.ts +1 -1
- package/dist/extensions/enforcement/self-state-claims.js +3 -2
- package/dist/extensions/manifest.js +2 -2
- package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.d.ts +22 -5
- package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.js +43 -11
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +174 -50
- package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.js +4 -1
- package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.js +16 -0
- package/dist/extensions/memory/memory-agent-bridge/memory-tool.js +21 -9
- package/dist/extensions/memory/scratchpad/format.js +8 -2
- package/dist/extensions/memory/scratchpad/index.js +11 -2
- package/dist/extensions/memory/session-recall/index.js +19 -6
- package/dist/extensions/memory/three-memory-stores/episodes.d.ts +1 -1
- package/dist/extensions/memory/three-memory-stores/episodes.js +2 -2
- package/dist/extensions/orchestrator/index.js +73 -8
- package/dist/extensions/self/health-maintenance/index.js +112 -9
- package/dist/lib/config/braid-settings.d.ts +21 -0
- package/dist/lib/config/braid-settings.js +36 -0
- package/dist/lib/constants/session-thresholds.d.ts +2 -3
- package/dist/lib/constants/session-thresholds.js +2 -3
- package/dist/lib/enforcement/turn-dedup.d.ts +2 -2
- package/dist/lib/enforcement/turn-dedup.js +2 -2
- package/dist/lib/harness/index.d.ts +1 -1
- package/dist/lib/harness/index.js +1 -1
- package/dist/lib/harness/types.d.ts +1 -1
- package/dist/lib/harness/types.js +1 -1
- package/dist/lib/orchestrator/index.d.ts +2 -2
- package/dist/lib/orchestrator/index.js +1 -1
- package/dist/lib/orchestrator/workers.d.ts +184 -2
- package/dist/lib/orchestrator/workers.js +521 -6
- package/dist/lib/utils/injection-tracker.js +1 -1
- package/docs/CONTEXT-POLICY.md +13 -5
- package/docs/LOCAL_DEV.md +31 -5
- package/docs/ROADMAP.md +10 -7
- package/docs/SETUP.md +3 -2
- package/package.json +11 -8
- package/skills/braid-reference/SKILL.md +23 -23
- package/skills/release-pipeline/SKILL.md +46 -37
- package/skills/subagent-orchestration/SKILL.md +51 -1
- package/src/extensions/cognitive/metacognition/handlers/hypothesize.ts +14 -1
- package/src/extensions/cognitive/metacognition/handlers/verify.ts +39 -5
- package/src/extensions/core/prompt-builder/inspect.ts +10 -3
- package/src/extensions/enforcement/AGENTS.md +25 -19
- package/src/extensions/enforcement/handlers/register-tool-result-formatting.ts +1 -1
- package/src/extensions/enforcement/handlers/turn-end-handler.ts +1 -1
- package/src/extensions/enforcement/self-state-claims.ts +3 -2
- package/src/extensions/heartbeat/heartbeat-scheduler/AGENTS.md +6 -3
- package/src/extensions/manifest.ts +2 -2
- package/src/extensions/memory/AGENTS.md +13 -5
- package/src/extensions/memory/context-manager/handlers/tool-batch-boundary.ts +45 -11
- package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +202 -60
- package/src/extensions/memory/context-manager/handlers/tools/context-navigate.ts +4 -1
- package/src/extensions/memory/memory-agent-bridge/memory-store-tool.ts +16 -0
- package/src/extensions/memory/memory-agent-bridge/memory-tool.ts +22 -9
- package/src/extensions/memory/scratchpad/format.ts +8 -2
- package/src/extensions/memory/scratchpad/index.ts +12 -2
- package/src/extensions/memory/session-recall/index.ts +20 -8
- package/src/extensions/memory/three-memory-stores/episodes.ts +2 -2
- package/src/extensions/orchestrator/index.ts +100 -11
- package/src/extensions/scheduling/timer/AGENTS.md +7 -0
- package/src/extensions/self/health-maintenance/index.ts +143 -14
- package/src/extensions/self/watchdog/AGENTS.md +1 -0
- package/src/lib/AGENTS.md +21 -21
- package/src/lib/config/braid-settings.ts +74 -0
- package/src/lib/constants/session-thresholds.ts +2 -3
- package/src/lib/enforcement/turn-dedup.ts +2 -2
- package/src/lib/harness/AGENTS.md +1 -1
- package/src/lib/harness/index.ts +1 -1
- package/src/lib/harness/types.ts +1 -1
- package/src/lib/orchestrator/index.ts +26 -0
- package/src/lib/orchestrator/workers.ts +705 -7
- package/src/lib/utils/AGENTS.md +1 -1
- package/src/lib/utils/injection-tracker.ts +1 -1
|
@@ -68,6 +68,26 @@ function captureUsage(ctx: any): { percent: number; tokens: number; contextWindo
|
|
|
68
68
|
}
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
// Blank optional selectors.
|
|
72
|
+
//
|
|
73
|
+
// Some clients emit every schema property and send "" for the ones they do
|
|
74
|
+
// not use. A blank string is "absent": a tag lookup or a percent parse on ""
|
|
75
|
+
// would otherwise reject a call that named nothing. Blank NUMERIC selectors
|
|
76
|
+
// are harder - the framework validates arguments before any handler runs and
|
|
77
|
+
// converts "" to 0 - so a numeric optional cannot tell a blank from a typed
|
|
78
|
+
// 0; the archive range guard reads the {0,0} index pair as the blank
|
|
79
|
+
// signature instead.
|
|
80
|
+
|
|
81
|
+
/** The non-blank string a selector names, or undefined when it names none. */
|
|
82
|
+
function optionalString(v: unknown): string | undefined {
|
|
83
|
+
return typeof v === "string" && v.trim().length > 0 ? v : undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The finite number a selector names, or undefined when it names none. */
|
|
87
|
+
function optionalNumber(v: unknown): number | undefined {
|
|
88
|
+
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
71
91
|
// Batch-settle compaction scheduler.
|
|
72
92
|
// Contract: the tool returns its result FIRST (execute() resolves before a
|
|
73
93
|
// compaction is armed), but ctx.compact() — which aborts the turn — fires only
|
|
@@ -75,13 +95,20 @@ function captureUsage(ctx: any): { percent: number; tokens: number; contextWindo
|
|
|
75
95
|
// no-op) or turn_end inside a live run (the turn's messages and tool results
|
|
76
96
|
// are already persisted; the abort lands between turns, where a queued steer
|
|
77
97
|
// is appended before the loop polls the abort signal and its turn runs on the
|
|
78
|
-
// post-compaction resume). Firing
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
//
|
|
98
|
+
// post-compaction resume). Firing while a tool call is still active aborts a
|
|
99
|
+
// still-live run (the agent is streaming its response to the context_compress
|
|
100
|
+
// result), surfacing a spurious "This operation was aborted" error in the TUI
|
|
101
|
+
// and tearing the finishing turn. agent_settled alone never drains a run kept
|
|
102
|
+
// alive by continuous steers, so the armed compaction stalls behind live work
|
|
103
|
+
// while usage keeps climbing, hence the turn_end boundary.
|
|
104
|
+
//
|
|
105
|
+
// Active work is tracked by TOOL CALL ID, never by a count: tool_execution_start
|
|
106
|
+
// registers an id, tool_execution_end deletes its own, and a turn boundary
|
|
107
|
+
// deletes every id the turn's persisted toolResults account for. A count can
|
|
108
|
+
// only be decremented by the exact end event that was missed, so one lost end
|
|
109
|
+
// left it positive and every later boundary returned before the armed
|
|
110
|
+
// compaction could drain; an id-set repaired from the boundary's own result
|
|
111
|
+
// identity cannot drift that way.
|
|
85
112
|
|
|
86
113
|
interface PendingCompaction {
|
|
87
114
|
/** Which action armed this entry. */
|
|
@@ -95,12 +122,29 @@ interface PendingCompaction {
|
|
|
95
122
|
}
|
|
96
123
|
|
|
97
124
|
interface BatchSettleState {
|
|
98
|
-
/**
|
|
99
|
-
|
|
125
|
+
/** Active tool calls of the current batch (per session): call ids and the
|
|
126
|
+
* unidentifiable-start marker below, which no call id can equal. */
|
|
127
|
+
activeToolCallIds: Set<string | symbol>;
|
|
100
128
|
/** Pending compactions armed by context_compress actions, drained at settle. */
|
|
101
129
|
pending: PendingCompaction[];
|
|
102
130
|
}
|
|
103
131
|
|
|
132
|
+
/**
|
|
133
|
+
* Marker for a tool_execution_start whose event carries no usable call id.
|
|
134
|
+
* A SYMBOL, never a string: every string is a possible call id and a marker
|
|
135
|
+
* that is one can be deleted by a persisted result that happens to name it,
|
|
136
|
+
* which drained the batch at a boundary the unidentifiable start had not
|
|
137
|
+
* reached. A symbol cannot equal any persisted id, so the marker keeps every
|
|
138
|
+
* boundary conservative and is released only by the AGENT_SETTLED backstop.
|
|
139
|
+
*/
|
|
140
|
+
const UNIDENTIFIED_TOOL_CALL = Symbol("unidentified-tool-call-start");
|
|
141
|
+
|
|
142
|
+
/** The non-empty call id an event names, or undefined when it names none. */
|
|
143
|
+
function toolCallIdOf(event: any): string | undefined {
|
|
144
|
+
const id = event?.toolCallId;
|
|
145
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
146
|
+
}
|
|
147
|
+
|
|
104
148
|
/**
|
|
105
149
|
* The pending list is bounded: one entry per armed action, capped so a
|
|
106
150
|
* pathological re-arming loop cannot grow it without bound. Beyond the cap the
|
|
@@ -114,11 +158,25 @@ const PENDING_COMPACT_QUEUE_MAX = 8;
|
|
|
114
158
|
|
|
115
159
|
function getBatchSettleState(ctx: any): BatchSettleState {
|
|
116
160
|
return getExtensionState(ctx, "context-manager/batch-settle", () => ({
|
|
117
|
-
|
|
161
|
+
activeToolCallIds: new Set<string | symbol>(),
|
|
118
162
|
pending: [],
|
|
119
163
|
}));
|
|
120
164
|
}
|
|
121
165
|
|
|
166
|
+
/**
|
|
167
|
+
* Release the call ids a turn's persisted tool results account for. A result
|
|
168
|
+
* with no usable id is ignored: an unmatched active id stays protective, so a
|
|
169
|
+
* malformed event can only delay a drain to a later boundary or the settle
|
|
170
|
+
* backstop, never release a sibling that is still executing.
|
|
171
|
+
*/
|
|
172
|
+
function releaseSettledToolCallIds(st: BatchSettleState, toolResults: unknown): void {
|
|
173
|
+
if (!Array.isArray(toolResults)) return;
|
|
174
|
+
for (const result of toolResults) {
|
|
175
|
+
const id = toolCallIdOf(result);
|
|
176
|
+
if (id) st.activeToolCallIds.delete(id);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
122
180
|
/**
|
|
123
181
|
* Read the pending queue without creating state (inspect surfaces it).
|
|
124
182
|
* Exported so context_inspect and the heartbeat advisory can report
|
|
@@ -208,7 +266,7 @@ function coalesceIntoSlide(ctx: any, queue: PendingCompaction[]): { trigger: ()
|
|
|
208
266
|
}
|
|
209
267
|
|
|
210
268
|
function firePendingCompactionsIfSettled(ctx: any, st: BatchSettleState): void {
|
|
211
|
-
if (st.pending.length === 0 || st.
|
|
269
|
+
if (st.pending.length === 0 || st.activeToolCallIds.size > 0) return;
|
|
212
270
|
const queue = st.pending;
|
|
213
271
|
st.pending = [];
|
|
214
272
|
let trigger = queue[0].trigger;
|
|
@@ -547,24 +605,27 @@ export const contextCompressSchema = Type.Object({
|
|
|
547
605
|
});
|
|
548
606
|
|
|
549
607
|
export function registerContextCompress(pi: ExtensionAPI): void {
|
|
550
|
-
// Batch-settle scheduling: track
|
|
551
|
-
// fire the deferred compaction
|
|
552
|
-
//
|
|
553
|
-
//
|
|
554
|
-
//
|
|
555
|
-
//
|
|
556
|
-
onEvent(pi, TOOL_EXECUTION_START, (
|
|
608
|
+
// Batch-settle scheduling: track the ACTIVE tool calls of every running
|
|
609
|
+
// batch by call id and fire the deferred compaction only at a safe boundary
|
|
610
|
+
// (turn_end or agent_settled). Never mid-batch (would drop a parallel
|
|
611
|
+
// sibling's result) and never at tool_execution_end (the run is still live
|
|
612
|
+
// there — an aborting compact would surface a spurious "This operation was
|
|
613
|
+
// aborted" error and tear the finishing turn).
|
|
614
|
+
onEvent(pi, TOOL_EXECUTION_START, (event: any, ctx: any) => {
|
|
557
615
|
try {
|
|
558
|
-
getBatchSettleState(ctx)
|
|
616
|
+
const st = getBatchSettleState(ctx);
|
|
617
|
+
st.activeToolCallIds.add(toolCallIdOf(event) ?? UNIDENTIFIED_TOOL_CALL);
|
|
559
618
|
} catch {
|
|
560
619
|
// Settle tracking is unavailable — the pending compact then only fires
|
|
561
620
|
// via AGENT_SETTLED below, which is the conservative path.
|
|
562
621
|
}
|
|
563
622
|
});
|
|
564
|
-
onEvent(pi, TOOL_EXECUTION_END, (
|
|
623
|
+
onEvent(pi, TOOL_EXECUTION_END, (event: any, ctx: any) => {
|
|
565
624
|
try {
|
|
566
|
-
const
|
|
567
|
-
|
|
625
|
+
const id = toolCallIdOf(event);
|
|
626
|
+
// Only this call's id is released: a sibling's id survives its own end
|
|
627
|
+
// event, so the batch stays active until that sibling releases too.
|
|
628
|
+
if (id) getBatchSettleState(ctx).activeToolCallIds.delete(id);
|
|
568
629
|
// NOTE: do NOT fire here. The run is still active (the agent is
|
|
569
630
|
// processing this tool's result and streaming its next response); an
|
|
570
631
|
// aborting compact now would surface a spurious "This operation was
|
|
@@ -575,19 +636,24 @@ export function registerContextCompress(pi: ExtensionAPI): void {
|
|
|
575
636
|
// AGENT_SETTLED handler remains the conservative trigger.
|
|
576
637
|
}
|
|
577
638
|
});
|
|
578
|
-
onEvent(pi, TURN_END, (
|
|
639
|
+
onEvent(pi, TURN_END, (event: any, ctx: any) => {
|
|
579
640
|
// Between-turns boundary: the turn's assistant message and tool results
|
|
580
641
|
// are already persisted when turn_end fires, so the abort inside
|
|
581
|
-
// ctx.compact() cannot tear a live turn or drop a sibling result.
|
|
582
|
-
//
|
|
583
|
-
//
|
|
584
|
-
//
|
|
585
|
-
//
|
|
586
|
-
//
|
|
587
|
-
//
|
|
642
|
+
// ctx.compact() cannot tear a live turn or drop a sibling result. The
|
|
643
|
+
// persisted results carry the toolCallIds of the calls they answer, which
|
|
644
|
+
// releases a call whose tool_execution_end never arrived; an active id
|
|
645
|
+
// with NO result in this event is kept (it may still be executing, and a
|
|
646
|
+
// count could not tell which sibling completed). A run kept alive by
|
|
647
|
+
// continuous steers never reaches agent_settled — this boundary keeps an
|
|
648
|
+
// armed compaction from stalling behind live work. A steer queued at this
|
|
649
|
+
// moment survives: the loop appends it before the aborted response stream,
|
|
650
|
+
// and its turn runs on the post-compaction resume. Ids are never blanket-
|
|
651
|
+
// reset here (only agent_settled owns that backstop, which is what keeps a
|
|
652
|
+
// missed end event from parking the queue forever).
|
|
588
653
|
try {
|
|
589
654
|
const st = getBatchSettleState(ctx);
|
|
590
|
-
|
|
655
|
+
releaseSettledToolCallIds(st, event?.toolResults);
|
|
656
|
+
if (st.pending.length === 0 || st.activeToolCallIds.size > 0) return;
|
|
591
657
|
if (isCompactionActive(ctx)) return;
|
|
592
658
|
firePendingCompactionsIfSettled(ctx, st);
|
|
593
659
|
} catch {
|
|
@@ -599,13 +665,14 @@ export function registerContextCompress(pi: ExtensionAPI): void {
|
|
|
599
665
|
// Backstop boundary: the run has fully settled, so ctx.compact()'s
|
|
600
666
|
// abort() is a clean no-op — no spurious abort error, no torn turn, and
|
|
601
667
|
// the post-compaction resume wake lands when the session is
|
|
602
|
-
// idle/promptable. The whole pending queue drains here (coalesced);
|
|
603
|
-
//
|
|
604
|
-
//
|
|
605
|
-
// run stays alive; this handler catches
|
|
668
|
+
// idle/promptable. The whole pending queue drains here (coalesced); the
|
|
669
|
+
// active set is cleared so parked compactions always fire even when a
|
|
670
|
+
// start never saw its end and no turn boundary ever accounted for it.
|
|
671
|
+
// Turn boundaries drain first when a run stays alive; this handler catches
|
|
672
|
+
// everything they cannot reach.
|
|
606
673
|
try {
|
|
607
674
|
const st = getBatchSettleState(ctx);
|
|
608
|
-
st.
|
|
675
|
+
st.activeToolCallIds.clear();
|
|
609
676
|
firePendingCompactionsIfSettled(ctx, st);
|
|
610
677
|
} catch {
|
|
611
678
|
// A failed settle trigger must not tear down the AGENT_SETTLED event
|
|
@@ -794,54 +861,115 @@ export function registerContextCompress(pi: ExtensionAPI): void {
|
|
|
794
861
|
const sessionLength = analyzeSession(ctx).branchLength;
|
|
795
862
|
|
|
796
863
|
// Resolve range via priority: startTag/endTag > beforeTag > range > keepRecentTurns > startIndex/endIndex > auto
|
|
797
|
-
|
|
798
|
-
|
|
864
|
+
const startTag = optionalString(params.startTag);
|
|
865
|
+
const endTag = optionalString(params.endTag);
|
|
866
|
+
const beforeTag = optionalString(params.beforeTag);
|
|
867
|
+
const range = optionalString(params.range);
|
|
868
|
+
const keepRecentTurns = optionalNumber(params.keepRecentTurns);
|
|
869
|
+
const rawStartIndex = optionalNumber(params.startIndex);
|
|
870
|
+
const rawEndIndex = optionalNumber(params.endIndex);
|
|
871
|
+
let startIndex: number | undefined = rawStartIndex;
|
|
872
|
+
let endIndex: number | undefined = rawEndIndex;
|
|
873
|
+
|
|
874
|
+
const hasStringSelector =
|
|
875
|
+
startTag !== undefined ||
|
|
876
|
+
endTag !== undefined ||
|
|
877
|
+
beforeTag !== undefined ||
|
|
878
|
+
range !== undefined;
|
|
879
|
+
// 0 turns is never a usable instruction (priority 3 refuses it), so a
|
|
880
|
+
// 0 here is a blank conversion too.
|
|
881
|
+
const keepRecentTurnsNamed = keepRecentTurns !== undefined && keepRecentTurns > 0;
|
|
882
|
+
|
|
883
|
+
// The blank numeric signature: a blank-filled call arrives as
|
|
884
|
+
// {startIndex: 0, endIndex: 0}, a pair that selects nothing a caller
|
|
885
|
+
// could have meant (a real 0 start bound travels with a non-zero
|
|
886
|
+
// end). Refuse before any state write when nothing else names a
|
|
887
|
+
// span; otherwise read the pair as absent and let the named selector
|
|
888
|
+
// decide.
|
|
889
|
+
if (rawStartIndex === 0 && rawEndIndex === 0) {
|
|
890
|
+
if (!hasStringSelector && !keepRecentTurnsNamed) {
|
|
891
|
+
return {
|
|
892
|
+
content: [
|
|
893
|
+
{
|
|
894
|
+
type: "text" as const,
|
|
895
|
+
text:
|
|
896
|
+
"context_compress archive: startIndex/endIndex both resolved to 0 and no " +
|
|
897
|
+
"tag/range/keepRecentTurns was given; blank numeric selectors cannot select " +
|
|
898
|
+
"a span. Name startTag/endTag/beforeTag/range/keepRecentTurns instead.",
|
|
899
|
+
},
|
|
900
|
+
],
|
|
901
|
+
details: { action, error: "blank numeric selectors named no span" },
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
startIndex = undefined;
|
|
905
|
+
endIndex = undefined;
|
|
906
|
+
}
|
|
799
907
|
|
|
800
908
|
// Priority 1: Tag-based range
|
|
801
|
-
if (
|
|
802
|
-
const idx = resolveTagToIndex(ctx,
|
|
909
|
+
if (startTag !== undefined) {
|
|
910
|
+
const idx = resolveTagToIndex(ctx, startTag);
|
|
803
911
|
if (idx < 0) {
|
|
804
912
|
return {
|
|
805
913
|
content: [
|
|
806
914
|
{
|
|
807
915
|
type: "text" as const,
|
|
808
|
-
text: `Tag '${
|
|
916
|
+
text: `Tag '${startTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
|
|
809
917
|
},
|
|
810
918
|
],
|
|
811
|
-
details: { action, error: `tag not found: ${
|
|
919
|
+
details: { action, error: `tag not found: ${startTag}` },
|
|
812
920
|
};
|
|
813
921
|
}
|
|
814
922
|
startIndex = idx;
|
|
815
923
|
|
|
816
|
-
if (
|
|
817
|
-
const idxEnd = resolveTagToIndex(ctx,
|
|
924
|
+
if (endTag !== undefined) {
|
|
925
|
+
const idxEnd = resolveTagToIndex(ctx, endTag);
|
|
818
926
|
if (idxEnd < 0) {
|
|
819
927
|
return {
|
|
820
928
|
content: [
|
|
821
929
|
{
|
|
822
930
|
type: "text" as const,
|
|
823
|
-
text: `Tag '${
|
|
931
|
+
text: `Tag '${endTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
|
|
824
932
|
},
|
|
825
933
|
],
|
|
826
|
-
details: { action, error: `tag not found: ${
|
|
934
|
+
details: { action, error: `tag not found: ${endTag}` },
|
|
827
935
|
};
|
|
828
936
|
}
|
|
829
937
|
endIndex = idxEnd;
|
|
830
938
|
}
|
|
831
939
|
}
|
|
832
940
|
|
|
941
|
+
// A start tag names where the archive begins, not where it ends:
|
|
942
|
+
// without a usable end bound the resolution below would either
|
|
943
|
+
// auto-clobber the resolved start index (endIndex absent) or die on
|
|
944
|
+
// the generic invalid-range sentence (endIndex 0 from a blank).
|
|
945
|
+
if (
|
|
946
|
+
startTag !== undefined &&
|
|
947
|
+
endTag === undefined &&
|
|
948
|
+
(endIndex === undefined || endIndex <= 0)
|
|
949
|
+
) {
|
|
950
|
+
return {
|
|
951
|
+
content: [
|
|
952
|
+
{
|
|
953
|
+
type: "text" as const,
|
|
954
|
+
text: "startTag requires endTag or endIndex; use beforeTag to archive everything before a tag.",
|
|
955
|
+
},
|
|
956
|
+
],
|
|
957
|
+
details: { action, error: "startTag without endTag or endIndex" },
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
|
|
833
961
|
// Priority 1b: beforeTag convenience (archive everything before this tag)
|
|
834
|
-
if (startIndex === undefined &&
|
|
835
|
-
const idx = resolveTagToIndex(ctx,
|
|
962
|
+
if (startIndex === undefined && beforeTag !== undefined) {
|
|
963
|
+
const idx = resolveTagToIndex(ctx, beforeTag);
|
|
836
964
|
if (idx < 0) {
|
|
837
965
|
return {
|
|
838
966
|
content: [
|
|
839
967
|
{
|
|
840
968
|
type: "text" as const,
|
|
841
|
-
text: `Tag '${
|
|
969
|
+
text: `Tag '${beforeTag}' not found in session branch. Use context_navigate action=log to see available tags.`,
|
|
842
970
|
},
|
|
843
971
|
],
|
|
844
|
-
details: { action, error: `tag not found: ${
|
|
972
|
+
details: { action, error: `tag not found: ${beforeTag}` },
|
|
845
973
|
};
|
|
846
974
|
}
|
|
847
975
|
startIndex = 0;
|
|
@@ -849,17 +977,17 @@ export function registerContextCompress(pi: ExtensionAPI): void {
|
|
|
849
977
|
}
|
|
850
978
|
|
|
851
979
|
// Priority 2: Percentage-based range
|
|
852
|
-
if (
|
|
853
|
-
const match =
|
|
980
|
+
if (range !== undefined && (startIndex === undefined || endIndex === undefined)) {
|
|
981
|
+
const match = range.match(/^(\d+)%$/);
|
|
854
982
|
if (!match) {
|
|
855
983
|
return {
|
|
856
984
|
content: [
|
|
857
985
|
{
|
|
858
986
|
type: "text" as const,
|
|
859
|
-
text: `Invalid range format: '${
|
|
987
|
+
text: `Invalid range format: '${range}'. Use 'N%' e.g. '80%'.`,
|
|
860
988
|
},
|
|
861
989
|
],
|
|
862
|
-
details: { action, error: `invalid range: ${
|
|
990
|
+
details: { action, error: `invalid range: ${range}` },
|
|
863
991
|
};
|
|
864
992
|
}
|
|
865
993
|
const pct = parseInt(match[1], 10);
|
|
@@ -880,11 +1008,8 @@ export function registerContextCompress(pi: ExtensionAPI): void {
|
|
|
880
1008
|
}
|
|
881
1009
|
|
|
882
1010
|
// Priority 3: Keep-recent-turns
|
|
883
|
-
if (
|
|
884
|
-
|
|
885
|
-
params.keepRecentTurns !== undefined
|
|
886
|
-
) {
|
|
887
|
-
const keep = params.keepRecentTurns;
|
|
1011
|
+
if ((startIndex === undefined || endIndex === undefined) && keepRecentTurns !== undefined) {
|
|
1012
|
+
const keep = keepRecentTurns;
|
|
888
1013
|
if (keep <= 0) {
|
|
889
1014
|
return {
|
|
890
1015
|
content: [
|
|
@@ -927,6 +1052,23 @@ export function registerContextCompress(pi: ExtensionAPI): void {
|
|
|
927
1052
|
}
|
|
928
1053
|
|
|
929
1054
|
if (startIndex < 0 || endIndex < startIndex) {
|
|
1055
|
+
// endIndex 0 under a positive startIndex is the blank-selector
|
|
1056
|
+
// signature, not a number the caller typed: name the hypothesis.
|
|
1057
|
+
// Genuinely invalid numbers keep the generic sentence.
|
|
1058
|
+
if (endIndex === 0 && startIndex > 0) {
|
|
1059
|
+
return {
|
|
1060
|
+
content: [
|
|
1061
|
+
{
|
|
1062
|
+
type: "text" as const,
|
|
1063
|
+
text:
|
|
1064
|
+
`Invalid range: endIndex is 0 while startIndex is ${startIndex} - a blank ` +
|
|
1065
|
+
`endIndex selector ("") is converted to 0 by argument validation; send a ` +
|
|
1066
|
+
`real endIndex or name the span with beforeTag/range.`,
|
|
1067
|
+
},
|
|
1068
|
+
],
|
|
1069
|
+
details: { action, error: "endIndex 0 (blank selector) below startIndex" },
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
930
1072
|
return {
|
|
931
1073
|
content: [
|
|
932
1074
|
{
|
|
@@ -1110,7 +1252,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
|
|
|
1110
1252
|
};
|
|
1111
1253
|
}
|
|
1112
1254
|
|
|
1113
|
-
const tagName = params.tagName ?? "before-cleanup";
|
|
1255
|
+
const tagName = optionalString(params.tagName) ?? "before-cleanup";
|
|
1114
1256
|
const usageBefore = captureUsage(ctx);
|
|
1115
1257
|
|
|
1116
1258
|
try {
|
|
@@ -60,7 +60,10 @@ export const contextNavigateSchema = Type.Object({
|
|
|
60
60
|
|
|
61
61
|
function formatLog(ctx: any, sm: any, params: any): string | { error: true; text: string } {
|
|
62
62
|
const verbose = params.verbose ?? false;
|
|
63
|
-
|
|
63
|
+
// Argument validation converts a blank limit to 0, and slice(-0) is
|
|
64
|
+
// slice(0): a blank limit would dump the whole visible history. A
|
|
65
|
+
// non-positive bound is read as absent and the documented default applies.
|
|
66
|
+
const limit = typeof params.limit === "number" && params.limit > 0 ? params.limit : 50;
|
|
64
67
|
const branch = sm.getBranch();
|
|
65
68
|
const currentLeafId = sm.getLeafId();
|
|
66
69
|
|
|
@@ -100,6 +100,22 @@ export function createMemoryStoreTool(
|
|
|
100
100
|
recordMemoryToolCall(ctx, "memory_store");
|
|
101
101
|
await initPromise;
|
|
102
102
|
try {
|
|
103
|
+
// A blank string is not content. The store gate rejects short text as
|
|
104
|
+
// "Duplicate or low-utility content" for most types but exempts
|
|
105
|
+
// error/goal, so a blank landed as a real memory and every other type
|
|
106
|
+
// was refused under a misnamed cause. Refuse by name before the store
|
|
107
|
+
// call instead.
|
|
108
|
+
if (typeof params.content !== "string" || params.content.trim().length === 0) {
|
|
109
|
+
return {
|
|
110
|
+
content: [
|
|
111
|
+
{
|
|
112
|
+
type: "text",
|
|
113
|
+
text: "memory_store requires non-empty 'content' (got a blank string). Nothing was stored.",
|
|
114
|
+
},
|
|
115
|
+
],
|
|
116
|
+
details: { stored: false },
|
|
117
|
+
};
|
|
118
|
+
}
|
|
103
119
|
const related: Array<{
|
|
104
120
|
id: string;
|
|
105
121
|
type: "related" | "fixes" | "supersedes" | "example";
|
|
@@ -39,6 +39,17 @@ import { flushEpisodeAppends } from "../three-memory-stores/episodes-disk.js";
|
|
|
39
39
|
|
|
40
40
|
const log = createLogger("memory-agent-bridge/memory-tool");
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* Read an optional limit selector. The framework's argument validation
|
|
44
|
+
* converts a blank string to 0 for `Type.Optional(Type.Number())` and the
|
|
45
|
+
* converted value passes validation, so the handler cannot tell a blank from a
|
|
46
|
+
* typed 0. 0 is never a usable limit (`slice(0, 0)`) so a non-positive or
|
|
47
|
+
* non-finite value is read as absent and the documented default applies.
|
|
48
|
+
*/
|
|
49
|
+
function positiveLimit(value: unknown): number | undefined {
|
|
50
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
42
53
|
// Recency filtering helpers
|
|
43
54
|
|
|
44
55
|
/** Parse a since/until value into a Unix timestamp (ms), or undefined if invalid. */
|
|
@@ -270,6 +281,8 @@ export function createMemoryTool(
|
|
|
270
281
|
// The action may be undefined if the caller sent a malformed request;
|
|
271
282
|
// record as "memory:unknown" in that case so it's still counted.
|
|
272
283
|
recordMemoryToolCall(ctx, `memory:${params?.action ?? "unknown"}`);
|
|
284
|
+
// One read at the boundary; every limit-consuming branch below uses it.
|
|
285
|
+
const limit = positiveLimit(params?.limit);
|
|
273
286
|
try {
|
|
274
287
|
switch (params?.action) {
|
|
275
288
|
// recall_*
|
|
@@ -295,7 +308,7 @@ export function createMemoryTool(
|
|
|
295
308
|
}
|
|
296
309
|
const results = await memory.recall(params.query, {
|
|
297
310
|
type,
|
|
298
|
-
limit
|
|
311
|
+
limit,
|
|
299
312
|
tags: params.tags,
|
|
300
313
|
currentProject,
|
|
301
314
|
projectScope: params.projectScope as "current" | "all" | undefined,
|
|
@@ -357,7 +370,7 @@ export function createMemoryTool(
|
|
|
357
370
|
const episodes = retrieveByRUMS(
|
|
358
371
|
threeMem,
|
|
359
372
|
params.query!,
|
|
360
|
-
|
|
373
|
+
limit ?? 3,
|
|
361
374
|
threeMem.currentSessionId,
|
|
362
375
|
effectiveScope === "current" ? projectId : undefined,
|
|
363
376
|
effectiveScope,
|
|
@@ -401,7 +414,7 @@ export function createMemoryTool(
|
|
|
401
414
|
const lines: string[] = [];
|
|
402
415
|
if (annotatedResults.length > 0) {
|
|
403
416
|
lines.push(`Found ${annotatedResults.length} semantic memories:`);
|
|
404
|
-
for (const r of annotatedResults.slice(0,
|
|
417
|
+
for (const r of annotatedResults.slice(0, limit ?? 5)) {
|
|
405
418
|
lines.push(
|
|
406
419
|
` [${r.memory.type}] ${r.memory.content.slice(0, 300)}... (${r.relevanceReason}, id: ${r.memory.id})`,
|
|
407
420
|
);
|
|
@@ -434,7 +447,7 @@ export function createMemoryTool(
|
|
|
434
447
|
details: {
|
|
435
448
|
count: annotatedResults.length + episodeResults.length,
|
|
436
449
|
relevanceReasons: annotatedResults
|
|
437
|
-
.slice(0,
|
|
450
|
+
.slice(0, limit ?? 5)
|
|
438
451
|
.map(
|
|
439
452
|
(r: {
|
|
440
453
|
memory: { id: string };
|
|
@@ -450,10 +463,10 @@ export function createMemoryTool(
|
|
|
450
463
|
};
|
|
451
464
|
}
|
|
452
465
|
case "recall_list": {
|
|
453
|
-
const
|
|
466
|
+
const listLimit = limit ?? 20;
|
|
454
467
|
const currentProject =
|
|
455
468
|
ctx && typeof ctx.cwd === "string" ? deriveProjectIdFromCwd(ctx.cwd) : undefined;
|
|
456
|
-
const allMemories = memory.getAll(
|
|
469
|
+
const allMemories = memory.getAll(listLimit);
|
|
457
470
|
// Filter to current-project entries (or legacy entries without a projectId).
|
|
458
471
|
const memories = currentProject
|
|
459
472
|
? allMemories.filter(
|
|
@@ -483,7 +496,7 @@ export function createMemoryTool(
|
|
|
483
496
|
(a: { timestamp: number }, b: { timestamp: number }) =>
|
|
484
497
|
b.timestamp - a.timestamp,
|
|
485
498
|
)
|
|
486
|
-
.slice(0, Math.min(
|
|
499
|
+
.slice(0, Math.min(listLimit, 5));
|
|
487
500
|
if (recent.length > 0) {
|
|
488
501
|
if (lines.length > 0) lines.push("");
|
|
489
502
|
lines.push(`Recent episodes (${threeMem.episodes.length} total):`);
|
|
@@ -584,11 +597,11 @@ export function createMemoryTool(
|
|
|
584
597
|
}
|
|
585
598
|
const state = getThreeMem(ctx);
|
|
586
599
|
if (!state) return textResult("No episodes stored yet.");
|
|
587
|
-
const
|
|
600
|
+
const episodeLimit = limit ?? 3;
|
|
588
601
|
const episodes = retrieveEpisodes(
|
|
589
602
|
state,
|
|
590
603
|
params.query,
|
|
591
|
-
|
|
604
|
+
episodeLimit,
|
|
592
605
|
deriveProjectId(ctx?.cwd ?? ""),
|
|
593
606
|
);
|
|
594
607
|
if (episodes.length === 0)
|
|
@@ -29,8 +29,14 @@ export function formatScratchpad(
|
|
|
29
29
|
if (filter?.sinceTurn !== undefined) {
|
|
30
30
|
out = out.filter((it) => (it.turn ?? 0) >= (filter.sinceTurn ?? 0));
|
|
31
31
|
}
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
// A blank untilTurn arrives as 0 (argument validation converts "" before
|
|
33
|
+
// the handler runs) and `(it.turn ?? 0) <= 0` would drop every item that
|
|
34
|
+
// has a turn, answering a filter-less read with an almost-empty pad. Turn 0
|
|
35
|
+
// is never a real upper bound, so a non-positive bound is no filter - the
|
|
36
|
+
// same gate the limit branch below applies to its blank.
|
|
37
|
+
const untilTurn = filter?.untilTurn;
|
|
38
|
+
if (untilTurn !== undefined && untilTurn > 0) {
|
|
39
|
+
out = out.filter((it) => (it.turn ?? 0) <= untilTurn);
|
|
34
40
|
}
|
|
35
41
|
if (filter?.limit !== undefined && filter.limit > 0 && out.length > filter.limit) {
|
|
36
42
|
out = out.slice(-filter.limit);
|
|
@@ -48,6 +48,16 @@ interface ScratchpadCache {
|
|
|
48
48
|
pad: TaskScratchpad | null;
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/**
|
|
52
|
+
* A blank string is "not provided". A client that emits every schema key sends
|
|
53
|
+
* "" for the keys it does not use, and `??` alone keeps that "" as a real value
|
|
54
|
+
* (a blank id would then be looked up literally instead of falling back to the
|
|
55
|
+
* text). Whitespace-only counts as blank: the handlers refuse such text anyway.
|
|
56
|
+
*/
|
|
57
|
+
function nonBlank(value: unknown): string | undefined {
|
|
58
|
+
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
51
61
|
function getCache(ctx?: ExtensionContext): ScratchpadCache {
|
|
52
62
|
if (!ctx) return { pad: null };
|
|
53
63
|
return getExtensionState(ctx, "scratchpad-cache", () => ({ pad: null }));
|
|
@@ -169,8 +179,8 @@ async function scratchpadExecute(
|
|
|
169
179
|
ctx: ExtensionContext,
|
|
170
180
|
): Promise<AgentToolResult<unknown>> {
|
|
171
181
|
const action = params.action as string;
|
|
172
|
-
const text = (params.text
|
|
173
|
-
const idOrText = (params.id
|
|
182
|
+
const text = nonBlank(params.text) ?? "";
|
|
183
|
+
const idOrText = nonBlank(params.id) ?? text;
|
|
174
184
|
|
|
175
185
|
const pad = await getOrCreateScratchpad(ctx);
|
|
176
186
|
|
|
@@ -124,11 +124,22 @@ const sessionSchema = Type.Object({
|
|
|
124
124
|
until: Type.Optional(
|
|
125
125
|
Type.String({ description: "Only include sessions until this date (YYYY-MM-DD). Optional." }),
|
|
126
126
|
),
|
|
127
|
-
limit: Type.Optional(
|
|
128
|
-
Type.Number({ description: "Max sessions in output (default: 10). Use 0 for all." }),
|
|
129
|
-
),
|
|
127
|
+
limit: Type.Optional(Type.Number({ description: "Max sessions in output (default: 10)" })),
|
|
130
128
|
});
|
|
131
129
|
|
|
130
|
+
/**
|
|
131
|
+
* Read an optional session limit. Argument validation converts a blank string
|
|
132
|
+
* to 0 for `Type.Optional(Type.Number())` and the converted value passes, so
|
|
133
|
+
* the handler cannot tell a blank from a typed 0. 0 used to select the
|
|
134
|
+
* documented "all sessions" mode, which a blank then triggered silently; a
|
|
135
|
+
* deliberate 0 is indistinguishable from a blank after conversion, so the
|
|
136
|
+
* documented default is the safe reading and the unbounded mode is no longer
|
|
137
|
+
* reachable through this selector.
|
|
138
|
+
*/
|
|
139
|
+
function positiveLimit(value: unknown): number | undefined {
|
|
140
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
132
143
|
// Extension
|
|
133
144
|
|
|
134
145
|
export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
@@ -478,9 +489,10 @@ export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
|
478
489
|
// Total matches
|
|
479
490
|
const totalMatches = filtered.reduce((sum, m) => sum + m.count, 0);
|
|
480
491
|
|
|
481
|
-
// Top N sessions
|
|
482
|
-
|
|
483
|
-
const
|
|
492
|
+
// Top N sessions. A blank limit is read as absent (see positiveLimit),
|
|
493
|
+
// never as the old unbounded mode.
|
|
494
|
+
const limit = positiveLimit(params.limit) ?? 10;
|
|
495
|
+
const topSessions = filtered.slice(0, limit);
|
|
484
496
|
|
|
485
497
|
const lines: string[] = [
|
|
486
498
|
`## Batch: "${params.pattern}"`,
|
|
@@ -720,7 +732,7 @@ export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
|
720
732
|
since: params.since,
|
|
721
733
|
until: params.until,
|
|
722
734
|
project: params.project === "all" ? null : (params.project ?? null),
|
|
723
|
-
maxFiles: params.limit
|
|
735
|
+
maxFiles: positiveLimit(params.limit),
|
|
724
736
|
});
|
|
725
737
|
return {
|
|
726
738
|
content: [{ type: "text" as const, text: formatContextAggregate(aggregate) }],
|
|
@@ -793,7 +805,7 @@ export default function sessionRecallExtension(pi: ExtensionAPI) {
|
|
|
793
805
|
byMonth[month].size += s.size;
|
|
794
806
|
}
|
|
795
807
|
|
|
796
|
-
const limit = params.limit ?? 10;
|
|
808
|
+
const limit = positiveLimit(params.limit) ?? 10;
|
|
797
809
|
const topSessions = [...sessionStats].sort((a, b) => b.size - a.size).slice(0, limit);
|
|
798
810
|
|
|
799
811
|
function formatSize(bytes: number): string {
|