@brunobracaioli/aibrain 0.1.0-beta.1 → 0.3.0-beta.13

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
@@ -15,20 +15,38 @@ import {
15
15
  stateRoot,
16
16
  tokenDigest,
17
17
  } from './state.mjs';
18
- import { isTestedNativeVersion, nativeVersion, platformCheck, resolveNative } from './platform.mjs';
18
+ import {
19
+ isTestedNativeVersion,
20
+ nativeVersion,
21
+ nativeVersionDiagnostic,
22
+ platformCheck,
23
+ resolveNative,
24
+ } from './platform.mjs';
19
25
  import { launchClaude, launchCodex } from './launch.mjs';
26
+ import { codexCompatibilityError, resolveCodexCompatibility } from './codex-compatibility.mjs';
20
27
  import { providerFreeProbe } from './mcp.mjs';
28
+ import { codexPolicyJson, makePolicy, publicPolicy, isProfile } from './policy.mjs';
29
+ import { readDiagnostics } from './claude-observation.mjs';
30
+ import { readCodexDiagnostics } from './codex-diagnostics.mjs';
21
31
 
22
- const VERSION = '0.1.0-beta.1';
32
+ const VERSION = '0.3.0-beta.13';
23
33
  const ENDPOINT = 'https://mcp.ai-brain.aisac.cloud/mcp';
24
34
  const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
35
+ const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
25
36
 
26
37
  function usage() {
27
38
  console.log(
28
- `aibrain ${VERSION}\n\nUsage:\n aibrain setup [--client claude|codex|both] [--token-file PATH] [--accept-disclosure]\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...]`,
39
+ `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.`,
40
+ );
41
+ console.log(
42
+ 'Telemetry: setup --telemetry on|off (omitted preserves the stored choice; fresh defaults off).',
43
+ );
44
+ console.log(
45
+ 'Claude shadow: setup --claude-shadow on|off and --claude-diagnostics on|off (preview stays applied=false).',
29
46
  );
30
47
  }
31
48
 
49
+ // Telemetry is opt-in; setup omits the flag to preserve the stored choice.
32
50
  function version() {
33
51
  console.log(`aibrain ${VERSION}`);
34
52
  }
@@ -97,6 +115,195 @@ function validateOptions(args, allowed, valueOptions) {
97
115
  }
98
116
  }
99
117
 
