@brunobracaioli/aibrain 0.1.0-beta.1 → 0.2.0-beta.1

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.
@@ -56,10 +56,25 @@ type HookApi = {
56
56
  readonly mcp: {
57
57
  call(server: string, tool: string, args?: Record<string, unknown>): Promise<McpResult>;
58
58
  };
59
- readonly ui: { log(text: string): void };
59
+ readonly ui: {
60
+ log(text: string): void;
61
+ toast(text: string, options?: { timeoutMs?: number }): void;
62
+ };
60
63
  };
61
64
  type HookOptions = Record<string, unknown>;
62
65
  type PreservationMode = 'preserve_internal' | 'upstream_compatible';
66
+ type ToolPolicy = 'read_only' | 'compatible';
67
+ type PolicyVersion = 1 | 2;
68
+ type V2Options = {
69
+ readonly keepThreshold: number;
70
+ readonly preserveRecentMessages: number;
71
+ readonly minReductionRatio: number;
72
+ readonly truncateHeadChars: number;
73
+ readonly maxStateTokens: number;
74
+ readonly maxRequestTokens: number;
75
+ readonly toolPolicy: ToolPolicy;
76
+ readonly goal?: string;
77
+ };
63
78
  type FallbackStage =
64
79
  | 'snapshot_hash'
65
80
  | 'reread_before'
@@ -94,6 +109,15 @@ const MAX_PROJECTION_INPUT = 4_096;
94
109
  const MAX_CHECKPOINT_BYTES = 3_500_000;
95
110
  const CHECKPOINT_KEY_PREFIX = 'context-compaction/checkpoint/';
96
111
  const CHECKPOINT_INDEX_KEY = 'context-compaction/checkpoints';
112
+ const V2_DEFAULTS: V2Options = {
113
+ keepThreshold: 0.5,
114
+ preserveRecentMessages: 6,
115
+ minReductionRatio: 0.25,
116
+ truncateHeadChars: 300,
117
+ maxStateTokens: 25_000,
118
+ maxRequestTokens: 30_000,
119
+ toolPolicy: 'compatible',
120
+ };
97
121
 
