gdp-wired 0.32.0 → 0.33.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/README.md CHANGED
@@ -114,6 +114,14 @@ laws about when it raises, a store's attributes, an untyped result) go in a `gdp
114
114
  in pyproject.toml, `"gdp"` in package.json), per rule under `[rules.<name>]`. The exit code is 1 when a stated law is
115
115
  broken, 2 when one couldn't be checked: `uses: monotykamary/gdp-wired@main` with `paths:` runs it in CI.
116
116
 
117
+ Laws about two runs read the same way: `diagnosis never reaches status, result` (two runs differing only in the
118
+ secret keep what is named the same, and fail alike), `isolated by user_id` (what the caller whose `user_id` is B sees
119
+ is the same whatever the others do), `agrees with LimiterV1` (a migration: another class of the target, the same state
120
+ after every history). A duration is linear over the request's time: `now - received < 30 days` (seconds, minutes,
121
+ hours, days, weeks; a month, a year or a business day is refused). `gdp: cite <law name>: <clause>` ties a law to the
122
+ clause it answers: printed with the law, and with `--cert <dir>` kept in the meta of each proven law's certificate,
123
+ never in what is checked (`research/regulated/DESIGN.md`).
124
+
117
125
  ## Where it fits
118
126
 
119
127
  <img src="https://raw.githubusercontent.com/monotykamary/gdp-wired/main/static/venn.svg" alt="What Lean, Bend and gdp-wired each cover, and where they overlap" width="640" />
@@ -235,6 +243,11 @@ All of these are proven automatically, and each proof is also a Lean theorem:
235
243
  - **Pure functions and two-run laws**: laws about what a function returns, and laws comparing two calls, like "the
236
244
  secret never changes the answer". `examples/jev-fabric/` ports a Bend project's policy core and proves all 59 laws its
237
245
  Bend proofs state.
246
+ - **Laws about two runs of a stateful rule** (`gdp-wired/relational`): noninterference (`noninterference(rule, {secret,
247
+ visible})`: what a party sees never depends on the secret, nor which requests fail), tenant isolation (`isolation(rule,
248
+ {owner})`: what tenant B sees is the same whatever the others do) and migration agreement (`agreement(old, next)`),
249
+ on rules read from code as on written ones; `proveTwoRuns` proves the law of the two runs side by side as one rule, a
250
+ refutation the two runs (`research/regulated/`).
238
251
 
239
252
  When a law is false, the GPU search finds a real run that breaks it. When a law needs an invariant nobody wrote,
240
253
  `inferLaws` finds one on the CPU (and the GPU synthesizer, at scale, in `research/synth/`) and the kernel proves it.
@@ -7,21 +7,25 @@ export function checkRefutation(constraints, steps, integral = true) {
7
7
  if (!(Number.isInteger(s.index) && s.index >= 0 && s.index < constraints.length))
8
8
  return false;
9
9
  const c = constraints[s.index];
10
- if (!integral && !exact(c.lin))
10
+ if (!exact(c.lin))
11
11
  return false;
12
12
  rows.push(c.lin);
13
13
  strict.push(!integral && c.strict === true);
14
14
  }
