@brunobracaioli/aibrain 0.2.0-beta.1 → 0.3.0-beta.7

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/dist/cli.mjs CHANGED
@@ -19,8 +19,10 @@ import { isTestedNativeVersion, nativeVersion, platformCheck, resolveNative } fr
19
19
  import { launchClaude, launchCodex } from './launch.mjs';
20
20
  import { providerFreeProbe } from './mcp.mjs';
21
21
  import { codexPolicyJson, makePolicy, publicPolicy, isProfile } from './policy.mjs';
22
+ import { readDiagnostics } from './claude-observation.mjs';
23
+ import { readCodexDiagnostics } from './codex-diagnostics.mjs';
22
24
 
23
- const VERSION = '0.2.0-beta.1';
25
+ const VERSION = '0.3.0-beta.7';
24
26
  const ENDPOINT = 'https://mcp.ai-brain.aisac.cloud/mcp';
25
27
  const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
26
28
  const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
@@ -29,8 +31,15 @@ function usage() {
29
31
  console.log(
30
32
  `aibrain ${VERSION}\n\nUsage:\n aibrain setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n aibrain doctor [--json]\n aibrain status [--json]\n aibrain disable\n aibrain setup --undo\n aibrain claude [-- native-args...]\n aibrain codex [-- native-args...]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
31
33
  );
34
+ console.log(
35
+ 'Telemetry: setup --telemetry on|off (omitted preserves the stored choice; fresh defaults off).',
36
+ );
37
+ console.log(
38
+ 'Claude shadow: setup --claude-shadow on|off and --claude-diagnostics on|off (preview stays applied=false).',
39
+ );
32
40
  }
33
41
 
42
+ // Telemetry is opt-in; setup omits the flag to preserve the stored choice.
34
43
  function version() {
35
44
  console.log(`aibrain ${VERSION}`);
36
45
  }
@@ -141,7 +150,13 @@ function selectedPolicy(args, previous) {
141
150
  const explicitProfile = option(args, '--context-profile');
142
151
  const explicitV2 =
143
152
  explicitProfile !== undefined ||
144
- args.some((item) => POLICY_OPTION_NAMES.has(item) || item === '--goal');
153
+ args.some(
154
+ (item) =>
155
+ POLICY_OPTION_NAMES.has(item) ||
156
+ item === '--goal' ||
157
+ item === '--claude-shadow' ||
158
+ item === '--claude-diagnostics',
159
+ );
145
160
  if (previous?.schemaVersion === 1 && !explicitV2)
146
161
  return { v2: false, policy: makePolicy('conservative') };
147
162
  const inherited = previous?.schemaVersion === 2 ? previous.context : undefined;
@@ -188,6 +203,100 @@ function policySummary(policy) {
188
203
  return JSON.stringify({ effective: publicPolicy(policy) });
189
204
  }
190
205
 
206
+ /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
207
+ function telemetrySelection(args, previous) {
208
+ const requested = option(args, '--telemetry');
209
+ if (requested !== undefined && requested !== 'on' && requested !== 'off')
210
+ throw new Error('invalid_telemetry');
211
+ const current = previous?.telemetry;
212
+ const enabled = requested === undefined ? current?.enabled === true : requested === 'on';
213
+ return {
214
+ enabled,
215
+ disclosedAt: current?.disclosedAt ?? null,
216
+ };
217
+ }
218
+
219
+ /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
220
+ function claudeObservationSelection(args, previous) {
221
+ const shadow = option(args, '--claude-shadow');
222
+ const diagnostics = option(args, '--claude-diagnostics');
223
+ for (const value of [shadow, diagnostics]) {
224
+ if (value !== undefined && value !== 'on' && value !== 'off')
225
+ throw new Error('invalid_claude_observation');
226
+ }
227
+ const current = previous?.claudeObservation;
228
+ const shadowEnabled = shadow === undefined ? current?.shadowEnabled === true : shadow === 'on';
229
+ const diagnosticsEnabled =
230
+ diagnostics === undefined ? current?.diagnosticsEnabled === true : diagnostics === 'on';
231
+ const enabled = shadowEnabled || diagnosticsEnabled;
232
+ return {
233
+ shadowEnabled,
234
+ diagnosticsEnabled,
235
+ disclosedAt: enabled
236
+ ? (current?.disclosedAt ?? new Date().toISOString())
237
+ : (current?.disclosedAt ?? null),
238
+ };
239
+ }
240
+
241
+ /** @param {Awaited<ReturnType<typeof readConfig>>} previous Disable future-launch egress locally without probing the server or requiring native clients. */
242
+ async function disableTelemetryLocally(previous) {
243
+ if (!previous) {
244
+ console.log('Context dashboard telemetry is already disabled; no local setup exists.');
245
+ return;
246
+ }
247
+ const root = await ensureStateRoot();
248
+ await atomicJson(`${root}/config.json`, {
249
+ ...previous,
250
+ telemetry: {
251
+ enabled: false,
252
+ disclosedAt: previous.telemetry?.disclosedAt ?? null,
253
+ },
254
+ });
255
+ console.log(
256
+ `Context dashboard telemetry disabled for future launches in ${root}. Close and restart currently monitored sessions to stop their launch-captured reporting settings.`,
257
+ );
258
+ }
259
+
260
+ /** @param {Awaited<ReturnType<typeof readConfig>>} previous @param {string[]} args */
261
+ async function updateLocalOptOut(previous, args) {
262
+ const allowed = new Set([
263
+ '--accept-disclosure',
264
+ '--telemetry',
265
+ 'off',
266
+ '--claude-shadow',
267
+ '--claude-diagnostics',
268
+ ]);
269
+ const hasOptOut =
270
+ args.includes('--telemetry') ||
271
+ args.includes('--claude-shadow') ||
272
+ args.includes('--claude-diagnostics');
273
+ if (!hasOptOut || args.some((argument) => !allowed.has(argument))) return false;
274
+ const requestedOff =
275
+ option(args, '--telemetry') === 'off' ||
276
+ option(args, '--claude-shadow') === 'off' ||
277
+ option(args, '--claude-diagnostics') === 'off';
278
+ if (!requestedOff) return false;
279
+ if (!previous) {
280
+ console.log(
281
+ 'AI Brain local opt-out already has no configured account; no provider call was made.',
282
+ );
283
+ return true;
284
+ }
285
+ const root = await ensureStateRoot();
286
+ const observation = claudeObservationSelection(args, previous);
287
+ const telemetry = telemetrySelection(args, previous);
288
+ await atomicJson(`${root}/config.json`, {
289
+ ...previous,
290
+ telemetry: {
291
+ enabled: telemetry.enabled,
292
+ disclosedAt: telemetry.disclosedAt,
293
+ },
294
+ claudeObservation: observation,
295
+ });
296
+ console.log(`Local observation settings updated in ${root}; no provider call was made.`);
297
+ return true;
298
+ }
299
+
191
300
  /** @param {string} endpoint */
192
301
  function validateEndpoint(endpoint) {
193
302
  if (endpoint.length > 2048) throw new Error('endpoint_too_long');
@@ -209,9 +318,28 @@ function validateEndpoint(endpoint) {
209
318
  throw new Error('endpoint_credentials_query_or_fragment_rejected');
210
319
  }
211
320
 
212
- /** @param {string[]} args @param {string} endpoint @param {import('./policy.mjs').ContextPolicy} policy @param {string} disclosureVersion */
213
- async function disclosureAccepted(args, endpoint, policy, disclosureVersion) {
214
- const disclosure = `AI Brain sends selected task/message/tool-input projections through AI Brain to JEV/TypeSafe at https://api.typesafe.ai/v1/systemone. Retention profile: ${policy.profile}; compact at ${policy.compactAtPercent}%; keep threshold ${policy.keepThreshold}; recent messages ${policy.preserveRecentMessages}; Claude tool policy ${policy.toolPolicy}. Selected projections are bounded and filtered; private local recovery files remain on this machine. Hidden fields and redaction limits apply; no zero-retention or complete-redaction claim. Goal present: ${policy.goal !== undefined}. Endpoint: ${endpoint}. Disclosure: ${disclosureVersion}.`;
321
+ /** @param {string[]} args @param {string} endpoint @param {import('./policy.mjs').ContextPolicy} policy @param {string} disclosureVersion @param {boolean} telemetryEnabled @param {boolean} shadowEnabled @param {boolean} diagnosticsEnabled */
322
+ async function disclosureAccepted(
323
+ args,
324
+ endpoint,
325
+ policy,
326
+ disclosureVersion,
327
+ telemetryEnabled,
328
+ shadowEnabled,
329
+ diagnosticsEnabled,
330
+ ) {
331
+ const telemetryDisclosure = telemetryEnabled
332
+ ? ' Operational telemetry is enabled: only a hashed native session key, random lifecycle identifiers, client version, phase, timestamps, numeric counts and allowed measurement/reason enums are sent for the authenticated Contexto dashboard. Prompts, notes, paths, tool names, credentials and raw errors are excluded; the dashboard shows a 30-day visible window and physical cleanup runs on the next successful daily cleanup; delivery failure does not affect compaction.'
333
+ : '';
334
+ const shadowDisclosure =
335
+ shadowEnabled || option(args, '--claude-shadow') === 'on'
336
+ ? ' Claude shadow observation is enabled: bounded redacted task and tool metadata may be sent through AI Brain to the existing JEV selection service for hypothetical decisions; native Claude results remain unchanged and private diagnostics exclude prompts, paths, inputs, result bodies, credentials and raw errors.'
337
+ : '';
338
+ const diagnosticsDisclosure =
339
+ diagnosticsEnabled || option(args, '--claude-diagnostics') === 'on'
340
+ ? ' Claude compact diagnostics are enabled locally: bounded stages, enums, pseudonymous identifiers, timestamps and numeric measurements are stored in private rotated logs; prompts, paths, inputs, result bodies, credentials and raw errors are excluded.'
341
+ : '';
342
+ const disclosure = `AI Brain sends selected task/message/tool-input projections through AI Brain to JEV/TypeSafe at https://api.typesafe.ai/v1/systemone. Retention profile: ${policy.profile}; compact at ${policy.compactAtPercent}%; keep threshold ${policy.keepThreshold}; recent messages ${policy.preserveRecentMessages}; Claude tool policy ${policy.toolPolicy}. Selected projections are bounded and filtered; private local recovery files remain on this machine. Hidden fields and redaction limits apply; no zero-retention or complete-redaction claim. Goal present: ${policy.goal !== undefined}.${telemetryDisclosure}${shadowDisclosure}${diagnosticsDisclosure} Endpoint: ${endpoint}. Disclosure: ${disclosureVersion}.`;
215
343
  if (args.includes('--accept-disclosure')) {
216
344
  console.log(disclosure);
217
345
  return true;
@@ -241,6 +369,9 @@ async function setup(args) {
241
369
  '--context-profile',
242
370
  ...POLICY_OPTION_NAMES,
243
371
  '--goal',
372
+ '--telemetry',
373
+ '--claude-shadow',
374
+ '--claude-diagnostics',
244
375
  ]),
245
376
  new Set([
246
377
  '--client',
@@ -249,25 +380,51 @@ async function setup(args) {
249
380
  '--context-profile',
250
381
  ...POLICY_OPTION_NAMES,
251
382
  '--goal',
383
+ '--telemetry',
384
+ '--claude-shadow',
385
+ '--claude-diagnostics',
252
386
  ]),
253
387
  );
254
388
  if (args.includes('--undo') && args.length !== 1)
255
389
  throw new Error('setup_undo_cannot_have_options');
256
390
  const previous = await readConfig();
391
+ if (await updateLocalOptOut(previous, args)) return;
392
+ const localOptOut =
393
+ option(args, '--telemetry') === 'off' &&
394
+ args.every((argument) => ['--telemetry', 'off', '--accept-disclosure'].includes(argument));
395
+ if (localOptOut) return disableTelemetryLocally(previous);
257
396
  const platform = platformCheck();
258
397
  if (!platform.ok) throw new Error(`${platform.code}:${platform.message}`);
259
398
  const clients = option(args, '--client') ?? 'both';
260
399
  if (!['claude', 'codex', 'both'].includes(clients)) throw new Error('invalid_client');
400
+ if (
401
+ clients === 'codex' &&
402
+ (option(args, '--claude-shadow') !== undefined ||
403
+ option(args, '--claude-diagnostics') !== undefined)
404
+ )
405
+ throw new Error('claude_observation_requires_claude_client');
261
406
  const endpoint = option(args, '--endpoint') ?? ENDPOINT;
262
407
  validateEndpoint(endpoint);
263
408
  const selection = selectedPolicy(args, previous);
409
+ const telemetry = telemetrySelection(args, previous);
410
+ const claudeObservation = claudeObservationSelection(args, previous);
264
411
  const policy = selection.policy;
265
412
  const disclosureVersion = selection.v2
266
413
  ? DISCLOSURE_VERSION
267
414
  : (previous?.disclosureVersion ?? LEGACY_DISCLOSURE_VERSION);
268
415
  if (selection.v2 && (clients === 'codex' || clients === 'both')) codexPolicyJson(policy);
269
416
  console.log(`Effective context policy ${policySummary(policy)}`);
270
- if (!(await disclosureAccepted(args, endpoint, policy, disclosureVersion)))
417
+ if (
418
+ !(await disclosureAccepted(
419
+ args,
420
+ endpoint,
421
+ policy,
422
+ disclosureVersion,
423
+ telemetry.enabled,
424
+ claudeObservation.shadowEnabled,
425
+ claudeObservation.diagnosticsEnabled,
426
+ ))
427
+ )
271
428
  throw new Error('disclosure_not_accepted');
272
429
  const root = await ensureStateRoot();
273
430
  const tokenPath = option(args, '--token-file');
@@ -299,6 +456,13 @@ async function setup(args) {
299
456
  codexVersion,
300
457
  packageRoot: PACKAGE_ROOT,
301
458
  ...(selection.v2 ? { context: policy } : {}),
459
+ telemetry: {
460
+ enabled: telemetry.enabled,
461
+ disclosedAt: telemetry.enabled
462
+ ? (telemetry.disclosedAt ?? new Date().toISOString())
463
+ : telemetry.disclosedAt,
464
+ },
465
+ claudeObservation,
302
466
  };
303
467
  let probe;
304
468
  try {
@@ -373,6 +537,18 @@ async function doctor(json) {
373
537
  nativeVersions,
374
538
  nativeReady,
375
539
  context: publicPolicy(policy),
540
+ telemetry: {
541
+ enabled: config?.telemetry?.enabled === true,
542
+ disclosed:
543
+ config?.telemetry?.disclosedAt !== null && config?.telemetry?.disclosedAt !== undefined,
544
+ },
545
+ claudeObservation: {
546
+ shadowEnabled: config?.claudeObservation?.shadowEnabled === true,
547
+ diagnosticsEnabled: config?.claudeObservation?.diagnosticsEnabled === true,
548
+ disclosed:
549
+ config?.claudeObservation?.disclosedAt !== null &&
550
+ config?.claudeObservation?.disclosedAt !== undefined,
551
+ },
376
552
  paidOrPilot: probe?.ok
377
553
  ? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
378
554
  : config
@@ -396,6 +572,18 @@ async function status(json) {
396
572
  disclosed: config?.disclosureVersion !== undefined,
397
573
  schemaVersion: config?.schemaVersion ?? null,
398
574
  context: publicPolicy(policy),
575
+ telemetry: {
576
+ enabled: config?.telemetry?.enabled === true,
577
+ disclosed:
578
+ config?.telemetry?.disclosedAt !== null && config?.telemetry?.disclosedAt !== undefined,
579
+ },
580
+ claudeObservation: {
581
+ shadowEnabled: config?.claudeObservation?.shadowEnabled === true,
582
+ diagnosticsEnabled: config?.claudeObservation?.diagnosticsEnabled === true,
583
+ disclosed:
584
+ config?.claudeObservation?.disclosedAt !== null &&
585
+ config?.claudeObservation?.disclosedAt !== undefined,
586
+ },
399
587
  monitoredSession: null,
400
588
  monitoringStatus: 'not_observed',
401
589
  };
@@ -423,6 +611,27 @@ async function main(argv) {
423
611
  validateOptions(rest, new Set(['--json']), new Set());
424
612
  return status(rest.includes('--json'));
425
613
  }
614
+ if (command === 'diagnostics') {
615
+ validateOptions(
616
+ rest,
617
+ new Set(['--client', '--tail', '--json']),
618
+ new Set(['--client', '--tail']),
619
+ );
620
+ const requestedClient = option(rest, '--client');
621
+ if (requestedClient !== undefined && !['claude', 'codex'].includes(requestedClient))
622
+ throw new Error('diagnostics_client_unsupported');
623
+ const tail = Number(option(rest, '--tail') ?? '20');
624
+ if (!Number.isSafeInteger(tail) || tail < 1 || tail > 100)
625
+ throw new Error('invalid_diagnostics_tail');
626
+ const client = requestedClient ?? 'claude';
627
+ const records =
628
+ client === 'codex'
629
+ ? await readCodexDiagnostics(stateRoot(), tail)
630
+ : await readDiagnostics(stateRoot(), tail);
631
+ if (rest.includes('--json')) console.log(JSON.stringify({ client, records }));
632
+ else console.log(records);
633
+ return;
634
+ }
426
635
  if (command === 'disable') {
427
636
  if (rest.length > 0) throw new Error('disable_does_not_accept_options');
428
637
  return removeOwnedSetup();