@bonesofspring/ai-rules 0.2.69 → 0.2.71

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.
@@ -3,10 +3,11 @@
3
3
  * Fixed context cost of the preset: per host the always-on files, their bytes,
4
4
  * and a labelled `bytes / 4` estimate; per Cursor fixture the attached lines
5
5
  * against its cap; per task the artifact bytes; the `usage_recorded` totals;
6
- * the OpenCode output-guard replacement totals.
6
+ * the OpenCode output-guard replacement totals; the hook-time MCP schema split.
7
7
  *
8
- * Counts the bytes of *inputs* — prompt files and task artifacts — not the
9
- * tokens of a session. Read-only: prints to stdout, writes nothing.
8
+ * Counts the bytes of *inputs* — prompt files, task artifacts, and the tool
9
+ * schemas the output-guard snapshot recorded — not the tokens of a session.
10
+ * Read-only: prints to stdout, writes nothing.
10
11
  *
11
12
  * Usage (any cwd; the repo root is resolved from this file):
12
13
  * node packages/ai-rules/scripts/report-context-cost.mjs [--json]
@@ -58,6 +59,39 @@ function readJson(file) {
58
59
  return JSON.parse(text);
59
60
  }
60
61
 
62
+ /** The report's only unit conversion, always labelled `EST.TOKENS`. */
63
+ const estimateTokens = (bytes) => Math.round(bytes / 4);
64
+
65
+ /** A byte count that is absent or unusable reads as `null`, never as zero. */
66
+ function numericBytes(value) {
67
+ if (value === null || value === undefined) return null;
68
+ if (typeof value === 'string' && value.trim() === '') return null;
69
+ const number = Number(value);
70
+ return Number.isFinite(number) && number >= 0 ? number : null;
71
+ }
72
+
73
+ /** JSONL rows; unparsable lines are counted and skipped, an absent file reads as empty. */
74
+ function readJsonlRows(file) {
75
+ let text;
76
+ try {
77
+ text = fs.readFileSync(file, 'utf8');
78
+ } catch (error) {
79
+ if (error.code === 'ENOENT') return { rows: [], invalid: 0, present: false };
80
+ throw error;
81
+ }
82
+ const rows = [];
83
+ let invalid = 0;
84
+ for (const line of text.split('\n')) {
85
+ if (line.trim() === '') continue;
86
+ try {
87
+ rows.push(JSON.parse(line));
88
+ } catch {
89
+ invalid += 1;
90
+ }
91
+ }
92
+ return { rows, invalid, present: true };
93
+ }
94
+
61
95
  function splitFrontmatter(text) {
62
96
  if (!text.startsWith('---')) return { frontmatter: '', body: text };
63
97
  const end = text.indexOf('\n---', 3);
@@ -102,7 +136,7 @@ function hostEntry(rule, candidates) {
102
136
  rule: missing.length === 0 ? rule : `${rule} (missing: ${missing.sort().join(', ')})`,
103
137
  alwaysOnFiles: alwaysOnFiles.sort(),
104
138
  alwaysOnBytes: bytes,
105
- estimatedTokens: Math.round(bytes / 4),
139
+ estimatedTokens: estimateTokens(bytes),
106
140
  };
107
141
  }
108
142
 
@@ -307,6 +341,135 @@ export function summarizeOutputGuard(rows) {
307
341
  };
308
342
  }
309
343
 