15
15
  else if (s.kind === 'combine') {
16
- if (!(s.a < i && s.b < i && Number.isInteger(s.ma) && Number.isInteger(s.mb) && s.ma > 0 && s.mb > 0))
16
+ if (!(s.a < i && s.b < i && Number.isSafeInteger(s.ma) && Number.isSafeInteger(s.mb) && s.ma > 0 && s.mb > 0))
17
17
  return false;
18
18
  if (!integral && !(Number.isInteger(s.a) && Number.isInteger(s.b) && s.a >= 0 && s.b >= 0))
19
19
  return false;
20
20
  const out = {};
21
+ // Each product safe too: a rounded one is past 2^53, but the other row's could bring the sum back under it.
21
22
  for (const [lin, m] of [[rows[s.a], s.ma], [rows[s.b], s.mb]])
22
- for (const [key, c] of Object.entries(lin))
23
+ for (const [key, c] of Object.entries(lin)) {
24
+ if (!Number.isSafeInteger(m * c))
25
+ return false;
23
26
  out[key] = (out[key] ?? 0) + m * c;
24
- if (!integral && !exact(out))
27
+ }
28
+ if (!exact(out))
25
29
  return false;
26
30
  rows.push(out);
27
31
  strict.push(strict[s.a] || strict[s.b]);
@@ -29,8 +33,9 @@ export function checkRefutation(constraints, steps, integral = true) {
29
33
  else {
30
34
  if (!integral)
31
35
  return false;
36
+ // (c / g rounded is never an integer c / g isn't, nor past the next one, for a safe c: its ceiling is exact.)
32
37
  const row = rows[s.of];
33
- if (!(row !== undefined && s.of < i && Number.isInteger(s.g) && s.g > 0 && vars(row).every(key => row[key] % s.g === 0)))
38
+ if (!(row !== undefined && s.of < i && Number.isSafeInteger(s.g) && s.g > 0 && vars(row).every(key => row[key] % s.g === 0)))
34
39
  return false;
35
40
  rows.push({ ...Object.fromEntries(vars(row).map(key => [key, row[key] / s.g])), 1: Math.ceil((row['1'] ?? 0) / s.g) });
36
41
  strict.push(false);
@@ -40,5 +45,14 @@ export function checkRefutation(constraints, steps, integral = true) {
40
45
  return last !== undefined && vars(last).every(key => last[key] === 0) && (constant > 0 || (strict.at(-1) && constant >= 0));
41
46
  }
42
47
  export function checkWitness(constraints, witness) {
43
- return constraints.every(c => Object.entries(c.lin).reduce((sum, [key, a]) => sum + a * (key === '1' ? 1 : (witness[key] ?? NaN)), 0) <= 0);
48
+ return constraints.every(c => {
49
+ let sum = 0;
50
+ for (const [key, a] of Object.entries(c.lin)) {
51
+ const value = key === '1' ? 1 : witness[key], term = a * value;
52
+ if (!(Number.isSafeInteger(a) && Number.isSafeInteger(value) && Number.isSafeInteger(term) && Number.isSafeInteger(sum + term)))
53
+ return false;
54
+ sum += term;
55
+ }
56
+ return sum <= 0;
57
+ });
44
58
  }
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import type { Name } from './extract.js';
2
+ import type { Extraction, Name } from './extract.js';
3
+ import { type Verdict } from './dsl.js';
3
4
  export declare const colors: (env: Record<string, string | undefined>, tty: boolean, json?: boolean) => boolean;
4
5
  export type Opts = {
5
6
  entry?: string;
@@ -11,9 +12,11 @@ export type Opts = {
11
12
  propose: boolean;
12
13
  root?: string;
13
14
  python?: string;
15
+ clock?: string;
16
+ cert?: string;
14
17
  [k: string]: unknown;
15
18
  };
16
- type Lang = 'python' | 'ruby' | 'elixir' | 'java' | 'kotlin' | 'go' | 'rust' | 'swift' | 'c' | 'cpp' | 'ts';
19
+ export type Lang = 'python' | 'ruby' | 'elixir' | 'java' | 'kotlin' | 'go' | 'rust' | 'swift' | 'c' | 'cpp' | 'ts';
17
20
  export declare const LANG_NAME: Record<Lang, string>;
18
21
  type Target = {
19
22
  lang: Lang;
@@ -32,12 +35,14 @@ type LawOut = {
32
35
  name: string;
33
36
  expr: string;
34
37
  where?: string;
35
- kind?: 'law' | 'step';
38
+ kind?: 'law' | 'step' | 'two runs';
36
39
  verdict: 'proven' | 'broken' | 'unknown' | 'not read';
37
40
  run?: string[];
38
41
  why?: string;
39
42
  assumes?: string[];
40
43
  found?: string[];
44
+ cites?: string[];
45
+ cert?: string;
41
46
  ms: number;
42
47
  };
43
48
  export type RuleOut = {
@@ -58,6 +63,11 @@ export type RuleOut = {
58
63
  source?: string;
59
64
  };
60
65
  export declare function checkTarget(t: Target, o: Opts): Promise<RuleOut[]>;
66
+ export declare function runOf(x: Extraction, run: NonNullable<Verdict['run']>): string[];
67
+ export declare const proposedLaws: (x: Extraction, lang: Lang, ms?: number) => {
68
+ shown: LawOut[];
69
+ broken: number;
70
+ };
61
71
  export declare function check(targets: string[], given?: Partial<Opts>, each?: (r: RuleOut) => void): Promise<{
62
72
  rules: RuleOut[];
63
73
  exit: number;
package/dist/core/cli.js CHANGED
@@ -8,7 +8,8 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
8
8
  return path;
9
9
  };
10
10
  import { proveRule, proveSteps } from "./dsl.js";
11
- import { LawError, buildLaw, lawsIn } from "./laws.js";
11
+ import { LawError, buildLaw, buildTwoRuns, citesIn, isTwoRuns, lawsIn, namesWithClock } from "./laws.js";
12
+ import { certify, proveTwoRuns } from "./relational.js";
12
13
  const proc = globalThis.process;
13
14
  const fs = proc.getBuiltinModule('node:fs'), path = proc.getBuiltinModule('node:path');
14
15
  const out = (s = '') => proc.stdout.write(`${s}\n`);
@@ -250,14 +251,18 @@ const merge = (a, b) => {
250
251
  // The entries to read: the one given, else the one inferred; where several classes or structs qualify, each of them; a
251
252
  // file of functions, each function a law is stated on.
252
253
  async function rulesOf(t, o, laws) {
253
- const { json: _j, ms: _m, propose: _p, ...flags } = o;
254
+ const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, ...flags } = o;
254
255
  void _j;
255
256
  void _m;
256
257
  void _p;
258
+ void _c;
259
+ void _t;
257
260
  // (the options: gdp.toml's for every rule, then the rule's own, then the flags; a rule found with no entry named is
258
261
  // read again where gdp.toml has options of its own for it)
259
262
  const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
260
- const optsFor = (entry) => merge(merge(cfg.all, (entry && cfg.rules[entry]) || {}), flags);
263
+ const { clock: _k, ...shared } = cfg.all;
264
+ void _k;
265
+ const optsFor = (entry) => merge(merge(shared, (entry && cfg.rules[entry]) || {}), flags);
261
266
  const one = async (entry) => {
262
267
  const x = await extractOne(t, { ...optsFor(entry), ...(entry ? { entry } : {}) }), found = x.model?.name;
263
268
  return !entry && found && cfg.rules[found] ? { entry: found, x: await extractOne(t, { ...optsFor(found), entry: found }) } : { entry, x };
@@ -308,12 +313,17 @@ function scoped(file) {
308
313
  });
309
314
  }
310
315
  export async function checkTarget(t, o) {
311
- const laws = t.files.flatMap(scoped);
316
+ const laws = t.files.flatMap(scoped), cites = t.files.flatMap(f => citesIn(fs.readFileSync(f, 'utf8'), path.basename(f)));
312
317
  const rules = await rulesOf(t, o, laws);
313
318
  const outs = [];
319
+ // (the clock's unit, for durations in a law: the language's clock, or clock = "s" | "ms" in gdp.toml or --clock)
320
+ const unit = o.clock ?? configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at)).all.clock ?? CLOCK[t.lang];
321
+ const others = Object.fromEntries(rules.filter(r => r.x.ok).map(r => [r.entry ?? r.x.model?.name ?? '', r.x]));
322
+ const ctx = { ms: o.ms, clock: unit === 's' ? 1 : unit === 'ms' ? 1000 : undefined, others, cites, cert: o.cert, file: path.relative(proc.cwd(), t.at) || t.at };
314
323
  for (const { entry, x } of rules) {
315
324
  const name = entry ?? (x.model?.name || undefined);
316
- const r = { file: path.relative(proc.cwd(), t.at) || t.at, lang: LANG_NAME[t.lang], ...(name ? { entry: name } : {}), ok: x.ok, refusals: x.refusals, notes: x.notes, names: x.names ?? [], laws: [], proposed: [], ...(x.source ? { source: x.source } : {}) };
325
+ // (a target that is the working directory, a crate's or a package's: `.`)
326
+ const r = { file: path.relative(proc.cwd(), t.at) || '.', lang: LANG_NAME[t.lang], ...(name ? { entry: name } : {}), ok: x.ok, refusals: x.refusals, notes: x.notes, names: x.names ?? [], laws: [], proposed: [], ...(x.source ? { source: x.source } : {}) };
317
327
  outs.push(r);
318
328
  // (the laws of this rule: all where it is the file's one, else those in its class or on it or its methods, and those
319
329
  // outside every class and function)
@@ -333,44 +343,79 @@ export async function checkTarget(t, o) {
333
343
  const proven = [];
334
344
  // (a law is known by its name: a name stated twice in one rule is refused, both times)
335
345
  const twice = (l) => stated.filter(m => m.name === l.name).map(m => m.where);
336
- r.laws = stated.map(l => (twice(l).length > 1 ? { name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `a law of this name is stated twice (${twice(l).join(', ')}): a law is known by its name`, ms: 0 } : prove(x, l, o.ms, proven)));
346
+ r.laws = stated.map(l => (twice(l).length > 1 ? { name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `a law of this name is stated twice (${twice(l).join(', ')}): a law is known by its name`, ms: 0 } : prove(x, l, o.ms, proven, { ...ctx, entry: name })));
337
347
  if (o.propose && x.model) {
338
348
  const p = propose(x, t.lang, o, proven, new Set(stated.map(l => l.expr.replace(/\s+/g, ''))));
339
349
  r.proposed = p.shown;
340
350
  r.brokenProposed = p.broken;
341
351
  }
342
352
  }
353
+ // (a citation of no law stated in the target: refused, as a law not read is)
354
+ const named = new Set(laws.map(l => l.name));
355
+ for (const c of cites.filter(c => !named.has(c.law)))
356
+ outs[0]?.laws.push({ name: c.law, expr: '', where: c.where, verdict: 'not read', why: `a citation of no law stated here (gdp: cite <law name>: <clause>): ${c.text}`, ms: 0 });
343
357
  return outs;
344
358
  }
359
+ // The unit of each language's clock (Date.now() and a Clock's millis count milliseconds; time.time(), DateTime.diff in
360
+ // seconds and Instant's as_secs count seconds); the others say it in gdp.toml (clock = "s" or "ms").
361
+ const CLOCK = { python: 's', elixir: 's', rust: 's', ts: 'ms', java: 'ms', kotlin: 'ms' };
345
362
  // A law proven: an invariant with the rule's own invariants beside it, a step law with them and the invariants proven
346
- // so far (each holds in every reachable state, so the step laws may assume them).
347
- function prove(x, l, ms, proven) {
348
- const t0 = Date.now(), base = { name: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}) };
349
- let b;
363
+ // so far (each holds in every reachable state, so the step laws may assume them); a law about two runs with the rule's
364
+ // invariants holding of each run (core/relational.ts). Its citations go beside it, and with --cert <dir> the proof, as
365
+ // an interchange document whose meta holds them.
366
+ function prove(x, l, ms, proven, ctx) {
367
+ const t0 = Date.now(), cites = ctx?.cites.filter(c => c.law === l.name).map(c => c.text) ?? [];
368
+ const base = { name: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}), ...(cites.length ? { cites } : {}) };
369
+ const inv = x.invariants ?? [], search = { search: { ms } };
370
+ let b, two;
350
371
  try {
351
- b = buildLaw(x, l);
372
+ if (isTwoRuns(l.expr))
373
+ two = buildTwoRuns(x, l, ctx?.others);
374
+ else
375
+ b = buildLaw(x, l, { clock: ctx?.clock });
352
376
  }
353
377
  catch (e) {
354
- if (e instanceof LawError)
378
+ if (e instanceof LawError || two === undefined && isTwoRuns(l.expr))
355
379
  return { ...base, verdict: 'not read', why: e.message, ms: 0 };
356
380
  throw e;
357
381
  }
358
- const inv = x.invariants ?? [], search = { search: { ms } };
382
+ const kind = two ? 'two runs' : b.kind;
359
383
  let v;
360
384
  try {
361
- v = b.kind === 'law' ? proveRule(x.rule, [...inv, b.law], search) : proveSteps(x.rule, [...inv, ...proven], [b.law], search);
385
+ v = two ? proveTwoRuns(two, { ...search, invariants: [two.sides[0] === x.rule ? inv : (ctx?.others && Object.values(ctx.others).find(o => o.rule === two.sides[0])?.invariants) ?? [], inv] }) : b.kind === 'law' ? proveRule(x.rule, [...inv, b.law], search) : proveSteps(x.rule, [...inv, ...proven], [b.law], search);
362
386
  }
363
387
  catch (e) {
364
- return { ...base, kind: b.kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
388
+ return { ...base, kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
365
389
  }
366
390
  const verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown';
367
391
  // (a state the laws allow from which a step breaks the law, no run from the start reaching it: shown, not a break)
368
- const at = !v.run && v.witness ? (x.names ?? []).filter(n => n.rule && n.rule in v.witness && n.role !== 'const').map(n => `${label(n)} = ${shownValue(x, n.rule, v.witness, n.none)}`) : [];
369
- if (verdict === 'proven' && b.kind === 'law')
392
+ const at = !v.run && v.witness && !two ? (x.names ?? []).filter(n => n.rule && n.rule in v.witness && n.role !== 'const').map(n => `${label(n)} = ${shownValue(x, n.rule, v.witness, n.none)}`) : [];
393
+ if (verdict === 'proven' && b?.kind === 'law')
370
394
  proven.push(b.law);
371
395
  const found = v.found?.laws?.map(f => f.text);
372
- return { ...base, kind: b.kind, verdict, ...(v.run ? { run: runOf(x, v.run) } : {}), ...(verdict === 'unknown' ? { why: [v.why ?? v.stuck ?? 'not proven', ...(at.length ? [`a state the laws allow where a step breaks it, no run from the start found reaching it: ${at.join(', ')}`] : [])].join('; ') } : {}),
373
- ...(v.run ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ms: Date.now() - t0 };
396
+ let cert;
397
+ if (verdict === 'proven' && ctx?.cert) {
398
+ const more = v.found?.laws?.map(f => f.law) ?? [];
399
+ const meta = { producer: 'gdp-wired check', file: ctx.file, ...(ctx.entry ? { entry: ctx.entry } : {}), law: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}), cites };
400
+ const doc = v.k ? undefined : two ? certify(two.rule, [...v.given ?? [], ...more, ...two.laws], two.stepLaws, meta)
401
+ : b.kind === 'law' ? certify(x.rule, [...inv, ...more, b.law], [], meta) : certify(x.rule, [...inv, ...proven, ...more], [b.law], meta);
402
+ if (doc) {
403
+ fs.mkdirSync(ctx.cert, { recursive: true });
404
+ cert = path.join(ctx.cert, `${[ctx.entry ?? path.basename(ctx.file), l.name].join('.').replace(/[^\w.-]+/g, '-')}.json`);
405
+ fs.writeFileSync(cert, JSON.stringify(doc));
406
+ }
407
+ }
408
+ return { ...base, kind, verdict, ...(v.run ? { run: two ? pairRunOf(x, v.run, two) : runOf(x, v.run) } : {}), ...(verdict === 'unknown' ? { why: [v.why ?? v.stuck ?? 'not proven', ...(at.length ? [`a state the laws allow where a step breaks it, no run from the start found reaching it: ${at.join(', ')}`] : [])].join('; ') } : {}),
409
+ ...(v.run && !two ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ...(cert ? { cert } : {}), ms: Date.now() - t0 };
410
+ }
411
+ // Two runs as calls of the code: each request once, the values the two runs take apart as `a | b`, and the run b leaves
412
+ // out (isolation's: the others' calls) marked.
413
+ function pairRunOf(x, run, two) {
414
+ const sideOf = (vars, p) => Object.fromEntries(Object.entries(vars).flatMap(([k, val]) => (k.startsWith(p) ? [[k.slice(2), val]] : /^[ab]_/.test(k) ? [] : [[k, val]])));
415
+ const a = runOf(x, { params: sideOf(run.params, 'a_'), trace: run.trace.map(q => sideOf(q, 'a_')) });
416
+ const b = runOf(x, { params: sideOf(run.params, 'b_'), trace: run.trace.map(q => sideOf(q, 'b_')) });
417
+ const tenant = 'tenant' in run.params && !two.shared.every(n => n !== 'tenant') ? [`B is ${run.params.tenant} (run b takes only B's calls)`] : [];
418
+ return [...tenant, ...a.map((s, i) => (s === b[i] ? s : `${s} | ${b[i]}`))];
374
419
  }
375
420
  // What a refutation assumes of the answers inferred (core/extract-step.ts's `assumed`), at the run's last request.
376
421
  function assumedOf(x, run) {
@@ -402,8 +447,8 @@ function shownValue(x, rule, vars, none) {
402
447
  }
403
448
  // A run as calls of the code: the constructor's arguments, then each request (the method, its arguments by the code's
404
449
  // names, the answers and the clock), the last the one that breaks the law.
405
- function runOf(x, run) {
406
- const names = x.names ?? [], code = (n) => n.code;
450
+ export function runOf(x, run) {
451
+ const names = namesWithClock(x), code = (n) => n.code;
407
452
  const ps = names.filter(n => n.role === 'param' && n.rule && n.rule in run.params);
408
453
  const lines = ps.length ? [`made with ${ps.map(n => `${code(n)} = ${shownValue(x, n.rule, run.params, n.none)}`).join(', ')}`] : [];
409
454
  const ev = names.find(n => n.role === 'method');
@@ -489,6 +534,8 @@ function propose(x, lang, o, proven, stated) {
489
534
  }
490
535
  return { shown, broken };
491
536
  }
537
+ // The laws `check` proposes for an extraction with nothing stated, each proven (`shown`: those not broken by a run).
538
+ export const proposedLaws = (x, lang, ms = 2000) => propose(x, lang, { ms, propose: true }, [], new Set());
492
539
  // --- printing ------------------------------------------------------------------------------------------------------------
493
540
  const ROLE = { state: 'state', param: 'made with', input: 'request', answer: 'answered', result: 'result', failed: 'failed', method: 'method', clock: 'clock', const: 'constant' };
494
541
  function printRule(r, o) {
@@ -512,6 +559,10 @@ function printRule(r, o) {
512
559
  out(` ${paint(VERDICT[l.verdict], l.verdict)}${' '.repeat(Math.max(0, 9 - l.verdict.length))}${l.name}${proposed ? '' : ` ${paint('dim', `(${l.where})`)}`}`);
513
560
  if (!proposed && l.verdict !== 'proven')
514
561
  out(` ${l.expr}`);
562
+ for (const c of l.cites ?? [])
563
+ out(` cites: ${c}`);
564
+ if (l.cert)
565
+ out(` ${paint('dim', `certificate: ${l.cert}`)}`);
515
566
  if (l.run)
516
567
  for (const [i, s] of l.run.entries())
517
568
  out(` ${i === 0 ? 'run: ' : ' '}${paint('red', s)}`);
@@ -542,11 +593,14 @@ function printRule(r, o) {
542
593
  out();
543
594
  }
544
595
  const label = (n) => (n.role === 'answer' ? `${n.code.split('.').pop()}(...)` : n.role === 'input' && n.method ? `${n.method}(${n.code})` : n.role === 'result' && n.method ? `${n.method}() result` : n.code);
545
- const USAGE = `gdp-wired check <file|dir>... [--entry X] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose]
596
+ const USAGE = `gdp-wired check <file|dir>... [--entry X] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose] [--clock s|ms] [--cert <dir>]
546
597
 
547
598
  Reads the rule in each file (Python, Ruby, Elixir, Java, Kotlin, Go, Rust, Swift, C, C++, TypeScript, Effect, XState), checks it
548
599
  against the code by running both, proves the laws stated in the code (\`# gdp: law <name>: <expr>\`, \`// gdp: law ...\`,
549
- @GdpLaw("<name>: <expr>")) and proposes others. Exit code: 1 when a stated law is broken, 2 when one couldn't be checked.`;
600
+ @GdpLaw("<name>: <expr>")) and proposes others. Laws about two runs: \`<secret> never reaches <fields>\`, \`isolated by <argument>\`,
601
+ \`agrees with <Class>\`; a duration over the clock: \`now - t < 30 days\`; the clause a law answers: \`gdp: cite <law name>: <clause>\`;
602
+ --cert <dir> writes each proven law's certificate (its meta the citations). Exit code: 1 when a stated law is broken, 2 when
603
+ one couldn't be checked.`;
550
604
  // Every target's rules and their laws, and the exit code (1: a stated law broken; 2: one not checked).
551
605
  export async function check(targets, given = {}, each) {
552
606
  const o = { ms: 10_000, propose: true, ...given }, all = [];
@@ -289,7 +289,7 @@ export declare class MapRef {
289
289
  readonly init: number;
290
290
  private readonly cells;
291
291
  constructor(name: string, init: number);
292
- at(key: TermLike): Term;
292
+ at(key0: TermLike | Str): Term;
293
293
  set(key: TermLike, value: TermLike): MapWrite;
294
294
  bump(key: TermLike, c?: Cond, by?: TermLike): MapWrite;
295
295
  each(f: (key: Term) => TermLike): MapWrite;
@@ -351,7 +351,7 @@ export declare class CellsRef<V> {
351
351
  readonly kind: Kind<V>;
352
352
  private readonly map;
353
353
  constructor(name: string, kind: Kind<V>, map: (part: string) => MapRef);
354
- at(key: TermLike): V;
354
+ at(key: TermLike | Str): V;
355
355
  set(key: TermLike, value: Writes<V>): PartsWrite;
356
356
  each(f: (key: Term) => Writes<V>): PartsWrite;
357
357
  sum(of: (value: V) => TermLike): Term;
package/dist/core/dsl.js CHANGED
@@ -900,7 +900,8 @@ export class MapRef {
900
900
  this.init = init;
901
901
  this.cells = scope?.maps[name];
902
902
  }
903
- at(key) { const k = valOf(key); return new Term({ op: 'get', map: this.name, key: termOf(key) }, this.cells && k !== undefined ? this.cells.cells.get(k) ?? this.cells.dflt : undefined); }
903
+ // (a string key is its interned id, as a map keyed by strings holds it)
904
+ at(key0) { const key = key0 instanceof Str ? key0.id : key0, k = valOf(key); return new Term({ op: 'get', map: this.name, key: termOf(key) }, this.cells && k !== undefined ? this.cells.cells.get(k) ?? this.cells.dflt : undefined); }
904
905
  set(key, value) { return { map: this.name, key: termOf(key), value: termOf(value), concrete: { key: valOf(key), value: valOf(value) } }; }
905
906
  // key's cell plus `by` where `c` holds (the counter every cap keeps).
906
907
  bump(key, c = yes, by = 1) { return this.set(key, when(c, this.at(key).plus(by), this.at(key))); }
@@ -2788,7 +2789,8 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2788
2789
  && facts.filter(readsParams).every(f => holds(f, params));
2789
2790
  const cap = watchWork.n + perTrial * budget.trials;
2790
2791
  try {
2791
- for (let trial = 0; trial < budget.trials && watchWork.n <= cap; trial++) {
2792
+ const late = () => budget.until !== undefined && performance.now() > budget.until;
2793
+ for (let trial = 0; trial < budget.trials && watchWork.n <= cap && !late(); trial++) {
2792
2794
  // (`mixed`: the trials in turn at bounds 1 to 4, every fourth near)
2793
2795
  const bound = budget.mixed ? 1 + trial % 4 : budget.bound, guided = guides, near = budget.mixed && trial % 4 ? undefined : budget.near;
2794
2796
  const params = r.randomParams(rand, bound);
@@ -2806,7 +2808,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2806
2808
  for (const { w, on } of watching)
2807
2809
  if (!('then' in w) && !on.start(st))
2808
2810
  return broken(w, '@start', st);
2809
- for (let d = 0, tries = 0; d < budget.depth && tries < 40 && watchWork.n <= cap; tries++) {
2811
+ for (let d = 0, tries = 0; d < budget.depth && tries < 40 && watchWork.n <= cap && !late(); tries++) {
2810
2812
  const input = r.randomInput(rand, bound, params);
2811
2813
  if (near)
2812
2814
  for (const x of m.inputs)
@@ -2928,8 +2930,10 @@ function searched(r, laws, stepLaws, v, opts) {
2928
2930
  return v;
2929
2931
  // The deeper runs; then runs over small values (keys that meet, small params), whose requests meet their
2930
2932
  // assumption's equalities and clocks, or near the counterexample the verdict ends at.
2933
+ // (the three within the search's budget again, on the wall: past it they stop, and the search starts as it would)
2934
+ const ms = typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000, runsUntil = performance.now() + ms;
2931
2935
  for (const b of [deeperBudget, { ...deeperBudget, bound: 1, seed: 31, states: false }, { ...deeperBudget, trials: 1200, seed: 41, states: false, mixed: true, ...(v.witness ? { near: v.witness } : {}) }]) {
2932
- const deeper = refuteByRuns(r, laws, stepLaws, b);
2936
+ const deeper = refuteByRuns(r, laws, stepLaws, { ...b, until: runsUntil });
2933
2937
  if (deeper?.run)
2934
2938
  return refutedVerdict(deeper);
2935
2939
  }
@@ -156,19 +156,31 @@ function solved(atoms, g) {
156
156
  // Whether ∃ vars. P holds where env and st give every other value, with a witness: exact when the bound values are one
157
157
  // natural or one integer read linearly (P's truth changes only next to the values its atoms solve for, so those, their
158
158
  // neighbours, 0 and one past them are every case); otherwise found among those points, or undefined.
159
+ // (what P is, apart from the state: its groups, atoms and shape, read once a law; a run reads a law with "there exists"
160
+ // at every tuple of its keys at every state, and P's atoms are quadratic in its size to read)
161
+ const shapes = new WeakMap();
162
+ const shapeOf = (body, vars) => {
163
+ let byVars = shapes.get(body);
164
+ if (!byVars)
165
+ shapes.set(body, (byVars = new Map()));
166
+ const id = vars.join(','), had = byVars.get(id);
167
+ if (had)
168
+ return had;
169
+ const bound = new Set(vars), out = { groups: groupsOf(vars), atoms: atomsOf(body, bound), linearOnly: linearIn(body, bound), reads: JSON.stringify(body).includes('"op":"get"') };
170
+ byVars.set(id, out);
171
+ return out;
172
+ };
159
173
  export function someHolds(body, vars, env, st, m) {
160
- const groups = groupsOf(vars), bound = new Set(vars);
174
+ const { groups, atoms, linearOnly, reads } = shapeOf(body, vars);
161
175
  const value = (e) => { try {
162
176
  return evalE(e, env, st, m);
163
177
  }
164
178
  catch {
165
179
  return undefined;
166
180
  } };
167
- const atoms = atomsOf(body, bound);
168
- const linearOnly = linearIn(body, bound);
169
181
  // A bound natural read as a map's key: the cells the maps hold, and one past them, are every case a read gives.
170
182
  const cells = new Set();
171
- if (JSON.stringify(body).includes('"op":"get"'))
183
+ if (reads)
172
184
  for (const c of Object.values(st.maps))
173
185
  for (const key of c.keys())
174
186
  cells.add(key);
@@ -38,6 +38,10 @@ export declare const inferRates: {
38
38
  evals: number;
39
39
  watched: number;
40
40
  work: number;
41
+ etries: number;
42
+ epr: number;
43
+ erows: number;
44
+ efull: number;
41
45
  };
42
46
  export declare const inferRuns = 16000;
43
47
  export declare function inferLaws(target: AnyRule | Machine, laws: Law[], stepLaws?: StepLaw[], opts?: InferOptions): Inferred;