118
+ const POLICY_OPTION_NAMES = new Set([
119
+ '--compact-at',
120
+ '--keep-threshold',
121
+ '--preserve-recent',
122
+ '--min-reduction',
123
+ '--truncate-head-chars',
124
+ '--max-state-tokens',
125
+ '--max-request-tokens',
126
+ '--tool-policy',
127
+ ]);
128
+
129
+ /** @param {string[]} args */
130
+ function policyOverrides(args) {
131
+ /** @type {Record<string, string | number>} */
132
+ const values = {};
133
+ /** @type {Map<string, [string, (value: string) => string | number]>} */
134
+ const fields = new Map([
135
+ ['--compact-at', ['compactAtPercent', Number]],
136
+ ['--keep-threshold', ['keepThreshold', Number]],
137
+ ['--preserve-recent', ['preserveRecentMessages', Number]],
138
+ ['--min-reduction', ['minReductionRatio', Number]],
139
+ ['--truncate-head-chars', ['truncateHeadChars', Number]],
140
+ ['--max-state-tokens', ['maxStateTokens', Number]],
141
+ ['--max-request-tokens', ['maxRequestTokens', Number]],
142
+ ['--tool-policy', ['toolPolicy', String]],
143
+ ]);
144
+ for (const [optionName, [field, convert]] of fields) {
145
+ const raw = option(args, optionName);
146
+ if (raw === undefined) continue;
147
+ const converted = convert(raw);
148
+ if (typeof converted === 'number' && !Number.isFinite(converted))
149
+ throw new Error(`invalid_${field}`);
150
+ values[field] = converted;
151
+ }
152
+ return values;
153
+ }
154
+
155
+ /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
156
+ function selectedPolicy(args, previous) {
157
+ const explicitProfile = option(args, '--context-profile');
158
+ const explicitV2 =
159
+ explicitProfile !== undefined ||
160
+ args.some(
161
+ (item) =>
162
+ POLICY_OPTION_NAMES.has(item) ||
163
+ item === '--goal' ||
164
+ item === '--claude-shadow' ||
165
+ item === '--claude-diagnostics',
166
+ );
167
+ if (previous?.schemaVersion === 1 && !explicitV2)
168
+ return { v2: false, policy: makePolicy('conservative') };
169
+ const inherited = previous?.schemaVersion === 2 ? previous.context : undefined;
170
+ const profile = explicitProfile ?? inherited?.profile ?? (previous ? 'conservative' : 'upstream');
171
+ if (!isProfile(profile)) throw new Error('invalid_context_profile');
172
+ const overrides = policyOverrides(args);
173
+ if (inherited !== undefined && explicitProfile === undefined) {
174
+ for (const key of [
175
+ 'compactAtPercent',
176
+ 'keepThreshold',
177
+ 'preserveRecentMessages',
178
+ 'minReductionRatio',
179
+ 'truncateHeadChars',
180
+ 'maxStateTokens',
181
+ 'maxRequestTokens',
182
+ 'toolPolicy',
183
+ ]) {
184
+ if (!Object.hasOwn(overrides, key))
185
+ overrides[key] =
186
+ inherited[
187
+ /** @type {keyof Omit<import('./policy.mjs').ContextPolicy, 'profile' | 'goal'>} */ (
188
+ key
189
+ )
190
+ ];
191
+ }
192
+ if (option(args, '--goal') === undefined && inherited.goal !== undefined)
193
+ overrides.goal = inherited.goal;
194
+ }
195
+ const clients = option(args, '--client') ?? 'both';
196
+ if (
197
+ clients === 'codex' &&
198
+ args.some(
199
+ (item) =>
200
+ item === '--min-reduction' || item === '--truncate-head-chars' || item === '--tool-policy',
201
+ )
202
+ )
203
+ throw new Error('claude_only_policy_option_for_codex');
204
+ const goal = option(args, '--goal');
205
+ return { v2: true, policy: makePolicy(profile, overrides, goal ?? inherited?.goal) };
206
+ }
207
+
208
+ /** @param {import('./policy.mjs').ContextPolicy} policy */
209
+ function policySummary(policy) {
210
+ return JSON.stringify({ effective: publicPolicy(policy) });
211
+ }
212
+
213
+ /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
214
+ function telemetrySelection(args, previous) {
215
+ const requested = option(args, '--telemetry');
216
+ if (requested !== undefined && requested !== 'on' && requested !== 'off')
217
+ throw new Error('invalid_telemetry');
218
+ const current = previous?.telemetry;
219
+ const enabled = requested === undefined ? current?.enabled === true : requested === 'on';
220
+ return {
221
+ enabled,
222
+ disclosedAt: current?.disclosedAt ?? null,
223
+ };
224
+ }
225
+
226
+ /** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
227
+ function claudeObservationSelection(args, previous) {
228
+ const shadow = option(args, '--claude-shadow');
229
+ const diagnostics = option(args, '--claude-diagnostics');
230
+ for (const value of [shadow, diagnostics]) {
231
+ if (value !== undefined && value !== 'on' && value !== 'off')
232
+ throw new Error('invalid_claude_observation');
233
+ }
234
+ const current = previous?.claudeObservation;
235
+ const shadowEnabled = shadow === undefined ? current?.shadowEnabled === true : shadow === 'on';
236
+ const diagnosticsEnabled =
237
+ diagnostics === undefined ? current?.diagnosticsEnabled === true : diagnostics === 'on';
238
+ const enabled = shadowEnabled || diagnosticsEnabled;
239
+ return {
240
+ shadowEnabled,
241
+ diagnosticsEnabled,
242
+ disclosedAt: enabled
243
+ ? (current?.disclosedAt ?? new Date().toISOString())
244
+ : (current?.disclosedAt ?? null),
245
+ };
246
+ }
247
+
248
+ /** @param {Awaited<ReturnType<typeof readConfig>>} previous Disable future-launch egress locally without probing the server or requiring native clients. */
249
+ async function disableTelemetryLocally(previous) {
250
+ if (!previous) {
251
+ console.log('Context dashboard telemetry is already disabled; no local setup exists.');
252
+ return;
253
+ }
254
+ const root = await ensureStateRoot();
255
+ await atomicJson(`${root}/config.json`, {
256
+ ...previous,
257
+ telemetry: {
258
+ enabled: false,
259
+ disclosedAt: previous.telemetry?.disclosedAt ?? null,
260
+ },
261
+ });
262
+ console.log(
263
+ `Context dashboard telemetry disabled for future launches in ${root}. Close and restart currently monitored sessions to stop their launch-captured reporting settings.`,
264
+ );
265
+ }
266
+
267
+ /** @param {Awaited<ReturnType<typeof readConfig>>} previous @param {string[]} args */
268
+ async function updateLocalOptOut(previous, args) {
269
+ const allowed = new Set([
270
+ '--accept-disclosure',
271
+ '--telemetry',
272
+ 'off',
273
+ '--claude-shadow',
274
+ '--claude-diagnostics',
275
+ ]);
276
+ const hasOptOut =
277
+ args.includes('--telemetry') ||
278
+ args.includes('--claude-shadow') ||
279
+ args.includes('--claude-diagnostics');
280
+ if (!hasOptOut || args.some((argument) => !allowed.has(argument))) return false;
281
+ const requestedOff =
282
+ option(args, '--telemetry') === 'off' ||
283
+ option(args, '--claude-shadow') === 'off' ||
284
+ option(args, '--claude-diagnostics') === 'off';
285
+ if (!requestedOff) return false;
286
+ if (!previous) {
287
+ console.log(
288
+ 'AI Brain local opt-out already has no configured account; no provider call was made.',
289
+ );
290
+ return true;
291
+ }
292
+ const root = await ensureStateRoot();
293
+ const observation = claudeObservationSelection(args, previous);
294
+ const telemetry = telemetrySelection(args, previous);
295
+ await atomicJson(`${root}/config.json`, {
296
+ ...previous,
297
+ telemetry: {
298
+ enabled: telemetry.enabled,
299
+ disclosedAt: telemetry.disclosedAt,
300
+ },
301
+ claudeObservation: observation,
302
+ });
303
+ console.log(`Local observation settings updated in ${root}; no provider call was made.`);
304
+ return true;
305
+ }
306
+
100
307
  /** @param {string} endpoint */
