@boringparts/verule 0.1.0 → 0.2.0

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/main.js CHANGED
@@ -1,11 +1,10 @@
1
- import { dirname } from "node:path";
2
1
  import { performance } from "node:perf_hooks";
3
- import { CliWriteError, defineCli, executeCli, helpCapability, parseCliInvocation, schemaCapability, text, versionCapability, } from "@ykdz/cli-contract";
4
- import { isNodeBrokenPipe } from "@ykdz/cli-contract/node";
2
+ import { CliWriteError, defineCli, executeCli, helpCapability, parseCliInvocation, schemaCapability, text, versionCapability, } from "@boringparts/cli-contract";
3
+ import { isNodeBrokenPipe } from "@boringparts/cli-contract/node";
5
4
  import { z } from "zod";
6
5
  import { loadProjectConfigWithDependencies } from "./config-loader.js";
7
6
  import { REPORT_SCHEMA_VERSION, VeruleExecutionError, getEngineVersion, parseObserveLimit, requestSharedReport, runCheck, } from "./index.js";
8
- import { appendGapLines, checkFailureSchema, checkReportSchema, formatDiagnosticsLines, formatScopeLines, toWireFactConflict, toWireReport, } from "./report-wire.js";
7
+ import { appendGapLines, checkFailureSchema, checkReportSchema, formatDiagnosticsLines, formatScopeLines, toWireReport, } from "./report-wire.js";
9
8
  import { formatSessionReadyText, sessionReadyRecordSchema, streamSharedSession, } from "./session-command.js";
10
9
  import { formatWatchReportText, streamWatchEvents, watchFailureRecordSchema, watchReportRecordSchema, } from "./watch-command.js";
