@seanhogg/builderforce-memory 2026.10.62 → 2026.10.63

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 (69) hide show
  1. package/dist/stats/distributions.d.ts +34 -0
  2. package/dist/stats/distributions.d.ts.map +1 -0
  3. package/dist/stats/distributions.js +180 -0
  4. package/dist/stats/distributions.js.map +1 -0
  5. package/dist/stats/estimators.d.ts +53 -0
  6. package/dist/stats/estimators.d.ts.map +1 -0
  7. package/dist/stats/estimators.js +79 -0
  8. package/dist/stats/estimators.js.map +1 -0
  9. package/dist/stats/fitting.d.ts +48 -0
  10. package/dist/stats/fitting.d.ts.map +1 -0
  11. package/dist/stats/fitting.js +209 -0
  12. package/dist/stats/fitting.js.map +1 -0
  13. package/dist/stats/index.d.ts +26 -0
  14. package/dist/stats/index.d.ts.map +1 -0
  15. package/dist/stats/index.js +18 -0
  16. package/dist/stats/index.js.map +1 -0
  17. package/dist/stats/information.d.ts +9 -0
  18. package/dist/stats/information.d.ts.map +1 -0
  19. package/dist/stats/information.js +21 -0
  20. package/dist/stats/information.js.map +1 -0
  21. package/dist/stats/multivariate.d.ts +25 -0
  22. package/dist/stats/multivariate.d.ts.map +1 -0
  23. package/dist/stats/multivariate.js +89 -0
  24. package/dist/stats/multivariate.js.map +1 -0
  25. package/dist/stats/policies.d.ts +19 -0
  26. package/dist/stats/policies.d.ts.map +1 -0
  27. package/dist/stats/policies.js +75 -0
  28. package/dist/stats/policies.js.map +1 -0
  29. package/dist/stats/prng.d.ts +11 -0
  30. package/dist/stats/prng.d.ts.map +1 -0
  31. package/dist/stats/prng.js +41 -0
  32. package/dist/stats/prng.js.map +1 -0
  33. package/dist/stats/scores.d.ts +33 -0
  34. package/dist/stats/scores.d.ts.map +1 -0
  35. package/dist/stats/scores.js +134 -0
  36. package/dist/stats/scores.js.map +1 -0
  37. package/dist/stats/tests.d.ts +48 -0
  38. package/dist/stats/tests.d.ts.map +1 -0
  39. package/dist/stats/tests.js +143 -0
  40. package/dist/stats/tests.js.map +1 -0
  41. package/dist/stats/timeSeries.d.ts +34 -0
  42. package/dist/stats/timeSeries.d.ts.map +1 -0
  43. package/dist/stats/timeSeries.js +71 -0
  44. package/dist/stats/timeSeries.js.map +1 -0
  45. package/dist/working/fold.d.ts +51 -0
  46. package/dist/working/fold.d.ts.map +1 -0
  47. package/dist/working/fold.js +218 -0
  48. package/dist/working/fold.js.map +1 -0
  49. package/dist/working/index.d.ts +1 -0
  50. package/dist/working/index.d.ts.map +1 -1
  51. package/dist/working/index.js +1 -0
  52. package/dist/working/index.js.map +1 -1
  53. package/package.json +5 -1
  54. package/src/contract/exports.snapshot.json +41 -0
  55. package/src/stats/distributions.ts +180 -0
  56. package/src/stats/estimators.ts +101 -0
  57. package/src/stats/fitting.ts +252 -0
  58. package/src/stats/index.ts +59 -0
  59. package/src/stats/information.ts +20 -0
  60. package/src/stats/multivariate.ts +93 -0
  61. package/src/stats/policies.ts +84 -0
  62. package/src/stats/prng.ts +45 -0
  63. package/src/stats/scores.ts +135 -0
  64. package/src/stats/stats.test.ts +294 -0
  65. package/src/stats/tests.ts +164 -0
  66. package/src/stats/timeSeries.ts +92 -0
  67. package/src/working/fold.test.ts +196 -0
  68. package/src/working/fold.ts +241 -0
  69. package/src/working/index.ts +1 -0
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Advisory folds of the working transcript (PRD 45 §4.7 B6/B7) — pure post-processing
3
+ * over the messages {@link buildWorkingTranscript} returns, before a host sends them to
4
+ * the model. The folds are COMPRESSION ONLY: the run's own transcript (`state.transcript`)
5
+ * and its trace keep every message at full fidelity; only what the MODEL sees is folded.
6
+ *
7
+ * B6 — fold superseded reads: when an edit/write to path P succeeds at step N, every
8
+ * earlier `read_file` result for P in the model transcript becomes a one-line marker.
9
+ * The stale content leaves the model's window (the edit changed those bytes — anything
10
+ * the model still needs it re-reads), and stays in the trace at full fidelity.
11
+ *
12
+ * B7 — fold repeated narration: assistant text PRECEDING tool calls whose word-set
13
+ * overlaps the previous such text by ≥ {@link NARRATION_OVERLAP} becomes
14
+ * `"(progress note)"`. A final answer and a turn without tool calls are NEVER folded —
15
+ * those carry the run's actual output.
16
+ *
17
+ * A "step" is the index of the assistant message carrying the tool call, in the message
18
+ * list the fold runs over (the model transcript, system prompt included).
19
+ *
20
+ * Pure: no `node:*`, no I/O — runs wherever the `./working` subpath runs.
21
+ */
22
+
23
+ import type { TranscriptMessage } from './transcript.js';
24
+
25
+ /** B7's fold threshold: |intersection| / |union| of the two texts' word sets (Jaccard). */
26
+ export const NARRATION_OVERLAP = 0.8;
27
+
28
+ /** B6's replacement for a read result whose file a later successful edit superseded. */
29
+ export function supersededReadMarker(path: string, step: number): string {
30
+ return `(read of ${path} superseded by the edit at step ${step} — re-read if needed)`;
31
+ }
32
+
33
+ /** B7's replacement for a tool-call turn's narration that merely repeats the previous one. */
34
+ export const PROGRESS_NOTE = '(progress note)';
35
+
36
+ interface NamedToolCall {
37
+ id?: unknown;
38
+ function?: { name?: unknown; arguments?: unknown };
39
+ }
40
+
41
+ interface ToolResult {
42
+ ok?: unknown;
43
+ error?: unknown;
44
+ }
45
+
46
+ function callsOf(m: TranscriptMessage): NamedToolCall[] {
47
+ return Array.isArray(m.tool_calls) ? (m.tool_calls as NamedToolCall[]) : [];
48
+ }
49
+
50
+ function nameOf(call: NamedToolCall): string | null {
51
+ const name = call.function?.name;
52
+ return typeof name === 'string' && name.length > 0 ? name : null;
53
+ }
54
+
55
+ /** The `path` argument of a tool call — from the object form or parsed out of a JSON string. */
56
+ function pathOf(call: NamedToolCall): string | null {
57
+ const raw = call.function?.arguments;
58
+ let parsed: unknown = raw;
59
+ if (typeof raw === 'string') {
60
+ try {
61
+ parsed = JSON.parse(raw);
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ if (!parsed || typeof parsed !== 'object') return null;
67
+ const path = (parsed as { path?: unknown }).path;
68
+ return typeof path === 'string' && path.length > 0 ? path : null;
69
+ }
70
+
71
+ /** The tool result answering `call`: by `tool_call_id` when present, else positionally. */
72
+ function resultFor(convo: readonly TranscriptMessage[], call: NamedToolCall, callIndex: number): TranscriptMessage | undefined {
73
+ const id = typeof call.id === 'string' && call.id.length > 0 ? call.id : null;
74
+ if (id) {
75
+ const byId = convo.find((m) => m.role === 'tool' && m.tool_call_id === id);
76
+ if (byId) return byId;
77
+ }
78
+ // No ids (or an unmatched one): the nth tool result answers the nth call.
79
+ const results = convo.filter((m) => m.role === 'tool');
80
+ return results[callIndex];
81
+ }
82
+
83
+ /** Did the tool call SUCCEED? An explicit `{ok:false}` / `error` fails; anything else —
84
+ * including a textual error, which is still informative — passes. Absent result fails
85
+ * (a write nobody confirmed changed nothing). */
86
+ function succeeded(m: TranscriptMessage | undefined): boolean {
87
+ if (!m) return false;
88
+ const content: unknown = m.content;
89
+ if (typeof content === 'string') return content.trim().length > 0;
90
+ if (!content || typeof content !== 'object') return false;
91
+ const r = content as ToolResult;
92
+ if (typeof r.ok === 'boolean') return r.ok;
93
+ return r.error == null;
94
+ }
95
+
96
+ const EDIT_OR_WRITE = /^(edit|write)/i;
97
+ const READ = /^read/i;
98
+
99
+ function wordSet(text: string): Set<string> {
100
+ return new Set(
101
+ text
102
+ .toLowerCase()
103
+ .split(/[^a-z0-9_]+/)
104
+ .filter((w) => w.length > 0),
105
+ );
106
+ }
107
+
108
+ /** Jaccard similarity of two texts' word sets. */
109
+ function wordOverlap(a: string, b: string): number {
110
+ const sa = wordSet(a);
111
+ const sb = wordSet(b);
112
+ if (sa.size === 0 || sb.size === 0) return 0;
113
+ let intersection = 0;
114
+ for (const w of sa) if (sb.has(w)) intersection += 1;
115
+ return intersection / (sa.size + sb.size - intersection);
116
+ }
117
+
118
+ /** Containment: is every word of the smaller set present in the larger? True when one
119
+ * narration is the other plus a trailing qualifier ("…once more", "…again", "…now") —
120
+ * a repeat Jaccard under-counts because the union grows with the qualifier's words. */
121
+ function wordContained(a: string, b: string): boolean {
122
+ const sa = wordSet(a);
123
+ const sb = wordSet(b);
124
+ if (sa.size === 0 || sb.size === 0) return false;
125
+ const [small, large] = sa.size <= sb.size ? [sa, sb] : [sb, sa];
126
+ for (const w of small) if (!large.has(w)) return false;
127
+ return true;
128
+ }
129
+
130
+ /** The narration an assistant turn carries before its tool calls — null when it carries
131
+ * none (an empty-content tool-call turn, or any turn without tool calls). */
132
+ function narrationOf(m: TranscriptMessage): string | null {
133
+ const content = m.content;
134
+ const text = typeof content === 'string' ? content : content == null ? '' : JSON.stringify(content);
135
+ const t = text.trim();
136
+ return callsOf(m).length > 0 && t.length > 0 ? t : null;
137
+ }
138
+
139
+ interface ReadRow {
140
+ /** The assistant step that issued the read. */
141
+ step: number;
142
+ path: string;
143
+ /** The message carrying the read's result — what the marker replaces. */
144
+ result: TranscriptMessage;
145
+ /** The read call itself — B7 skips a narration that narrated a now-folded read. */
146
+ call: NamedToolCall;
147
+ }
148
+
149
+ /** Tracks which read CALLS were superseded, so `foldWorkingTranscript`'s B7 pass can
150
+ * skip the narration that introduced a read whose content B6 just replaced. */
151
+ const SUPERSEDED_CALL = new WeakSet<object>();
152
+
153
+ /**
154
+ * B6 — fold reads a later successful edit/write superseded. Returns the input unchanged
155
+ * (same reference, no copy) when nothing is superseded; otherwise a new list whose
156
+ * replaced messages are shallow copies with only `content` changed. The caller's
157
+ * transcript is never touched.
158
+ */
159
+ export function foldSupersededReads<M extends TranscriptMessage>(msgs: readonly M[]): M[] {
160
+ interface Edit {
161
+ path: string;
162
+ step: number;
163
+ }
164
+ const edits: Edit[] = [];
165
+ const reads: ReadRow[] = [];
166
+ let callIndex = 0;
167
+ for (let i = 0; i < msgs.length; i++) {
168
+ const m = msgs[i]!;
169
+ for (const call of callsOf(m)) {
170
+ const name = nameOf(call);
171
+ if (!name) continue;
172
+ const path = pathOf(call);
173
+ const result = resultFor(msgs, call, callIndex);
174
+ if (path && EDIT_OR_WRITE.test(name)) {
175
+ if (succeeded(result)) edits.push({ path, step: i });
176
+ } else if (path && READ.test(name) && result) {
177
+ reads.push({ step: i, path, result, call });
178
+ }
179
+ callIndex += 1;
180
+ }
181
+ }
182
+ if (edits.length === 0 || reads.length === 0) return msgs as M[];
183
+ const superseded = new Map<TranscriptMessage, string>();
184
+ for (const read of reads) {
185
+ // The LATEST successful edit of the same path after the read wins — an earlier read
186
+ // re-made after an edit is not superseded by that edit.
187
+ let step = -1;
188
+ for (const e of edits) {
189
+ if (e.path === read.path && e.step > read.step && e.step > step) step = e.step;
190
+ }
191
+ if (step >= 0) {
192
+ superseded.set(read.result, supersededReadMarker(read.path, step));
193
+ SUPERSEDED_CALL.add(read.call);
194
+ }
195
+ }
196
+ if (superseded.size === 0) return msgs as M[];
197
+ return msgs.map((m) => {
198
+ const marker = superseded.get(m);
199
+ return marker == null ? m : ({ ...m, content: marker } as M);
200
+ });
201
+ }
202
+
203
+ /**
204
+ * B7 — fold a tool-call turn's narration when it merely repeats the previous one.
205
+ * Only assistant messages WITH tool calls are candidates: a final answer and a turn
206
+ * without tool calls are never folded. The FIRST narration is kept verbatim (it has no
207
+ * predecessor to repeat); each later one folds when its word-set overlap with the most
208
+ * recent kept narration is ≥ {@link NARRATION_OVERLAP}. Once folded, it does not become
209
+ * the comparison text — the model keeps the last thing actually said.
210
+ */
211
+ export function foldRepeatedNarration<M extends TranscriptMessage>(msgs: readonly M[], overlap = NARRATION_OVERLAP): M[] {
212
+ let lastKept: string | null = null;
213
+ let changed = false;
214
+ const out = msgs.map((m) => {
215
+ if (m.role !== 'assistant') return m;
216
+ const narration = narrationOf(m);
217
+ if (narration == null) return m; // no tool calls, or no narration: never folded
218
+ // A narration that introduced a read B6 folded is the model's only record of why it
219
+ // read — it never folds itself, but it IS what a later repeat is compared against.
220
+ if (callsOf(m).some((call) => SUPERSEDED_CALL.has(call))) {
221
+ lastKept = narration;
222
+ return m;
223
+ }
224
+ if (lastKept != null && (wordOverlap(narration, lastKept) >= overlap || wordContained(narration, lastKept))) {
225
+ changed = true;
226
+ return { ...m, content: PROGRESS_NOTE } as M;
227
+ }
228
+ lastKept = narration;
229
+ return m;
230
+ });
231
+ return changed ? out : (msgs as M[]);
232
+ }
233
+
234
+ /**
235
+ * Both folds, B6 then B7, over the working transcript a host is about to send to the
236
+ * model. Pure and advisory: `msgs` is not mutated, and the run's own transcript/trace
237
+ * keep every message at full fidelity.
238
+ */
239
+ export function foldWorkingTranscript<M extends TranscriptMessage>(msgs: readonly M[]): M[] {
240
+ return foldRepeatedNarration(foldSupersededReads(msgs));
241
+ }
@@ -54,6 +54,7 @@ export {
54
54
  buildWorkingTranscript,
55
55
  } from './transcript.js';
56
56
  export type { TranscriptMessage, CompactMemo, WorkingTranscriptState, TranscriptFold } from './transcript.js';
57
+ export { NARRATION_OVERLAP, PROGRESS_NOTE, supersededReadMarker, foldSupersededReads, foldRepeatedNarration, foldWorkingTranscript } from './fold.js';
57
58
  export { TRANSCRIPT_SUMMARY_PROMPT, TRANSCRIPT_SUMMARY_MAX_TOKENS, TRANSCRIPT_SUMMARY_INPUT_TOKENS, renderForSummary, summaryChunks, summarizeTranscript } from './summary.js';
58
59
  export type { SummaryCompletion } from './summary.js';
59
60
  export {