gdp-wired 0.50.2 → 0.50.4
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 +8 -2
- package/dist/core/agent-consult/cli.d.ts +2 -0
- package/dist/core/agent-consult/cli.js +19 -0
- package/dist/core/agent-consult/protocol.d.ts +93 -0
- package/dist/core/agent-consult/protocol.js +154 -0
- package/dist/core/agent-consult/service.d.ts +435 -0
- package/dist/core/agent-consult/service.js +84 -0
- package/dist/core/agent-consult/session.d.ts +13 -0
- package/dist/core/agent-consult/session.js +163 -0
- package/dist/core/agent-consult/source-service.d.ts +83 -0
- package/dist/core/agent-consult/source-service.js +51 -0
- package/dist/core/agent-consult/tsconfig.json +5 -0
- package/dist/core/agent-consult/worker.d.ts +1 -0
- package/dist/core/agent-consult/worker.js +17 -0
- package/dist/core/agent-consult/workspace.d.ts +27 -0
- package/dist/core/agent-consult/workspace.js +66 -0
- package/dist/core/agent-consult.d.ts +8 -0
- package/dist/core/agent-consult.js +6 -0
- package/dist/core/cli.d.ts +17 -1
- package/dist/core/cli.js +174 -68
- package/dist/core/discover.d.ts +6 -1
- package/dist/core/discover.js +54 -7
- package/dist/core/dsl-deadline.d.ts +3 -0
- package/dist/core/dsl-deadline.js +26 -2
- package/dist/core/dsl.d.ts +3 -1
- package/dist/core/dsl.js +93 -30
- package/dist/core/effect.d.ts +12 -0
- package/dist/core/effect.js +26 -9
- package/dist/core/ex/harness.exs +171 -5
- package/dist/core/extract-c.js +63 -6
- package/dist/core/extract-check.d.ts +5 -1
- package/dist/core/extract-check.js +28 -10
- package/dist/core/extract-go-check.js +127 -1
- package/dist/core/extract-go.js +8 -2
- package/dist/core/extract-jvm.js +2 -2
- package/dist/core/extract-rs.js +51 -5
- package/dist/core/extract-step.js +40 -6
- package/dist/core/extract-swift.js +47 -3
- package/dist/core/extract.d.ts +8 -0
- package/dist/core/infer.d.ts +8 -0
- package/dist/core/infer.js +133 -16
- package/dist/core/jvm/Harness.java +135 -3
- package/dist/core/jvm/Rt.java +66 -4
- package/dist/core/laws.js +51 -10
- package/dist/core/native-law.d.ts +3 -1
- package/dist/core/native-law.js +126 -14
- package/dist/core/native-observations.d.ts +20 -0
- package/dist/core/native-observations.js +41 -0
- package/dist/core/native-wire.d.ts +1 -0
- package/dist/core/native-wire.js +16 -2
- package/dist/core/py/harness.py +21 -4
- package/dist/core/rb/harness.rb +178 -9
- package/dist/core/search-termination.d.ts +35 -0
- package/dist/core/search-termination.js +13 -0
- package/dist/core/search-watchdog.d.ts +8 -0
- package/dist/core/search-watchdog.js +34 -0
- package/dist/core/source-check.d.ts +3 -0
- package/dist/core/swift/Harness.swift +65 -4
- package/dist/core/swift/Main.swift +27 -4
- package/dist/core/wall.d.ts +3 -1
- package/dist/core/wall.js +7 -4
- package/dist/core/work-refusal.d.ts +3 -0
- package/dist/core/work-refusal.js +8 -0
- package/dist/kernel/prove.d.ts +2 -0
- package/dist/kernel/prove.js +13 -5
- package/docs/agent-consult-workspace-check.md +118 -0
- package/docs/agent-consult.md +151 -0
- package/examples/agent-consult.json +22 -0
- package/package.json +11 -3
package/dist/core/infer.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { retainFrom } from "./proof-output.js";
|
|
2
2
|
import { searchNow as countedSearchNow, checkWorkEndpoint } from "./wall.js";
|
|
3
|
+
import { inWorkScope } from "../kernel/prove.js";
|
|
4
|
+
import { completedSearch, completedSourceRefusal, searchContext, stoppedSearch } from "./search-termination.js";
|
|
5
|
+
import { WatchdogExpired, checkWatchdog, withSearchWatchdog } from "./search-watchdog.js";
|
|
3
6
|
// Invariants nobody wrote: a law that holds but isn't inductive, proven with laws the search finds. Nothing here is
|
|
4
7
|
// trusted; what it finds is proven by the kernel with the rule's own laws, as laws of the same rule.
|
|
5
8
|
// - runs: random runs from the start (params and requests by their kinds, the assumption met) give reachable states,
|
|
@@ -42,7 +45,7 @@ import { sampleStep } from "./sample-step.js";
|
|
|
42
45
|
import { all, any, atMost, carriedView, compileC, compileE, cpair, fastStep, divisorsIn, evalC, evalE, get, hasFinite, interpret, machineTerms, fnValue, modName, n, not, partsOf as tupleOf, plus, same, seeded, times, walk, withArithmetic, x } from "./machine.js";
|
|
43
46
|
import { bool, refuteModelByRuns, verdictOf } from "./dsl.js";
|
|
44
47
|
import { allowed, keysOf, linKey, watch } from "./watch.js";
|
|
45
|
-
import { clock, counted, fullWork, searchWork, decideLaw, decideNote, machineKey, memoHits, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withSearchWork } from "../kernel/prove.js";
|
|
48
|
+
import { BudgetExpired, checkBudget, clock, counted, fullWork, searchWork, decideLaw, decideNote, machineKey, memoHits, withBudget, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withSearchWork } from "../kernel/prove.js";
|
|
46
49
|
import { assumed, eachParts, obligations, plainOf, stepLawObligations, substC, tuple, tupleParts } from "../kernel/kernel.js";
|
|
47
50
|
import { env, gcd, work } from "./solver.js";
|
|
48
51
|
import { bgcd } from "./q.js";
|
|
@@ -1023,19 +1026,84 @@ function comparisons(m, laws, atoms, coords, more = []) {
|
|
|
1023
1026
|
return [...found.values()];
|
|
1024
1027
|
}
|
|
1025
1028
|
export function inferLaws(target, laws, stepLaws = [], opts = {}) {
|
|
1029
|
+
if (opts.work !== undefined && (opts.ms !== undefined || opts.wall !== undefined || opts.timed || opts.runsMs !== undefined))
|
|
1030
|
+
throw new RangeError('choose an explicit work budget or a legacy ms/wall/timed budget, not both');
|
|
1031
|
+
if (typeof opts.work === 'number' && (!Number.isFinite(opts.work) || opts.work < 0))
|
|
1032
|
+
throw new RangeError('work budget must be finite and nonnegative');
|
|
1026
1033
|
// Repeated rounds and minimization can ask the same root goal again. Keep only
|
|
1027
1034
|
// completed trees for this search, keyed by exact hypotheses and prover modes.
|
|
1028
|
-
|
|
1035
|
+
const started = fullWork(), observed = {};
|
|
1036
|
+
let result;
|
|
1037
|
+
const run = () => {
|
|
1038
|
+
const enteredAt = countedSearchNow(), enteredWork = fullWork();
|
|
1039
|
+
observed.snapshot = () => ({ samples: 0, candidates: 0, alive: 0, proofs: 0, ms: Math.round(countedSearchNow() - enteredAt), work: Math.max(0, fullWork() - enteredWork), stopped: true });
|
|
1040
|
+
try {
|
|
1041
|
+
const out = withTrees(() => quietly(() => withDeadline(clock() + (opts.work === undefined ? (opts.wall === undefined ? opts.ms ?? 20000 : Math.max(0, opts.wall - countedSearchNow())) : Infinity), () => inferLawsSearch(target, laws, stepLaws, opts, observed))));
|
|
1042
|
+
// A completed source refusal is terminal, but never proof authority or
|
|
1043
|
+
// metadata to clean up. Preserve its exact object and refusal fields.
|
|
1044
|
+
if (completedSourceRefusal(out))
|
|
1045
|
+
return out;
|
|
1046
|
+
if (completedSearch(out)) {
|
|
1047
|
+
const { termination: _statsTermination, ...stats } = out.stats;
|
|
1048
|
+
const { stopped: _stopped, termination: _termination, context: _context, ...completed } = out;
|
|
1049
|
+
void _statsTermination;
|
|
1050
|
+
void _stopped;
|
|
1051
|
+
void _termination;
|
|
1052
|
+
void _context;
|
|
1053
|
+
return retainFrom({ ...completed, stats: { ...stats, stopped: false } }, [out]);
|
|
1054
|
+
}
|
|
1055
|
+
return out.stats.termination ? stoppedSearch({ ...out, context: observed.context?.() ?? searchContext(out) }, out.stats.termination) : out;
|
|
1056
|
+
}
|
|
1057
|
+
catch (error) {
|
|
1058
|
+
observed.last ??= observed.snapshot?.();
|
|
1059
|
+
observed.lastContext ??= observed.context?.();
|
|
1060
|
+
// A watchdog must not hide a rejected work admission while this work
|
|
1061
|
+
// owner is still active. This check does not admit or execute new work.
|
|
1062
|
+
if (error instanceof WatchdogExpired)
|
|
1063
|
+
checkBudget(error.termination.phase);
|
|
1064
|
+
throw error;
|
|
1065
|
+
}
|
|
1066
|
+
};
|
|
1067
|
+
try {
|
|
1068
|
+
return withSearchWatchdog(opts.watchdogMs, () => result = opts.work === undefined ? run() : withBudget(opts.work, run));
|
|
1069
|
+
}
|
|
1070
|
+
catch (error) {
|
|
1071
|
+
if (error instanceof WatchdogExpired) {
|
|
1072
|
+
checkBudget(error.termination.phase);
|
|
1073
|
+
checkWatchdog(error.termination.phase);
|
|
1074
|
+
}
|
|
1075
|
+
else if (error instanceof BudgetExpired)
|
|
1076
|
+
checkWorkEndpoint(error.phase);
|
|
1077
|
+
else
|
|
1078
|
+
throw error;
|
|
1079
|
+
if (error instanceof WatchdogExpired) {
|
|
1080
|
+
if (completedSearch(result) || result?.stopped && result.termination)
|
|
1081
|
+
return result;
|
|
1082
|
+
// Retained before final statistics/trace polls: those observations may
|
|
1083
|
+
// throw before the outer result assignment ever receives the verdict.
|
|
1084
|
+
if (observed.completed)
|
|
1085
|
+
return observed.completed;
|
|
1086
|
+
}
|
|
1087
|
+
const termination = error instanceof WatchdogExpired ? error.termination : { kind: 'work-exhausted', phase: error.phase, scope: 'search' };
|
|
1088
|
+
return { ...stoppedSearch({ ...result, ...opts.first, proven: false, checked: false, stuck: 'unknown', ...((observed.lastContext ?? observed.context?.()) ? { context: observed.lastContext ?? observed.context?.() } : {}) }, termination), found: [], stats: { ...(observed.last ?? result?.stats ?? { samples: 0, candidates: 0, alive: 0, proofs: 0, ms: 0, work: Math.max(0, fullWork() - started) }), stopped: true, termination } };
|
|
1089
|
+
}
|
|
1029
1090
|
}
|
|
1030
|
-
function inferLawsSearch(target, laws, stepLaws
|
|
1031
|
-
|
|
1091
|
+
function inferLawsSearch(target, laws, stepLaws, opts, observed) {
|
|
1092
|
+
try {
|
|
1093
|
+
return withEvaluationAdmission(() => inferLawsSearchIn(target, laws, stepLaws, opts, observed));
|
|
1094
|
+
}
|
|
1095
|
+
catch (error) {
|
|
1096
|
+
observed.last = observed.snapshot?.();
|
|
1097
|
+
observed.lastContext = observed.context?.();
|
|
1098
|
+
throw error;
|
|
1099
|
+
}
|
|
1032
1100
|
}
|
|
1033
|
-
function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
1101
|
+
function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
|
|
1034
1102
|
checkWorkEndpoint('inference entry');
|
|
1035
1103
|
// (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
|
|
1036
1104
|
if (env.GDP_INFER_TRACE === '2' && !opts.progress)
|
|
1037
1105
|
opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
|
|
1038
|
-
const t0 = countedSearchNow(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms;
|
|
1106
|
+
const t0 = countedSearchNow(), work0 = fullWork(), ms = opts.work === undefined ? opts.ms ?? 20000 : Infinity, wallUntil = opts.work === undefined ? opts.wall ?? t0 + ms : Infinity;
|
|
1039
1107
|
// Divisor declarations are mutable rule metadata. Keep a private copy even
|
|
1040
1108
|
// when withSumsOf would return the original rule: candidate search and returned
|
|
1041
1109
|
// remainder laws must not add arithmetic facts to the caller's next proof.
|
|
@@ -1044,8 +1112,18 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1044
1112
|
const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0, erows: 0, etries: 0 };
|
|
1045
1113
|
const now = () => (timed ? countedSearchNow() - t0
|
|
1046
1114
|
: used.tries / inferRates.tries + used.rows / inferRates.rows + used.evals / inferRates.evals + used.watched / inferRates.watched + (work.n - w0) / inferRates.work);
|
|
1047
|
-
|
|
1048
|
-
|
|
1115
|
+
// searchNow's domain is captured with this endpoint, before nested counted
|
|
1116
|
+
// proof calls can change it. Do not classify a stop from stats.ms or its text.
|
|
1117
|
+
const stopDomain = inWorkScope() ? 'counted' : 'real';
|
|
1118
|
+
let stopped = false, termination;
|
|
1119
|
+
const stop = () => {
|
|
1120
|
+
checkWorkEndpoint('inference poll');
|
|
1121
|
+
if (!stopped && countedSearchNow() > wallUntil) {
|
|
1122
|
+
stopped = true;
|
|
1123
|
+
termination = { kind: stopDomain === 'real' ? 'wall-deadline' : 'work-exhausted', phase: 'inference poll', scope: 'stage' };
|
|
1124
|
+
}
|
|
1125
|
+
return stopped;
|
|
1126
|
+
};
|
|
1049
1127
|
// The engine's clock (the stage below, from the small instance on): counted as `now` is, with the EPR path's work
|
|
1050
1128
|
// (kernel/epr.ts's eprMeter) and the views' rows beside it, so that every choice it makes by its budget (a BFS cut, the
|
|
1051
1129
|
// filter, a goal's cap, a round's growth) is the same on any machine; the wall (`stop`, `until` past `ms`) only ends it.
|
|
@@ -1074,6 +1152,10 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1074
1152
|
}
|
|
1075
1153
|
const m = rule ? rule.machine : target;
|
|
1076
1154
|
let proofs = 0;
|
|
1155
|
+
let sampleCount = () => 0, candidateCount = () => 0, aliveCount = () => 0;
|
|
1156
|
+
// Read actual partial counters while their owning clock scope is still live.
|
|
1157
|
+
// Before an array exists its observed population is genuinely zero.
|
|
1158
|
+
observed.snapshot = () => ({ samples: sampleCount(), candidates: candidateCount(), alive: aliveCount(), proofs, ms: Math.round(countedSearchNow() - t0), work: Math.max(0, fullWork() - work0), stopped: true });
|
|
1077
1159
|
// The rule (or machine) the kernel proves the candidates with: once a remainder is among them, one that declares
|
|
1078
1160
|
// div$k and mod$k for its divisors (all declarations stay on the private rule copy).
|
|
1079
1161
|
// Only the laws proven read: a search none of whose chosen candidates is a remainder proves with the rule as it is.
|
|
@@ -1100,16 +1182,33 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1100
1182
|
const model = normalized?.machine ?? mm;
|
|
1101
1183
|
const given = normalized ? [...normalized.kindLaws().filter(k => !ls.some(l => l.name === k.name)), ...ls] : ls;
|
|
1102
1184
|
const out = stepLaws.length ? proveStepLaws(model, given, stepLaws) : (fast ? proveSetFast : proveLaws)(model, given);
|
|
1103
|
-
|
|
1185
|
+
const verdict = verdictOf(out);
|
|
1186
|
+
// Engine callbacks can observe a completed whole family before enumProof
|
|
1187
|
+
// or last receives it. Retain only a proof of EVERY caller law, with the
|
|
1188
|
+
// exact additional laws it used; a proved candidate alone is not success.
|
|
1189
|
+
if (verdict.proven && verdict.checked && laws.every(law => ls.includes(law)))
|
|
1190
|
+
observed.completed = retainFrom({ ...verdict, found: ls.filter(law => !laws.includes(law)).map(law => ({ law, text: law.name })), stats: completedStats(sampleCount(), candidateCount(), aliveCount()) }, [verdict], { kind: 'inference', original: m, laws });
|
|
1191
|
+
return verdict;
|
|
1192
|
+
};
|
|
1193
|
+
const completedStats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(countedSearchNow() - t0), work: Math.max(0, fullWork() - work0), stopped: false });
|
|
1194
|
+
const stats = (samples, candidates, alive) => {
|
|
1195
|
+
stop();
|
|
1196
|
+
// This is the actual local search-budget predicate, not reported elapsed
|
|
1197
|
+
// time. wall:Infinity disables only the separate scheduling stop.
|
|
1198
|
+
if (!termination && now() >= until)
|
|
1199
|
+
termination = { kind: timed && stopDomain === 'real' ? 'wall-deadline' : 'work-exhausted', phase: 'inference allowance', scope: 'stage' };
|
|
1200
|
+
return { samples, candidates, alive, proofs, ms: Math.round(countedSearchNow() - t0), work: Math.max(0, fullWork() - work0), stopped: stopped || termination !== undefined, ...(termination ? { termination } : {}) };
|
|
1104
1201
|
};
|
|
1105
|
-
const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(countedSearchNow() - t0), stopped: stop() });
|
|
1106
1202
|
// The old public prover's first pass also sampled reachable counterexamples.
|
|
1107
1203
|
// Keep that negative model evidence without invoking a source finalizer.
|
|
1108
1204
|
const refuted = !opts.first && !opts.cubes && rule ? refuteModelByRuns(rule, laws, stepLaws) : undefined;
|
|
1109
1205
|
const first = opts.first ?? (refuted?.run ? { proven: false, checked: false, stuck: 'sat', ...refuted }
|
|
1110
1206
|
: opts.cubes ? { proven: false, checked: false } : prove(laws));
|
|
1111
|
-
|
|
1112
|
-
|
|
1207
|
+
observed.context = () => searchContext(first);
|
|
1208
|
+
if ((first.proven && first.checked) || first.run) {
|
|
1209
|
+
const completed = observed.completed = retainFrom({ ...first, found: [], stats: completedStats(0, 0, 0) }, [first]);
|
|
1210
|
+
return retainFrom({ ...completed, stats: stats(0, 0, 0) }, [completed]);
|
|
1211
|
+
}
|
|
1113
1212
|
// --- runs ------------------------------------------------------------------------------------------------------------
|
|
1114
1213
|
const run = interpret(m), stepSample = sampleStep(m, run), rand = seeded(17), kinds = rule ? rule.kindsOfState() : [];
|
|
1115
1214
|
const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
|
|
@@ -1118,6 +1217,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1118
1217
|
: { ...Object.fromEntries(m.inputs.map(i => [i, r(bound + 1)])), ...Object.fromEntries((m.inputMaps ?? []).map(i => [i, new Map()])) });
|
|
1119
1218
|
// (each state once: a machine with no requests walks one path, and its copies pushed out the caller's states (opts.seen))
|
|
1120
1219
|
const samples = [], cap = 3000, keys = [], held = new Set();
|
|
1220
|
+
sampleCount = () => samples.length;
|
|
1121
1221
|
const mapsText = (st) => JSON.stringify(Object.values(st.maps).map(c => [...c]));
|
|
1122
1222
|
let offered = 0;
|
|
1123
1223
|
// (how many states offered held each value of each state variable: `rare`, below)
|
|
@@ -1418,6 +1518,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1418
1518
|
}
|
|
1419
1519
|
const sizeOf = (coef) => coef.length * 100 + coef.reduce((s, [, c]) => s + Math.abs(c), 0);
|
|
1420
1520
|
const forms = [];
|
|
1521
|
+
candidateCount = () => forms.length;
|
|
1421
1522
|
const NS = rowsS.length, NK = rowsK.length;
|
|
1422
1523
|
const at = (coef, vals, j) => { observeCubeTest(); let s = 0; for (const [i, c] of coef)
|
|
1423
1524
|
s += c * vals[i][j]; return s; };
|
|
@@ -1894,6 +1995,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1894
1995
|
tupleMaps.add(String(o.map)); });
|
|
1895
1996
|
const plainKeyed = (f) => f.view !== undefined || !atomsIn(f).some(i => atoms[i].cell && tupleMaps.has(atoms[i].parts[0][0]));
|
|
1896
1997
|
let alive = forms.filter(plainKeyed).sort((p, q) => p.size - q.size).slice(0, maxCandidates);
|
|
1998
|
+
aliveCount = () => alive.length;
|
|
1897
1999
|
const ctis = [];
|
|
1898
2000
|
// (a law about keys is evaluated at every tuple of the state's keys, as watch does: counted as that many evaluations)
|
|
1899
2001
|
const lawful = (params, st) => {
|
|
@@ -1979,6 +2081,8 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1979
2081
|
let enumSome = [];
|
|
1980
2082
|
const goalName = (g) => g.replace(/ @[^@]*$/, '');
|
|
1981
2083
|
let last = first;
|
|
2084
|
+
// Keep the original first verdict immutable; later candidate failures must
|
|
2085
|
+
// not replace its SAT/goal/witness provenance.
|
|
1982
2086
|
const slow = Math.max(3000, ms / 10);
|
|
1983
2087
|
// A point a form is false at; a cell form is judged only at rows that read every map it reads.
|
|
1984
2088
|
const reads = (f, r) => f.coef.every(([i]) => !atoms[i].cell || atoms[i].parts.every(([q]) => AT + q in r));
|
|
@@ -5247,12 +5351,20 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
5247
5351
|
};
|
|
5248
5352
|
// A cell form's mirror, −Σ ≤ −d beside Σ ≤ d under the same guard (its text).
|
|
5249
5353
|
const mirrorText = (f) => (!f.cells || f.mod || f.cong || f.never || f.nevers || f.cube || f.unreachable || f.also || !f.coef.length ? undefined : textOf({ ...f, coef: f.coef.map(([i, c]) => [i, -c]), d: -f.d }));
|
|
5250
|
-
|
|
5354
|
+
// Keep the checked family and its exact supports/custody before any local
|
|
5355
|
+
// progress, minimization, trace or statistics observation can stop us. A
|
|
5356
|
+
// later actual work refusal still propagates; this is not budget authority.
|
|
5357
|
+
const captureCompleted = () => observed.completed = retainFrom({ ...last, found: [...chosen.map(f => { const law = lawFor(f), text = law.name, source = sourceOf(f, text); return { law, text, ...(source ? { source } : {}) }; }), ...(enumProof ? enumSome : []).map(law => ({ law, text: law.name }))], stats: completedStats(samples.length, forms.length, alive.length) }, [last], { kind: 'inference', original: m, laws });
|
|
5358
|
+
if (enumProof) {
|
|
5251
5359
|
last = enumProof;
|
|
5360
|
+
captureCompleted();
|
|
5361
|
+
}
|
|
5252
5362
|
for (let iter = 0; iter < 300 && !enumProof && now() < until && !stop(); iter++) {
|
|
5253
5363
|
const began = now(), wall = countedSearchNow();
|
|
5254
5364
|
// (each law proven alone, then the set as a whole: the same goals, grown once)
|
|
5255
5365
|
last = withTrees(() => search([...given, ...chosen.map(lawFor)]));
|
|
5366
|
+
if (last.proven && last.checked)
|
|
5367
|
+
captureCompleted();
|
|
5256
5368
|
const took = now() - began;
|
|
5257
5369
|
opts.progress?.('proof', { chosen: chosen.length, goal: last.goal ?? '', stuck: last.stuck ?? '', ms: Math.round(countedSearchNow() - wall), counted: Math.round(took) });
|
|
5258
5370
|
if (last.proven && last.checked)
|
|
@@ -5321,6 +5433,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
5321
5433
|
if (v.proven && v.checked) {
|
|
5322
5434
|
chosen = [f];
|
|
5323
5435
|
last = v;
|
|
5436
|
+
captureCompleted();
|
|
5324
5437
|
break;
|
|
5325
5438
|
}
|
|
5326
5439
|
}
|
|
@@ -5335,12 +5448,16 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
5335
5448
|
if (now() > until || stop())
|
|
5336
5449
|
break;
|
|
5337
5450
|
const without = chosen.filter(g => g !== f), v = prove([...laws, ...without.map(lawFor)]);
|
|
5338
|
-
if (v.proven && v.checked)
|
|
5339
|
-
|
|
5451
|
+
if (v.proven && v.checked) {
|
|
5452
|
+
chosen = without;
|
|
5453
|
+
last = v;
|
|
5454
|
+
captureCompleted();
|
|
5455
|
+
}
|
|
5340
5456
|
}
|
|
5341
5457
|
const kept = chosen.flatMap(f => (f.mod ? [f.mod.k] : []));
|
|
5342
5458
|
if (kept.length)
|
|
5343
5459
|
rule?.dividesBy(...kept);
|
|
5460
|
+
const completed = captureCompleted();
|
|
5344
5461
|
trace('end', { proven: true, stopped: stop(), found: chosen.map(f => textOf(f)).join('; ') });
|
|
5345
|
-
return retainFrom({ ...
|
|
5462
|
+
return retainFrom({ ...completed, stats: stats(samples.length, forms.length, alive.length) }, [completed]);
|
|
5346
5463
|
}
|
|
@@ -87,13 +87,14 @@ public final class Harness {
|
|
|
87
87
|
for (int i = 0; i < urls.length; i++) urls[i] = cp.get(i).toURI().toURL();
|
|
88
88
|
loader = new URLClassLoader(urls, Harness.class.getClassLoader());
|
|
89
89
|
cls = Class.forName((String) req.get("jcls"), false, loader);
|
|
90
|
-
return m("ok", true);
|
|
90
|
+
return m("ok", true, "nativeBindings", 1, "nativeSnapshot", 1, "nativeObservations", 1);
|
|
91
91
|
}
|
|
92
92
|
case "new": try { return m("id", make((List<?>) req.get("a"))); } catch (Throwable e) { return m("err", err(e)); }
|
|
93
93
|
case "at":
|
|
94
94
|
try { long i = make((List<?>) req.get("a")); setState(OBJS.get(i), (Map<?, ?>) req.get("state")); return m("id", i); }
|
|
95
95
|
catch (Throwable e) { return m("bad", err(e)); }
|
|
96
96
|
case "get": { long id = ((Number) req.get("id")).longValue(); ST = STORES.get(id); return m("state", stateOf(OBJS.get(id))); }
|
|
97
|
+
case "native": return m("snapshot", nativeState(OBJS.get(((Number) req.get("id")).longValue())));
|
|
97
98
|
case "call": return call(req);
|
|
98
99
|
case "coverage": return m("hit", List.of());
|
|
99
100
|
default: return m("error", "no op " + op);
|
|
@@ -336,6 +337,129 @@ public final class Harness {
|
|
|
336
337
|
STORES.put(id, ST);
|
|
337
338
|
return id;
|
|
338
339
|
}
|
|
340
|
+
// Scalar arguments observed after JVM conversion and before invocation. Names
|
|
341
|
+
// come from the callable's bytecode, never from the symbolic request schema.
|
|
342
|
+
// Unsupported values or classes without parameter metadata remain unchecked.
|
|
343
|
+
static long nativeIdentity = 0;
|
|
344
|
+
static final IdentityHashMap<Object, String> nativeObjects = new IdentityHashMap<>();
|
|
345
|
+
static String nativeId(Object value) {
|
|
346
|
+
String id = nativeObjects.get(value);
|
|
347
|
+
if (id == null) {
|
|
348
|
+
if (nativeObjects.size() >= 100000) throw new IllegalArgumentException("native snapshot exceeds identity bound");
|
|
349
|
+
id = Long.toString(++nativeIdentity); nativeObjects.put(value, id);
|
|
350
|
+
}
|
|
351
|
+
return id;
|
|
352
|
+
}
|
|
353
|
+
static Object nativeValue(Object value, Set<Object> seen, int[] nodes, boolean root) throws Exception {
|
|
354
|
+
if (++nodes[0] > 10000) throw new IllegalArgumentException("native snapshot exceeds node bound");
|
|
355
|
+
if (value == null || value instanceof Boolean || value instanceof String) return value;
|
|
356
|
+
if (value instanceof Character c) return (int) c.charValue();
|
|
357
|
+
if (value instanceof Enum<?> e) return e.name();
|
|
358
|
+
if (value instanceof AtomicInteger a) return a.get();
|
|
359
|
+
if (value instanceof AtomicLong a) return nativeValue(a.get(), seen, nodes, false);
|
|
360
|
+
if (value instanceof AtomicBoolean a) return a.get();
|
|
361
|
+
if (value instanceof AtomicReference<?> a) return nativeValue(a.get(), seen, nodes, false);
|
|
362
|
+
if (value instanceof Optional<?> o) return nativeValue(o.orElse(null), seen, nodes, false);
|
|
363
|
+
if (value instanceof Number n) {
|
|
364
|
+
if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double))
|
|
365
|
+
throw new IllegalArgumentException("unsupported native snapshot number: " + value.getClass().getName());
|
|
366
|
+
double number = n.doubleValue();
|
|
367
|
+
if (!Double.isFinite(number) || Math.rint(number) != number || Math.abs(number) > 9007199254740991d)
|
|
368
|
+
throw new IllegalArgumentException("native snapshot number outside exact integer range");
|
|
369
|
+
return n.longValue();
|
|
370
|
+
}
|
|
371
|
+
String id = nativeId(value);
|
|
372
|
+
if (!seen.add(value)) return m("kind", "ref", "id", id);
|
|
373
|
+
List<Object> entries = new ArrayList<>();
|
|
374
|
+
String kind = "object";
|
|
375
|
+
if (value instanceof Map<?, ?> map) {
|
|
376
|
+
if (value.getClass().getClassLoader() != null) throw new IllegalArgumentException("unsupported native snapshot map implementation");
|
|
377
|
+
kind = "map";
|
|
378
|
+
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
|
379
|
+
Object key = entry.getKey();
|
|
380
|
+
if (!(key instanceof String) && !(key instanceof Number)) throw new IllegalArgumentException("unsupported native snapshot map key");
|
|
381
|
+
entries.add(Arrays.asList(nativeValue(key, seen, nodes, false), nativeValue(entry.getValue(), seen, nodes, false)));
|
|
382
|
+
}
|
|
383
|
+
} else if (value instanceof List<?> list) {
|
|
384
|
+
if (value.getClass().getClassLoader() != null) throw new IllegalArgumentException("unsupported native snapshot list implementation");
|
|
385
|
+
kind = "array";
|
|
386
|
+
for (Object item : list) entries.add(nativeValue(item, seen, nodes, false));
|
|
387
|
+
} else if (value.getClass().isArray()) {
|
|
388
|
+
kind = "array";
|
|
389
|
+
for (int i = 0; i < Array.getLength(value); i++) entries.add(nativeValue(Array.get(value, i), seen, nodes, false));
|
|
390
|
+
} else {
|
|
391
|
+
Set<String> names = new LinkedHashSet<>();
|
|
392
|
+
if (root) {
|
|
393
|
+
for (Object leaf0 : list(S.get("leaves"))) {
|
|
394
|
+
Map<?, ?> leaf = (Map<?, ?>) leaf0;
|
|
395
|
+
List<?> path = list(leaf.get("path"));
|
|
396
|
+
if (!path.isEmpty() && !"frame".equals(leaf.get("kind"))) names.add((String) path.get(0));
|
|
397
|
+
}
|
|
398
|
+
} else {
|
|
399
|
+
if (value.getClass().getName().startsWith("java.")) throw new IllegalArgumentException("unsupported native snapshot value: " + value.getClass().getName());
|
|
400
|
+
for (Class<?> c = value.getClass(); c != null && c != Object.class; c = c.getSuperclass())
|
|
401
|
+
for (Field f : c.getDeclaredFields()) if (!Modifier.isStatic(f.getModifiers()) && !f.isSynthetic()) names.add(f.getName());
|
|
402
|
+
}
|
|
403
|
+
for (String name : names) entries.add(Arrays.asList(name, nativeValue(field(value.getClass(), name).get(value), seen, nodes, false)));
|
|
404
|
+
}
|
|
405
|
+
return m("kind", kind, "id", id, "items", entries);
|
|
406
|
+
}
|
|
407
|
+
static Object nativeState(Object value) throws Exception {
|
|
408
|
+
return m("version", 1, "root", nativeValue(value, Collections.newSetFromMap(new IdentityHashMap<>()), new int[]{0}, true));
|
|
409
|
+
}
|
|
410
|
+
static Object nativeBindings(Method method, Object[] args) {
|
|
411
|
+
Parameter[] parameters = method.getParameters();
|
|
412
|
+
if (parameters.length != args.length) throw new IllegalArgumentException("native parameter arity unavailable");
|
|
413
|
+
List<Object> entries = new ArrayList<>();
|
|
414
|
+
for (int i = 0; i < parameters.length; i++) {
|
|
415
|
+
Parameter parameter = parameters[i];
|
|
416
|
+
if (!parameter.isNamePresent()) throw new IllegalArgumentException("native parameter name unavailable: " + method.getName());
|
|
417
|
+
Object value = args[i];
|
|
418
|
+
if (value instanceof Character c) value = (int) c.charValue();
|
|
419
|
+
else if (value instanceof Enum<?> e) value = e.name();
|
|
420
|
+
else if (value instanceof Number n) {
|
|
421
|
+
if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double))
|
|
422
|
+
throw new IllegalArgumentException("unsupported native parameter number: " + parameter.getName());
|
|
423
|
+
double number = n.doubleValue();
|
|
424
|
+
if (!Double.isFinite(number) || Math.rint(number) != number || Math.abs(number) > 9007199254740991d)
|
|
425
|
+
throw new IllegalArgumentException("native parameter number outside exact integer range: " + parameter.getName());
|
|
426
|
+
value = n.longValue();
|
|
427
|
+
} else if (value != null && !(value instanceof String) && !(value instanceof Boolean))
|
|
428
|
+
throw new IllegalArgumentException("unsupported native parameter value: " + parameter.getName());
|
|
429
|
+
entries.add(Arrays.asList(parameter.getName(), value));
|
|
430
|
+
}
|
|
431
|
+
return m("version", 1, "root", m("kind", "object", "id", Long.toString(++nativeIdentity), "items", entries));
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Metadata objects are transport records, not native source maps. Actual
|
|
435
|
+
// answer values were captured and range-checked by Rt at the read occurrence.
|
|
436
|
+
static Object observationObject(Map<String, Object> fields) throws Exception {
|
|
437
|
+
List<Object> entries = new ArrayList<>();
|
|
438
|
+
for (Map.Entry<String, Object> entry : fields.entrySet()) {
|
|
439
|
+
Object value = entry.getValue();
|
|
440
|
+
if (value instanceof Map<?, ?> map) {
|
|
441
|
+
Map<String, Object> nested = new LinkedHashMap<>();
|
|
442
|
+
for (Map.Entry<?, ?> item : map.entrySet()) nested.put((String) item.getKey(), item.getValue());
|
|
443
|
+
value = observationObject(nested);
|
|
444
|
+
} else value = nativeValue(value, Collections.newSetFromMap(new IdentityHashMap<>()), new int[]{0}, false);
|
|
445
|
+
entries.add(Arrays.asList(entry.getKey(), value));
|
|
446
|
+
}
|
|
447
|
+
return m("kind", "object", "id", Long.toString(++nativeIdentity), "items", entries);
|
|
448
|
+
}
|
|
449
|
+
static Map<String, Object> nativeObservations(gdp.Rt.Observations observed) {
|
|
450
|
+
if (observed.error != null) return m("error", observed.error);
|
|
451
|
+
try {
|
|
452
|
+
Map<String, Object> calls = new LinkedHashMap<>();
|
|
453
|
+
for (Map.Entry<String, gdp.Rt.Call> entry : observed.calls.entrySet()) {
|
|
454
|
+
gdp.Rt.Call call = entry.getValue();
|
|
455
|
+
calls.put(entry.getKey(), call.kind.equals("returned") ? m("kind", "returned", "value", call.value) : m("kind", "raised", "raised", call.raised));
|
|
456
|
+
}
|
|
457
|
+
Map<String, Object> fields = m("invocation", observed.invocation, "calls", calls);
|
|
458
|
+
if (observed.clock != null) fields.put("clock", observed.clock);
|
|
459
|
+
return m("snapshot", m("version", 1, "root", observationObject(fields)));
|
|
460
|
+
} catch (Exception error) { return m("error", err(error)); }
|
|
461
|
+
}
|
|
462
|
+
|
|
339
463
|
static Object call(Map<?, ?> req) throws Exception {
|
|
340
464
|
long id = ((Number) req.get("id")).longValue();
|
|
341
465
|
Object obj = OBJS.get(id);
|
|
@@ -351,17 +475,25 @@ public final class Harness {
|
|
|
351
475
|
Object[] a = new Object[ts.length];
|
|
352
476
|
try { for (int i = 0; i < ts.length; i++) a[i] = i < specs.size() ? build(((List<?>) specs.get(i)).get(1), ts[i], gs[i]) : inert(ts[i]); }
|
|
353
477
|
catch (Exception e) { return m("bad", err(e)); }
|
|
478
|
+
Map<String, Object> bindings;
|
|
479
|
+
try { bindings = m("snapshot", nativeBindings(m, a)); }
|
|
480
|
+
catch (Exception e) { bindings = m("error", err(e)); }
|
|
354
481
|
Map<String, String> before = frames(obj);
|
|
355
482
|
Map<String, Object> snap = Boolean.TRUE.equals(S.get("discard")) ? stateOf(obj) : null;
|
|
356
483
|
Object out = null;
|
|
357
484
|
String err = null;
|
|
358
|
-
|
|
485
|
+
Set<String> observedKeys = new HashSet<>();
|
|
486
|
+
for (Object answer : list(S.get("answers"))) observedKeys.add((String) ((Map<?, ?>) answer).get("key"));
|
|
487
|
+
gdp.Rt.Observations observed = gdp.Rt.beginObservations(observedKeys);
|
|
488
|
+
try { out = m.invoke(Modifier.isStatic(m.getModifiers()) ? null : obj, a); }
|
|
489
|
+
catch (InvocationTargetException e) { err = err(e); }
|
|
490
|
+
finally { gdp.Rt.endObservations(observed); }
|
|
359
491
|
if (err != null && snap != null) setState(obj, snap);
|
|
360
492
|
// A method returning the object's next value (an immutable class's step): the object is that value.
|
|
361
493
|
if (err == null && ((List<?>) S.get("reducers")).contains(key) && cls.isInstance(out)) { OBJS.put(id, out); obj = out; out = null; }
|
|
362
494
|
Map<String, String> after = frames(obj);
|
|
363
495
|
for (Map.Entry<String, String> e : before.entrySet()) if (!e.getValue().equals(after.get(e.getKey())) && !((List<?>) S.get("reducers")).contains(key)) return m("frame", e.getKey());
|
|
364
|
-
Map<String, Object> res = m("out", tag(out));
|
|
496
|
+
Map<String, Object> res = m("out", tag(out), "nativeBindings", bindings, "nativeObservations", nativeObservations(observed));
|
|
365
497
|
if (err != null) res.put("err", err);
|
|
366
498
|
return res;
|
|
367
499
|
}
|
package/dist/core/jvm/Rt.java
CHANGED
|
@@ -1,10 +1,72 @@
|
|
|
1
|
-
//
|
|
2
|
-
// (core/extract-jvm.ts rewrites those sites): the request's time and the request's answer, set by core/jvm/Harness.java.
|
|
1
|
+
// Runtime hooks used only by the check's instrumented copy of original code.
|
|
3
2
|
package gdp;
|
|
4
3
|
|
|
4
|
+
import java.util.*;
|
|
5
|
+
import java.util.concurrent.atomic.AtomicLong;
|
|
6
|
+
|
|
5
7
|
public final class Rt {
|
|
6
8
|
public static volatile long NOW;
|
|
7
9
|
public static java.util.function.BiFunction<String, Class<?>, Object> ANSWER = (k, c) -> null;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
private static final AtomicLong NEXT = new AtomicLong();
|
|
11
|
+
private static final ThreadLocal<Observations> ACTIVE = new ThreadLocal<>();
|
|
12
|
+
public static final class Call {
|
|
13
|
+
public final String kind, raised;
|
|
14
|
+
public final Object value;
|
|
15
|
+
private Call(String kind, Object value, String raised) { this.kind = kind; this.value = value; this.raised = raised; }
|
|
16
|
+
}
|
|
17
|
+
public static final class Observations {
|
|
18
|
+
public final long invocation;
|
|
19
|
+
public final Map<String, Call> calls = new LinkedHashMap<>();
|
|
20
|
+
public Long clock;
|
|
21
|
+
public String error;
|
|
22
|
+
private final Set<String> expected;
|
|
23
|
+
private Observations(Set<String> expected) { this.invocation = NEXT.incrementAndGet(); this.expected = Set.copyOf(expected); }
|
|
24
|
+
private void fail(String message) { if (error == null) error = message; }
|
|
25
|
+
}
|
|
26
|
+
public static Observations beginObservations(Set<String> expected) {
|
|
27
|
+
if (ACTIVE.get() != null) throw new IllegalStateException("nested native observation invocation");
|
|
28
|
+
Observations value = new Observations(expected); ACTIVE.set(value); return value;
|
|
29
|
+
}
|
|
30
|
+
public static void endObservations(Observations value) {
|
|
31
|
+
if (ACTIVE.get() != value) throw new IllegalStateException("native observation invocation changed");
|
|
32
|
+
ACTIVE.remove();
|
|
33
|
+
}
|
|
34
|
+
private static boolean scalar(Object value) {
|
|
35
|
+
if (value == null || value instanceof Boolean || value instanceof String || value instanceof Character || value instanceof Enum<?>) return true;
|
|
36
|
+
if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double)) return false;
|
|
37
|
+
if (value instanceof Double d && Double.doubleToRawLongBits(d) == Long.MIN_VALUE || value instanceof Float f && Float.floatToRawIntBits(f) == Integer.MIN_VALUE) return false;
|
|
38
|
+
double n = ((Number) value).doubleValue();
|
|
39
|
+
return Double.isFinite(n) && Math.rint(n) == n && Math.abs(n) <= 9007199254740991d;
|
|
40
|
+
}
|
|
41
|
+
private static void record(String key, Call call) {
|
|
42
|
+
Observations observations = ACTIVE.get();
|
|
43
|
+
if (observations == null) return;
|
|
44
|
+
if (!observations.expected.contains(key)) { observations.fail("unbound instrumented answer: " + key); return; }
|
|
45
|
+
if (call.kind.equals("returned") && !scalar(call.value)) { observations.fail("unsupported actual answer value: " + key); return; }
|
|
46
|
+
Call previous = observations.calls.get(key);
|
|
47
|
+
if (previous != null && (!previous.kind.equals(call.kind) || !Objects.equals(previous.value, call.value) || !Objects.equals(previous.raised, call.raised))) {
|
|
48
|
+
observations.fail("different actual answers in one invocation: " + key); return;
|
|
49
|
+
}
|
|
50
|
+
observations.calls.put(key, call);
|
|
51
|
+
}
|
|
52
|
+
public static long now() {
|
|
53
|
+
long value = NOW;
|
|
54
|
+
Observations observations = ACTIVE.get();
|
|
55
|
+
if (observations != null) {
|
|
56
|
+
if (value < -9007199254740991L || value > 9007199254740991L) observations.fail("actual clock outside exact integer range");
|
|
57
|
+
if (observations.clock != null && observations.clock.longValue() != value) observations.fail("different actual clock reads in one invocation");
|
|
58
|
+
else observations.clock = value;
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
public static Object answer(String key, Class<?> c) {
|
|
63
|
+
try {
|
|
64
|
+
Object value = ANSWER.apply(key, c);
|
|
65
|
+
record(key, new Call("returned", value, null));
|
|
66
|
+
return value;
|
|
67
|
+
} catch (RuntimeException | Error error) {
|
|
68
|
+
record(key, new Call("raised", null, error.getClass().getName()));
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
10
72
|
}
|
package/dist/core/laws.js
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
// every item of a list (o.price its field; `o in asks` whether that item is still
|
|
28
28
|
// in it, the same item, not an equal one), at every two (or three) at once
|
|
29
29
|
// mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
|
|
30
|
-
import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
|
|
30
|
+
import { Choice, Int, ItemsRef, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
|
|
31
31
|
import { copyVariable } from "./dsl-binders.js";
|
|
32
32
|
import { attachNativeLaw } from "./source-check.js";
|
|
33
33
|
import { nativeLaw } from "./native-law.js";
|
|
@@ -256,8 +256,22 @@ export function parse(s) {
|
|
|
256
256
|
// The extraction's names, with the request's time as `now` where the rule reads it and no name says so (a TypeScript
|
|
257
257
|
// class's Date.now()).
|
|
258
258
|
export function namesWithClock(x) {
|
|
259
|
-
|
|
260
|
-
|
|
259
|
+
// Result names from the model are the actual lowered variables; source method
|
|
260
|
+
// spelling is not necessarily a valid rule identifier (for example Ruby `seen?`).
|
|
261
|
+
const original = x.names ?? [];
|
|
262
|
+
const ns = original.map(n => {
|
|
263
|
+
if (n.role !== 'result' || n.code !== 'result' || !n.method)
|
|
264
|
+
return n;
|
|
265
|
+
const result = x.model?.results?.[n.method];
|
|
266
|
+
if (!result)
|
|
267
|
+
return n;
|
|
268
|
+
const value = result.k === 'rec' ? result.fields.find(([field]) => field === 'value')?.[1] : result.name;
|
|
269
|
+
const none = result.k === 'rec' ? result.fields.find(([field]) => field === 'none')?.[1] : result.k === 'maybe' ? result.missing : undefined;
|
|
270
|
+
return value && (value !== n.rule || (n.none && none && n.none !== none)) ? { ...n, rule: value, ...(n.none && none ? { none } : {}) } : n;
|
|
271
|
+
});
|
|
272
|
+
const ins = x.rule?.parts?.inputs.map(([n]) => n) ?? [];
|
|
273
|
+
const named = ns.every((n, i) => n === original[i]) ? original : ns;
|
|
274
|
+
return named.some(n => n.role === 'clock') || !ins.includes('now') || named.some(n => n.code === 'now') ? named : [...named, { code: 'now', rule: 'now', role: 'clock', native: { kind: 'clock', key: 'now' } }];
|
|
261
275
|
}
|
|
262
276
|
const calendarOf = (opts) => {
|
|
263
277
|
if (!opts.calendar)
|
|
@@ -309,7 +323,7 @@ export function buildLaw(x, l, opts = {}) {
|
|
|
309
323
|
};
|
|
310
324
|
// (a law of one step reads no function, so business days there pin each time's week to a key, ∀w. guard → law)
|
|
311
325
|
const body = (b, a) => (step && probe.roles.has('bdays') ? pinned(b, a, (bb, aa, p) => body0(bb, aa, p)) : bitBody(b, a));
|
|
312
|
-
const bind = (built) => { attachNativeLaw(x.rule, built.law, l.name, built.kind === 'step' ? gate ?? method : undefined, nativeLaw(e, opts, parse, { ...Object.fromEntries(names.filter(n => n.role === 'const' && n.value !== undefined).map(n => [n.code, n.value])), ...x.consts }, new Set(names.map(n => n.code.split('.')[0])))); return built; };
|
|
326
|
+
const bind = (built) => { attachNativeLaw(x.rule, built.law, l.name, built.kind === 'step' ? gate ?? method : undefined, nativeLaw(e, opts, parse, { ...Object.fromEntries(names.filter(n => n.role === 'const' && n.value !== undefined).map(n => [n.code, n.value])), ...x.consts }, new Set(names.map(n => n.code.split('.')[0])), names.flatMap(n => n.native ? [{ ...n.native, code: n.code, ...(n.method ? { method: n.method } : {}) }] : []), names)); return built; };
|
|
313
327
|
if (!step)
|
|
314
328
|
return bind({ kind: 'law', law: r.law(l.name, (env) => (x.quiet ? env[x.quiet].eq(0).implies(body0(env, env)) : body0(env, env))) });
|
|
315
329
|
const mname = names.find(n => n.role === 'method')?.rule;
|
|
@@ -622,7 +636,7 @@ const constOf = (x) => (x.k === 'num' ? x.v : x.k === 'un' && x.op === '-' && x.
|
|
|
622
636
|
function compare(op, a, b, e, strictOptional) {
|
|
623
637
|
if (b.t === 'null' || a.t === 'null') {
|
|
624
638
|
const literal = a.t === 'null' ? a : b;
|
|
625
|
-
const o = a.t === 'null' ? b : a, none = o.t === 'opt' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
|
|
639
|
+
const o = a.t === 'null' ? b : a, none = o.t === 'opt' || o.t === 'map' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
|
|
626
640
|
if (strictOptional && o.t === 'opt' && literal.absence && o.absence && literal.absence !== o.absence)
|
|
627
641
|
return op === '==' ? no : op === '!=' ? yes : fail(`${op} with None`);
|
|
628
642
|
if (!none)
|
|
@@ -760,7 +774,7 @@ function path(e, c, names, dry) {
|
|
|
760
774
|
}
|
|
761
775
|
const segs = e.segs.slice(skip + n - 1 + (hit.role === 'answer' && next && 'call' in next ? 1 : 0));
|
|
762
776
|
// (a map read where it is named: old(m) is the map before the step wherever its cells are read, `k in old(m)`)
|
|
763
|
-
return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code), env: c.a } : leaf(hit, c, dry), c, names, dry, e);
|
|
777
|
+
return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code), env: c.a, ...(hit.none ? { none: dry ? yes : c.a[hit.none] } : {}) } : leaf(hit, c, dry), c, names, dry, e);
|
|
764
778
|
}
|
|
765
779
|
}
|
|
766
780
|
}
|
|
@@ -801,10 +815,21 @@ function find(code, names, c, stateOnly, called) {
|
|
|
801
815
|
return inputs[0];
|
|
802
816
|
throw new LawError(`${code} is an argument of ${inputs.map(n => n.method).join(', ')}: write the law on the method it is about (the line above it), or as <method>.${code}`);
|
|
803
817
|
}
|
|
804
|
-
|
|
805
|
-
?? (stateOnly ? undefined : names.find(n => (n.role === 'param' || n.role === 'const' || n.role === 'clock') && n.code === code && !called))
|
|
806
|
-
|
|
807
|
-
|
|
818
|
+
const preferred = names.find(n => n.role === 'state' && at(n) && !called)
|
|
819
|
+
?? (stateOnly ? undefined : names.find(n => (n.role === 'param' || n.role === 'const' || n.role === 'clock') && n.code === code && !called));
|
|
820
|
+
if (preferred)
|
|
821
|
+
return preferred;
|
|
822
|
+
const answers = names.filter(n => n.role === 'answer' && last(n));
|
|
823
|
+
const here = c.method ? answers.filter(n => n.method === c.method) : [];
|
|
824
|
+
const generic = answers.filter(n => n.method === undefined);
|
|
825
|
+
const candidates = here.length ? here : generic.length ? generic : c.method ? [] : answers;
|
|
826
|
+
if (candidates.length > 1)
|
|
827
|
+
throw new LawError(`${code}: ambiguous answered call of ${candidates.map(n => n.method ?? n.code).join(', ')}; write the law on its method or use its qualified name`);
|
|
828
|
+
if (candidates.length === 1)
|
|
829
|
+
return candidates[0];
|
|
830
|
+
if (answers.length && c.method)
|
|
831
|
+
throw new LawError(`${code}: no answer belongs to ${c.method} (its methods: ${answers.map(n => n.method).join(', ')})`);
|
|
832
|
+
return stateOnly ? undefined : names.find(n => n.rule === code && !called);
|
|
808
833
|
}
|
|
809
834
|
const results = (names, c) => {
|
|
810
835
|
const rs = names.filter(n => n.role === 'result' && n.code === 'result');
|
|
@@ -815,6 +840,8 @@ const results = (names, c) => {
|
|
|
815
840
|
};
|
|
816
841
|
// A name's value: its variable in the environment (the state after the step where the law is a step's), its None-ness.
|
|
817
842
|
function leaf(n, c, dry) {
|
|
843
|
+
if (n.list)
|
|
844
|
+
return { t: 'list', n, env: c.step && n.role === 'state' ? c.a : c.b };
|
|
818
845
|
if (dry)
|
|
819
846
|
return n.none && !n.rule ? { t: 'opt', none: yes } : n.none ? { t: 'opt', none: yes, v: DRY } : DRY;
|
|
820
847
|
if (n.role === 'const')
|
|
@@ -829,6 +856,20 @@ function leaf(n, c, dry) {
|
|
|
829
856
|
function rest(segs, v, c, names, dry, e) {
|
|
830
857
|
for (let i = 0; i < segs.length; i++) {
|
|
831
858
|
const s = segs[i];
|
|
859
|
+
if (v.t === 'list') {
|
|
860
|
+
if (!('i' in s))
|
|
861
|
+
throw new LawError(`${show(e)}: a scalar list is read at a position (xs[i])`);
|
|
862
|
+
const index = val(s.i, c, names, dry);
|
|
863
|
+
if (dry) {
|
|
864
|
+
v = DRY;
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
const value = v.env[v.n.rule];
|
|
868
|
+
if (!(value instanceof ItemsRef))
|
|
869
|
+
throw new LawError(`${v.n.code}: not a scalar item list in the rule's environment`);
|
|
870
|
+
v = wrap(value.at(key(index)));
|
|
871
|
+
continue;
|
|
872
|
+
}
|
|
832
873
|
if (v.t === 'map') {
|
|
833
874
|
const isGet = 'f' in s && ['get', 'fetch', 'getOrDefault', 'lookup'].includes(s.f) && segs[i + 1] && 'call' in segs[i + 1];
|
|
834
875
|
const isHas = 'f' in s && ['has', 'contains', 'containsKey', 'has_key', 'key?', 'has_key?', 'include?'].includes(s.f);
|