101
308
  function validateEndpoint(endpoint) {
102
309
  if (endpoint.length > 2048) throw new Error('endpoint_too_long');
@@ -118,9 +325,28 @@ function validateEndpoint(endpoint) {
118
325
  throw new Error('endpoint_credentials_query_or_fragment_rejected');
119
326
  }
120
327
 
121
- /** @param {string[]} args @param {string} endpoint */
122
- async function disclosureAccepted(args, endpoint) {
123
- const disclosure = `AI Brain sends selected task/message/tool-input projections through AI Brain to JEV/TypeSafe at https://api.typesafe.ai/v1/systemone. 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. Endpoint: ${endpoint}. Disclosure: ${DISCLOSURE_VERSION}.`;
328
+ /** @param {string[]} args @param {string} endpoint @param {import('./policy.mjs').ContextPolicy} policy @param {string} disclosureVersion @param {boolean} telemetryEnabled @param {boolean} shadowEnabled @param {boolean} diagnosticsEnabled */
329
+ async function disclosureAccepted(
330
+ args,
331
+ endpoint,
332
+ policy,
333
+ disclosureVersion,
334
+ telemetryEnabled,
335
+ shadowEnabled,
336
+ diagnosticsEnabled,
337
+ ) {
338
+ const telemetryDisclosure = telemetryEnabled
339
+ ? ' 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.'
340
+ : '';
341
+ const shadowDisclosure =
342
+ shadowEnabled || option(args, '--claude-shadow') === 'on'
343
+ ? ' 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.'
344
+ : '';
345
+ const diagnosticsDisclosure =
346
+ diagnosticsEnabled || option(args, '--claude-diagnostics') === 'on'
347
+ ? ' 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.'
348
+ : '';
349
+ 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}.`;
124
350
  if (args.includes('--accept-disclosure')) {
125
351
  console.log(disclosure);
126
352
  return true;
@@ -140,18 +366,73 @@ async function setup(args) {
140
366
  if (args.includes('--yes')) throw new Error('explicit_disclosure_flag_required');
141
367
  validateOptions(
142
368
  args,
143
- new Set(['--client', '--token-file', '--accept-disclosure', '--endpoint', '--yes', '--undo']),
144
- new Set(['--client', '--token-file', '--endpoint']),
369
+ new Set([
370
+ '--client',
371
+ '--token-file',
372
+ '--accept-disclosure',
373
+ '--endpoint',
374
+ '--yes',
375
+ '--undo',
376
+ '--context-profile',
377
+ ...POLICY_OPTION_NAMES,
378
+ '--goal',
379
+ '--telemetry',
380
+ '--claude-shadow',
381
+ '--claude-diagnostics',
382
+ ]),
383
+ new Set([
384
+ '--client',
385
+ '--token-file',
386
+ '--endpoint',
387
+ '--context-profile',
388
+ ...POLICY_OPTION_NAMES,
389
+ '--goal',
390
+ '--telemetry',
391
+ '--claude-shadow',
392
+ '--claude-diagnostics',
393
+ ]),
145
394
  );
146
395
  if (args.includes('--undo') && args.length !== 1)
147
396
  throw new Error('setup_undo_cannot_have_options');
397
+ const previous = await readConfig();
398
+ if (await updateLocalOptOut(previous, args)) return;
399
+ const localOptOut =
400
+ option(args, '--telemetry') === 'off' &&
401
+ args.every((argument) => ['--telemetry', 'off', '--accept-disclosure'].includes(argument));
402
+ if (localOptOut) return disableTelemetryLocally(previous);
148
403
  const platform = platformCheck();
149
404
  if (!platform.ok) throw new Error(`${platform.code}:${platform.message}`);
150
405
  const clients = option(args, '--client') ?? 'both';
151
406
  if (!['claude', 'codex', 'both'].includes(clients)) throw new Error('invalid_client');
407
+ if (
408
+ clients === 'codex' &&
409
+ (option(args, '--claude-shadow') !== undefined ||
410
+ option(args, '--claude-diagnostics') !== undefined)
411
+ )
412
+ throw new Error('claude_observation_requires_claude_client');
152
413
  const endpoint = option(args, '--endpoint') ?? ENDPOINT;
153
414
  validateEndpoint(endpoint);
154
- if (!(await disclosureAccepted(args, endpoint))) throw new Error('disclosure_not_accepted');
415
+ const selection = selectedPolicy(args, previous);
416
+ const telemetry = telemetrySelection(args, previous);
417
+ const claudeObservation = claudeObservationSelection(args, previous);
418
+ const policy = selection.policy;
419
+ const disclosureVersion = selection.v2
420
+ ? DISCLOSURE_VERSION
421
+ : (previous?.disclosureVersion ?? LEGACY_DISCLOSURE_VERSION);
422
+ if (selection.v2 && (clients === 'codex' || clients === 'both')) codexPolicyJson(policy);
423
+ console.log(`Effective context policy ${policySummary(policy)}`);
424
+ if (
425
+ !(await disclosureAccepted(
426
+ args,
427
+ endpoint,
428
+ policy,
429
+ disclosureVersion,
430
+ telemetry.enabled,
431
+ claudeObservation.shadowEnabled,
432
+ claudeObservation.diagnosticsEnabled,
433
+ ))
434
+ )
435
+ throw new Error('disclosure_not_accepted');
155
436
  const root = await ensureStateRoot();
156
437
  const tokenPath = option(args, '--token-file');
157
438
  let token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
@@ -164,27 +445,40 @@ async function setup(args) {
164
445
  if ((clients === 'codex' || clients === 'both') && (!codex || !node))
165
446
  throw new Error('codex_or_node_not_found');
166
447
  const claudeVersion = claude ? nativeVersion(claude) : null;
167
- const codexVersion = codex ? nativeVersion(codex) : null;
168
448
  const claudeSupported = claudeVersion !== null && isTestedNativeVersion('claude', claudeVersion);
169
- const codexSupported = codexVersion !== null && isTestedNativeVersion('codex', codexVersion);
170
449
  if ((clients === 'claude' || clients === 'both') && !claudeSupported)
171
- throw new Error('claude_version_unverified');
172
- if ((clients === 'codex' || clients === 'both') && !codexSupported)
173
- throw new Error('codex_version_unverified');
450
+ throw new Error(nativeVersionDiagnostic('claude', claudeVersion ?? ''));
451
+ let codexCompatibility = null;
452
+ if (clients === 'codex' || clients === 'both') {
453
+ codexCompatibility = codex ? await resolveCodexCompatibility(codex) : null;
454
+ if (codexCompatibility?.status === 'rejected')
455
+ throw new Error(codexCompatibilityError(codexCompatibility));
456
+ }
457
+ const codexVersion = codexCompatibility?.version ?? (codex ? nativeVersion(codex) : null);
174
458
  const config = {
175
- schemaVersion: 1,
459
+ schemaVersion: selection.v2 ? 2 : 1,
176
460
  packageVersion: VERSION,
177
- disclosureVersion: DISCLOSURE_VERSION,
461
+ disclosureVersion,
178
462
  disclosedAt: new Date().toISOString(),
179
463
  endpoint,
180
464
  clientSelection: clients,
181
465
  claudeVersion,
182
466
  codexVersion,
183
467
  packageRoot: PACKAGE_ROOT,
468
+ ...(selection.v2 ? { context: policy } : {}),
469
+ telemetry: {
470
+ enabled: telemetry.enabled,
471
+ disclosedAt: telemetry.enabled
472
+ ? (telemetry.disclosedAt ?? new Date().toISOString())
473
+ : telemetry.disclosedAt,
474
+ },
475
+ claudeObservation,
184
476
  };
185
477
  let probe;
186
478
  try {
187
- probe = await providerFreeProbe(endpoint, token);
479
+ probe = selection.v2
480
+ ? await providerFreeProbe(endpoint, token, policy, clients)
481
+ : await providerFreeProbe(endpoint, token);
188
482
  } catch (error) {
189
483
  throw new Error(`provider_free_probe_failed:${errorMessage(error)}`);
190
484
  }
@@ -204,11 +498,18 @@ async function setup(args) {
204
498
  async function doctor(json) {
205
499
  const platform = platformCheck();
206
500
  const config = await readConfig();
501
+ const policy =
502
+ config?.schemaVersion === 2 && config.context !== undefined
503
+ ? config.context
504
+ : makePolicy('conservative');
207
505
  let probe = null;
208
506
  let probeError = null;
209
507
  if (config) {
210
508
  try {
211
- probe = await providerFreeProbe(config.endpoint, config.token);
509
+ probe =
510
+ config.schemaVersion === 2
511
+ ? await providerFreeProbe(config.endpoint, config.token, policy, config.clientSelection)
512
+ : await providerFreeProbe(config.endpoint, config.token);
212
513
  } catch (error) {
213
514
  probeError = errorMessage(error);
214
515
  }
@@ -218,10 +519,16 @@ async function doctor(json) {
218
519
  codex: resolveNative('codex'),
219
520
  node: resolveNative('node'),
220
521
  };
221
- const nativeVersions = {
522
+ const rawNativeVersions = {
222
523
  claude: native.claude ? nativeVersion(native.claude) : '',
223
524
  codex: native.codex ? nativeVersion(native.codex) : '',
224
525
  };
526
+ const codexCompatibility =
527
+ native.codex !== null ? await resolveCodexCompatibility(native.codex) : null;
528
+ const nativeVersions = {
529
+ ...rawNativeVersions,
530
+ codex: codexCompatibility?.version ?? rawNativeVersions.codex,
531
+ };
225
532
  const needsClaude = config?.clientSelection === 'claude' || config?.clientSelection === 'both';
226
533
  const needsCodex = config?.clientSelection === 'codex' || config?.clientSelection === 'both';
227
534
  const nativeReady =
@@ -230,19 +537,38 @@ async function doctor(json) {
230
537
  (!needsCodex ||
231
538
  (native.codex !== null &&
232
539
  native.node !== null &&
233
- isTestedNativeVersion('codex', nativeVersions.codex)));
540
+ (codexCompatibility?.status === 'qualified' ||
541
+ codexCompatibility?.status === 'protocol_match')));
234
542
  const result = {
235
543
  version: VERSION,
236
544
  platform: platform.ok ? process.platform : platform.code,
237
545
  setup: config !== null,
238
- disclosed: config?.disclosureVersion === DISCLOSURE_VERSION,
546
+ disclosed:
547
+ config?.disclosureVersion === DISCLOSURE_VERSION ||
548
+ config?.disclosureVersion === LEGACY_DISCLOSURE_VERSION,
239
549
  native: {
240
550
  claude: native.claude !== null,
241
551
  codex: native.codex !== null,
242
552
  node: native.node !== null,
243
553
  },
244
554
  nativeVersions,
555
+ codexCompatibility: codexCompatibility?.status ?? 'unavailable',
556
+ codexCompatibilityReason: codexCompatibility?.reason ?? 'codex_not_found',
557
+ codexCompatibilityVersion: codexCompatibility?.version ?? null,
245
558
  nativeReady,
559
+ context: publicPolicy(policy),
560
+ telemetry: {
561
+ enabled: config?.telemetry?.enabled === true,
562
+ disclosed:
563
+ config?.telemetry?.disclosedAt !== null && config?.telemetry?.disclosedAt !== undefined,
564
+ },
565
+ claudeObservation: {
566
+ shadowEnabled: config?.claudeObservation?.shadowEnabled === true,
567
+ diagnosticsEnabled: config?.claudeObservation?.diagnosticsEnabled === true,
568
+ disclosed:
569
+ config?.claudeObservation?.disclosedAt !== null &&
570
+ config?.claudeObservation?.disclosedAt !== undefined,
571
+ },
246
572
  paidOrPilot: probe?.ok
247
573
  ? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
248
574
  : config
@@ -257,9 +583,27 @@ async function doctor(json) {
257
583
  /** @param {boolean} json */
258
584
  async function status(json) {
259
585
  const config = await readConfig();
586
+ const policy =
587
+ config?.schemaVersion === 2 && config.context !== undefined
588
+ ? config.context
589
+ : makePolicy('conservative');
260
590
  const result = {
261
591
  setup: config !== null,
262
- disclosed: config?.disclosureVersion === DISCLOSURE_VERSION,
592
+ disclosed: config?.disclosureVersion !== undefined,
593
+ schemaVersion: config?.schemaVersion ?? null,
594
+ context: publicPolicy(policy),
595
+ telemetry: {
596
+ enabled: config?.telemetry?.enabled === true,
597
+ disclosed:
598
+ config?.telemetry?.disclosedAt !== null && config?.telemetry?.disclosedAt !== undefined,
599
+ },
600
+ claudeObservation: {
601
+ shadowEnabled: config?.claudeObservation?.shadowEnabled === true,
602
+ diagnosticsEnabled: config?.claudeObservation?.diagnosticsEnabled === true,
603
+ disclosed:
604
+ config?.claudeObservation?.disclosedAt !== null &&
605
+ config?.claudeObservation?.disclosedAt !== undefined,
606
+ },
263
607
  monitoredSession: null,
264
608
  monitoringStatus: 'not_observed',
265
609
  };
@@ -287,6 +631,27 @@ async function main(argv) {
287
631
  validateOptions(rest, new Set(['--json']), new Set());
288
632
  return status(rest.includes('--json'));
289
633
  }
634
+ if (command === 'diagnostics') {
635
+ validateOptions(
636
+ rest,
637
+ new Set(['--client', '--tail', '--json']),
638
+ new Set(['--client', '--tail']),
639
+ );
640
+ const requestedClient = option(rest, '--client');
641
+ if (requestedClient !== undefined && !['claude', 'codex'].includes(requestedClient))
642
+ throw new Error('diagnostics_client_unsupported');
643
+ const tail = Number(option(rest, '--tail') ?? '20');
644
+ if (!Number.isSafeInteger(tail) || tail < 1 || tail > 100)
645
+ throw new Error('invalid_diagnostics_tail');
646
+ const client = requestedClient ?? 'claude';
647
+ const records =
648
+ client === 'codex'
649
+ ? await readCodexDiagnostics(stateRoot(), tail)
650
+ : await readDiagnostics(stateRoot(), tail);
651
+ if (rest.includes('--json')) console.log(JSON.stringify({ client, records }));
652
+ else console.log(records);
653
+ return;
654
+ }
290
655
  if (command === 'disable') {
291
656
  if (rest.length > 0) throw new Error('disable_does_not_accept_options');
292
657
  return removeOwnedSetup();
@@ -294,7 +659,8 @@ async function main(argv) {
294
659
  if (command === 'claude' || command === 'codex') {
295
660
  const config = await readConfig();
296
661
  if (!config || config.disclosedAt === undefined) throw new Error('setup_required');
297
- if (config.disclosureVersion !== DISCLOSURE_VERSION) throw new Error('disclosure_outdated');
662
+ if (config.schemaVersion === 2 && config.disclosureVersion !== DISCLOSURE_VERSION)
663
+ throw new Error('disclosure_outdated');
298
664
  if (config.clientSelection !== command && config.clientSelection !== 'both')
299
665
  throw new Error('client_not_configured');
300
666
  if (
@@ -302,12 +668,13 @@ async function main(argv) {
302
668
  (typeof config.claudeVersion !== 'string' ||
303
669
  !isTestedNativeVersion('claude', config.claudeVersion))
304
670
  )
305
- throw new Error('claude_version_unverified');
306
- if (
307
- command === 'codex' &&
308
- (typeof config.codexVersion !== 'string' ||
309
- !isTestedNativeVersion('codex', config.codexVersion))
310
- )
671
+ throw new Error(
672
+ nativeVersionDiagnostic(
673
+ 'claude',
674
+ typeof config.claudeVersion === 'string' ? config.claudeVersion : '',
675
+ ),
676
+ );
677
+ if (command === 'codex' && typeof config.codexVersion !== 'string')
311
678
  throw new Error('codex_version_unverified');
312
679
  const root = stateRoot();
313
680
  const result = await (command === 'claude'