@sublang/slc 0.16.8 → 0.17.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.
@@ -28,6 +28,23 @@ import { createActor, fromPromise } from 'xstate';
28
28
  import { AWAIT_BOSS_REPLY_STATE, BOSS_REPLY_EVENT, INTERRUPT_EVENT, NEEDS_BOSS_REPLY, VERIFY_MODULE, controllerDecisionNearMiss, enumerateCaptainStates, enumeratePlaybookStates, enumerateScriptStates, initialStateTarget, isControllerDecisionResult, isControllerMachine, loadFsmModule, normalizeArms, prepareGearsFsmConformance, findConcurrentRoleSets, ReachedLiteralChildChecks, resolveArtifactSchemaForVerification, usesKeyedBossQuestionContext, } from './verify.js';
29
29
  /** The `gears2fsm`-mandated captain actor name a machine declares. */
30
30
  export const CAPTAIN_ACTOR = 'captain';
31
+ /** Validate before artifact access and return an independent immutable policy. */
32
+ export function resolveCoverageBudget(value = {}) {
33
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
34
+ throw new TypeError('coverage must be an object');
35
+ for (const key of Reflect.ownKeys(value))
36
+ if (key !== 'maxInvocations' && key !== 'maxAttempts')
37
+ throw new TypeError(`Unknown coverage budget key: ${String(key)}`);
38
+ const { maxInvocations = 8, maxAttempts = 64 } = value;
39
+ for (const [key, limit, cap] of [
40
+ ['maxInvocations', maxInvocations, 64],
41
+ ['maxAttempts', maxAttempts, 1024],
42
+ ]) {
43
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > cap)
44
+ throw new RangeError(`coverage.${key} must be an integer from 1 to ${cap}`);
45
+ }
46
+ return Object.freeze({ maxInvocations, maxAttempts });
47
+ }
31
48
  // Each check owns its resources, including concurrent checks and async actor
32
49
  // callbacks. No current-run variable is shared between invocations.
33
50
  const coverageRuns = new AsyncLocalStorage();
@@ -211,8 +228,6 @@ const SETTLE_MS = 1_000;
211
228
  const PARALLEL_SETTLE_MS = 250;
212
229
  const PARALLEL_QUESTION_SETTLE_MS = 500;
213
230
  const MAX_PARALLEL_COMBINATIONS = 64;
214
- const MAX_COVERAGE_PATH_STEPS = 8;
215
- const MAX_COVERAGE_PATH_ATTEMPTS = 64;
216
231
  /** Stable values shared by machine input, result output, and guard probing. */
217
232
  const COVERAGE_PLAYBOOK_ID = 'coverage-child-playbook';
218
233
  const COVERAGE_PLAYBOOK_INPUT = 'coverage: complete the child request';
@@ -1971,6 +1986,7 @@ async function replayCoveragePath(machine, nodes, path) {
1971
1986
  }
1972
1987
  /** Finite path replay, including bounded canonical question/reply revisits. */
