pi-braid 0.43.7 → 0.43.9
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/CHANGELOG.md +72 -0
- package/TOOLS.md +1 -1
- package/build-info.json +4 -4
- package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
- package/dist/extensions/core/skills-tool/auto-inject.d.ts +21 -0
- package/dist/extensions/core/skills-tool/auto-inject.js +105 -1
- package/dist/extensions/core/skills-tool/index.js +20 -2
- package/dist/extensions/core/skills-tool/loading-guidance.d.ts +4 -1
- package/dist/extensions/core/skills-tool/loading-guidance.js +4 -1
- package/dist/extensions/core/skills-tool/session-records.d.ts +107 -9
- package/dist/extensions/core/skills-tool/session-records.js +141 -5
- package/dist/extensions/enforcement/handlers/analysis/dreamer-handler.js +5 -1
- package/dist/extensions/enforcement/handlers/register-tool-call.js +5 -2
- package/dist/extensions/enforcement/verification-judge.d.ts +7 -0
- package/dist/extensions/enforcement/verification-judge.js +28 -21
- package/dist/extensions/memory/session-recall/ask.d.ts +95 -0
- package/dist/extensions/memory/session-recall/ask.js +376 -0
- package/dist/extensions/memory/session-recall/corpus-index.d.ts +200 -0
- package/dist/extensions/memory/session-recall/corpus-index.js +480 -0
- package/dist/extensions/memory/session-recall/index.js +173 -21
- package/dist/extensions/memory/session-recall/search.d.ts +29 -0
- package/dist/extensions/memory/session-recall/search.js +42 -9
- package/dist/lib/ai/payload-hygiene.d.ts +3 -0
- package/dist/lib/ai/payload-hygiene.js +34 -2
- package/dist/lib/config/braid-paths.d.ts +4 -0
- package/dist/lib/config/braid-paths.js +6 -0
- package/dist/lib/config/braid-settings.d.ts +44 -0
- package/dist/lib/config/braid-settings.js +41 -0
- package/dist/lib/detection/tool-loop-detector.d.ts +95 -46
- package/dist/lib/detection/tool-loop-detector.js +288 -180
- package/dist/lib/memory/constants.d.ts +38 -0
- package/dist/lib/memory/constants.js +196 -0
- package/dist/lib/memory/index.js +49 -10
- package/dist/lib/memory/lifecycle.d.ts +8 -0
- package/dist/lib/memory/lifecycle.js +43 -18
- package/dist/lib/reasoning/dreamer.d.ts +2 -1
- package/dist/lib/reasoning/dreamer.js +12 -7
- package/docs/LOCAL_DEV.md +1 -1
- package/docs/SETUP.md +2 -0
- package/package.json +1 -1
- package/src/extensions/core/AGENTS.md +3 -2
- package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
- package/src/extensions/core/skills-tool/auto-inject.ts +118 -1
- package/src/extensions/core/skills-tool/index.ts +21 -1
- package/src/extensions/core/skills-tool/loading-guidance.ts +4 -1
- package/src/extensions/core/skills-tool/session-records.ts +201 -9
- package/src/extensions/enforcement/handlers/analysis/dreamer-handler.ts +5 -1
- package/src/extensions/enforcement/handlers/register-tool-call.ts +5 -2
- package/src/extensions/enforcement/verification-judge.ts +32 -25
- package/src/extensions/memory/AGENTS.md +2 -2
- package/src/extensions/memory/session-recall/AGENTS.md +92 -18
- package/src/extensions/memory/session-recall/ask.ts +435 -0
- package/src/extensions/memory/session-recall/corpus-index.ts +609 -0
- package/src/extensions/memory/session-recall/index.ts +202 -21
- package/src/extensions/memory/session-recall/search.ts +61 -10
- package/src/lib/ai/payload-hygiene.ts +47 -3
- package/src/lib/config/braid-paths.ts +7 -0
- package/src/lib/config/braid-settings.ts +93 -3
- package/src/lib/detection/AGENTS.md +8 -7
- package/src/lib/detection/tool-loop-detector.ts +339 -195
- package/src/lib/memory/constants.ts +202 -0
- package/src/lib/memory/index.ts +59 -8
- package/src/lib/memory/lifecycle.ts +50 -16
- package/src/lib/reasoning/dreamer.ts +13 -6
|
@@ -16,6 +16,202 @@ export const MEMORY_FILE = SEMANTIC_MEMORY_FILE;
|
|
|
16
16
|
export const MAX_ENTRIES = 200;
|
|
17
17
|
export const MIN_UTILITY_THRESHOLD = 0.15;
|
|
18
18
|
export const CONSOLIDATION_INTERVAL = 5;
|
|
19
|
+
// ── Recall scoring ───────────────────────────────────────────────────────────
|
|
20
|
+
/**
|
|
21
|
+
* Shortest token the matcher looks at. One- and two-character tokens carry no
|
|
22
|
+
* topic in any language this store sees, and matching them turns a query into
|
|
23
|
+
* a scan of nearly every entry.
|
|
24
|
+
*/
|
|
25
|
+
export const QUERY_MIN_TOKEN_LENGTH = 3;
|
|
26
|
+
/**
|
|
27
|
+
* English function words, dropped from a query before matching. They name no
|
|
28
|
+
* topic, and counting each as a full word match is what let a long entry
|
|
29
|
+
* outrank a short quote that shared the question's actual subject.
|
|
30
|
+
*
|
|
31
|
+
* Generic vocabulary only. A word that names anything about this deployment,
|
|
32
|
+
* its files, or its roles belongs to that owner, not in a shared matcher.
|
|
33
|
+
*/
|
|
34
|
+
export const QUERY_STOP_WORDS = new Set([
|
|
35
|
+
"a",
|
|
36
|
+
"about",
|
|
37
|
+
"above",
|
|
38
|
+
"across",
|
|
39
|
+
"after",
|
|
40
|
+
"against",
|
|
41
|
+
"all",
|
|
42
|
+
"along",
|
|
43
|
+
"also",
|
|
44
|
+
"am",
|
|
45
|
+
"among",
|
|
46
|
+
"an",
|
|
47
|
+
"and",
|
|
48
|
+
"another",
|
|
49
|
+
"any",
|
|
50
|
+
"are",
|
|
51
|
+
"aren't",
|
|
52
|
+
"around",
|
|
53
|
+
"as",
|
|
54
|
+
"at",
|
|
55
|
+
"be",
|
|
56
|
+
"because",
|
|
57
|
+
"been",
|
|
58
|
+
"before",
|
|
59
|
+
"behind",
|
|
60
|
+
"being",
|
|
61
|
+
"below",
|
|
62
|
+
"beneath",
|
|
63
|
+
"beside",
|
|
64
|
+
"between",
|
|
65
|
+
"beyond",
|
|
66
|
+
"both",
|
|
67
|
+
"but",
|
|
68
|
+
"by",
|
|
69
|
+
"can",
|
|
70
|
+
"could",
|
|
71
|
+
"did",
|
|
72
|
+
"do",
|
|
73
|
+
"does",
|
|
74
|
+
"doesn't",
|
|
75
|
+
"doing",
|
|
76
|
+
"done",
|
|
77
|
+
"don't",
|
|
78
|
+
"during",
|
|
79
|
+
"each",
|
|
80
|
+
"either",
|
|
81
|
+
"every",
|
|
82
|
+
"except",
|
|
83
|
+
"few",
|
|
84
|
+
"for",
|
|
85
|
+
"from",
|
|
86
|
+
"had",
|
|
87
|
+
"has",
|
|
88
|
+
"have",
|
|
89
|
+
"having",
|
|
90
|
+
"he",
|
|
91
|
+
"her",
|
|
92
|
+
"hers",
|
|
93
|
+
"him",
|
|
94
|
+
"his",
|
|
95
|
+
"how",
|
|
96
|
+
"however",
|
|
97
|
+
"i",
|
|
98
|
+
"if",
|
|
99
|
+
"in",
|
|
100
|
+
"inside",
|
|
101
|
+
"into",
|
|
102
|
+
"is",
|
|
103
|
+
"isn't",
|
|
104
|
+
"it",
|
|
105
|
+
"its",
|
|
106
|
+
"just",
|
|
107
|
+
"many",
|
|
108
|
+
"may",
|
|
109
|
+
"me",
|
|
110
|
+
"might",
|
|
111
|
+
"mine",
|
|
112
|
+
"more",
|
|
113
|
+
"most",
|
|
114
|
+
"much",
|
|
115
|
+
"must",
|
|
116
|
+
"my",
|
|
117
|
+
"near",
|
|
118
|
+
"neither",
|
|
119
|
+
"no",
|
|
120
|
+
"nor",
|
|
121
|
+
"not",
|
|
122
|
+
"of",
|
|
123
|
+
"off",
|
|
124
|
+
"on",
|
|
125
|
+
"one",
|
|
126
|
+
"only",
|
|
127
|
+
"onto",
|
|
128
|
+
"or",
|
|
129
|
+
"other",
|
|
130
|
+
"our",
|
|
131
|
+
"ours",
|
|
132
|
+
"out",
|
|
133
|
+
"outside",
|
|
134
|
+
"over",
|
|
135
|
+
"own",
|
|
136
|
+
"per",
|
|
137
|
+
"same",
|
|
138
|
+
"shall",
|
|
139
|
+
"she",
|
|
140
|
+
"should",
|
|
141
|
+
"since",
|
|
142
|
+
"so",
|
|
143
|
+
"some",
|
|
144
|
+
"such",
|
|
145
|
+
"than",
|
|
146
|
+
"that",
|
|
147
|
+
"the",
|
|
148
|
+
"their",
|
|
149
|
+
"theirs",
|
|
150
|
+
"them",
|
|
151
|
+
"then",
|
|
152
|
+
"there",
|
|
153
|
+
"these",
|
|
154
|
+
"they",
|
|
155
|
+
"this",
|
|
156
|
+
"those",
|
|
157
|
+
"through",
|
|
158
|
+
"throughout",
|
|
159
|
+
"till",
|
|
160
|
+
"to",
|
|
161
|
+
"too",
|
|
162
|
+
"toward",
|
|
163
|
+
"two",
|
|
164
|
+
"under",
|
|
165
|
+
"until",
|
|
166
|
+
"up",
|
|
167
|
+
"upon",
|
|
168
|
+
"us",
|
|
169
|
+
"very",
|
|
170
|
+
"via",
|
|
171
|
+
"was",
|
|
172
|
+
"wasn't",
|
|
173
|
+
"we",
|
|
174
|
+
"were",
|
|
175
|
+
"weren't",
|
|
176
|
+
"what",
|
|
177
|
+
"when",
|
|
178
|
+
"where",
|
|
179
|
+
"which",
|
|
180
|
+
"while",
|
|
181
|
+
"who",
|
|
182
|
+
"whom",
|
|
183
|
+
"whose",
|
|
184
|
+
"why",
|
|
185
|
+
"will",
|
|
186
|
+
"with",
|
|
187
|
+
"within",
|
|
188
|
+
"without",
|
|
189
|
+
"would",
|
|
190
|
+
"yet",
|
|
191
|
+
"you",
|
|
192
|
+
"your",
|
|
193
|
+
"yours",
|
|
194
|
+
]);
|
|
195
|
+
/**
|
|
196
|
+
* What a query-named tag is worth, in matched-word units: two ordinary terms.
|
|
197
|
+
* The shipped matcher counted a word as 1 and a tag as 2, so 2 keeps the
|
|
198
|
+
* shipped meaning now that a word's weight is a rarity weight instead.
|
|
199
|
+
*/
|
|
200
|
+
export const MEMORY_TAG_BONUS_WORDS = 2;
|
|
201
|
+
/**
|
|
202
|
+
* Document-frequency fraction that fixes the "ordinary term" the weights are
|
|
203
|
+
* expressed in: a token carried by this share of the store. At 0.5 the
|
|
204
|
+
* reference weight is ln(1 + 1 / 0.5) = ln 3, and a tag is worth
|
|
205
|
+
* MEMORY_TAG_BONUS_WORDS of those.
|
|
206
|
+
*/
|
|
207
|
+
export const MEMORY_REFERENCE_DF_FRACTION = 0.5;
|
|
208
|
+
/**
|
|
209
|
+
* Defaults for `braid.memory.reservedProvenance`. The partition ships OFF:
|
|
210
|
+
* which entries carry a provenance class is a property of the writer that
|
|
211
|
+
* filed them, so the operator names it with a source prefix. An empty prefix
|
|
212
|
+
* and a zero slot count both mean "no partition", leaving the prune as it was.
|
|
213
|
+
*/
|
|
214
|
+
export const RESERVED_PROVENANCE_DEFAULTS = { prefix: "", slots: 0 };
|
|
19
215
|
export const CATEGORY_BASE_UTILITY = {
|
|
20
216
|
goal: 0.9,
|
|
21
217
|
error: 0.8,
|
package/dist/lib/memory/index.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* helpers are in sibling modules (types.ts, constants.ts, storage.ts, utils.ts).
|
|
6
6
|
*/
|
|
7
7
|
import { createLogger } from "../core/logger.js";
|
|
8
|
-
import { MAX_ENTRIES, CONSOLIDATION_INTERVAL } from "./constants.js";
|
|
8
|
+
import { MAX_ENTRIES, CONSOLIDATION_INTERVAL, QUERY_MIN_TOKEN_LENGTH, QUERY_STOP_WORDS, MEMORY_TAG_BONUS_WORDS, MEMORY_REFERENCE_DF_FRACTION, } from "./constants.js";
|
|
9
9
|
import { loadMemory, saveMemory } from "./storage.js";
|
|
10
10
|
import { generateAutoTags, generateId } from "./utils.js";
|
|
11
11
|
// MAX_ENTRIES, MIN_UTILITY_THRESHOLD, CATEGORY_BASE_UTILITY are
|
|
@@ -17,6 +17,17 @@ export { formatMemoryTimestamp, formatMemoryEntry, parseStructuredContent, gener
|
|
|
17
17
|
// constants (MAX_ENTRIES, MIN_UTILITY_THRESHOLD, CATEGORY_BASE_UTILITY)
|
|
18
18
|
// are now in ./lifecycle.ts. The class below uses them.
|
|
19
19
|
import { shouldStore, calculateUtility, pruneMemories, consolidate } from "./lifecycle.js";
|
|
20
|
+
/**
|
|
21
|
+
* The tokens a matcher can see: lowercase, split on everything except letters,
|
|
22
|
+
* digits and inner hyphens, and long enough to name something. Splitting the
|
|
23
|
+
* query this way is what lets a question ending in "APIs?" reach the stored
|
|
24
|
+
* token "apis" instead of carrying "apis?" to a substring test that can never
|
|
25
|
+
* match it. The same split runs over content, so a phrase test compares tokens
|
|
26
|
+
* with tokens instead of punctuation with punctuation.
|
|
27
|
+
*/
|
|
28
|
+
function matchTokens(text) {
|
|
29
|
+
return (text.toLowerCase().match(/[a-z0-9-]+/g) ?? []).filter((token) => token.length >= QUERY_MIN_TOKEN_LENGTH);
|
|
30
|
+
}
|
|
20
31
|
// INTENTIONAL: CognitiveMemory is a cross-session knowledge base (memories
|
|
21
32
|
// from past sessions inform new sessions via memory-recall). The singleton
|
|
22
33
|
// pattern here means all callers share the same in-memory store, which is
|
|
@@ -245,10 +256,33 @@ export class CognitiveMemory {
|
|
|
245
256
|
}
|
|
246
257
|
async recall(query, options) {
|
|
247
258
|
const lowerQuery = query.toLowerCase();
|
|
248
|
-
const queryWords = lowerQuery
|
|
259
|
+
const queryWords = matchTokens(lowerQuery).filter((word) => !QUERY_STOP_WORDS.has(word));
|
|
260
|
+
const phrase = queryWords.join(" ");
|
|
249
261
|
const limit = options?.limit ?? 5;
|
|
262
|
+
// Rarity is measured over the live store, once per call: df(w) is the
|
|
263
|
+
// number of entries carrying w, and a matched word weighs ln(1 + N/df). A
|
|
264
|
+
// word no entry carries (df 0) earns the maximum weight, which is what a
|
|
265
|
+
// word the store has never seen should earn. What this buys: a store's
|
|
266
|
+
// common words stop deciding by count, so four of them no longer outweigh
|
|
267
|
+
// the one rare word a question is about.
|
|
268
|
+
const live = this.filterExpired(this.memoryStore.memories);
|
|
269
|
+
const contentTokens = new Map();
|
|
270
|
+
const documentFrequency = new Map();
|
|
271
|
+
for (const memory of live) {
|
|
272
|
+
const tokens = matchTokens(memory.content);
|
|
273
|
+
contentTokens.set(memory.id, tokens);
|
|
274
|
+
for (const token of new Set(tokens)) {
|
|
275
|
+
documentFrequency.set(token, (documentFrequency.get(token) ?? 0) + 1);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const idf = (word) => Math.log(1 + live.length / Math.max(1, documentFrequency.get(word) ?? 1));
|
|
279
|
+
const phraseWeight = queryWords.reduce((sum, word) => sum + idf(word), 0);
|
|
280
|
+
// A tag stays worth MEMORY_TAG_BONUS_WORDS ordinary terms, measured at the
|
|
281
|
+
// reference document frequency, so the bonus keeps its shipped meaning on
|
|
282
|
+
// the rarity scale.
|
|
283
|
+
const tagBonus = MEMORY_TAG_BONUS_WORDS * Math.log(1 + 1 / MEMORY_REFERENCE_DF_FRACTION);
|
|
250
284
|
const results = [];
|
|
251
|
-
for (const memory of
|
|
285
|
+
for (const memory of live) {
|
|
252
286
|
if (options?.type && memory.type !== options.type)
|
|
253
287
|
continue;
|
|
254
288
|
if (options?.tags?.length && !options.tags.some((t) => memory.tags.includes(t)))
|
|
@@ -261,17 +295,22 @@ export class CognitiveMemory {
|
|
|
261
295
|
memory.projectId !== options.currentProject) {
|
|
262
296
|
continue;
|
|
263
297
|
}
|
|
264
|
-
const
|
|
298
|
+
const haystack = (contentTokens.get(memory.id) ?? []).join(" ");
|
|
265
299
|
let matches = 0;
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
300
|
+
if (phrase && haystack.includes(phrase)) {
|
|
301
|
+
// The whole normalized query, in order: the strongest lexical signal
|
|
302
|
+
// the store can offer, so it is scored as every term matched.
|
|
303
|
+
matches = phraseWeight;
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
for (const word of queryWords) {
|
|
307
|
+
if (haystack.includes(word))
|
|
308
|
+
matches += idf(word);
|
|
309
|
+
}
|
|
269
310
|
}
|
|
270
|
-
if (contentLower.includes(lowerQuery))
|
|
271
|
-
matches += queryWords.length;
|
|
272
311
|
for (const tag of memory.tags) {
|
|
273
312
|
if (lowerQuery.includes(tag.toLowerCase()))
|
|
274
|
-
matches +=
|
|
313
|
+
matches += tagBonus;
|
|
275
314
|
}
|
|
276
315
|
const relevance = matches * (0.5 + memory.utility * 0.5);
|
|
277
316
|
if (relevance > 0) {
|
|
@@ -37,6 +37,14 @@ export declare function calculateUtility(type: CognitiveMemoryType, content: str
|
|
|
37
37
|
* Prune memories down to MAX_ENTRIES, keeping recent-access and
|
|
38
38
|
* high-utility entries. Recent (last 5 min) entries are always kept.
|
|
39
39
|
* Other entries are sorted by utility, then timestamp, and trimmed.
|
|
40
|
+
*
|
|
41
|
+
* A configured partition (`braid.memory.reservedProvenance`) takes its slots
|
|
42
|
+
* first: entries whose `source` starts with the configured prefix may occupy
|
|
43
|
+
* up to `slots` of the cap, and everything else, including class entries that
|
|
44
|
+
* did not win a slot, competes for what remains. The class arrives as
|
|
45
|
+
* configuration because which entries carry provenance is a property of the
|
|
46
|
+
* writer that filed them; the store only reads the prefix as an opaque
|
|
47
|
+
* string. Absent or zero, this function is the prune it always was.
|
|
40
48
|
*/
|
|
41
49
|
export declare function pruneMemories(memories: CognitiveMemoryEntry[]): CognitiveMemoryEntry[];
|
|
42
50
|
/**
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* a new CognitiveMemoryStore with the consolidated state.
|
|
14
14
|
*/
|
|
15
15
|
import { jaccardSimilarity } from "./utils.js";
|
|
16
|
+
import { getMemoryReservedProvenance } from "../config/braid-settings.js";
|
|
16
17
|
// ── Constants ────────────────────────────────────────────────────────────────
|
|
17
18
|
const GENERIC_CONTENT_PATTERNS = [/auto-captured memory from enforcement/i, /auto-captured/i];
|
|
18
19
|
// Re-exported for the CognitiveMemory class which also gates on these.
|
|
@@ -59,32 +60,56 @@ export function calculateUtility(type, content, importance) {
|
|
|
59
60
|
return base * 0.7 + importance * 0.3;
|
|
60
61
|
}
|
|
61
62
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
63
|
+
* The order the prune applies: a utility difference larger than 0.1 decides,
|
|
64
|
+
* and inside that tolerance the newer entry wins. Extracted so the reserved
|
|
65
|
+
* partition ranks its own population exactly as the general pool is ranked.
|
|
65
66
|
*/
|
|
66
|
-
|
|
67
|
+
function byUtilityThenRecency(a, b) {
|
|
68
|
+
if (Math.abs(a.utility - b.utility) > 0.1)
|
|
69
|
+
return b.utility - a.utility;
|
|
70
|
+
return b.timestamp - a.timestamp;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Keep the top `cap` entries: everything touched in the last five minutes is
|
|
74
|
+
* kept outside the competition for slots, and the rest is ranked by
|
|
75
|
+
* byUtilityThenRecency.
|
|
76
|
+
*/
|
|
77
|
+
function pruneToCap(memories, cap) {
|
|
67
78
|
const now = Date.now();
|
|
68
79
|
const RECENT_ACCESS_MS = 5 * 60 * 1000;
|
|
69
80
|
const recent = memories.filter((m) => now - m.lastAccessed < RECENT_ACCESS_MS);
|
|
70
81
|
const others = memories.filter((m) => now - m.lastAccessed >= RECENT_ACCESS_MS);
|
|
71
|
-
const sorted = [...others].sort(
|
|
72
|
-
|
|
73
|
-
return b.utility - a.utility;
|
|
74
|
-
return b.timestamp - a.timestamp;
|
|
75
|
-
});
|
|
76
|
-
const remainingSlots = Math.max(0, MAX_ENTRIES - recent.length);
|
|
82
|
+
const sorted = [...others].sort(byUtilityThenRecency);
|
|
83
|
+
const remainingSlots = Math.max(0, cap - recent.length);
|
|
77
84
|
const pruned = sorted
|
|
78
85
|
.filter((m, i) => i < remainingSlots || m.utility >= MIN_UTILITY_THRESHOLD)
|
|
79
86
|
.slice(0, remainingSlots);
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
87
|
+
return [...recent, ...pruned].sort(byUtilityThenRecency).slice(0, cap);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Prune memories down to MAX_ENTRIES, keeping recent-access and
|
|
91
|
+
* high-utility entries. Recent (last 5 min) entries are always kept.
|
|
92
|
+
* Other entries are sorted by utility, then timestamp, and trimmed.
|
|
93
|
+
*
|
|
94
|
+
* A configured partition (`braid.memory.reservedProvenance`) takes its slots
|
|
95
|
+
* first: entries whose `source` starts with the configured prefix may occupy
|
|
96
|
+
* up to `slots` of the cap, and everything else, including class entries that
|
|
97
|
+
* did not win a slot, competes for what remains. The class arrives as
|
|
98
|
+
* configuration because which entries carry provenance is a property of the
|
|
99
|
+
* writer that filed them; the store only reads the prefix as an opaque
|
|
100
|
+
* string. Absent or zero, this function is the prune it always was.
|
|
101
|
+
*/
|
|
102
|
+
export function pruneMemories(memories) {
|
|
103
|
+
const { prefix, slots } = getMemoryReservedProvenance();
|
|
104
|
+
const classEntries = prefix && slots > 0
|
|
105
|
+
? memories.filter((memory) => typeof memory.source === "string" && memory.source.startsWith(prefix))
|
|
106
|
+
: [];
|
|
107
|
+
if (classEntries.length === 0)
|
|
108
|
+
return pruneToCap(memories, MAX_ENTRIES);
|
|
109
|
+
const reserved = [...classEntries].sort(byUtilityThenRecency).slice(0, slots);
|
|
110
|
+
const reservedIds = new Set(reserved.map((memory) => memory.id));
|
|
111
|
+
const general = pruneToCap(memories.filter((memory) => !reservedIds.has(memory.id)), Math.max(0, MAX_ENTRIES - reserved.length));
|
|
112
|
+
return [...reserved, ...general];
|
|
88
113
|
}
|
|
89
114
|
/**
|
|
90
115
|
* Consolidate a memory store: merge near-duplicates, decay old utility.
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* Not a cognitive simulation - a simple histogram-based predictor.
|
|
9
9
|
*/
|
|
10
10
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import type { ToolCallLike } from "../detection/tool-loop-detector.js";
|
|
11
12
|
export interface SimulatedPath {
|
|
12
13
|
sequence: string[];
|
|
13
14
|
probability: number;
|
|
@@ -31,7 +32,7 @@ export declare function simulatePaths(currentSequence: string[], historicalSeque
|
|
|
31
32
|
* Generate proactive advice from simulated paths.
|
|
32
33
|
* Only returns advice if a concerning path is detected with sufficient confidence.
|
|
33
34
|
*/
|
|
34
|
-
export declare function dream(ctx: ExtensionContext, currentSequence: string[], historicalSequences?: string[][]): DreamAdvice | null;
|
|
35
|
+
export declare function dream(ctx: ExtensionContext, currentSequence: string[], historicalSequences?: string[][], loopSequence?: ToolCallLike[]): DreamAdvice | null;
|
|
35
36
|
/** Reset dreamer state (for testing or session reset) */
|
|
36
37
|
export declare function resetDreamer(ctx: ExtensionContext): void;
|
|
37
38
|
//# sourceMappingURL=dreamer.d.ts.map
|
|
@@ -89,19 +89,24 @@ export function simulatePaths(currentSequence, historicalSequences = []) {
|
|
|
89
89
|
* Generate proactive advice from simulated paths.
|
|
90
90
|
* Only returns advice if a concerning path is detected with sufficient confidence.
|
|
91
91
|
*/
|
|
92
|
-
export function dream(ctx, currentSequence, historicalSequences) {
|
|
92
|
+
export function dream(ctx, currentSequence, historicalSequences, loopSequence) {
|
|
93
93
|
const state = getState(ctx);
|
|
94
94
|
const now = Date.now();
|
|
95
95
|
// Cooldown check - dynamic threshold adjusted by advice tracker feedback loop
|
|
96
96
|
if (now - state.lastDreamAt < dynamicCooldown)
|
|
97
97
|
return null;
|
|
98
98
|
// Path 1: detect a tool loop in the current sequence (consecutive-
|
|
99
|
-
// same-
|
|
100
|
-
// format are all owned by lib/detection/tool-loop-detector - the
|
|
101
|
-
// source of truth. Delegating avoids the contradictory-whisper
|
|
102
|
-
// separate detectors with separate thresholds firing in one turn
|
|
103
|
-
// the agent conflicting remedies.
|
|
104
|
-
|
|
99
|
+
// same-call heuristic). The threshold, window, cooldown, identity rule, and
|
|
100
|
+
// message format are all owned by lib/detection/tool-loop-detector - the
|
|
101
|
+
// single source of truth. Delegating avoids the contradictory-whisper
|
|
102
|
+
// failure: separate detectors with separate thresholds firing in one turn
|
|
103
|
+
// hand the agent conflicting remedies.
|
|
104
|
+
//
|
|
105
|
+
// loopSequence carries the recorded calls (name + argument identity). A
|
|
106
|
+
// caller that holds only the name log passes nothing, and the detector then
|
|
107
|
+
// returns no loop: names cannot show one call repeating, only one name
|
|
108
|
+
// repeating.
|
|
109
|
+
const loopResult = detectToolLoopFromSequence(loopSequence ?? currentSequence);
|
|
105
110
|
if (loopResult.isLoop) {
|
|
106
111
|
state.lastDreamAt = now;
|
|
107
112
|
return {
|
package/docs/LOCAL_DEV.md
CHANGED
|
@@ -138,7 +138,7 @@ before and after a full run. A non-zero delta is the leak this rule prevents.
|
|
|
138
138
|
### New fixtures: use `node:test`
|
|
139
139
|
|
|
140
140
|
A new fixture is written on `node:test`. The runner does not care which style a
|
|
141
|
-
file uses -
|
|
141
|
+
file uses - 94 of the core suite's 329 fixtures already use `node:test` - so the
|
|
142
142
|
reason is the failure the other style produces. A hand-rolled helper that calls
|
|
143
143
|
`fn()` without awaiting it discards the case's promise, so an `async` case runs
|
|
144
144
|
detached and the file can print its green tally before that case settles, with
|
package/docs/SETUP.md
CHANGED
|
@@ -305,6 +305,7 @@ The user-global file always exists; the project one is optional and belongs to p
|
|
|
305
305
|
| `braid.timezone` | IANA name | `Europe/Moscow` | Time zone for all braid-facing time rendering. |
|
|
306
306
|
| `braid.enforcement.nudgeConfigs.<type>` | object | built-in per-type defaults | Per-nudge-type overrides with leaf shape `braid.enforcement.nudgeConfigs.<type>.<key>`; accepted fields are `baseCooldownMs` (number), `escalateAfter` (number), and `deduplicate` (boolean). Types: `validation`, `recordFailure`, `malformed`, `memory`, `scratchpad`, `context`, `sessionSignals`. Invalid entries are logged and dropped. |
|
|
307
307
|
| `braid.memory.writeGate` | object | gate ON, 20-min cooldown, `enforce` | Review-before-write gate on episode writes; `mode: "warn"` logs decisions and writes anyway; `sites` opts individual writers out. |
|
|
308
|
+
| `braid.memory.reservedProvenance` | object | OFF (`prefix: ""`, `slots: 0`) | Reserved partition for the semantic store's prune: entries whose `source` starts with `prefix` may occupy up to `slots` of the 200-entry cap, and everything else competes for what remains. The prefix is the operator's, because which entries carry provenance belongs to the writer that filed them. `slots` is an integer clamped to 200; an empty prefix or `slots: 0` leaves the prune exactly as shipped. |
|
|
308
309
|
| `braid.timers.maxWakeAttempts` | integer 1..10 | `3` | Redelivery cap for a failed timer wake before it is dropped with a visible notice. |
|
|
309
310
|
| `braid.session.routeBreaker` | object | ON, 3 failures, 1h floor | Route-failure latch: after `threshold` provider failures of any class except a context-window overflow or an abort since the session's last successful call, self-started turns park - timer wakes, watchdog escalations and explicitly-waking whispers are delivered non-waking, the content still reaches the session and the out-of-band line still fires. Released by a successful provider call, a clean wake turn, a route change, an owner recovery or a session start; while open it still releases one turn per `floorMs`. `enabled: false` makes it inert. |
|
|
310
311
|
| `braid.timers.wakeAlert` | object | ON, `outcomeTimeouts: 2` | Dead-wake page: repeated outcome timeouts / exhausted redeliveries feed the watchdog's wake-delivery condition, which pages the owner out of band (telegram) once per episode plus one recovery line. `mode: "off"` disables the feed (delivery itself is unchanged); `outcomeTimeouts` is an integer 2..10 (1 would page on every normal long turn). |
|
|
@@ -313,6 +314,7 @@ The user-global file always exists; the project one is optional and belongs to p
|
|
|
313
314
|
| `braid.context.staleToolResultOffload` | object | OFF | Opt-in age/size offload of stale large tool results (defaults: `minChars` 4000, `stalenessTurns` 40, `keepRecentTurns` 20, `maxOffloadCharsPerRun` 65536). |
|
|
314
315
|
| `braid.context.contextEmergencyOffload` | object | ON | Emergency offload of the largest tool results when a context-window (413) error fires, then one retry (defaults: `minChars` 262144, `maxCharsPerRun` 1048576, `keepRecentTurns` 1). |
|
|
315
316
|
| `braid.skills.ranking` | `keyword`/`auto`/`model` | `keyword` | Tier policy for the `list_skills` relevance ranking. `keyword` (implemented): the deterministic scorer orders the rows and reports its own verdict (`unambiguous` / `tie` / `thin-margin` / `short-task` / `no-score` / `no-task`) with per-row `relevance {score, reason}`. `auto` and `model` are reserved for a model tier that would answer on an ambiguous verdict; it was measured against the scorer and not kept, so both evaluate to the keyword path and the read echoes the configured value as `ranking.policy`. An unknown value falls back to `keyword`. |
|
|
317
|
+
| `braid.skills.inform` | `off`/`inform` | `off` | At-use line. When `inform`, a completed call in a tool family a visible skill declares with `governs:` and no read of that body in the session emits one steer naming the file and the obligation, once per session per skill. It observes a call that already ran: it never refuses, delays or rewrites a tool result. Its conversion is reported by `skill_stats` (`inform.verdict`: `undecided` below 20 informs, `beats` when the lower Wilson bound clears the suggestion channel's 18.8%, `noise` otherwise). An unknown value falls back to `off`. |
|
|
316
318
|
| `braid.telegram.sendMaxChars` | positive number | `4096` | Plain-text cap for `telegram_send`, re-read per call. |
|
|
317
319
|
| `braid.telegram.notifyMaxChars` | positive number | `1200` | Craft target and guard for turn-end notifications. |
|
|
318
320
|
| `braid.telegram.pauseStateFile` | path string | built-in default | Override for the `/telegram` pause-state file path. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-braid",
|
|
3
|
-
"version": "0.43.
|
|
3
|
+
"version": "0.43.9",
|
|
4
4
|
"description": "🥨 Braid - Metacognitive extension suite for pi coding agent: Adds memory, plan tracking, structured cognitive signals and completion checks on top of pi core loop, so long sessions keep their context and stop claiming unfinished work.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -26,7 +26,7 @@ environmental awareness, and system prompt assembly.
|
|
|
26
26
|
|
|
27
27
|
## Skills adoption contract
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
Two surfaces in `skills-tool/` put a skill body in front of the agent: the auto-inject whisper, before the prompt is answered, and the at-use line, after a call in a family a file's `governs:` declaration names has already run. The rules about whether either arrived live in one place, here, and nowhere else:
|
|
30
30
|
|
|
31
31
|
- **Delivery is observable.** `sendTrackedMessage` returns a boolean: `true` when the message was handed to `pi.sendMessage` (immediately or on the deferred triggerTurn macrotask), `false` when a suppression path dropped it (cognitive nudges disabled, per-turn/per-source flood cap, reprime cooldown). A suggestion is delivered with the park class (`delivery: "park", deliverAs: "steer"`) at source `skills-auto-inject`, which pi-core appends to the session stream - immediately when the session is idle, at the turn's end when a run is active. Both land in the session JSONL; a suppression upstream of `pi.sendMessage` reaches no stream at all.
|
|
32
32
|
- **Counters move after delivery.** `recordSkillSuggestion` runs only on a `true` return, and the cooldown/LRU bookkeeping runs after the send too, so `suggested` counts arrivals and an undelivered suggestion consumes no slot. The suggestion bypasses the per-turn whisper cap (`bypassFloodCap: true`) because prompt-builder's once-per-session hygiene whisper fires earlier in the same `before_agent_start` at the same priority and would otherwise spend the only advisory slot; the module's own budget (cooldown turns, max active suggestions, one send per turn) is the bound that keeps the whisper a whisper.
|
|
@@ -34,4 +34,5 @@ The auto-inject whisper in `skills-tool/` is the only channel that surfaces a ma
|
|
|
34
34
|
- **The trigger has a mechanical form.** `skills-tool/loading-guidance.ts` carries both the judgment form (the task entered a listed skill's domain) and the mechanical form (about to call a tool family whose word appears in a skill's name). `prompt-builder` renders that text through the `skillsLoadingText` builder as the `skills-loading` section and holds no copy of the rules; the trigger's worked examples are derived at assembly from the live tool and skill names, so the text names no pair that the running session does not have. The identity's skills prose stays one sentence.
|
|
35
35
|
- **The catalog is in the prompt.** The same section renders every visible skill as one `- name: description` row, with the read path derived from the skills' own file paths (one root for a single pack, a directory heading per pack when a catalog is installed from several). A tool call is no longer the way the agent learns which skills exist: the floor exists because the prompt that opens a resumed session carries no domain vocabulary for a matcher to rank against. `list_skills` remains the price tool (reach, headings, ranking) rather than the catalog.
|
|
36
36
|
- **Drift re-points at the floor.** When the session's own path-taking calls (`read`/`edit`/`write`) accumulate entries in a work area the floor was not rendered against, one steer line names that area and points back at the catalog. The rule and its bounds (two entries, one fire per twelve calls, three per session, quiet for the same window after any skill surface) live in `loading-guidance.ts` beside the floor text; the wiring is the `tool_result` handler in `auto-inject.ts`. Bounds are the whole design: the line is only worth its noise if it stays rare.
|
|
37
|
-
- **
|
|
37
|
+
- **The at-use line is observed, never enforced.** With `braid.skills.inform` set to `inform` (default `off`), a `tool_result` whose call **succeeded**, whose tool name yields a family token some visible cached skill declares with `governs:`, and whose obligation row carries no `read` leg emits one steer line naming the file path and the family. It runs after the result exists, returns no replacement, and refuses, delays and rewrites nothing: any gating change can only make it quieter, which is the property that separates it from a refusal gate. The payload is derived from the declaration and the catalogue entry only (the skill's own `filePath`, the token the call's name yields), so no skill name is invented in code and no tool argument is echoed. Once per session per skill, suppressed by the same obligation record the legs write (its `informed` leg), silenced by a read at any point, and hidden skills are never named. `skill_stats` reports it as `inform` from the store: `undecided` below twenty informs, `beats` only when the lower Wilson bound clears the suggestion channel's 18.8% pair conversion, `noise` otherwise.
|
|
38
|
+
- **Applicability is recorded, never enforced.** The counters cannot tell a skill that applied and was ignored from one that never applied, and the sessions that read nothing are mostly sessions no phrase matches. `skills-tool/applicability.ts` decides that difference from the skill's own declaration (the trigger phrases its file carries: frontmatter `trigger:`/`triggers:`, a `## trigger:` body heading, a description `Triggers:` tail), never from the ranking heuristic, with the injector's occurrence boundary and a clause-scoped negation read, so a phrase inside "do not research this" is not a condition met. The verdict is `read` (condition held and a detected read followed), `ignored` (condition held and no read followed), or `not-applicable` (derived: the census's `evaluated` minus the verdict rows); a skill whose file declares no phrase is named `undeclared` rather than judged either way. It reaches disk as `kind: "applicability"` rows in the per-session store (one verdict row per applicable skill keyed on `sessionId` + `skill`, one census row per session) and out through `skill_stats`. It is an observer: it writes no delivery, slot, cooldown, counter or prompt, and it owns no compliance leg. `suggested`/`listed`/`informed`/`read`/`applied` belong to the record that owns each skill's declared tool family; the verdict row joins it on the skill name.
|
|
@@ -128,7 +128,7 @@ export const TOOL_GUIDELINES: Record<string, string> = {
|
|
|
128
128
|
|
|
129
129
|
// ── session-recall (default-enabled) ──
|
|
130
130
|
session:
|
|
131
|
-
"when: prior-work context needed across sessions (search/query/analyze/stats); args: action + query/sessionPath; caveat: project-scoped by default",
|
|
131
|
+
"when: prior-work context needed across sessions (search/query/analyze/stats), or a question about what was said or decided earlier (ask, which cites project, session, line and time); args: action + query/sessionPath; caveat: project-scoped by default, and ask refuses when the corpus index cannot answer",
|
|
132
132
|
|
|
133
133
|
// ── error-tracking (opt-in) ──
|
|
134
134
|
error:
|