344
+ /**
345
+ * Attribute the hook-time schema snapshot. The plugin writes one row per
346
+ * `(sessionID, toolset)`; a reload can repeat a key, so the first row wins.
347
+ *
348
+ * `mcpServers` is *absent* when the plugin's MCP list call failed, and an empty
349
+ * array is a measured zero — the two must not read the same. A server with no
350
+ * dispatched schema is omitted by the writer, so an empty array means "none of
351
+ * the listed servers owned a tool", not "no server is configured".
352
+ */
353
+ export function summarizeMcpSnapshots(rows) {
354
+ const seen = new Set();
355
+ const snapshots = [];
356
+ let invalid = 0;
357
+ for (const row of Array.isArray(rows) ? rows : []) {
358
+ if (!row || typeof row !== 'object') {
359
+ invalid += 1;
360
+ continue;
361
+ }
362
+ const sessionID = typeof row.sessionID === 'string' ? row.sessionID : '';
363
+ const toolset = typeof row.toolset === 'string' ? row.toolset : '';
364
+ const toolSchemaBytes = numericBytes(row.toolSchemaBytes);
365
+ if (sessionID === '' || toolset === '' || toolSchemaBytes === null) {
366
+ invalid += 1;
367
+ continue;
368
+ }
369
+ const key = `${sessionID}|${toolset}`;
370
+ if (seen.has(key)) continue;
371
+ seen.add(key);
372
+ snapshots.push({
373
+ at: typeof row.at === 'string' ? row.at : '',
374
+ sessionID,
375
+ toolset,
376
+ tools: numericBytes(row.tools),
377
+ toolSchemaBytes,
378
+ systemBytes: numericBytes(row.systemBytes),
379
+ mcpServers: Array.isArray(row.mcpServers) ? row.mcpServers : null,
380
+ });
381
+ }
382
+
383
+ const groups = new Map();
384
+ for (const snapshot of snapshots) {
385
+ const group = groups.get(snapshot.toolset) ?? {
386
+ toolset: snapshot.toolset,
387
+ count: 0,
388
+ latest: snapshot,
389
+ captured: null,
390
+ };
391
+ group.count += 1;
392
+ const at = Date.parse(snapshot.at);
393
+ if (Number.isFinite(at) && at > Date.parse(group.latest.at)) group.latest = snapshot;
394
+ if (snapshot.mcpServers !== null) {
395
+ if (group.captured === null) {
396
+ group.captured = snapshot;
397
+ } else {
398
+ const previous = Date.parse(group.captured.at);
399
+ if (Number.isFinite(at) && (!Number.isFinite(previous) || at >= previous)) {
400
+ group.captured = snapshot;
401
+ }
402
+ }
403
+ }
404
+ groups.set(snapshot.toolset, group);
405
+ }
406
+
407
+ const toolsets = [...groups.values()]
408
+ .sort((a, b) => b.latest.toolSchemaBytes - a.latest.toolSchemaBytes || a.toolset.localeCompare(b.toolset))
409
+ .map((group) => {
410
+ // A newer snapshot whose MCP list call failed does not erase an older
411
+ // measurement; the printed `at` names the row the split came from.
412
+ const latest = group.captured ?? group.latest;
413
+ const captured = latest.mcpServers !== null;
414
+ const servers = captured
415
+ ? latest.mcpServers.map((server) => {
416
+ const record = server && typeof server === 'object' ? server : {};
417
+ const bytes = numericBytes(record.bytes) ?? 0;
418
+ return {
419
+ name: typeof record.name === 'string' && record.name !== '' ? record.name : '(unnamed)',
420
+ tools: numericBytes(record.tools),
421
+ bytes,
422
+ estTokens: estimateTokens(bytes),
423
+ };
424
+ })
425
+ : [];
426
+ const mcpBytes = captured
427
+ ? servers.reduce((sum, server) => sum + server.bytes, 0)
428
+ : null;
429
+ const builtInBytes = captured ? Math.max(0, latest.toolSchemaBytes - mcpBytes) : null;
430
+ const remainderBytes =
431
+ captured && latest.systemBytes !== null ? builtInBytes + latest.systemBytes : null;
432
+ return {
433
+ toolset: group.toolset,
434
+ snapshots: group.count,
435
+ at: latest.at,
436
+ sessionID: latest.sessionID,
437
+ tools: latest.tools,
438
+ toolSchemaBytes: latest.toolSchemaBytes,
439
+ systemBytes: latest.systemBytes,
440
+ mcp: {
441
+ captured,
442
+ bytes: mcpBytes,
443
+ estTokens: mcpBytes === null ? null : estimateTokens(mcpBytes),
444
+ servers,
445
+ },
446
+ nonMcp: {
447
+ builtInBytes,
448
+ builtInTokens: builtInBytes === null ? null : estimateTokens(builtInBytes),
449
+ systemBytes: latest.systemBytes,
450
+ systemTokens: latest.systemBytes === null ? null : estimateTokens(latest.systemBytes),
451
+ bytes: remainderBytes,
452
+ estTokens: remainderBytes === null ? null : estimateTokens(remainderBytes),
453
+ },
454
+ };
455
+ });
456
+
457
+ return {
458
+ present: snapshots.length > 0,
459
+ snapshots: snapshots.length,
460
+ sessions: new Set(snapshots.map((snapshot) => snapshot.sessionID)).size,
461
+ invalid,
462
+ toolsets,
463
+ };
464
+ }
465
+
466
+ function mcpSchemasReport() {
467
+ const file = path.join(repoRoot, '.ai.local', 'team', 'output-guard', 'context.jsonl');
468
+ const ledger = readJsonlRows(file);
469
+ const summary = summarizeMcpSnapshots(ledger.rows);
470
+ return { file: toRepoPath(file), ...summary, invalid: summary.invalid + ledger.invalid };
471
+ }
472
+
310
473
  function outputGuardReport() {
311
474
  const file = path.join(repoRoot, '.ai.local', 'team', 'output-guard', 'stats.jsonl');
312
475
  let text;
@@ -343,6 +506,7 @@ function buildReport() {
343
506
  tasks: taskReport(slugs),
344
507
  usage: usageReport(slugs),
345
508
  outputGuard: outputGuardReport(),
509
+ mcpSchemas: mcpSchemasReport(),
346
510
  };
347
511
  }