1973
1988
  async function searchCoverageEntry(machine, target, refs, captains, playbooks, candidates, check) {
1989
+ const budget = coverageRuns.getStore().coverage;
1974
1990
  const nodes = coverageNodes(captains, playbooks);
1975
1991
  const nodesForTarget = (raw, source) => {
1976
1992
  const targetName = rawArmTarget(raw);
@@ -2001,6 +2017,12 @@ async function searchCoverageEntry(machine, target, refs, captains, playbooks, c
2001
2017
  if (entry !== undefined)
2002
2018
  queue.push({ root: node, ...entry, steps: [] });
2003
2019
  }
2020
+ // Family identity is only the declared root invocation. Keep every actual
2021
+ // context, prefix and lazy entry alternative distinct within that family.
2022
+ const rootFamilies = [
2023
+ ...new Set(queue.map((path) => coverageNodeKey(path.root))),
2024
+ ];
2025
+ let familyCursor = 0;
2004
2026
  let attempts = 0;
2005
2027
  let entered = false;
2006
2028
  let transitionCovered = false;
@@ -2009,9 +2031,19 @@ async function searchCoverageEntry(machine, target, refs, captains, playbooks, c
2009
2031
  false);
2010
2032
  const limitations = new Set();
2011
2033
  let inputFailure;
2012
- while (queue.length > 0 && attempts < MAX_COVERAGE_PATH_ATTEMPTS) {
2034
+ while (queue.length > 0 && attempts < budget.maxAttempts) {
2013
2035
  await coverageYield();
2014
- const path = queue.shift();
2036
+ let pathIndex = 0;
2037
+ for (let scanned = 0; scanned < rootFamilies.length; scanned++) {
2038
+ const family = rootFamilies[familyCursor];
2039
+ familyCursor = (familyCursor + 1) % rootFamilies.length;
2040
+ const candidate = queue.findIndex((path) => coverageNodeKey(path.root) === family);
2041
+ if (candidate < 0)
2042
+ continue;
2043
+ pathIndex = candidate;
2044
+ break;
2045
+ }
2046
+ const [path] = queue.splice(pathIndex, 1);
2015
2047
  attempts++;
2016
2048
  let replay = await replayCoveragePath(machine, nodes, path);
2017
2049
  let covered = false;
@@ -2031,8 +2063,8 @@ async function searchCoverageEntry(machine, target, refs, captains, playbooks, c
2031
2063
  // authored prefix before considering successors, charging that replay
2032
2064
  // against the same attempt limit.
2033
2065
  replay.actor.stop();
2034
- if (attempts >= MAX_COVERAGE_PATH_ATTEMPTS) {
2035
- limitations.add(`exhausted ${MAX_COVERAGE_PATH_ATTEMPTS}-attempt path budget`);
2066
+ if (attempts >= budget.maxAttempts) {
2067
+ limitations.add(`exhausted ${budget.maxAttempts}-attempt path budget`);
2036
2068
  break;
2037
2069
  }
2038
2070
  attempts++;
@@ -2082,8 +2114,8 @@ async function searchCoverageEntry(machine, target, refs, captains, playbooks, c
2082
2114
  }
2083
2115
  const continuations = [];
2084
2116
  for (const step of nextSteps) {
2085
- if (path.steps.length + 1 >= MAX_COVERAGE_PATH_STEPS) {
2086
- limitations.add(`exhausted ${MAX_COVERAGE_PATH_STEPS}-invocation path depth`);
2117
+ if (path.steps.length + 1 >= budget.maxInvocations) {
2118
+ limitations.add(`exhausted ${budget.maxInvocations}-invocation path depth`);
2087
2119
  continue;
2088
2120
  }
2089
2121
  const visited = [path.root, ...path.steps.map((step) => step.next)].map(coverageNodeKey);
@@ -2103,14 +2135,14 @@ async function searchCoverageEntry(machine, target, refs, captains, playbooks, c
2103
2135
  queue.push(successor);
2104
2136
  }
2105
2137
  // Replay a discovered target, including its canonical question continuation,
2106
- // before unrelated prefixes; retain candidate order and the same budgets.
2138
+ // before unrelated prefixes in its family; retain candidate order and budgets.
2107
2139
  queue.unshift(...continuations);
2108
2140
  }
2109
2141
  finally {
2110
2142
  replay.actor.stop();
2111
2143
  if ((!covered || needsLiteral()) &&
2112
2144
  path.alternatives !== undefined &&
2113
- attempts < MAX_COVERAGE_PATH_ATTEMPTS) {
2145
+ attempts < budget.maxAttempts) {
2114
2146
  const next = path.alternatives.next();
2115
2147
  if (!next.done)
2116
2148
  queue.push({
@@ -2123,7 +2155,7 @@ async function searchCoverageEntry(machine, target, refs, captains, playbooks, c
2123
2155
  }
2124
2156
  }
2125
2157
  if (queue.length > 0)
2126
- limitations.add(`exhausted ${MAX_COVERAGE_PATH_ATTEMPTS}-attempt path budget`);
2158
+ limitations.add(`exhausted ${budget.maxAttempts}-attempt path budget`);
2127
2159
  return {
2128
2160
  covered: transitionCovered,
2129
2161
  entered,
@@ -2868,7 +2900,8 @@ async function probeParallelJoins(machine, parallel, refs, captains, interruptVa
2868
2900
  * guard search, and a final scheduling margin. Generated tests use this instead
2869
2901
  * of Vitest's five-second default.
2870
2902
  */
2871
- export function fsmCoverageTestTimeout(fsmModule) {
2903
+ export function fsmCoverageTestTimeout(fsmModule, coverage) {
2904
+ const budget = resolveCoverageBudget(coverage);
2872
2905
  const machine = findMachine(fsmModule);
2873
2906
  const config = machine.config;
2874
2907
  const refs = stateRefs(config);
@@ -2979,15 +3012,15 @@ export function fsmCoverageTestTimeout(fsmModule) {
2979
3012
  guardProbeCalls +=
2980
3013
  pathSearches *
2981
3014
  (nodes.length * (1 + entryArmCount) +
2982
- MAX_COVERAGE_PATH_ATTEMPTS * 2 * maxNodeCandidates);
3015
+ budget.maxAttempts * 2 * maxNodeCandidates);
2983
3016
  // Parallel question/join helpers retain their independent entry probes.
2984
3017
  guardProbeCalls += 2 * parallels.length;
2985
- // Each charged replay contains at most eight invocation waits, up to
2986
- // seven parked question waits and two target/reply settles, plus
3018
+ // Each charged replay contains at most the selected invocation count and
3019
+ // one fewer parked question waits, plus two target/reply settles and
2987
3020
  // no-transition checks.
2988
3021
  const pathSettles = pathSearches *
2989
- MAX_COVERAGE_PATH_ATTEMPTS *
2990
- ((2 * MAX_COVERAGE_PATH_STEPS + 1) * PARALLEL_SETTLE_MS + 2 * 10);
3022
+ budget.maxAttempts *
3023
+ ((2 * budget.maxInvocations + 1) * PARALLEL_SETTLE_MS + 2 * 10);
2991
3024
  const parallelSettles = parallels.reduce((total, parallel) => total +
2992
3025
  2 * PARALLEL_QUESTION_SETTLE_MS +
2993
3026
  transitionArms(parallel.state.onDone).length *
@@ -3014,6 +3047,7 @@ export async function checkFsmCoverage(fsmModule, opts = {}) {
3014
3047
  }
3015
3048
  /** Conformance suites replay only pending literal bindings; coverage stays separate. */
3016
3049
  export async function checkGearsFsmConformanceAsync(gears, fsmModule, options = {}) {
3050
+ options = { ...options, coverage: resolveCoverageBudget(options.coverage) };
3017
3051
  const { findings, literalChecks } = prepareGearsFsmConformance(gears, findMachine(fsmModule).config, { concurrentRoleSets: findConcurrentRoleSets(fsmModule), ...options });
3018
3052
  options.signal?.throwIfAborted();
3019
3053
  return findings.length > 0 || !literalChecks.pending()
@@ -3022,6 +3056,7 @@ export async function checkGearsFsmConformanceAsync(gears, fsmModule, options =
3022
3056
  }
3023
3057
  /** One bounded replay owns transition coverage and reached literal-child proof. */
3024
3058
  export async function checkGearsFsmArtifact(gears, fsmModule, options = {}) {
3059
+ options = { ...options, coverage: resolveCoverageBudget(options.coverage) };
3025
3060
  const { findings, literalChecks } = prepareGearsFsmConformance(gears, findMachine(fsmModule).config, {
3026
3061
  concurrentRoleSets: findConcurrentRoleSets(fsmModule),
3027
3062
  ...options,
@@ -3032,12 +3067,14 @@ export async function checkGearsFsmArtifact(gears, fsmModule, options = {}) {
3032
3067
  : fsmCoverage(fsmModule, options, literalChecks);
3033
3068
  }
3034
3069
  async function fsmCoverage(fsmModule, opts = {}, literalChecks, literalOnly = false) {
3070
+ const coverage = resolveCoverageBudget(opts.coverage);
3035
3071
  opts.signal?.throwIfAborted();
3036
3072
  if (opts.timeoutMs !== undefined &&
3037
3073
  (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0))
3038
3074
  throw new RangeError('FSM coverage timeout must be a positive finite number');
3039
3075
  const started = performance.now();
3040
3076
  const run = {
3077
+ coverage,
3041
3078
  literalChecks,
3042
3079
  signal: opts.signal,
3043
3080
  deadline: started +
@@ -3050,7 +3087,7 @@ async function fsmCoverage(fsmModule, opts = {}, literalChecks, literalOnly = fa
3050
3087
  return coverageRuns.run(run, async () => {
3051
3088
  let completed = false;
3052
3089
  try {
3053
- run.deadline = Math.min(run.deadline, started + fsmCoverageTestTimeout(fsmModule));
3090
+ run.deadline = Math.min(run.deadline, started + fsmCoverageTestTimeout(fsmModule, coverage));
3054
3091
  await coverageYield(true);
3055
3092
  const schema = resolveArtifactSchemaForVerification({
3056
3093
  config: findMachine(fsmModule).config,
@@ -3738,6 +3775,7 @@ async function runFsmCoverage(fsmModule, sourceText) {
3738
3775
  * beside the artifacts (verification-6).
3739
3776
  */
3740
3777
  export function generateFsmCoverageTest(opts) {
3778
+ const coverage = resolveCoverageBudget(opts.coverage);
3741
3779
  const commentBasename = JSON.stringify(opts.basename)
3742
3780
  .replaceAll('\u2028', '\\u2028')
3743
3781
  .replaceAll('\u2029', '\\u2029');
@@ -3757,14 +3795,16 @@ import { describe, expect, it } from 'vitest';
3757
3795
  import { checkFsmCoverage, fsmCoverageTestTimeout } from ${verifyModule};
3758
3796
  import * as fsm from ${fsmModule};
3759
3797
 
3798
+ const coverage = ${JSON.stringify(coverage)};
3799
+
3760
3800
  describe(${suiteName}, () => {
3761
3801
  it('reaches every declared transition', async () => {
3762
3802
  const sourceText = readFileSync(
3763
3803
  fileURLToPath(new URL(${fsmSourceFile}, import.meta.url)),
3764
3804
  'utf8',
3765
3805
  );
3766
- expect(await checkFsmCoverage(fsm, { sourceText${opts.artifactSchema === undefined ? '' : `, artifactSchema: ${opts.artifactSchema}`} })).toEqual([]);
3767
- }, fsmCoverageTestTimeout(fsm));
3806
+ expect(await checkFsmCoverage(fsm, { coverage, sourceText${opts.artifactSchema === undefined ? '' : `, artifactSchema: ${opts.artifactSchema}`} })).toEqual([]);
3807
+ }, fsmCoverageTestTimeout(fsm, coverage));
3768
3808
  });
3769
3809
  `;
3770
3810
  }
@@ -3777,6 +3817,7 @@ describe(${suiteName}, () => {
3777
3817
  * @throws when the `fsm` artifact cannot be imported or exports no machine.
3778
3818
  */
3779
3819
  export async function emitFsmCoverageTest(opts) {
3820
+ const coverage = resolveCoverageBudget(opts.coverage);
3780
3821
  const fsmPath = join(opts.artifactDir, `${opts.basename}.fsm.ts`);
3781
3822
  const module = await loadFsmModule(fsmPath);
3782
3823
  const schema = resolveArtifactSchemaForVerification({
@@ -3788,12 +3829,14 @@ export async function emitFsmCoverageTest(opts) {
3788
3829
  });
3789
3830
  const artifactSchema = schema.artifactSchema;
3790
3831
  const findings = await checkFsmCoverage(module, {
3832
+ coverage,
3791
3833
  sourceText: await readFile(fsmPath, 'utf8'),
3792
3834
  ...(opts.artifactSchema === undefined
3793
3835
  ? {}
3794
3836
  : { artifactSchema: opts.artifactSchema }),
3795
3837
  });
3796
3838
  const content = generateFsmCoverageTest({
3839
+ coverage,
3797
3840
  basename: opts.basename,
3798
3841
  fsmModule: `./${opts.basename}.fsm.js`,
3799
3842
  fsmSourceFile: `./${opts.basename}.fsm.ts`,