98
122
  function isRecord(value: unknown): value is Record<string, unknown> {
99
123
  return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -122,6 +146,117 @@ function unique(values: readonly string[]): string[] {
122
146
  return [...new Set(values)];
123
147
  }
124
148
 
149
+ function boundedGoal(messages: readonly ClaudeMessage[], explicit?: string): string {
150
+ const raw =
151
+ explicit ??
152
+ messages
153
+ .filter((message) => message.role === 'user' && message.text.trim().length > 0)
154
+ .slice(-3)
155
+ .map((message) => message.text)
156
+ .join('\n');
157
+ const redacted = redact(raw, raw.length);
158
+ if (redacted.length <= 4_000) return redacted;
159
+ const marker = '[earlier goal context omitted]\n';
160
+ const budget = 4_000 - marker.length;
161
+ let start = Math.max(0, redacted.length - budget);
162
+ if (
163
+ start > 0 &&
164
+ start < redacted.length &&
165
+ redacted.charCodeAt(start) >= 0xdc00 &&
166
+ redacted.charCodeAt(start) <= 0xdfff
167
+ )
168
+ start += 1;
169
+ return `${marker}${redacted.slice(start)}`;
170
+ }
171
+
172
+ function policyOptions(value: HookOptions): { policyVersion: PolicyVersion; options?: V2Options } {
173
+ const policyVersion = value.policyVersion === undefined ? 1 : value.policyVersion;
174
+ if (policyVersion !== 1 && policyVersion !== 2)
175
+ throw new Error('unsupported context policy version');
176
+ if (policyVersion === 1) return { policyVersion: 1 };
177
+ const numberOption = (
178
+ key: string,
179
+ fallback: number,
180
+ min: number,
181
+ max: number,
182
+ integer = false,
183
+ ): number => {
184
+ const candidate = value[key];
185
+ const result = candidate === undefined ? fallback : candidate;
186
+ if (
187
+ typeof result !== 'number' ||
188
+ !Number.isFinite(result) ||
189
+ result < min ||
190
+ result > max ||
191
+ (integer && !Number.isSafeInteger(result))
192
+ )
193
+ throw new Error(`invalid v2 context option: ${key}`);
194
+ return result;
195
+ };
196
+ const keepThreshold = numberOption('keepThreshold', V2_DEFAULTS.keepThreshold, 0, 1);
197
+ const preserveRecentMessages = numberOption(
198
+ 'preserveRecentMessages',
199
+ V2_DEFAULTS.preserveRecentMessages,
200
+ 1,
201
+ 100,
202
+ true,
203
+ );
204
+ const minReductionRatio = numberOption('minReductionRatio', V2_DEFAULTS.minReductionRatio, 0, 1);
205
+ const truncateHeadChars = numberOption(
206
+ 'truncateHeadChars',
207
+ V2_DEFAULTS.truncateHeadChars,
208
+ 0,
209
+ 4096,
210
+ true,
211
+ );
212
+ const maxStateTokens = numberOption(
213
+ 'maxStateTokens',
214
+ V2_DEFAULTS.maxStateTokens,
215
+ 1000,
216
+ 25_000,
217
+ true,
218
+ );
219
+ const maxRequestTokens = numberOption(
220
+ 'maxRequestTokens',
221
+ V2_DEFAULTS.maxRequestTokens,
222
+ 1000,
223
+ 30_000,
224
+ true,
225
+ );
226
+ if (maxRequestTokens <= maxStateTokens + 256) throw new Error('invalid v2 context token budget');
227
+ const toolPolicy = value.toolPolicy === undefined ? V2_DEFAULTS.toolPolicy : value.toolPolicy;
228
+ if (toolPolicy !== 'read_only' && toolPolicy !== 'compatible')
229
+ throw new Error('invalid v2 tool policy');
230
+ const goal = value.goal;
231
+ if (goal !== undefined && (typeof goal !== 'string' || goal.length > 4000))
232
+ throw new Error('invalid v2 context goal');
233
+ return {
234
+ policyVersion: 2,
235
+ options: {
236
+ keepThreshold,
237
+ preserveRecentMessages,
238
+ minReductionRatio,
239
+ truncateHeadChars,
240
+ maxStateTokens,
241
+ maxRequestTokens,
242
+ toolPolicy,
243
+ ...(goal === undefined ? {} : { goal }),
244
+ },
245
+ };
246
+ }
247
+
248
+ function v2WireOptions(options: V2Options): Record<string, unknown> {
249
+ return {
250
+ keep_threshold: options.keepThreshold,
251
+ preserve_recent_messages: options.preserveRecentMessages,
252
+ min_reduction_ratio: options.minReductionRatio,
253
+ truncate_head_chars: options.truncateHeadChars,
254
+ max_state_tokens: options.maxStateTokens,
255
+ max_request_tokens: options.maxRequestTokens,
256
+ tool_policy: options.toolPolicy,
257
+ };
258
+ }
259
+
125
260
  function safeErrorCategory(error: unknown): string {
126
261
  const record = isRecord(error) ? error : {};
127
262
  const code = typeof record.code === 'string' ? record.code.toLowerCase() : '';
@@ -153,10 +288,19 @@ function safeErrorCategory(error: unknown): string {
153
288
  return 'unknown';
154
289
  }
155
290
 
156
- function logFallback(api: HookApi, stage: FallbackStage, error?: unknown): void {
291
+ function toastSafe(api: HookApi, text: string): void {
292
+ try {
293
+ api.ui.toast(text, { timeoutMs: 15_000 });
294
+ } catch {
295
+ // Toasts are optional host feedback; structured logs remain authoritative.
296
+ }
297
+ }
298
+
299
+ function logFallback(api: HookApi, stage: FallbackStage, error?: unknown, toast = false): void {
157
300
  api.ui.log(
158
301
  `AI Brain context fallback ${JSON.stringify({ stage, category: safeErrorCategory(error) })}`,
159
302
  );
303
+ if (toast) toastSafe(api, `AI Brain context fallback: ${safeErrorCategory(error)}`);
160
304
  }
161
305
 
162
306
  function logDiagnostic(
@@ -372,6 +516,7 @@ type Pair = {
372
516
  readonly inputText: string;
373
517
  readonly resultText: string;
374
518
  readonly resultIsError: boolean;
519
+ readonly eligibility: 'reproducible_read' | 'compatible_tool' | 'protected';
375
520
  readonly protectedPair: boolean;
376
521
  readonly pinReasons: readonly string[];
377
522
  };
@@ -428,20 +573,32 @@ function supportedNativeMetadata(value: unknown): boolean {
428
573
  );
429
574
  }
430
575
 
431
- function unsupportedNested(value: unknown): boolean {
432
- if (Array.isArray(value)) return value.some(unsupportedNested);
576
+ function unsupportedNested(value: unknown, allowPlainTextContent = false): boolean {
577
+ if (Array.isArray(value))
578
+ return value.some((item) => unsupportedNested(item, allowPlainTextContent));
433
579
  if (!isRecord(value)) return false;
434
580
  return Object.entries(value).some(
435
581
  ([key, nested]) =>
436
- ['image', 'images', 'attachment', 'attachments', 'content', 'blocks'].includes(
437
- key.toLowerCase(),
438
- ) || unsupportedNested(nested),
582
+ [
583
+ 'image',
584
+ 'images',
585
+ 'attachment',
586
+ 'attachments',
587
+ 'audio',
588
+ 'encrypted',
589
+ 'signed',
590
+ 'hidden',
591
+ 'blocks',
592
+ ].includes(key.toLowerCase()) ||
593
+ (key.toLowerCase() === 'content' && !(allowPlainTextContent && typeof nested === 'string')) ||
594
+ unsupportedNested(nested, allowPlainTextContent),
439
595
  );
440
596
  }
441
597
 
442
598
  function buildProjection(
443
599
  messages: readonly ClaudeMessage[],
444
600
  preservationMode: PreservationMode,
601
+ options?: V2Options,
445
602
  ): {
446
603
  projection: Projection;
447
604
  pairs: readonly Pair[];
@@ -458,7 +615,7 @@ function buildProjection(
458
615
  results.set(result.tool_use_id, { message: index, result });
459
616
  });
460
617
  });
461
- const recentStart = Math.max(0, messages.length - 6);
618
+ const recentStart = Math.max(0, messages.length - (options?.preserveRecentMessages ?? 6));
462
619
  let pairs: Pair[] = [];
463
620
  for (const [callId, call] of calls) {
464
621
  const result = results.get(callId);
@@ -472,7 +629,7 @@ function buildProjection(
472
629
  if (
473
630
  !supportedNativeMetadata(call.tool.result) ||
474
631
  !supportedNativeMetadata(result.result.result) ||
475
- unsupportedNested(call.tool.input)
632
+ unsupportedNested(call.tool.input, options?.toolPolicy === 'compatible')
476
633
  )
477
634
  reasons.push('unknown_tool');
478
635
  if (
@@ -486,7 +643,9 @@ function buildProjection(
486
643
  )
487
644
  )
488
645
  reasons.push('unknown_tool');
489
- if (!ALLOWED_READ_TOOLS.has(call.tool.tool)) reasons.push('unknown_tool');
646
+ const compatible = options?.toolPolicy === 'compatible';
647
+ if (!ALLOWED_READ_TOOLS.has(call.tool.tool) && !compatible) reasons.push('unknown_tool');
648
+ if (result.result.isError || call.tool.isError) reasons.push('error');
490
649
  let inputText: string;
491
650
  try {
492
651
  inputText = redact(JSON.stringify(call.tool.input), MAX_PROJECTION_INPUT);
@@ -503,6 +662,12 @@ function buildProjection(
503
662
  inputText,
504
663
  resultText: result.result.text,
505
664
  resultIsError: result.result.isError === true,
665
+ eligibility:
666
+ reasons.length > 0
667
+ ? 'protected'
668
+ : ALLOWED_READ_TOOLS.has(call.tool.tool)
669
+ ? 'reproducible_read'
670
+ : 'compatible_tool',
506
671
  protectedPair: reasons.length > 0,
507
672
  pinReasons: unique(reasons),
508
673
  });
@@ -558,13 +723,7 @@ function buildProjection(
558
723
  }));
559
724
  return {
560
725
  projection: {
561
- goal: redact(
562
- messages
563
- .slice(-3)
564
- .map((message) => message.text)
565
- .join('\n'),
566
- 4_000,
567
- ),
726
+ goal: boundedGoal(messages, options?.goal),
568
727
  messages: projectionMessages,
569
728
  pairs: pairs.map((pair) => ({
570
729
  id: pair.id,
@@ -572,7 +731,7 @@ function buildProjection(
572
731
  input_text: pair.inputText,
573
732
  result_chars: Array.from(pair.resultText).length,
574
733
  result_is_error: pair.resultIsError,
575
- eligibility: pair.protectedPair ? 'protected' : 'reproducible_read',
734
+ eligibility: pair.protectedPair ? 'protected' : pair.eligibility,
576
735
  pin_reasons: pair.pinReasons,
577
736
  })),
578
737
  protected_item_count:
@@ -586,7 +745,11 @@ function buildProjection(
586
745
  };
587
746
  }
588
747
 
589
- function parsePlan(value: unknown): Record<string, unknown> {
748
+ function parsePlan(
749
+ value: unknown,
750
+ policyVersion: PolicyVersion = 1,
751
+ options?: V2Options,
752
+ ): Record<string, unknown> {
590
753
  if (!isRecord(value)) throw new Error('AI Brain returned no structured plan');
591
754
  const rootKeys = [
592
755
  'schema_version',
@@ -603,6 +766,7 @@ function parsePlan(value: unknown): Record<string, unknown> {
603
766
  'expires_at',
604
767
  'decisions',
605
768
  'stats',
769
+ ...(policyVersion === 2 ? ['options_hash', 'fitting'] : []),
606
770
  ];
607
771
  if (Object.keys(value).some((key) => !rootKeys.includes(key)))
608
772
  throw new Error('AI Brain plan contains unknown fields');
@@ -653,9 +817,10 @@ function parsePlan(value: unknown): Record<string, unknown> {
653
817
  expiresAt: value.expires_at,
654
818
  decisions: normalized,
655
819
  stats: value.stats,
820
+ ...(policyVersion === 2 ? { optionsHash: value.options_hash, fitting: value.fitting } : {}),
656
821
  };
657
822
  if (
658
- result.schemaVersion !== 1 ||
823
+ result.schemaVersion !== (policyVersion === 2 ? 2 : 1) ||
659
824
  result.applied !== false ||
660
825
  !['planned', 'noop'].includes(String(result.status)) ||
661
826
  typeof result.requestId !== 'string' ||
@@ -667,12 +832,68 @@ function parsePlan(value: unknown): Record<string, unknown> {
667
832
  !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
668
833
  result.requestId as string,
669
834
  ) ||
670
- result.policyVersion !== 'context-v1' ||
835
+ result.policyVersion !== (policyVersion === 2 ? 'context-v2' : 'context-v1') ||
671
836
  typeof result.expiresAt !== 'string' ||
672
837
  !Number.isFinite(Date.parse(result.expiresAt as string)) ||
673
838
  !isRecord(result.stats)
674
839
  )
675
840
  throw new Error('AI Brain plan has invalid metadata');
841
+ if (policyVersion === 2) {
842
+ const stats = result.stats as Record<string, unknown>;
843
+ const batchCount = typeof stats.batch_count === 'number' ? stats.batch_count : -1;
844
+ if (
845
+ typeof result.optionsHash !== 'string' ||
846
+ !/^[a-f0-9]{64}$/.test(result.optionsHash) ||
847
+ (result.fitting !== null && !isRecord(result.fitting))
848
+ )
849
+ throw new Error('AI Brain v2 fitting metadata is invalid');
850
+ if (isRecord(result.fitting)) {
851
+ const fitting = result.fitting;
852
+ const fittingKeys = [
853
+ 'version',
854
+ 'stage',
855
+ 'estimator',
856
+ 'before_estimated_state_tokens',
857
+ 'after_estimated_state_tokens',
858
+ ];
859
+ const stages = [
860
+ 'original',
861
+ 'inputs_1000',
862
+ 'inputs_200',
863
+ 'inputs_60',
864
+ 'text_head_tail',
865
+ 'text_omitted',
866
+ 'compact_calls',
867
+ 'callless_omitted',
868
+ 'runs_folded',
869
+ ];
870
+ const beforeState = fitting.before_estimated_state_tokens as number;
871
+ const afterState = fitting.after_estimated_state_tokens as number;
872
+ const estimatedRequest = (result.stats as Record<string, unknown>).estimated_request_tokens;
873
+ if (
874
+ Object.keys(fitting).some((key) => !fittingKeys.includes(key)) ||
875
+ fitting.version !== 'state-fit-v1' ||
876
+ fitting.estimator !== 'utf8-bytes-v1' ||
877
+ !stages.includes(String(fitting.stage)) ||
878
+ !Number.isSafeInteger(beforeState) ||
879
+ beforeState < 0 ||
880
+ !Number.isSafeInteger(afterState) ||
881
+ afterState < 0 ||
882
+ (options !== undefined && afterState > options.maxStateTokens)
883
+ )
884
+ throw new Error('AI Brain v2 fitting metadata is invalid');
885
+ if (
886
+ stats.estimated_state_tokens !== afterState ||
887
+ (options !== undefined &&
888
+ (typeof estimatedRequest !== 'number' || estimatedRequest > options.maxRequestTokens))
889
+ )
890
+ throw new Error('AI Brain v2 fitting statistics are invalid');
891
+ }
892
+ if (batchCount > 0 && !isRecord(result.fitting))
893
+ throw new Error('AI Brain v2 fitting metadata is required for provider batches');
894
+ if (batchCount === 0 && result.fitting !== null)
895
+ throw new Error('AI Brain v2 no-op fitting metadata must be null');
896
+ }
676
897
  const stats = result.stats;
677
898
  const statKeys = [
678
899
  'eligible_count',
@@ -737,7 +958,11 @@ function applyPlan(
737
958
  plan: Record<string, unknown>,
738
959
  requestId: string,
739
960
  preservationMode: PreservationMode,
961
+ options?: V2Options,
740
962
  ): ClaudeMessage[] {
963
+ const keepThreshold = options?.keepThreshold ?? 0.2;
964
+ const truncateHeadChars = options?.truncateHeadChars ?? MAX_TRUNCATED_CODE_POINTS;
965
+ const minReductionRatio = options?.minReductionRatio ?? 0.25;
741
966
  const decisions = planValue(plan, 'decisions');
742
967
  if (!Array.isArray(decisions) || decisions.length !== pairs.length)
743
968
  throw new Error('AI Brain plan does not decide every pair');
@@ -760,9 +985,9 @@ function applyPlan(
760
985
  item.action === 'drop_pair' &&
761
986
  !(
762
987
  typeof keepCall === 'number' &&
763
- keepCall < 0.2 &&
988
+ keepCall < keepThreshold &&
764
989
  typeof keepResult === 'number' &&
765
- keepResult < 0.2
990
+ keepResult < keepThreshold
766
991
  )
767
992
  )
768
993
  throw new Error('drop decision does not match its probabilities');
@@ -770,13 +995,16 @@ function applyPlan(
770
995
  item.action === 'truncate_result' &&
771
996
  !(
772
997
  typeof keepResult === 'number' &&
773
- keepResult < 0.2 &&
998
+ keepResult < keepThreshold &&
774
999
  typeof keepCall === 'number' &&
775
- keepCall >= 0.2
1000
+ keepCall >= keepThreshold
776
1001
  )
777
1002
  )
778
1003
  throw new Error('truncate decision does not match its probabilities');
779
- if (item.action === 'keep' && !(typeof keepResult === 'number' && keepResult >= 0.2))
1004
+ if (
1005
+ item.action === 'keep' &&
1006
+ !(typeof keepResult === 'number' && keepResult >= keepThreshold)
1007
+ )
780
1008
  throw new Error('keep decision does not match its probabilities');
781
1009
  }
782
1010
  byId.set(item.id, { action: String(item.action), keepCall, keepResult });
@@ -801,7 +1029,7 @@ function applyPlan(
801
1029
  const mappedToolUses = toolUses.map((tool) => {
802
1030
  if (actionFor(tool.tool_use_id) !== 'truncate_result') return tool;
803
1031
  const source = tool.text ?? '';
804
- const replacement = `${Array.from(source).slice(0, MAX_TRUNCATED_CODE_POINTS).join('')}\n[AI Brain context compaction truncated this local tool result]`;
1032
+ const replacement = `${Array.from(source).slice(0, truncateHeadChars).join('')}\n[AI Brain context compaction truncated this local tool result]`;
805
1033
  return replacement.length < source.length
806
1034
  ? { ...tool, text: replacement, result: undefined }
807
1035
  : { ...tool, result: undefined };
@@ -813,7 +1041,7 @@ function applyPlan(
813
1041
  if (action !== 'truncate_result') return item;
814
1042
  const codePoints = Array.from(item.text);
815
1043
  const marker = '\n[AI Brain context compaction truncated this local tool result]';
816
- const replacement = `${codePoints.slice(0, MAX_TRUNCATED_CODE_POINTS).join('')}${marker}`;
1044
+ const replacement = `${codePoints.slice(0, truncateHeadChars).join('')}${marker}`;
817
1045
  return replacement.length < item.text.length
818
1046
  ? { ...item, text: replacement, result: undefined }
819
1047
  : { ...item, result: undefined };
@@ -832,7 +1060,7 @@ function applyPlan(
832
1060
  })
833
1061
  .filter((message): message is ClaudeMessage => message !== null);
834
1062
  const after = snapshotChars(result);
835
- if (before === 0 || (before - after) / before < 0.25)
1063
+ if (before === 0 || (before - after) / before < minReductionRatio)
836
1064
  throw new Error('AI Brain plan does not meet the minimum estimated reduction');
837
1065
  return result;
838
1066
  }
@@ -854,14 +1082,25 @@ export const register: Register = (on, options) => {
854
1082
  if (preservationMode !== 'preserve_internal' && preservationMode !== 'upstream_compatible')
855
1083
  throw new Error('unsupported Claude preservation mode');
856
1084
  const diagnosticMode = options.diagnosticMode === true;
1085
+ const configuredPolicy = policyOptions(options);
1086
+ const policyVersion = configuredPolicy.policyVersion;
1087
+ const v2Options = configuredPolicy.options;
857
1088
  const brainServer =
858
1089
  typeof options.brainServer === 'string' && options.brainServer.length > 0
859
1090
  ? options.brainServer
860
1091
  : 'brain';
1092
+ if (
1093
+ policyVersion === 2 &&
1094
+ options.compactAtPercent !== undefined &&
1095
+ (typeof options.compactAtPercent !== 'number' || !Number.isFinite(options.compactAtPercent))
1096
+ )
1097
+ throw new Error('invalid v2 compact threshold');
861
1098
  const threshold =
862
1099
  typeof options.compactAtPercent === 'number' && Number.isFinite(options.compactAtPercent)
863
1100
  ? options.compactAtPercent
864
1101
  : 85;
1102
+ if (policyVersion === 2 && (!Number.isFinite(threshold) || threshold < 1 || threshold > 95))
1103
+ throw new Error('invalid v2 compact threshold');
865
1104
  let automaticRequest = false;
866
1105
  let inFlight = false;
867
1106
  let pendingMcp: Promise<McpResult> | null = null;
@@ -905,7 +1144,7 @@ export const register: Register = (on, options) => {
905
1144
  automaticRequest = true;
906
1145
  await Promise.resolve(api.session.compact())
907
1146
  .catch((error) => {
908
- logFallback(api, 'outer_compact', error);
1147
+ logFallback(api, 'outer_compact', error, policyVersion === 2);
909
1148
  })
910
1149
  .finally(() => {
911
1150
  automaticRequest = false;
@@ -953,11 +1192,11 @@ export const register: Register = (on, options) => {
953
1192
  const rereadBaselineHash = await sha256(canonicalJson(reread));
954
1193
  if (!visibleSnapshotsMatch(current, reread, event.trigger, event.instructions)) {
955
1194
  await diagnosticMismatch(api, diagnosticMode, 'reread_before', current, reread);
956
- logFallback(api, 'reread_before');
1195
+ logFallback(api, 'reread_before', undefined, policyVersion === 2);
957
1196
  return next(event);
958
1197
  }
959
1198
  stage = 'projection';
960
- const built = buildProjection(current, preservationMode);
1199
+ const built = buildProjection(current, preservationMode, v2Options);
961
1200
  if (diagnosticMode)
962
1201
  api.ui.log(
963
1202
  `AI Brain context diagnostic ${JSON.stringify({ hook: 'session.compact', phase: 'projection_ready', total_pairs: built.pairs.length, eligible_pairs: built.pairs.filter((pair) => !pair.protectedPair).length, protected_pairs: built.pairs.filter((pair) => pair.protectedPair).length })}`,
@@ -965,7 +1204,7 @@ export const register: Register = (on, options) => {
965
1204
  const sessionRef = await api.session.id();
966
1205
  const attemptKey = `${sessionRef}:${revision}`;
967
1206
  if (attemptedRevisions.has(attemptKey) || now - lastAttemptAt < COOLDOWN_MS) {
968
- logFallback(api, 'cooldown');
1207
+ logFallback(api, 'cooldown', undefined, policyVersion === 2);
969
1208
  return next(event);
970
1209
  }
971
1210
  lastAttemptAt = now;
@@ -975,14 +1214,18 @@ export const register: Register = (on, options) => {
975
1214
  stage = 'checkpoint';
976
1215
  await saveCheckpoint(api, sessionRef, revision, preservationMode, current);
977
1216
  } catch {
978
- logFallback(api, 'checkpoint');
1217
+ logFallback(api, 'checkpoint', undefined, policyVersion === 2);
979
1218
  }
980
- logFallback(api, 'no_eligible');
1219
+ logFallback(api, 'no_eligible', undefined, policyVersion === 2);
981
1220
  return next(event);
982
1221
  }
983
1222
  stage = 'checkpoint';
984
1223
  await saveCheckpoint(api, sessionRef, revision, preservationMode, current);
985
1224
  const requestId = uuid();
1225
+ const wireOptions =
1226
+ policyVersion === 2 && v2Options !== undefined ? v2WireOptions(v2Options) : undefined;
1227
+ const optionsHash =
1228
+ wireOptions === undefined ? undefined : await sha256(canonicalJson(wireOptions));
986
1229
  const input: Record<string, unknown> = {
987
1230
  schema_version: 1,
988
1231
  client: 'claude_code',
@@ -992,8 +1235,9 @@ export const register: Register = (on, options) => {
992
1235
  observed_at: new Date().toISOString(),
993
1236
  request_id: requestId,
994
1237
  projection_version: 1,
995
- policy_version: 'context-v1',
1238
+ policy_version: policyVersion === 2 ? 'context-v2' : 'context-v1',
996
1239
  projection: built.projection,
1240
+ ...(policyVersion === 2 ? { schema_version: 2, options: wireOptions } : {}),
997
1241
  };
998
1242
  stage = 'mcp_call';
999
1243
  if (diagnosticMode)
@@ -1051,7 +1295,7 @@ export const register: Register = (on, options) => {
1051
1295
  : JSON.parse(response.content[0].text));
1052
1296
  if (byteLength(JSON.stringify(structured)) > MAX_RESULT_BYTES)
1053
1297
  throw new Error('AI Brain response is too large');
1054
- const plan = parsePlan(structured);
1298
+ const plan = parsePlan(structured, policyVersion, v2Options);
1055
1299
  if (diagnosticMode)
1056
1300
  api.ui.log(
1057
1301
  `AI Brain context diagnostic ${JSON.stringify({ hook: 'session.compact', phase: 'plan_ready', status: plan.status, eligible_count: isRecord(plan.stats) && typeof plan.stats.eligible_count === 'number' ? plan.stats.eligible_count : 0, batch_count: isRecord(plan.stats) && typeof plan.stats.batch_count === 'number' ? plan.stats.batch_count : 0 })}`,
@@ -1061,6 +1305,7 @@ export const register: Register = (on, options) => {
1061
1305
  plan.sessionRef !== sessionRef ||
1062
1306
  plan.revision !== revision ||
1063
1307
  plan.projectionHash !== (await sha256(canonicalJson(built.projection))) ||
1308
+ (policyVersion === 2 && plan.optionsHash !== optionsHash) ||
1064
1309
  Date.parse(String(plan.expiresAt)) <= Date.now()
1065
1310
  )
1066
1311
  throw new Error('AI Brain plan is stale');
@@ -1070,27 +1315,40 @@ export const register: Register = (on, options) => {
1070
1315
  const latestVisible = await api.session.messages();
1071
1316
  if ((await sha256(canonicalJson(latestVisible))) !== rereadBaselineHash) {
1072
1317
  await diagnosticMismatch(api, diagnosticMode, 'reread_after', current, latestVisible);
1073
- logFallback(api, 'reread_after');
1318
+ logFallback(api, 'reread_after', undefined, policyVersion === 2);
1074
1319
  throw new Error('Claude transcript changed during planning');
1075
1320
  }
1076
1321
  if (plan.status === 'noop') return next(event);
1077
1322
  stage = 'apply_reduction';
1078
- const transformed = applyPlan(current, built.pairs, plan, requestId, preservationMode);
1323
+ const transformed = applyPlan(
1324
+ current,
1325
+ built.pairs,
1326
+ plan,
1327
+ requestId,
1328
+ preservationMode,
1329
+ v2Options,
1330
+ );
1079
1331
  const beforeChars = snapshotChars(current);
1080
1332
  const afterChars = snapshotChars(transformed);
1333
+ const preparedDecisions = plan.decisions as Array<Record<string, unknown>>;
1081
1334
  api.ui.log(
1082
- `AI Brain custom compaction candidate ${JSON.stringify({ mode: preservationMode, messages_before: current.length, messages_after: transformed.length, chars_before: beforeChars, chars_after: afterChars, estimated_reduction: beforeChars === 0 ? 0 : (beforeChars - afterChars) / beforeChars })}`,
1335
+ `AI Brain custom compaction prepared ${JSON.stringify({ mode: preservationMode, messages_before: current.length, messages_after: transformed.length, prepared_keep_count: preparedDecisions.filter((item) => item.action === 'keep').length, prepared_truncate_count: preparedDecisions.filter((item) => item.action === 'truncate_result').length, prepared_drop_count: preparedDecisions.filter((item) => item.action === 'drop_pair').length, chars_before: beforeChars, chars_after: afterChars, estimated_reduction: beforeChars === 0 ? 0 : (beforeChars - afterChars) / beforeChars })}`,
1083
1336
  );
1337
+ if (policyVersion === 2)
1338
+ toastSafe(
1339
+ api,
1340
+ `AI Brain compaction prepared: keep ${preparedDecisions.filter((item) => item.action === 'keep').length}, truncate ${preparedDecisions.filter((item) => item.action === 'truncate_result').length}, drop ${preparedDecisions.filter((item) => item.action === 'drop_pair').length}`,
1341
+ );
1084
1342
  return { messages: transformed };
1085
1343
  } catch (error) {
1086
- logFallback(api, stage, error);
1344
+ logFallback(api, stage, error, policyVersion === 2);
1087
1345
  return next(event);
1088
1346
  } finally {
1089
1347
  if (pendingMcp === null) inFlight = false;
1090
1348
  }
1091
1349
  };
1092
1350
  return await run().catch((error) => {
1093
- logFallback(api, 'outer_compact', error);
1351
+ logFallback(api, 'outer_compact', error, policyVersion === 2);
1094
1352
  return next(event);
1095
1353
  });
1096
1354
  });