348
512
 
@@ -361,7 +525,54 @@ function humanReport(report) {
361
525
  lines.push('');
362
526
  lines.push('EST.TOKENS = round(bytes / 4) — an estimate, not a measurement.');
363
527
  lines.push('');
364
- lines.push(`CURSOR FIXTURES — attached non-empty lines (reads .cursor/rules; caps from check-next-attached-budget.mjs)`);
528
+ const mcp = report.mcpSchemas;
529
+ lines.push('MCP SCHEMAS — tool schemas at hook time (context.jsonl, deduped by sessionID+toolset)');
530
+ if (!mcp.present) {
531
+ lines.push(`not captured — no snapshot in ${mcp.file}`);
532
+ } else {
533
+ lines.push(
534
+ `${formatInt(mcp.snapshots)} snapshots · ${formatInt(mcp.sessions)} sessions with a toolset · ` +
535
+ `${formatInt(mcp.toolsets.length)} toolset${mcp.toolsets.length === 1 ? '' : 's'}${mcp.invalid > 0 ? ` · ${formatInt(mcp.invalid)} invalid` : ''}`,
536
+ );
537
+ for (const entry of mcp.toolsets) {
538
+ lines.push(
539
+ `toolset ${entry.toolset} · ${formatInt(entry.snapshots)} row(s) · snapshot ${
540
+ entry.at === '' ? 'at unknown' : entry.at
541
+ } · ${entry.sessionID} · ${entry.tools === null ? '?' : formatInt(entry.tools)} tools`,
542
+ );
543
+ lines.push(
544
+ ` tool schemas ${padStart(formatInt(entry.toolSchemaBytes), 12)} B${padStart(`EST.TOKENS ${formatInt(estimateTokens(entry.toolSchemaBytes))}`, 20)}`,
545
+ );
546
+ if (entry.mcp.captured) {
547
+ lines.push(
548
+ ` mcp ${padStart(formatInt(entry.mcp.bytes), 12)} B${padStart(`EST.TOKENS ${formatInt(entry.mcp.estTokens)}`, 20)}` +
549
+ ` [measured: ${entry.mcp.bytes === 0 ? 'mcpServers=[] — no listed server owns a schema' : `${entry.mcp.servers.length} server(s)`}]`,
550
+ );
551
+ for (const server of entry.mcp.servers) {
552
+ lines.push(
553
+ ` ${padEnd(server.name, 20)}${padStart(formatInt(server.tools ?? 0), 3)} tools` +
554
+ `${padStart(formatInt(server.bytes), 12)} B${padStart(`EST.TOKENS ${formatInt(server.estTokens)}`, 20)}`,
555
+ );
556
+ }
557
+ } else {
558
+ lines.push(' mcp not captured — the snapshot carries no mcpServers (the list call failed)');
559
+ }
560
+ if (entry.nonMcp.bytes === null) {
561
+ lines.push(' non-mcp not captured — MCP bytes cannot be separated from the schema total');
562
+ } else {
563
+ lines.push(
564
+ ` non-mcp ${padStart(formatInt(entry.nonMcp.bytes), 12)} B${padStart(
565
+ `EST.TOKENS ${formatInt(entry.nonMcp.estTokens)}`,
566
+ 20,
567
+ )} [${formatInt(entry.nonMcp.builtInBytes)} B built-in schemas + ${formatInt(
568
+ entry.nonMcp.systemBytes ?? 0,
569
+ )} B system parts]`,
570
+ );
571
+ }
572
+ }
573
+ }
574
+ lines.push('');
575
+ lines.push('CURSOR FIXTURES — attached non-empty lines (reads .cursor/rules; caps from check-next-attached-budget.mjs)');
365
576
  for (const fixture of report.fixtures) {
366
577
  lines.push(
367
578
  `${padEnd(fixture.key, 8)}${padEnd(`${fixture.attachedLines}/${fixture.cap}`, 14)}headroom ${fixture.headroom}`,