11
10
  function appendExplanationLines(lines, exp) {
@@ -34,30 +33,12 @@ function appendExplanationLines(lines, exp) {
34
33
  if (exp.providers.length > 0) {
35
34
  lines.push(` providers: ${exp.providers.join(", ")}`);
36
35
  }
37
- for (const evalEntry of exp.providerEvaluations) {
38
- const factPart = evalEntry.factTypeId ? ` (${evalEntry.factTypeId})` : "";
39
- const reasonPart = evalEntry.reason ? `: ${evalEntry.reason}` : "";
40
- lines.push(` provider [${evalEntry.status}] ${evalEntry.providerId}${factPart}${reasonPart}`);
41
- }
42
36
  for (const gap of exp.gaps) {
43
37
  const atSuffix = gap.at
44
38
  ? ` (${gap.at.file}:${gap.at.line}:${gap.at.column})`
45
39
  : "";
46
40
  lines.push(` gap [${gap.kind}]: ${gap.message}${atSuffix}`);
47
41
  }
48
- for (const local of exp.localGaps) {
49
- const fieldPart = local.field ? ` field=${local.field}` : "";
50
- const gapAt = local.gap.at
51
- ? ` at ${local.gap.at.file}:${local.gap.at.line}:${local.gap.at.column}`
52
- : "";
53
- const resolvedPart = local.resolvedBy
54
- ? ` -> resolved_by ${local.resolvedBy.providerId} (${local.resolvedBy.operation}: ${local.resolvedBy.conclusion}${local.resolvedBy.at
55
- ? ` at ${local.resolvedBy.at.file}:${local.resolvedBy.at.line}:${local.resolvedBy.at.column}`
56
- : ""})`
57
- : "";
58
- const impactPart = local.impact ? ` [${local.impact}]` : "";
59
- lines.push(` localGap [${local.status}] ${local.factTypeId} (${local.providerId})${fieldPart}: ${local.gap.message}${gapAt}${resolvedPart}${impactPart}`);
60
- }
61
42
  for (const cp of exp.cleanupPaths) {
62
43
  const sites = cp.cleanupLocations
63
44
  .map((loc) => `${loc.file}:${loc.line}:${loc.column}`)
@@ -76,10 +57,9 @@ function appendObservationLines(lines, obs) {
76
57
  if (obs.providers.length > 0) {
77
58
  lines.push(` providers: ${obs.providers.join(", ")}`);
78
59
  }
79
- const nativeAdapters = obs.nativeAdapters.map((adapter) => `${adapter.packageName} (provider=${adapter.providerId}, status=${adapter.status})`);
80
- lines.push(` native adapters: ${nativeAdapters.length > 0 ? nativeAdapters.join(", ") : "none"}`);
81
- const nativeExtractions = Object.entries(obs.engineExtractions).map(([providerId, stats]) => `${providerId} (extractions=${stats.extractions}, candidates=${stats.candidates})`);
82
- lines.push(` native extractions: ${nativeExtractions.length > 0 ? nativeExtractions.join(", ") : "none"}`);
60
+ lines.push(` lowering: functions=${obs.lowering.functionsLowered}, vertices=${obs.lowering.verticesCreated}, duration=${obs.lowering.durationMs}ms`);
61
+ lines.push(` irCache: functionHits=${obs.irCache.functionHits}, functionMisses=${obs.irCache.functionMisses}, filesReused=${obs.irCache.filesReused}, filesInvalidated=${obs.irCache.filesInvalidated}`);
62
+ lines.push(` summaryLookup: lookups=${obs.summaryLookup.lookups}, hits=${obs.summaryLookup.hits}, misses=${obs.summaryLookup.misses} (local=${obs.summaryLookup.hitsBySource.local}, package=${obs.summaryLookup.hitsBySource.package}, community=${obs.summaryLookup.hitsBySource.community}, builtin=${obs.summaryLookup.hitsBySource.builtin})`);
83
63
  if (obs.truncated) {
84
64
  lines.push(` truncated: true (dropped=${obs.droppedCount})`);
85
65
  }
@@ -143,51 +123,33 @@ function formatCheckFindingsText(report) {
143
123
  ? text.lines([first, ...rest, summary, ...extras])
144
124
  : text.lines([summary, ...extras]);
145
125
  }
146
- function createCliContract(identity, workingDirectory, signal) {
147
- const define = defineCli();
148
- const versionInput = z.object({});
149
- const checkInput = z.object({
150
- config: z.string().min(1).optional(),
151
- session: z.string().min(1).optional(),
152
- rule: z.string().min(1).optional(),
153
- at: z.string().min(1).optional(),
154
- observe: z.enum(["off", "summary", "detail"]).optional(),
155
- observeLimit: z.string().min(1).optional(),
156
- });
157
- const watchInput = z.object({
158
- config: z.string().min(1).optional(),
159
- });
160
- const sessionInput = z.object({
161
- config: z.string().min(1).optional(),
162
- socket: z.string().min(1),
163
- });
164
- async function executeCheck(input) {
165
- try {
166
- const observeLimit = input.observeLimit !== undefined
167
- ? parseObserveLimit(input.observeLimit)
168
- : undefined;
169
- if (input.session !== undefined) {
170
- if (input.config !== undefined) {
171
- throw new VeruleExecutionError("INVALID_CONFIG", 'Cannot combine "--session" with "--config"; the shared session is already bound to a configuration.');
172
- }
173
- const report = await requestSharedReport({
174
- endpoint: input.session,
175
- cwd: workingDirectory,
176
- ...(input.rule !== undefined ? { ruleIds: [input.rule] } : {}),
177
- ...(input.at !== undefined ? { at: input.at } : {}),
178
- ...(input.observe !== undefined ? { observe: input.observe } : {}),
179
- ...(observeLimit !== undefined ? { observeLimit } : {}),
180
- });
181
- return { ok: true, report: toWireReport(report) };
182
- }
183
- const configStart = performance.now();
184
- const loaded = await loadProjectConfigWithDependencies(workingDirectory, input.config);
185
- const configLoadMs = performance.now() - configStart;
186
- const report = await runCheck({
126
+ const define = defineCli();
127
+ const versionInput = z.object({});
128
+ const versionOutputSchema = z.object({ cli: z.string(), engine: z.string() });
129
+ const checkInput = z.object({
130
+ config: z.string().min(1).optional(),
131
+ session: z.string().min(1).optional(),
132
+ rule: z.string().min(1).optional(),
133
+ at: z.string().min(1).optional(),
134
+ observe: z.enum(["off", "summary", "detail"]).optional(),
135
+ observeLimit: z.string().min(1).optional(),
136
+ });
137
+ const watchInput = z.object({
138
+ config: z.string().min(1).optional(),
139
+ });
140
+ const sessionInput = z.object({
141
+ config: z.string().min(1).optional(),
142
+ socket: z.string().min(1),
143
+ });
144
+ async function executeCheck(input, workingDirectory) {
145
+ try {
146
+ const observeLimit = input.observeLimit !== undefined
147
+ ? parseObserveLimit(input.observeLimit)
148
+ : undefined;
149
+ if (input.session !== undefined) {
150
+ const report = await requestSharedReport({
151
+ endpoint: input.session,
187
152
  cwd: workingDirectory,
188
- config: loaded.config,
189
- adapterResolutionRoot: dirname(loaded.configPath),
190
- configLoadMs,
191
153
  ...(input.rule !== undefined ? { ruleIds: [input.rule] } : {}),
192
154
  ...(input.at !== undefined ? { at: input.at } : {}),
193
155
  ...(input.observe !== undefined ? { observe: input.observe } : {}),
@@ -195,30 +157,42 @@ function createCliContract(identity, workingDirectory, signal) {
195
157
  });
196
158
  return { ok: true, report: toWireReport(report) };
197
159
  }
198
- catch (err) {
199
- if (err instanceof VeruleExecutionError) {
200
- return {
201
- ok: false,
202
- failure: {
203
- reportVersion: REPORT_SCHEMA_VERSION,
204
- code: err.code,
205
- message: err.message,
206
- ...(err.conflict !== undefined
207
- ? { conflict: toWireFactConflict(err.conflict) }
208
- : {}),
209
- },
210
- };
211
- }
160
+ const configStart = performance.now();
161
+ const loaded = await loadProjectConfigWithDependencies(workingDirectory, input.config);
162
+ const configLoadMs = performance.now() - configStart;
163
+ const report = await runCheck({
164
+ cwd: workingDirectory,
165
+ config: loaded.config,
166
+ configLoadMs,
167
+ ...(input.rule !== undefined ? { ruleIds: [input.rule] } : {}),
168
+ ...(input.at !== undefined ? { at: input.at } : {}),
169
+ ...(input.observe !== undefined ? { observe: input.observe } : {}),
170
+ ...(observeLimit !== undefined ? { observeLimit } : {}),
171
+ });
172
+ return { ok: true, report: toWireReport(report) };
173
+ }
174
+ catch (err) {
175
+ if (err instanceof VeruleExecutionError) {
212
176
  return {
213
177
  ok: false,
214
178
  failure: {
215
179
  reportVersion: REPORT_SCHEMA_VERSION,
216
- code: "ENGINE_ERROR",
217
- message: err instanceof Error ? err.message : String(err),
180
+ code: err.code,
181
+ message: err.message,
218
182
  },
219
183
  };
220
184
  }
185
+ return {
186
+ ok: false,
187
+ failure: {
188
+ reportVersion: REPORT_SCHEMA_VERSION,
189
+ code: "ENGINE_ERROR",
190
+ message: err instanceof Error ? err.message : String(err),
191
+ },
192
+ };
221
193
  }
194
+ }
195
+ function createCliContract(identity) {
222
196
  return define({
223
197
  root: "verule",
224
198
  help: helpCapability({
@@ -227,12 +201,18 @@ function createCliContract(identity, workingDirectory, signal) {
227
201
  usage: "Usage",
228
202
  commands: "Commands",
229
203
  options: "Options",
204
+ constraints: "Constraints",
230
205
  schema: "Contract Discovery",
231
206
  },
232
207
  wording: {
233
208
  commandPlaceholder: "command",
234
- choices: "(choices: {choices})",
235
- default: "(default: {value})",
209
+ outputModePlaceholder: "mode",
210
+ choices: "{usage} (choices: {choices})",
211
+ choicesAndDefault: "{usage} (choices: {choices}, default: {value})",
212
+ list: "{left}, {right}",
213
+ facts: "{left} with {right}",
214
+ present: "{field}",
215
+ forbiddenCombination: "Cannot combine {facts}.",
236
216
  },
237
217
  }),
238
218
  version: versionCapability({
@@ -256,33 +236,39 @@ function createCliContract(identity, workingDirectory, signal) {
256
236
  name: "version",
257
237
  description: "Show the installed Verule CLI and analysis engine versions.",
258
238
  input: versionInput,
259
- outputs: define.outputModes("version", versionInput, (mode) => ({
260
- default: "text",
261
- modes: {
262
- text: mode.atomic({
263
- format: "text",
264
- description: "Display the installed versions.",
265
- success: {
266
- kind: "data",
267
- variants: {
268
- versions: {
269
- description: "Installed CLI and engine versions.",
270
- schema: z.object({ cli: z.string(), engine: z.string() }),
271
- exitCode: 0,
272
- text: ({ cli, engine }) => text.line(`${identity.commandName} ${cli} (engine ${engine})`),
273
- },
239
+ outputs: (factory) => {
240
+ const execution = factory.atomic({
241
+ success: {
242
+ kind: "data",
243
+ variants: {
244
+ versions: {
245
+ description: "Installed CLI and engine versions.",
246
+ schema: versionOutputSchema,
247
+ exitCode: 0,
274
248
  },
275
249
  },
276
- failures: {},
277
- handler: async ({ outcome }) => {
278
- return outcome.data.versions({
279
- cli: identity.version,
280
- engine: await getEngineVersion(),
281
- });
282
- },
283
- }),
284
- },
285
- })),
250
+ },
251
+ failures: {},
252
+ handler: async ({ outcome }) => {
253
+ return outcome.data.versions({
254
+ cli: identity.version,
255
+ engine: await getEngineVersion(),
256
+ });
257
+ },
258
+ });
259
+ return {
260
+ default: "text",
261
+ modes: {
262
+ text: execution.text({
263
+ description: "Display the installed versions.",
264
+ success: {
265
+ versions: ({ cli, engine }) => text.line(`${identity.commandName} ${cli} (engine ${engine})`),
266
+ },
267
+ failures: {},
268
+ }),
269
+ },
270
+ };
271
+ },
286
272
  }),
287
273
  ...define.command("check")({
288
274
  kind: "command",
@@ -322,107 +308,69 @@ function createCliContract(identity, workingDirectory, signal) {
322
308
  description: "Limit detail observation entries (e.g. 20 or 4096b).",
323
309
  },
324
310
  },
311
+ usageConstraints: [
312
+ {
313
+ kind: "forbiddenCombination",
314
+ all: [
315
+ { kind: "present", field: "session" },
316
+ { kind: "present", field: "config" },
317
+ ],
318
+ },
319
+ ],
325
320
  input: checkInput,
326
- outputs: define.outputModes("check", checkInput, (mode) => ({
327
- default: "text",
328
- modes: {
329
- text: mode.atomic({
330
- format: "text",
331
- description: "Display check diagnostics as human-readable text.",
332
- success: {
333
- kind: "data",
334
- variants: {
335
- clean: {
336
- description: "Analysis completed with zero violations.",
337
- schema: checkReportSchema,
338
- exitCode: 0,
339
- text: formatCheckCleanText,
340
- },
341
- findings: {
342
- description: "Analysis completed and reported violations.",
343
- schema: checkReportSchema,
344
- exitCode: 1,
345
- text: formatCheckFindingsText,
346
- },
321
+ outputs: (factory) => {
322
+ const execution = factory.atomic({
323
+ success: {
324
+ kind: "data",
325
+ variants: {
326
+ clean: {
327
+ description: "Analysis completed with zero violations.",
328
+ schema: checkReportSchema,
329
+ exitCode: 0,
347
330
  },
348
- },
349
- failures: {
350
- failed: {
351
- description: "Configuration, project loading, rule execution, or engine failure.",
352
- schema: checkFailureSchema,
353
- exitCode: 2,
354
- text: ({ code, message, conflict }) => {
355
- if (!conflict) {
356
- return text.line(`Check failed [${code}]: ${message}`);
357
- }
358
- const loc = conflict.subjectLocation
359
- ? ` (${conflict.subjectLocation.file}:${conflict.subjectLocation.line}:${conflict.subjectLocation.column})`
360
- : "";
361
- const head = `Check failed [${code}]: ${message}`;
362
- const tail = [
363
- ` factType: ${conflict.factTypeId}`,
364
- ` subject: ${conflict.subjectHandleId}${loc}`,
365
- ];
366
- for (const party of conflict.parties) {
367
- tail.push(` provider [${party.providerId}]: ${party.conclusionSummary}`);
368
- for (const ev of party.evidence) {
369
- const evLoc = ev.at
370
- ? ` (${ev.at.file}:${ev.at.line}:${ev.at.column})`
371
- : "";
372
- tail.push(` evidence (${ev.kind}): ${ev.message}${evLoc}`);
373
- }
374
- }
375
- return text.lines([head, ...tail]);
376
- },
331
+ findings: {
332
+ description: "Analysis completed and reported violations.",
333
+ schema: checkReportSchema,
334
+ exitCode: 1,
377
335
  },
378
336
  },
379
- handler: async ({ input, outcome }) => {
380
- const outcomeResult = await executeCheck(input);
381
- if (!outcomeResult.ok) {
382
- return outcome.failure.failed(outcomeResult.failure);
383
- }
384
- return outcomeResult.report.status === "findings"
385
- ? outcome.data.findings(outcomeResult.report)
386
- : outcome.data.clean(outcomeResult.report);
337
+ },
338
+ failures: {
339
+ failed: {
340
+ description: "Configuration, project loading, rule execution, or engine failure.",
341
+ schema: checkFailureSchema,
342
+ exitCode: 2,
387
343
  },
388
- }),
389
- json: mode.atomic({
390
- format: "structured",
391
- description: "Emit a versioned JSON check report.",
392
- success: {
393
- kind: "data",
394
- variants: {
395
- clean: {
396
- description: "Analysis completed with zero violations.",
397
- schema: checkReportSchema,
398
- exitCode: 0,
399
- },
400
- findings: {
401
- description: "Analysis completed and reported violations.",
402
- schema: checkReportSchema,
403
- exitCode: 1,
404
- },
344
+ },
345
+ handler: async ({ input, dependencies, outcome }) => {
346
+ const outcomeResult = await executeCheck(input, dependencies.cwd);
347
+ if (!outcomeResult.ok) {
348
+ return outcome.failure.failed(outcomeResult.failure);
349
+ }
350
+ return outcomeResult.report.status === "findings"
351
+ ? outcome.data.findings(outcomeResult.report)
352
+ : outcome.data.clean(outcomeResult.report);
353
+ },
354
+ });
355
+ return {
356
+ default: "text",
357
+ modes: {
358
+ text: execution.text({
359
+ description: "Display check diagnostics as human-readable text.",
360
+ success: {
361
+ clean: formatCheckCleanText,
362
+ findings: formatCheckFindingsText,
405
363
  },
406
- },
407
- failures: {
408
- failed: {
409
- description: "Configuration, project loading, rule execution, or engine failure.",
410
- schema: checkFailureSchema,
411
- exitCode: 2,
364
+ failures: {
365
+ failed: ({ code, message }) => text.line(`Check failed [${code}]: ${message}`),
412
366
  },
413
- },
414
- handler: async ({ input, outcome }) => {
415
- const outcomeResult = await executeCheck(input);
416
- if (!outcomeResult.ok) {
417
- return outcome.failure.failed(outcomeResult.failure);
418
- }
419
- return outcomeResult.report.status === "findings"
420
- ? outcome.data.findings(outcomeResult.report)
421
- : outcome.data.clean(outcomeResult.report);
422
- },
423
- }),
424
- },
425
- })),
367
+ }),
368
+ json: execution.structured({
369
+ description: "Emit a versioned JSON check report.",
370
+ }),
371
+ },
372
+ };
373
+ },
426
374
  }),
427
375
  ...define.command("watch")({
428
376
  kind: "command",
@@ -438,52 +386,39 @@ function createCliContract(identity, workingDirectory, signal) {
438
386
  },
439
387
  },
440
388
  input: watchInput,
441
- outputs: define.outputModes("watch", watchInput, (mode) => ({
442
- default: "text",
443
- modes: {
444
- text: mode.stream({
445
- format: "text",
446
- description: "Display watch reports as human-readable text.",
447
- success: {
448
- kind: "stream",
449
- records: {
450
- report: {
451
- description: "Complete analysis report for a snapshot.",
452
- schema: watchReportRecordSchema,
453
- text: formatWatchReportText,
454
- },
455
- failed: {
456
- description: "Single-round check failure.",
457
- schema: watchFailureRecordSchema,
458
- text: ({ sequence, code, message }) => text.line(`[watch #${sequence}] Check failed [${code}]: ${message}`),
459
- },
460
- },
461
- text: () => text.line("Watch stopped."),
389
+ outputs: (factory) => {
390
+ const execution = factory.stream({
391
+ records: {
392
+ report: {
393
+ description: "Complete analysis report for a snapshot.",
394
+ schema: watchReportRecordSchema,
395
+ },
396
+ failed: {
397
+ description: "Single-round check failure.",
398
+ schema: watchFailureRecordSchema,
462
399
  },
463
- failures: {},
464
- handler: ({ input, outcome }) => streamWatchEvents(workingDirectory, input.config, signal, outcome),
465
- }),
466
- ndjson: mode.stream({
467
- format: "structured",
468
- description: "Emit complete analysis reports as NDJSON stream records.",
469
- success: {
470
- kind: "stream",
400
+ },
401
+ failures: {},
402
+ handler: ({ input, dependencies, outcome }) => streamWatchEvents(dependencies.cwd, input.config, dependencies.signal, outcome),
403
+ });
404
+ return {
405
+ default: "text",
406
+ modes: {
407
+ text: execution.text({
408
+ description: "Display watch reports as human-readable text.",
471
409
  records: {
472
- report: {
473
- description: "Complete analysis report for a snapshot.",
474
- schema: watchReportRecordSchema,
475
- },
476
- failed: {
477
- description: "Single-round check failure.",
478
- schema: watchFailureRecordSchema,
479
- },
410
+ report: formatWatchReportText,
411
+ failed: ({ sequence, code, message }) => text.line(`[watch #${sequence}] Check failed [${code}]: ${message}`),
480
412
  },
481
- },
482
- failures: {},
483
- handler: ({ input, outcome }) => streamWatchEvents(workingDirectory, input.config, signal, outcome),
484
- }),
485
- },
486
- })),
413
+ failures: {},
414
+ terminal: () => text.line("Watch stopped."),
415
+ }),
416
+ ndjson: execution.structured({
417
+ description: "Emit complete analysis reports as NDJSON stream records.",
418
+ }),
419
+ },
420
+ };
421
+ },
487
422
  }),
488
423
  ...define.command("session")({
489
424
  kind: "command",
@@ -504,71 +439,73 @@ function createCliContract(identity, workingDirectory, signal) {
504
439
  },
505
440
  },
506
441
  input: sessionInput,
507
- outputs: define.outputModes("session", sessionInput, (mode) => ({
508
- default: "text",
509
- modes: {
510
- text: mode.stream({
511
- format: "text",
512
- description: "Emit shared session readiness and shutdown text.",
513
- success: {
514
- kind: "stream",
515
- records: {
516
- ready: {
517
- description: "Shared session is initialized and listening for queries.",
518
- schema: sessionReadyRecordSchema,
519
- text: formatSessionReadyText,
520
- },
521
- },
522
- text: () => text.line("Shared session stopped."),
442
+ outputs: (factory) => {
443
+ const execution = factory.stream({
444
+ records: {
445
+ ready: {
446
+ description: "Shared session is initialized and listening for queries.",
447
+ schema: sessionReadyRecordSchema,
523
448
  },
524
- failures: {
525
- failed: {
526
- description: "Shared session failed to start.",
527
- schema: checkFailureSchema,
528
- exitCode: 2,
529
- text: ({ code, message }) => text.line(`Session failed [${code}]: ${message}`),
530
- },
449
+ },
450
+ failures: {
451
+ failed: {
452
+ description: "Shared session failed to start.",
453
+ schema: checkFailureSchema,
454
+ exitCode: 2,
531
455
  },
532
- handler: ({ input, outcome }) => streamSharedSession(workingDirectory, input.config, input.socket, signal, outcome),
533
- }),
534
- ndjson: mode.stream({
535
- format: "structured",
536
- description: "Emit shared session readiness and lifecycle events as NDJSON.",
537
- success: {
538
- kind: "stream",
456
+ },
457
+ handler: ({ input, dependencies, outcome }) => streamSharedSession(dependencies.cwd, input.config, input.socket, dependencies.signal, outcome),
458
+ });
459
+ return {
460
+ default: "text",
461
+ modes: {
462
+ text: execution.text({
463
+ description: "Emit shared session readiness and shutdown text.",
539
464
  records: {
540
- ready: {
541
- description: "Shared session is initialized and listening for queries.",
542
- schema: sessionReadyRecordSchema,
543
- },
465
+ ready: formatSessionReadyText,
544
466
  },
545
- },
546
- failures: {
547
- failed: {
548
- description: "Shared session failed to start.",
549
- schema: checkFailureSchema,
550
- exitCode: 2,
467
+ failures: {
468
+ failed: ({ code, message }) => text.line(`Session failed [${code}]: ${message}`),
551
469
  },
552
- },
553
- handler: ({ input, outcome }) => streamSharedSession(workingDirectory, input.config, input.socket, signal, outcome),
554
- }),
555
- },
556
- })),
470
+ terminal: () => text.line("Shared session stopped."),
471
+ }),
472
+ ndjson: execution.structured({
473
+ description: "Emit shared session readiness and lifecycle events as NDJSON.",
474
+ }),
475
+ },
476
+ };
477
+ },
557
478
  }),
558
479
  },
559
480
  });
560
481
  }
482
+ // Cache compiled contracts per identity so repeated CLI invocations do not rebuild schemas.
483
+ const cliContractCache = new Map();
484
+ /** Returns the memoized Verule CLI contract for the given command identity. */
485
+ export function getCliContract(identity) {
486
+ const cacheKey = `${identity.commandName}\0${identity.version}`;
487
+ const cached = cliContractCache.get(cacheKey);
488
+ if (cached !== undefined) {
489
+ return cached;
490
+ }
491
+ const contract = createCliContract(identity);
492
+ cliContractCache.set(cacheKey, contract);
493
+ return contract;
494
+ }
561
495
  /** Returns the process status after all output has been written. */
562
496
  export async function runCli(runtime) {
563
497
  try {
564
498
  const workingDirectory = runtime.cwd ?? process.cwd();
565
- const contract = createCliContract(runtime.identity, workingDirectory, runtime.signal);
499
+ const contract = getCliContract(runtime.identity);
566
500
  const rawArgs = runtime.argv.slice(2);
567
501
  const effectiveArgs = rawArgs.length === 0 ? ["version"] : rawArgs;
568
502
  const invocation = parseCliInvocation(contract, effectiveArgs);
569
503
  const { exitCode } = await executeCli(contract, {
570
504
  invocation,
571
- dependencies: undefined,
505
+ dependencies: {
506
+ cwd: workingDirectory,
507
+ signal: runtime.signal,
508
+ },
572
509
  write: runtime.write,
573
510
  });
574
511
  return exitCode;