@gettier/cli 0.0.0-stage → 0.1.0-beta.1
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 +180 -2
- package/dist/cli.js +3091 -0
- package/package.json +39 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3091 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { writeFileSync as writeFileSync3, readFileSync as readFileSync4, realpathSync } from "node:fs";
|
|
5
|
+
import path5 from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
// ../core/src/types.ts
|
|
9
|
+
var FALSIFIER_OPERATORS = ["=", "!=", ">", ">=", "<", "<="];
|
|
10
|
+
|
|
11
|
+
// ../core/src/declaration.ts
|
|
12
|
+
function parseFalsifyingObservation(input) {
|
|
13
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) return null;
|
|
14
|
+
const raw = input;
|
|
15
|
+
const key = typeof raw.key === "string" ? raw.key.trim() : "";
|
|
16
|
+
const value = typeof raw.value === "string" ? raw.value.trim() : String(raw.value ?? "").trim();
|
|
17
|
+
const operator = typeof raw.operator === "string" ? raw.operator.trim() : "";
|
|
18
|
+
if (!key || !value) return null;
|
|
19
|
+
if (!FALSIFIER_OPERATORS.includes(operator)) return null;
|
|
20
|
+
const observation = { key, operator, value };
|
|
21
|
+
if (typeof raw.sensor === "string" && raw.sensor.trim()) observation.sensor = raw.sensor.trim();
|
|
22
|
+
return observation;
|
|
23
|
+
}
|
|
24
|
+
var DECLARE_LEMMAS_TOOL = {
|
|
25
|
+
name: "declare_lemmas",
|
|
26
|
+
description: 'Enumerate the factual premises about THIS system, environment, or requirements that your plan depends on. A lemma is load-bearing if the plan fails or becomes wrong when the lemma is false. Declare what could differ HERE: versions, configuration, which host or database is connected, the shape of the actual data, what an installed dependency actually exports, how many processes serve a route. Do NOT declare facts that hold for the language or library everywhere \u2014 "Express middleware receives (req, res, next)" is documentation, not a premise about this deployment, and listing it buries the premises that can actually be wrong.',
|
|
27
|
+
input_schema: {
|
|
28
|
+
type: "object",
|
|
29
|
+
required: ["plan_summary", "lemmas"],
|
|
30
|
+
properties: {
|
|
31
|
+
plan_summary: { type: "string", maxLength: 500 },
|
|
32
|
+
lemmas: {
|
|
33
|
+
type: "array",
|
|
34
|
+
minItems: 0,
|
|
35
|
+
items: {
|
|
36
|
+
type: "object",
|
|
37
|
+
required: ["claim", "provenance", "load_bearing"],
|
|
38
|
+
properties: {
|
|
39
|
+
claim: {
|
|
40
|
+
type: "string",
|
|
41
|
+
description: "One verifiable factual statement in present tense. No compounds \u2014 split 'X and Y' into two lemmas."
|
|
42
|
+
},
|
|
43
|
+
provenance: {
|
|
44
|
+
type: "string",
|
|
45
|
+
enum: ["measured", "told", "believed"],
|
|
46
|
+
description: "measured = from a sensor/tool result in this conversation; told = stated by the user; believed = your prior."
|
|
47
|
+
},
|
|
48
|
+
load_bearing: { type: "boolean" },
|
|
49
|
+
falsifier: {
|
|
50
|
+
type: "string",
|
|
51
|
+
description: "What observation would prove this false. Optional but scored \u2014 a lemma with no conceivable falsifier is probably not a factual claim."
|
|
52
|
+
},
|
|
53
|
+
suggested_sensor: {
|
|
54
|
+
type: "string",
|
|
55
|
+
description: "Registry sensor id that could verify this, if known. Optional."
|
|
56
|
+
},
|
|
57
|
+
falsifying_observation: {
|
|
58
|
+
type: "object",
|
|
59
|
+
description: 'The falsifier as a checkable condition, when a sensor measures the value it turns on: "this is false if <key> <operator> <value>". Use the extract name a sensor reports (see the registry) \u2014 e.g. key "is_superuser", operator "=", value "true". Omit it when the falsifier is genuinely prose; a condition shaped right but meaningless is worse than none.',
|
|
60
|
+
required: ["key", "operator", "value"],
|
|
61
|
+
properties: {
|
|
62
|
+
sensor: { type: "string", description: "Registry sensor id that reports this key, if known." },
|
|
63
|
+
key: { type: "string", description: "The extract name whose value settles this." },
|
|
64
|
+
operator: { type: "string", enum: [...FALSIFIER_OPERATORS] },
|
|
65
|
+
value: { type: "string", description: "The value that would make the claim false." }
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
symbols: {
|
|
69
|
+
type: "array",
|
|
70
|
+
items: { type: "string" },
|
|
71
|
+
maxItems: 8,
|
|
72
|
+
description: "Dotted API paths this claim depends on, e.g. 'yaml.stringify', 'fs.promises.readFile', 'Array.prototype.toSorted'. They are resolved against the dependency tree actually installed, so name any method or export you are relying on \u2014 especially for less common packages."
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
var PROVENANCE_VALUES = ["measured", "told", "believed"];
|
|
81
|
+
function parseJsonOrThrow(text, message) {
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(text);
|
|
84
|
+
} catch {
|
|
85
|
+
throw new Error(message);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function parseDeclaration(input) {
|
|
89
|
+
const warnings = [];
|
|
90
|
+
if (typeof input === "string") {
|
|
91
|
+
input = parseJsonOrThrow(input, "declaration is not an object");
|
|
92
|
+
warnings.push("input double-encoded as a JSON string \u2014 unwrapped");
|
|
93
|
+
}
|
|
94
|
+
if (typeof input !== "object" || input === null) {
|
|
95
|
+
throw new Error("declaration is not an object");
|
|
96
|
+
}
|
|
97
|
+
let record = input;
|
|
98
|
+
if (typeof record.lemmas === "string") {
|
|
99
|
+
const inner = parseJsonOrThrow(record.lemmas, "declaration missing lemmas array");
|
|
100
|
+
if (Array.isArray(inner)) {
|
|
101
|
+
record = { ...record, lemmas: inner };
|
|
102
|
+
warnings.push("lemmas double-encoded as a JSON string \u2014 unwrapped");
|
|
103
|
+
} else if (inner !== null && typeof inner === "object" && Array.isArray(inner.lemmas)) {
|
|
104
|
+
const innerRecord = inner;
|
|
105
|
+
record = {
|
|
106
|
+
plan_summary: typeof record.plan_summary === "string" ? record.plan_summary : innerRecord.plan_summary,
|
|
107
|
+
lemmas: innerRecord.lemmas
|
|
108
|
+
};
|
|
109
|
+
warnings.push("entire declaration double-encoded into the lemmas field \u2014 unwrapped");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!Array.isArray(record.lemmas)) {
|
|
113
|
+
throw new Error("declaration missing lemmas array");
|
|
114
|
+
}
|
|
115
|
+
let planSummary;
|
|
116
|
+
if (typeof record.plan_summary === "string") {
|
|
117
|
+
planSummary = record.plan_summary;
|
|
118
|
+
} else {
|
|
119
|
+
planSummary = "(no plan summary provided)";
|
|
120
|
+
warnings.push("plan_summary missing \u2014 defaulted");
|
|
121
|
+
}
|
|
122
|
+
const lemmas = [];
|
|
123
|
+
record.lemmas.forEach((raw, i) => {
|
|
124
|
+
const item = raw;
|
|
125
|
+
if (typeof item?.claim !== "string" || item.claim.length === 0) {
|
|
126
|
+
warnings.push(`lemma[${i}] dropped: missing claim`);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
let provenance;
|
|
130
|
+
if (typeof item.provenance === "string" && PROVENANCE_VALUES.includes(item.provenance)) {
|
|
131
|
+
provenance = item.provenance;
|
|
132
|
+
} else {
|
|
133
|
+
provenance = "believed";
|
|
134
|
+
warnings.push(`lemma[${i}] provenance invalid \u2014 downgraded to believed`);
|
|
135
|
+
}
|
|
136
|
+
let loadBearing;
|
|
137
|
+
if (typeof item.load_bearing === "boolean") {
|
|
138
|
+
loadBearing = item.load_bearing;
|
|
139
|
+
} else {
|
|
140
|
+
loadBearing = true;
|
|
141
|
+
warnings.push(`lemma[${i}] load_bearing missing \u2014 defaulted to true`);
|
|
142
|
+
}
|
|
143
|
+
const lemma = { claim: item.claim, provenance, loadBearing };
|
|
144
|
+
if (typeof item.falsifier === "string") lemma.falsifier = item.falsifier;
|
|
145
|
+
const observation = parseFalsifyingObservation(item.falsifying_observation);
|
|
146
|
+
if (observation) lemma.falsifyingObservation = observation;
|
|
147
|
+
else if (item.falsifying_observation !== void 0) {
|
|
148
|
+
warnings.push("falsifying_observation was malformed and ignored \u2014 the prose falsifier still applies");
|
|
149
|
+
}
|
|
150
|
+
if (typeof item.suggested_sensor === "string") lemma.suggestedSensor = item.suggested_sensor;
|
|
151
|
+
if (Array.isArray(item.symbols)) {
|
|
152
|
+
const symbols = item.symbols.filter((sym) => typeof sym === "string").map((sym) => sym.trim()).filter((sym) => /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)+$/.test(sym)).slice(0, 8);
|
|
153
|
+
if (symbols.length > 0) lemma.symbols = symbols;
|
|
154
|
+
}
|
|
155
|
+
lemmas.push(lemma);
|
|
156
|
+
});
|
|
157
|
+
return { declaration: { planSummary, lemmas }, warnings };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ../core/src/sensors.ts
|
|
161
|
+
import { execFile } from "node:child_process";
|
|
162
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
163
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
164
|
+
|
|
165
|
+
// ../core/src/sensors-core.ts
|
|
166
|
+
import path from "node:path";
|
|
167
|
+
import { parse as parseYaml } from "yaml";
|
|
168
|
+
|
|
169
|
+
// ../core/src/redaction.ts
|
|
170
|
+
import { createHash } from "node:crypto";
|
|
171
|
+
var PATTERNS = [
|
|
172
|
+
// Value assigned to a secret-shaped variable name: API_KEY=..., DB_PASSWORD: "..."
|
|
173
|
+
{
|
|
174
|
+
kind: "secret_env_value",
|
|
175
|
+
regex: /\b([A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|APIKEY|PRIVATE_KEY|CREDENTIALS)[A-Z0-9_]*)\s*[=:]\s*["']?([^\s"']{4,})["']?/gi,
|
|
176
|
+
group: 2
|
|
177
|
+
},
|
|
178
|
+
// Connection strings with inline credentials: scheme://user:pass@host
|
|
179
|
+
{ kind: "connection_string_password", regex: /\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:([^\s@/]+)@/gi, group: 1 },
|
|
180
|
+
{ kind: "aws_access_key", regex: /\b(AKIA|ASIA)[A-Z0-9]{16}\b/g },
|
|
181
|
+
{ kind: "github_token", regex: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g },
|
|
182
|
+
{ kind: "openai_style_key", regex: /\bsk-[A-Za-z0-9_-]{16,}\b/g },
|
|
183
|
+
{ kind: "anthropic_key", regex: /\bsk-ant-[A-Za-z0-9_-]{16,}\b/g },
|
|
184
|
+
// Our own credentials must be caught without relying on their entropy. This
|
|
185
|
+
// includes base64url tails ending in '-' or '_', so no trailing word boundary.
|
|
186
|
+
{ kind: "gettier_ingestion_key", regex: /\bgt_live_[A-Za-z0-9_-]{24,}/g },
|
|
187
|
+
{ kind: "gettier_invitation_token", regex: /\bgt_inv_[A-Za-z0-9_-]{24,}/g },
|
|
188
|
+
{ kind: "bearer_token", regex: /\bBearer\s+([A-Za-z0-9._~+/=-]{16,})/gi, group: 1 },
|
|
189
|
+
{ kind: "jwt", regex: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g },
|
|
190
|
+
{ kind: "private_key_block", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g }
|
|
191
|
+
];
|
|
192
|
+
var ENTROPY_CANDIDATE = /\b[A-Za-z0-9+/_=-]{28,}\b/g;
|
|
193
|
+
var ENTROPY_THRESHOLD_BITS = 4.2;
|
|
194
|
+
function shannonEntropy(value) {
|
|
195
|
+
const counts = /* @__PURE__ */ new Map();
|
|
196
|
+
for (const ch of value) counts.set(ch, (counts.get(ch) ?? 0) + 1);
|
|
197
|
+
let bits = 0;
|
|
198
|
+
for (const count of counts.values()) {
|
|
199
|
+
const p = count / value.length;
|
|
200
|
+
bits -= p * Math.log2(p);
|
|
201
|
+
}
|
|
202
|
+
return bits;
|
|
203
|
+
}
|
|
204
|
+
function hash(value) {
|
|
205
|
+
return createHash("sha256").update(value).digest("hex").slice(0, 16);
|
|
206
|
+
}
|
|
207
|
+
var MASK = "[REDACTED]";
|
|
208
|
+
function isLikelySecret(candidate) {
|
|
209
|
+
if (shannonEntropy(candidate) < ENTROPY_THRESHOLD_BITS) return false;
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
function redact(input) {
|
|
213
|
+
return scan(input, true);
|
|
214
|
+
}
|
|
215
|
+
function redactPatternsOnly(input) {
|
|
216
|
+
return scan(input, false);
|
|
217
|
+
}
|
|
218
|
+
function scan(input, entropy) {
|
|
219
|
+
const redactions = [];
|
|
220
|
+
let clean = input;
|
|
221
|
+
for (const { kind, regex, group } of PATTERNS) {
|
|
222
|
+
clean = clean.replace(regex, (match, ...groups) => {
|
|
223
|
+
const value = group ? groups[group - 1] : match;
|
|
224
|
+
if (typeof value !== "string" || value.length === 0) return match;
|
|
225
|
+
redactions.push({ kind, valueHash: hash(value) });
|
|
226
|
+
return group ? match.replace(value, MASK) : MASK;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
if (entropy) {
|
|
230
|
+
clean = clean.replace(ENTROPY_CANDIDATE, (match) => {
|
|
231
|
+
if (match === MASK || !isLikelySecret(match)) return match;
|
|
232
|
+
redactions.push({ kind: "high_entropy_token", valueHash: hash(match) });
|
|
233
|
+
return MASK;
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
return { clean, redactions };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ../core/src/sensors-core.ts
|
|
240
|
+
function parseRegistry(source, filePath = "<inline>") {
|
|
241
|
+
const raw = parseYaml(source);
|
|
242
|
+
if (typeof raw?.version !== "number" || !Array.isArray(raw?.sensors)) {
|
|
243
|
+
throw new Error(`invalid sensor registry: ${filePath}`);
|
|
244
|
+
}
|
|
245
|
+
for (const sensor of raw.sensors) {
|
|
246
|
+
if (!sensor.id || !sensor.command || !Array.isArray(sensor.verifies)) {
|
|
247
|
+
throw new Error(`invalid sensor definition in registry: ${JSON.stringify(sensor)}`);
|
|
248
|
+
}
|
|
249
|
+
sensor.params = sensor.params ?? {};
|
|
250
|
+
if (sensor.effects !== void 0 && sensor.effects !== "none" && sensor.effects !== "mutates") {
|
|
251
|
+
throw new Error(
|
|
252
|
+
`invalid effects '${String(sensor.effects)}' on sensor '${sensor.id}' in ${filePath} \u2014 expected 'none' or 'mutates'`
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
sensor.effects = sensor.effects ?? "mutates";
|
|
256
|
+
sensor.ambient = sensor.ambient === true;
|
|
257
|
+
if (sensor.ambient && sensor.effects !== "none") {
|
|
258
|
+
throw new Error(
|
|
259
|
+
`sensor '${sensor.id}' in ${filePath} is ambient but not read-only \u2014 an ambient sensor runs on every turn, so a mutating one would mutate on every turn; declare 'effects: none'`
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return raw;
|
|
264
|
+
}
|
|
265
|
+
var SENSOR_CONCURRENCY = 4;
|
|
266
|
+
function sensorConcurrencyFromEnv(env = process.env) {
|
|
267
|
+
const raw = Number(env.GETTIER_SENSOR_CONCURRENCY);
|
|
268
|
+
return Number.isInteger(raw) && raw > 0 ? raw : SENSOR_CONCURRENCY;
|
|
269
|
+
}
|
|
270
|
+
function planSensorRuns(sensors, width = SENSOR_CONCURRENCY) {
|
|
271
|
+
const batches = [];
|
|
272
|
+
const readOnly = sensors.filter((s) => s.effects === "none");
|
|
273
|
+
const size = Number.isInteger(width) && width > 0 ? width : SENSOR_CONCURRENCY;
|
|
274
|
+
for (let i = 0; i < readOnly.length; i += size) {
|
|
275
|
+
batches.push(readOnly.slice(i, i + size));
|
|
276
|
+
}
|
|
277
|
+
for (const sensor of sensors) {
|
|
278
|
+
if (sensor.effects !== "none") batches.push([sensor]);
|
|
279
|
+
}
|
|
280
|
+
return batches;
|
|
281
|
+
}
|
|
282
|
+
function invocationFailure(invocation) {
|
|
283
|
+
if (invocation.exitCode === 0) return null;
|
|
284
|
+
const detail = redact(invocation.output).clean.replace(/\s+/g, " ").trim().slice(0, 140);
|
|
285
|
+
const what = invocation.exitCode === null ? "did not run" : `exited ${invocation.exitCode}`;
|
|
286
|
+
return detail ? `${what} \u2014 ${detail}` : what;
|
|
287
|
+
}
|
|
288
|
+
function validateParam(name, spec, value) {
|
|
289
|
+
if (spec.type === "path") {
|
|
290
|
+
const normalized = path.posix.normalize(value);
|
|
291
|
+
if (normalized.includes("..") || path.posix.isAbsolute(normalized)) {
|
|
292
|
+
throw new Error(`param '${name}' rejects traversal/absolute paths: ${value}`);
|
|
293
|
+
}
|
|
294
|
+
if (spec.allow) {
|
|
295
|
+
const prefix = spec.allow.replace(/\*\*$/, "").replace(/\*$/, "");
|
|
296
|
+
if (!normalized.startsWith(prefix)) {
|
|
297
|
+
throw new Error(`param '${name}' outside allowlist ${spec.allow}: ${value}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (/[\0\n\r]/.test(value)) {
|
|
302
|
+
throw new Error(`param '${name}' contains control characters`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function buildArgv(sensor, params) {
|
|
306
|
+
const supplied = {};
|
|
307
|
+
for (const [name, spec] of Object.entries(sensor.params)) {
|
|
308
|
+
const value = params[name] ?? spec.default;
|
|
309
|
+
if (value === void 0) {
|
|
310
|
+
throw new Error(`sensor ${sensor.id} requires param '${name}'`);
|
|
311
|
+
}
|
|
312
|
+
validateParam(name, spec, value);
|
|
313
|
+
supplied[name] = value;
|
|
314
|
+
}
|
|
315
|
+
return sensor.command.split(/\s+/).filter(Boolean).map((token) => {
|
|
316
|
+
const match = /^\{\{([a-zA-Z0-9_]+)\}\}$/.exec(token);
|
|
317
|
+
if (!match) {
|
|
318
|
+
if (token.includes("{{")) {
|
|
319
|
+
throw new Error(`sensor ${sensor.id}: partial interpolation not allowed in token '${token}'`);
|
|
320
|
+
}
|
|
321
|
+
return token;
|
|
322
|
+
}
|
|
323
|
+
const name = match[1];
|
|
324
|
+
const value = supplied[name];
|
|
325
|
+
if (value === void 0) {
|
|
326
|
+
throw new Error(`sensor ${sensor.id}: template references undeclared param '${name}'`);
|
|
327
|
+
}
|
|
328
|
+
return value;
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
function extractValues(sensor, output) {
|
|
332
|
+
const names = sensor.extract ?? [];
|
|
333
|
+
if (names.length === 0) return {};
|
|
334
|
+
const json = parseJsonObject(output);
|
|
335
|
+
return json ? extractFromJson(json, names) : extractFromText(output, names);
|
|
336
|
+
}
|
|
337
|
+
function parseJsonObject(output) {
|
|
338
|
+
try {
|
|
339
|
+
const parsed = JSON.parse(output);
|
|
340
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
341
|
+
} catch {
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
function extractFromJson(json, names) {
|
|
346
|
+
const extracted = {};
|
|
347
|
+
for (const name of names) {
|
|
348
|
+
let cur = json;
|
|
349
|
+
for (const key of name.split(".")) {
|
|
350
|
+
if (cur === null || typeof cur !== "object") {
|
|
351
|
+
cur = void 0;
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
cur = cur[key];
|
|
355
|
+
}
|
|
356
|
+
if (cur === null || cur === void 0 || typeof cur === "object") continue;
|
|
357
|
+
extracted[name] = String(cur);
|
|
358
|
+
}
|
|
359
|
+
return extracted;
|
|
360
|
+
}
|
|
361
|
+
function extractFromText(output, names) {
|
|
362
|
+
const extracted = {};
|
|
363
|
+
for (const name of names) {
|
|
364
|
+
const regex = new RegExp(`${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[=:\\s]\\s*([^;\\n]+)`, "m");
|
|
365
|
+
const match = regex.exec(output);
|
|
366
|
+
if (match) extracted[name] = match[1].trim().replace(/;$/, "").trim();
|
|
367
|
+
}
|
|
368
|
+
return extracted;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ../core/src/sensors.ts
|
|
372
|
+
function loadRegistry(filePath) {
|
|
373
|
+
return parseRegistry(readFileSync(filePath, "utf8"), filePath);
|
|
374
|
+
}
|
|
375
|
+
var ProcessSensorExecutor = class {
|
|
376
|
+
constructor(registry, options = {}) {
|
|
377
|
+
this.registry = registry;
|
|
378
|
+
this.options = options;
|
|
379
|
+
}
|
|
380
|
+
registry;
|
|
381
|
+
options;
|
|
382
|
+
get(sensorId) {
|
|
383
|
+
const sensor = this.registry.sensors.find((s) => s.id === sensorId);
|
|
384
|
+
if (!sensor) throw new Error(`unknown sensor id: '${sensorId}' \u2014 not in registry`);
|
|
385
|
+
return sensor;
|
|
386
|
+
}
|
|
387
|
+
async run(sensorId, params = {}) {
|
|
388
|
+
const sensor = this.get(sensorId);
|
|
389
|
+
const argv = buildArgv(sensor, params);
|
|
390
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
391
|
+
const timeoutMs = (sensor.timeout ?? 10) * 1e3;
|
|
392
|
+
const maxBytes = sensor.max_output_bytes ?? 65536;
|
|
393
|
+
const { exitCode, output } = await new Promise(
|
|
394
|
+
(resolve) => {
|
|
395
|
+
execFile(
|
|
396
|
+
argv[0],
|
|
397
|
+
argv.slice(1),
|
|
398
|
+
{ timeout: timeoutMs, maxBuffer: maxBytes * 4, cwd: this.options.cwd },
|
|
399
|
+
(error, stdout, stderr) => {
|
|
400
|
+
const combined = `${stdout}${stderr ? `
|
|
401
|
+
${stderr}` : ""}`;
|
|
402
|
+
if (error && typeof error.code === "string") {
|
|
403
|
+
resolve({ exitCode: null, output: `${combined}
|
|
404
|
+
${error.message}`.trim() });
|
|
405
|
+
} else if (error) {
|
|
406
|
+
resolve({ exitCode: error.code ?? null, output: combined });
|
|
407
|
+
} else {
|
|
408
|
+
resolve({ exitCode: 0, output: combined });
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
);
|
|
414
|
+
const truncated = Buffer.byteLength(output) > maxBytes;
|
|
415
|
+
const bounded = truncated ? Buffer.from(output).subarray(0, maxBytes).toString() : output;
|
|
416
|
+
return {
|
|
417
|
+
sensorId: sensor.id,
|
|
418
|
+
registryVersion: this.registry.version,
|
|
419
|
+
startedAt: startedAt.toISOString(),
|
|
420
|
+
durationMs: Date.now() - startedAt.getTime(),
|
|
421
|
+
exitCode,
|
|
422
|
+
output: bounded,
|
|
423
|
+
outputHash: createHash2("sha256").update(bounded).digest("hex"),
|
|
424
|
+
truncated
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
// ../core/src/api-existence.ts
|
|
430
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
431
|
+
import { promisify } from "node:util";
|
|
432
|
+
var exec = promisify(execFile2);
|
|
433
|
+
var FILE_LIKE = /^(js|ts|mjs|cjs|tsx|jsx|json|md|ya?ml|sql|html|css|sh|txt|lock|env|toml|ini)$/i;
|
|
434
|
+
var SYMBOL_PATTERN = /\b[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+\b/g;
|
|
435
|
+
var MAX_SYMBOLS = 8;
|
|
436
|
+
var MEMBERSHIP = /\b(export|exports|exported|provide|provides|expose|exposes|method|function|helper|member|property|named|called|has a|there is a)\b/i;
|
|
437
|
+
var QUOTED_IDENT = /[`'"]([A-Za-z_$][\w$]*)[`'"]/g;
|
|
438
|
+
function composeQuotedMembers(claim) {
|
|
439
|
+
if (!MEMBERSHIP.test(claim)) return [];
|
|
440
|
+
const idents = [...claim.matchAll(QUOTED_IDENT)].map((m) => m[1]);
|
|
441
|
+
const unique = [...new Set(idents)];
|
|
442
|
+
if (unique.length < 2 || unique.length > 4) return [];
|
|
443
|
+
const composed = [];
|
|
444
|
+
for (const root of unique) {
|
|
445
|
+
for (const member of unique) {
|
|
446
|
+
if (root !== member) composed.push(root + "." + member);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
return composed;
|
|
450
|
+
}
|
|
451
|
+
function extractSymbols(claim) {
|
|
452
|
+
const found = /* @__PURE__ */ new Set();
|
|
453
|
+
for (const match of claim.match(SYMBOL_PATTERN) ?? []) {
|
|
454
|
+
const parts = match.split(".");
|
|
455
|
+
if (parts.length < 2 || parts.length > 5) continue;
|
|
456
|
+
if (parts.some((p) => FILE_LIKE.test(p))) continue;
|
|
457
|
+
if (/\d/.test(parts[0])) continue;
|
|
458
|
+
if (parts.some((p) => p.length === 0)) continue;
|
|
459
|
+
found.add(match);
|
|
460
|
+
if (found.size >= MAX_SYMBOLS) break;
|
|
461
|
+
}
|
|
462
|
+
for (const composed of composeQuotedMembers(claim)) {
|
|
463
|
+
if (found.size >= MAX_SYMBOLS) break;
|
|
464
|
+
found.add(composed);
|
|
465
|
+
}
|
|
466
|
+
return [...found];
|
|
467
|
+
}
|
|
468
|
+
async function resolveSymbols(symbols, cwd) {
|
|
469
|
+
if (symbols.length === 0) return [];
|
|
470
|
+
const script = `
|
|
471
|
+
const { createRequire } = require('node:module');
|
|
472
|
+
const req = createRequire(process.cwd() + '/package.json');
|
|
473
|
+
const out = JSON.parse(process.argv[1]).map((symbol) => {
|
|
474
|
+
const parts = symbol.split('.');
|
|
475
|
+
const root = parts[0];
|
|
476
|
+
let base, version = null, rootResolved = false;
|
|
477
|
+
if (Object.prototype.hasOwnProperty.call(globalThis, root)) {
|
|
478
|
+
base = globalThis[root]; version = 'node ' + process.versions.node; rootResolved = true;
|
|
479
|
+
} else {
|
|
480
|
+
try { base = req(root); rootResolved = true; } catch (e) {
|
|
481
|
+
return { symbol, rootResolved: false, failedAtLast: false, resolved: false, version: null,
|
|
482
|
+
detail: "module '" + root + "' is not resolvable here" };
|
|
483
|
+
}
|
|
484
|
+
try { version = req(root + '/package.json').version; } catch (e) { version = 'unknown'; }
|
|
485
|
+
}
|
|
486
|
+
let cur = base;
|
|
487
|
+
const rest = parts.slice(1);
|
|
488
|
+
for (let i = 0; i < rest.length; i += 1) {
|
|
489
|
+
const seg = rest[i];
|
|
490
|
+
if (cur === null || cur === undefined) {
|
|
491
|
+
// Failed before the last segment: not a runtime path, so say nothing.
|
|
492
|
+
return { symbol, rootResolved, failedAtLast: false, resolved: false, version,
|
|
493
|
+
detail: "'" + seg + "' is not a runtime path here" };
|
|
494
|
+
}
|
|
495
|
+
cur = seg === 'prototype' ? cur.prototype : cur[seg];
|
|
496
|
+
}
|
|
497
|
+
return { symbol, rootResolved, failedAtLast: true, resolved: cur !== undefined, version,
|
|
498
|
+
detail: cur === undefined ? 'member is undefined' : typeof cur };
|
|
499
|
+
});
|
|
500
|
+
process.stdout.write(JSON.stringify(out));
|
|
501
|
+
`;
|
|
502
|
+
try {
|
|
503
|
+
const { stdout } = await exec(process.execPath, ["-e", script, JSON.stringify(symbols)], {
|
|
504
|
+
cwd,
|
|
505
|
+
timeout: 1e4,
|
|
506
|
+
maxBuffer: 1024 * 1024
|
|
507
|
+
});
|
|
508
|
+
return JSON.parse(stdout);
|
|
509
|
+
} catch {
|
|
510
|
+
return [];
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
function apiExistenceEvidence(resolutions) {
|
|
514
|
+
const checkable = resolutions.filter((r) => r.rootResolved && (r.resolved || r.failedAtLast));
|
|
515
|
+
const missing = checkable.filter((r) => !r.resolved);
|
|
516
|
+
const present = checkable.filter((r) => r.resolved);
|
|
517
|
+
return {
|
|
518
|
+
sensorId: "code.api_existence",
|
|
519
|
+
output: resolutions.map((r) => `${r.symbol} -> ${r.resolved ? "ok" : r.detail}`).join("\n"),
|
|
520
|
+
extracted: {
|
|
521
|
+
unresolved_members: String(missing.length),
|
|
522
|
+
resolved_members: String(present.length),
|
|
523
|
+
unresolved_list: missing.map((r) => `${r.symbol} (${r.version ?? "unknown"}: ${r.detail})`).join(", "),
|
|
524
|
+
resolved_list: present.map((r) => `${r.symbol}@${r.version ?? "unknown"}`).join(", ")
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// ../core/src/matching.ts
|
|
530
|
+
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
531
|
+
"the",
|
|
532
|
+
"a",
|
|
533
|
+
"an",
|
|
534
|
+
"is",
|
|
535
|
+
"are",
|
|
536
|
+
"was",
|
|
537
|
+
"were",
|
|
538
|
+
"be",
|
|
539
|
+
"been",
|
|
540
|
+
"being",
|
|
541
|
+
"in",
|
|
542
|
+
"on",
|
|
543
|
+
"at",
|
|
544
|
+
"to",
|
|
545
|
+
"for",
|
|
546
|
+
"of",
|
|
547
|
+
"and",
|
|
548
|
+
"or",
|
|
549
|
+
"not",
|
|
550
|
+
"this",
|
|
551
|
+
"that",
|
|
552
|
+
"it",
|
|
553
|
+
"its",
|
|
554
|
+
"with",
|
|
555
|
+
"by",
|
|
556
|
+
"from",
|
|
557
|
+
"as",
|
|
558
|
+
"has",
|
|
559
|
+
"have",
|
|
560
|
+
"had",
|
|
561
|
+
"will",
|
|
562
|
+
"would",
|
|
563
|
+
"should",
|
|
564
|
+
"can",
|
|
565
|
+
"could",
|
|
566
|
+
"our",
|
|
567
|
+
"we",
|
|
568
|
+
"you",
|
|
569
|
+
"your",
|
|
570
|
+
"they",
|
|
571
|
+
"their"
|
|
572
|
+
]);
|
|
573
|
+
function tokenize(text) {
|
|
574
|
+
return text.toLowerCase().split(/[^a-z0-9._-]+/).map((t) => t.replace(/^[._-]+|[._-]+$/g, "")).filter((t) => t.length >= 3 && !STOPWORDS.has(t));
|
|
575
|
+
}
|
|
576
|
+
function overlap(claimTokens, sourceText) {
|
|
577
|
+
const sourceTokens = new Set(tokenize(sourceText));
|
|
578
|
+
return [...new Set(claimTokens)].filter((t) => sourceTokens.has(t));
|
|
579
|
+
}
|
|
580
|
+
function sufficientOverlap(claimTokens, matched) {
|
|
581
|
+
return matched.length >= Math.max(2, Math.ceil(claimTokens.length * 0.25));
|
|
582
|
+
}
|
|
583
|
+
function auditProvenance(lemma, context) {
|
|
584
|
+
const claimTokens = tokenize(lemma.claim);
|
|
585
|
+
if (lemma.provenance === "measured") {
|
|
586
|
+
for (const fact of context.activeFacts) {
|
|
587
|
+
if (fact.source.kind !== "sensor") continue;
|
|
588
|
+
const matched = overlap(claimTokens, fact.claim);
|
|
589
|
+
if (sufficientOverlap(claimTokens, matched)) {
|
|
590
|
+
return {
|
|
591
|
+
lemma,
|
|
592
|
+
effectiveProvenance: "measured",
|
|
593
|
+
downgraded: false,
|
|
594
|
+
basis: `matches ledger fact ${fact.id} (${matched.join(", ")})`
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return {
|
|
599
|
+
lemma,
|
|
600
|
+
effectiveProvenance: "believed",
|
|
601
|
+
downgraded: true,
|
|
602
|
+
basis: "tagged measured but no sensor-sourced ledger fact overlaps the claim"
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
if (lemma.provenance === "told") {
|
|
606
|
+
for (const message of context.userMessages) {
|
|
607
|
+
const matched = overlap(claimTokens, message);
|
|
608
|
+
if (sufficientOverlap(claimTokens, matched)) {
|
|
609
|
+
return {
|
|
610
|
+
lemma,
|
|
611
|
+
effectiveProvenance: "told",
|
|
612
|
+
downgraded: false,
|
|
613
|
+
basis: `matches user message (${matched.join(", ")})`
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return {
|
|
618
|
+
lemma,
|
|
619
|
+
effectiveProvenance: "believed",
|
|
620
|
+
downgraded: true,
|
|
621
|
+
basis: "tagged told but no user message overlaps the claim"
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
return { lemma, effectiveProvenance: "believed", downgraded: false, basis: "self-declared prior" };
|
|
625
|
+
}
|
|
626
|
+
var CATEGORY_KEYWORDS = {
|
|
627
|
+
"request_path.size_limits": [
|
|
628
|
+
"limit",
|
|
629
|
+
"limits",
|
|
630
|
+
"size",
|
|
631
|
+
"payload",
|
|
632
|
+
"body",
|
|
633
|
+
"upload",
|
|
634
|
+
"uploads",
|
|
635
|
+
"413",
|
|
636
|
+
"cap",
|
|
637
|
+
"max",
|
|
638
|
+
"large",
|
|
639
|
+
"body-parser"
|
|
640
|
+
],
|
|
641
|
+
"proxy.configuration": ["nginx", "proxy", "reverse", "upstream", "gateway", "ingress"],
|
|
642
|
+
"request_path.middleware_order": [
|
|
643
|
+
"middleware",
|
|
644
|
+
"order",
|
|
645
|
+
"mounted",
|
|
646
|
+
"mount",
|
|
647
|
+
"route",
|
|
648
|
+
"body-parser",
|
|
649
|
+
"parser",
|
|
650
|
+
"express",
|
|
651
|
+
"express.json",
|
|
652
|
+
"urlencoded",
|
|
653
|
+
"multer",
|
|
654
|
+
"bodyparser",
|
|
655
|
+
"app-level",
|
|
656
|
+
"application-level"
|
|
657
|
+
],
|
|
658
|
+
"request_path.stream_consumption": [
|
|
659
|
+
"stream",
|
|
660
|
+
"streams",
|
|
661
|
+
"consume",
|
|
662
|
+
"consumes",
|
|
663
|
+
"consumed",
|
|
664
|
+
"drain",
|
|
665
|
+
"drained",
|
|
666
|
+
"req.on",
|
|
667
|
+
"data",
|
|
668
|
+
"raw",
|
|
669
|
+
"fires",
|
|
670
|
+
"chunk"
|
|
671
|
+
],
|
|
672
|
+
"database.identity": [
|
|
673
|
+
"database",
|
|
674
|
+
"staging",
|
|
675
|
+
"connected",
|
|
676
|
+
"connection",
|
|
677
|
+
"current_database",
|
|
678
|
+
"postgres",
|
|
679
|
+
"database_url",
|
|
680
|
+
"points",
|
|
681
|
+
"server",
|
|
682
|
+
"host",
|
|
683
|
+
"dev",
|
|
684
|
+
"shared-dev",
|
|
685
|
+
"shared_dev",
|
|
686
|
+
"production",
|
|
687
|
+
"prod",
|
|
688
|
+
"instance",
|
|
689
|
+
"ground"
|
|
690
|
+
],
|
|
691
|
+
"database.migration_state": [
|
|
692
|
+
"migration",
|
|
693
|
+
"schema",
|
|
694
|
+
"schema_migrations",
|
|
695
|
+
"head",
|
|
696
|
+
"applied",
|
|
697
|
+
"migrated",
|
|
698
|
+
"version"
|
|
699
|
+
],
|
|
700
|
+
"runtime.latency_stationarity": [
|
|
701
|
+
"latency",
|
|
702
|
+
"uptime",
|
|
703
|
+
"stationary",
|
|
704
|
+
"degrade",
|
|
705
|
+
"degradation",
|
|
706
|
+
"trend",
|
|
707
|
+
"timeout",
|
|
708
|
+
"threshold",
|
|
709
|
+
"slow",
|
|
710
|
+
"downstream",
|
|
711
|
+
"p99",
|
|
712
|
+
"p50",
|
|
713
|
+
"504",
|
|
714
|
+
"process",
|
|
715
|
+
"restart",
|
|
716
|
+
"creep"
|
|
717
|
+
],
|
|
718
|
+
"runtime.memory_trend": [
|
|
719
|
+
"memory",
|
|
720
|
+
"rss",
|
|
721
|
+
"leak",
|
|
722
|
+
"heap",
|
|
723
|
+
"allocation",
|
|
724
|
+
"oom",
|
|
725
|
+
"stable",
|
|
726
|
+
"grows",
|
|
727
|
+
"growth",
|
|
728
|
+
"cache",
|
|
729
|
+
"unbounded",
|
|
730
|
+
"gc"
|
|
731
|
+
],
|
|
732
|
+
"runtime.gc_pressure": ["gc", "garbage", "collection", "pause", "pauses", "throttle", "throttling"],
|
|
733
|
+
"data.cardinality": [
|
|
734
|
+
"active",
|
|
735
|
+
"subscription",
|
|
736
|
+
"subscriptions",
|
|
737
|
+
"customer",
|
|
738
|
+
"customers",
|
|
739
|
+
"row",
|
|
740
|
+
"rows",
|
|
741
|
+
"single",
|
|
742
|
+
"one",
|
|
743
|
+
"only",
|
|
744
|
+
"exactly",
|
|
745
|
+
"most",
|
|
746
|
+
"duplicate",
|
|
747
|
+
"duplicates",
|
|
748
|
+
"multiple",
|
|
749
|
+
"many",
|
|
750
|
+
"count",
|
|
751
|
+
"cardinality",
|
|
752
|
+
"unambiguous",
|
|
753
|
+
"per"
|
|
754
|
+
],
|
|
755
|
+
"schema.constraint_state": [
|
|
756
|
+
"constraint",
|
|
757
|
+
"constraints",
|
|
758
|
+
"unique",
|
|
759
|
+
"uniqueness",
|
|
760
|
+
"index",
|
|
761
|
+
"indexes",
|
|
762
|
+
"schema",
|
|
763
|
+
"enforce",
|
|
764
|
+
"enforces",
|
|
765
|
+
"enforced",
|
|
766
|
+
"guarantee",
|
|
767
|
+
"guarantees",
|
|
768
|
+
"guaranteed",
|
|
769
|
+
"invariant",
|
|
770
|
+
"integrity",
|
|
771
|
+
"duplicate",
|
|
772
|
+
"duplicates",
|
|
773
|
+
"primary",
|
|
774
|
+
"exclusion"
|
|
775
|
+
],
|
|
776
|
+
"runtime.concurrency": [
|
|
777
|
+
"concurrency",
|
|
778
|
+
"concurrent",
|
|
779
|
+
"concurrently",
|
|
780
|
+
"parallel",
|
|
781
|
+
"worker",
|
|
782
|
+
"workers",
|
|
783
|
+
"process",
|
|
784
|
+
"processes",
|
|
785
|
+
"thread",
|
|
786
|
+
"threads",
|
|
787
|
+
"threaded",
|
|
788
|
+
"single-threaded",
|
|
789
|
+
"instance",
|
|
790
|
+
"instances",
|
|
791
|
+
"cluster",
|
|
792
|
+
"serial",
|
|
793
|
+
"sequential",
|
|
794
|
+
"interleave",
|
|
795
|
+
"interleaved",
|
|
796
|
+
"interleaving",
|
|
797
|
+
"simultaneous",
|
|
798
|
+
"race",
|
|
799
|
+
"request",
|
|
800
|
+
"requests"
|
|
801
|
+
],
|
|
802
|
+
"database.write_isolation": [
|
|
803
|
+
"isolation",
|
|
804
|
+
"transaction",
|
|
805
|
+
"transactions",
|
|
806
|
+
"transactional",
|
|
807
|
+
"atomic",
|
|
808
|
+
"atomically",
|
|
809
|
+
"atomicity",
|
|
810
|
+
"lock",
|
|
811
|
+
"locks",
|
|
812
|
+
"locking",
|
|
813
|
+
"serializable",
|
|
814
|
+
"committed",
|
|
815
|
+
"commit",
|
|
816
|
+
"consistent",
|
|
817
|
+
"consistency"
|
|
818
|
+
],
|
|
819
|
+
"runtime.version_identity": [
|
|
820
|
+
"node",
|
|
821
|
+
"runtime",
|
|
822
|
+
"version",
|
|
823
|
+
"versions",
|
|
824
|
+
"engine",
|
|
825
|
+
"engines",
|
|
826
|
+
"container",
|
|
827
|
+
"image",
|
|
828
|
+
"production",
|
|
829
|
+
"deploy",
|
|
830
|
+
"deployed",
|
|
831
|
+
"platform",
|
|
832
|
+
"environment",
|
|
833
|
+
"fleet",
|
|
834
|
+
"major"
|
|
835
|
+
],
|
|
836
|
+
"data.null_coverage": [
|
|
837
|
+
"null",
|
|
838
|
+
"nulls",
|
|
839
|
+
"missing",
|
|
840
|
+
"absent",
|
|
841
|
+
"every",
|
|
842
|
+
"all",
|
|
843
|
+
"always",
|
|
844
|
+
"each",
|
|
845
|
+
"discount",
|
|
846
|
+
"optional",
|
|
847
|
+
"blank",
|
|
848
|
+
"empty",
|
|
849
|
+
"set",
|
|
850
|
+
"present",
|
|
851
|
+
"populated",
|
|
852
|
+
"value",
|
|
853
|
+
"values",
|
|
854
|
+
"product",
|
|
855
|
+
"products",
|
|
856
|
+
"row",
|
|
857
|
+
"rows",
|
|
858
|
+
"column",
|
|
859
|
+
"field"
|
|
860
|
+
],
|
|
861
|
+
"schema.nullability": [
|
|
862
|
+
"null",
|
|
863
|
+
"nullable",
|
|
864
|
+
"not",
|
|
865
|
+
"constraint",
|
|
866
|
+
"constraints",
|
|
867
|
+
"default",
|
|
868
|
+
"defaults",
|
|
869
|
+
"schema",
|
|
870
|
+
"guarantee",
|
|
871
|
+
"guarantees",
|
|
872
|
+
"guaranteed",
|
|
873
|
+
"enforce",
|
|
874
|
+
"enforces",
|
|
875
|
+
"enforced",
|
|
876
|
+
"required",
|
|
877
|
+
"mandatory",
|
|
878
|
+
"column",
|
|
879
|
+
"field"
|
|
880
|
+
],
|
|
881
|
+
"data.case_variance": [
|
|
882
|
+
"case",
|
|
883
|
+
"lowercase",
|
|
884
|
+
"lower",
|
|
885
|
+
"uppercase",
|
|
886
|
+
"upper",
|
|
887
|
+
"canonical",
|
|
888
|
+
"normalised",
|
|
889
|
+
"normalized",
|
|
890
|
+
"email",
|
|
891
|
+
"emails",
|
|
892
|
+
"address",
|
|
893
|
+
"addresses",
|
|
894
|
+
"stored",
|
|
895
|
+
"exactly",
|
|
896
|
+
"match",
|
|
897
|
+
"matches",
|
|
898
|
+
"matching",
|
|
899
|
+
"equality",
|
|
900
|
+
"compare",
|
|
901
|
+
"comparison",
|
|
902
|
+
"spelling"
|
|
903
|
+
],
|
|
904
|
+
"schema.case_folding": [
|
|
905
|
+
"citext",
|
|
906
|
+
"collation",
|
|
907
|
+
"index",
|
|
908
|
+
"indexes",
|
|
909
|
+
"case-insensitive",
|
|
910
|
+
"insensitive",
|
|
911
|
+
"schema",
|
|
912
|
+
"guarantee",
|
|
913
|
+
"guarantees",
|
|
914
|
+
"enforce",
|
|
915
|
+
"enforces",
|
|
916
|
+
"enforced",
|
|
917
|
+
"canonical",
|
|
918
|
+
"lower",
|
|
919
|
+
"column",
|
|
920
|
+
"email"
|
|
921
|
+
],
|
|
922
|
+
"runtime.version_gap": [
|
|
923
|
+
"runtime",
|
|
924
|
+
"node",
|
|
925
|
+
"version",
|
|
926
|
+
"versions",
|
|
927
|
+
"production",
|
|
928
|
+
"deploy",
|
|
929
|
+
"deployed",
|
|
930
|
+
"fleet",
|
|
931
|
+
"container",
|
|
932
|
+
"image",
|
|
933
|
+
"same",
|
|
934
|
+
"matches",
|
|
935
|
+
"environment",
|
|
936
|
+
"platform",
|
|
937
|
+
"major"
|
|
938
|
+
],
|
|
939
|
+
"code.runtime_compatibility": [
|
|
940
|
+
"api",
|
|
941
|
+
"apis",
|
|
942
|
+
"method",
|
|
943
|
+
"methods",
|
|
944
|
+
"javascript",
|
|
945
|
+
"supported",
|
|
946
|
+
"available",
|
|
947
|
+
"works",
|
|
948
|
+
"builtin",
|
|
949
|
+
"built-in",
|
|
950
|
+
"feature",
|
|
951
|
+
"features",
|
|
952
|
+
"syntax",
|
|
953
|
+
"compatible",
|
|
954
|
+
"compatibility",
|
|
955
|
+
"runtime",
|
|
956
|
+
"version",
|
|
957
|
+
"node"
|
|
958
|
+
],
|
|
959
|
+
"dependency.timeout_state": [
|
|
960
|
+
"timeout",
|
|
961
|
+
"timeouts",
|
|
962
|
+
"deadline",
|
|
963
|
+
"deadlines",
|
|
964
|
+
"abort",
|
|
965
|
+
"hang",
|
|
966
|
+
"hangs",
|
|
967
|
+
"hanging",
|
|
968
|
+
"unavailable",
|
|
969
|
+
"dependency",
|
|
970
|
+
"service",
|
|
971
|
+
"catch",
|
|
972
|
+
"catching",
|
|
973
|
+
"error",
|
|
974
|
+
"errors",
|
|
975
|
+
"fails",
|
|
976
|
+
"failure",
|
|
977
|
+
"down",
|
|
978
|
+
"degrade",
|
|
979
|
+
"gracefully"
|
|
980
|
+
],
|
|
981
|
+
"dependency.degradation_path": [
|
|
982
|
+
"degrade",
|
|
983
|
+
"degrades",
|
|
984
|
+
"gracefully",
|
|
985
|
+
"fallback",
|
|
986
|
+
"unavailable",
|
|
987
|
+
"down",
|
|
988
|
+
"hang",
|
|
989
|
+
"hangs",
|
|
990
|
+
"hanging",
|
|
991
|
+
"error",
|
|
992
|
+
"errors",
|
|
993
|
+
"surfaces",
|
|
994
|
+
"catch",
|
|
995
|
+
"dependency",
|
|
996
|
+
"service",
|
|
997
|
+
"enrichment",
|
|
998
|
+
"request",
|
|
999
|
+
"renders"
|
|
1000
|
+
],
|
|
1001
|
+
"data.money_representation": [
|
|
1002
|
+
"money",
|
|
1003
|
+
"amount",
|
|
1004
|
+
"amounts",
|
|
1005
|
+
"decimal",
|
|
1006
|
+
"numeric",
|
|
1007
|
+
"float",
|
|
1008
|
+
"floating",
|
|
1009
|
+
"precision",
|
|
1010
|
+
"cents",
|
|
1011
|
+
"currency",
|
|
1012
|
+
"total",
|
|
1013
|
+
"subtotal",
|
|
1014
|
+
"tax",
|
|
1015
|
+
"rounding",
|
|
1016
|
+
"round",
|
|
1017
|
+
"number"
|
|
1018
|
+
],
|
|
1019
|
+
"compute.precision_drift": [
|
|
1020
|
+
"sum",
|
|
1021
|
+
"summing",
|
|
1022
|
+
"sums",
|
|
1023
|
+
"arithmetic",
|
|
1024
|
+
"total",
|
|
1025
|
+
"totals",
|
|
1026
|
+
"drift",
|
|
1027
|
+
"precision",
|
|
1028
|
+
"exact",
|
|
1029
|
+
"exactly",
|
|
1030
|
+
"same",
|
|
1031
|
+
"equals",
|
|
1032
|
+
"cents",
|
|
1033
|
+
"rounding",
|
|
1034
|
+
"accumulate",
|
|
1035
|
+
"database",
|
|
1036
|
+
"javascript",
|
|
1037
|
+
"application"
|
|
1038
|
+
],
|
|
1039
|
+
"data.sort_stability": [
|
|
1040
|
+
"order",
|
|
1041
|
+
"ordering",
|
|
1042
|
+
"sort",
|
|
1043
|
+
"sorted",
|
|
1044
|
+
"unique",
|
|
1045
|
+
"total",
|
|
1046
|
+
"tie",
|
|
1047
|
+
"ties",
|
|
1048
|
+
"tied",
|
|
1049
|
+
"stable",
|
|
1050
|
+
"deterministic",
|
|
1051
|
+
"published_at",
|
|
1052
|
+
"timestamp",
|
|
1053
|
+
"key",
|
|
1054
|
+
"page",
|
|
1055
|
+
"pages",
|
|
1056
|
+
"pagination",
|
|
1057
|
+
"offset",
|
|
1058
|
+
"exactly"
|
|
1059
|
+
],
|
|
1060
|
+
"query.pagination_integrity": [
|
|
1061
|
+
"page",
|
|
1062
|
+
"pages",
|
|
1063
|
+
"pagination",
|
|
1064
|
+
"paginated",
|
|
1065
|
+
"offset",
|
|
1066
|
+
"limit",
|
|
1067
|
+
"walk",
|
|
1068
|
+
"feed",
|
|
1069
|
+
"repeat",
|
|
1070
|
+
"repeats",
|
|
1071
|
+
"twice",
|
|
1072
|
+
"duplicate",
|
|
1073
|
+
"missing",
|
|
1074
|
+
"once",
|
|
1075
|
+
"skipped",
|
|
1076
|
+
"articles"
|
|
1077
|
+
],
|
|
1078
|
+
"code.api_existence": [
|
|
1079
|
+
"method",
|
|
1080
|
+
"methods",
|
|
1081
|
+
"function",
|
|
1082
|
+
"api",
|
|
1083
|
+
"exists",
|
|
1084
|
+
"available",
|
|
1085
|
+
"returns",
|
|
1086
|
+
"accepts",
|
|
1087
|
+
"module",
|
|
1088
|
+
"package",
|
|
1089
|
+
"library",
|
|
1090
|
+
"import",
|
|
1091
|
+
"require",
|
|
1092
|
+
"export",
|
|
1093
|
+
"exports",
|
|
1094
|
+
"signature"
|
|
1095
|
+
],
|
|
1096
|
+
"api.idempotency_state": [
|
|
1097
|
+
"idempotent",
|
|
1098
|
+
"idempotency",
|
|
1099
|
+
"retry",
|
|
1100
|
+
"retries",
|
|
1101
|
+
"retrying",
|
|
1102
|
+
"retried",
|
|
1103
|
+
"duplicate",
|
|
1104
|
+
"twice",
|
|
1105
|
+
"again",
|
|
1106
|
+
"repeat",
|
|
1107
|
+
"repeated",
|
|
1108
|
+
"safe",
|
|
1109
|
+
"charge",
|
|
1110
|
+
"charged",
|
|
1111
|
+
"attempt",
|
|
1112
|
+
"attempts",
|
|
1113
|
+
"operation",
|
|
1114
|
+
"key"
|
|
1115
|
+
],
|
|
1116
|
+
"dependency.failure_modes": [
|
|
1117
|
+
"failure",
|
|
1118
|
+
"failures",
|
|
1119
|
+
"failed",
|
|
1120
|
+
"error",
|
|
1121
|
+
"errors",
|
|
1122
|
+
"timeout",
|
|
1123
|
+
"timeouts",
|
|
1124
|
+
"commit",
|
|
1125
|
+
"committed",
|
|
1126
|
+
"response",
|
|
1127
|
+
"downstream",
|
|
1128
|
+
"processor",
|
|
1129
|
+
"upstream",
|
|
1130
|
+
"transient",
|
|
1131
|
+
"flaky",
|
|
1132
|
+
"intermittent",
|
|
1133
|
+
"lost"
|
|
1134
|
+
],
|
|
1135
|
+
"api.retry_safety": [
|
|
1136
|
+
"retry",
|
|
1137
|
+
"retries",
|
|
1138
|
+
"retrying",
|
|
1139
|
+
"idempotent",
|
|
1140
|
+
"idempotency",
|
|
1141
|
+
"duplicate",
|
|
1142
|
+
"duplicates",
|
|
1143
|
+
"twice",
|
|
1144
|
+
"double",
|
|
1145
|
+
"charge",
|
|
1146
|
+
"charged",
|
|
1147
|
+
"safe",
|
|
1148
|
+
"success",
|
|
1149
|
+
"failure",
|
|
1150
|
+
"again"
|
|
1151
|
+
],
|
|
1152
|
+
"time.timezone_identity": [
|
|
1153
|
+
"timezone",
|
|
1154
|
+
"timezones",
|
|
1155
|
+
"tz",
|
|
1156
|
+
"utc",
|
|
1157
|
+
"gmt",
|
|
1158
|
+
"clock",
|
|
1159
|
+
"clocks",
|
|
1160
|
+
"offset",
|
|
1161
|
+
"local",
|
|
1162
|
+
"server",
|
|
1163
|
+
"zone",
|
|
1164
|
+
"time",
|
|
1165
|
+
"midnight",
|
|
1166
|
+
"date",
|
|
1167
|
+
"day",
|
|
1168
|
+
"calendar",
|
|
1169
|
+
"boundary"
|
|
1170
|
+
],
|
|
1171
|
+
"time.boundary_exposure": [
|
|
1172
|
+
"boundary",
|
|
1173
|
+
"boundaries",
|
|
1174
|
+
"midnight",
|
|
1175
|
+
"day",
|
|
1176
|
+
"days",
|
|
1177
|
+
"date",
|
|
1178
|
+
"dates",
|
|
1179
|
+
"window",
|
|
1180
|
+
"edge",
|
|
1181
|
+
"straddle",
|
|
1182
|
+
"overnight",
|
|
1183
|
+
"hour",
|
|
1184
|
+
"hours",
|
|
1185
|
+
"transactions",
|
|
1186
|
+
"grouping",
|
|
1187
|
+
"group",
|
|
1188
|
+
"billing",
|
|
1189
|
+
"daily"
|
|
1190
|
+
],
|
|
1191
|
+
"cache.invalidation_state": [
|
|
1192
|
+
"cache",
|
|
1193
|
+
"cached",
|
|
1194
|
+
"caching",
|
|
1195
|
+
"invalidate",
|
|
1196
|
+
"invalidation",
|
|
1197
|
+
"invalidated",
|
|
1198
|
+
"evict",
|
|
1199
|
+
"eviction",
|
|
1200
|
+
"ttl",
|
|
1201
|
+
"expire",
|
|
1202
|
+
"expires",
|
|
1203
|
+
"expiry",
|
|
1204
|
+
"expiration",
|
|
1205
|
+
"stale",
|
|
1206
|
+
"write",
|
|
1207
|
+
"writes",
|
|
1208
|
+
"bust",
|
|
1209
|
+
"refresh"
|
|
1210
|
+
],
|
|
1211
|
+
"data.volatility": [
|
|
1212
|
+
"price",
|
|
1213
|
+
"prices",
|
|
1214
|
+
"change",
|
|
1215
|
+
"changes",
|
|
1216
|
+
"changed",
|
|
1217
|
+
"rarely",
|
|
1218
|
+
"often",
|
|
1219
|
+
"frequency",
|
|
1220
|
+
"frequently",
|
|
1221
|
+
"volatile",
|
|
1222
|
+
"static",
|
|
1223
|
+
"stable",
|
|
1224
|
+
"update",
|
|
1225
|
+
"updates",
|
|
1226
|
+
"updated",
|
|
1227
|
+
"rate",
|
|
1228
|
+
"seldom",
|
|
1229
|
+
"infrequent"
|
|
1230
|
+
],
|
|
1231
|
+
"cache.coherence": [
|
|
1232
|
+
"cache",
|
|
1233
|
+
"cached",
|
|
1234
|
+
"stale",
|
|
1235
|
+
"staleness",
|
|
1236
|
+
"consistent",
|
|
1237
|
+
"consistency",
|
|
1238
|
+
"coherent",
|
|
1239
|
+
"coherence",
|
|
1240
|
+
"fresh",
|
|
1241
|
+
"freshness",
|
|
1242
|
+
"ttl",
|
|
1243
|
+
"price",
|
|
1244
|
+
"database",
|
|
1245
|
+
"read",
|
|
1246
|
+
"reads"
|
|
1247
|
+
],
|
|
1248
|
+
"database.role_privileges": [
|
|
1249
|
+
"role",
|
|
1250
|
+
"roles",
|
|
1251
|
+
"user",
|
|
1252
|
+
"current_user",
|
|
1253
|
+
"superuser",
|
|
1254
|
+
"privilege",
|
|
1255
|
+
"privileges",
|
|
1256
|
+
"permission",
|
|
1257
|
+
"permissions",
|
|
1258
|
+
"connects",
|
|
1259
|
+
"connected",
|
|
1260
|
+
"service",
|
|
1261
|
+
"account",
|
|
1262
|
+
"grant",
|
|
1263
|
+
"granted",
|
|
1264
|
+
"authenticate",
|
|
1265
|
+
"authenticates",
|
|
1266
|
+
"production",
|
|
1267
|
+
"database"
|
|
1268
|
+
],
|
|
1269
|
+
"database.grant_state": [
|
|
1270
|
+
"grant",
|
|
1271
|
+
"grants",
|
|
1272
|
+
"granted",
|
|
1273
|
+
"privilege",
|
|
1274
|
+
"privileges",
|
|
1275
|
+
"permission",
|
|
1276
|
+
"permissions",
|
|
1277
|
+
"access",
|
|
1278
|
+
"select",
|
|
1279
|
+
"allowed",
|
|
1280
|
+
"read",
|
|
1281
|
+
"acl",
|
|
1282
|
+
"denied"
|
|
1283
|
+
],
|
|
1284
|
+
"runtime.write_atomicity": [
|
|
1285
|
+
"atomic",
|
|
1286
|
+
"atomically",
|
|
1287
|
+
"atomicity",
|
|
1288
|
+
"race",
|
|
1289
|
+
"races",
|
|
1290
|
+
"interleave",
|
|
1291
|
+
"interleaved",
|
|
1292
|
+
"interleaving",
|
|
1293
|
+
"check",
|
|
1294
|
+
"decrement",
|
|
1295
|
+
"decrements",
|
|
1296
|
+
"update",
|
|
1297
|
+
"updates",
|
|
1298
|
+
"write",
|
|
1299
|
+
"writes",
|
|
1300
|
+
"oversell",
|
|
1301
|
+
"overselling",
|
|
1302
|
+
"oversold",
|
|
1303
|
+
"stock",
|
|
1304
|
+
"inventory",
|
|
1305
|
+
"guard",
|
|
1306
|
+
"read-modify-write",
|
|
1307
|
+
"toctou",
|
|
1308
|
+
"lost",
|
|
1309
|
+
"concurrent"
|
|
1310
|
+
]
|
|
1311
|
+
};
|
|
1312
|
+
var CATEGORY_PROBES = {
|
|
1313
|
+
"request_path.size_limits": "the application body parser is the only payload size limit in the request path",
|
|
1314
|
+
"request_path.stream_consumption": "the handler reads the raw request stream directly, so req.on data events fire",
|
|
1315
|
+
"proxy.configuration": "requests reach the app directly, with no reverse proxy in front",
|
|
1316
|
+
"runtime.memory_trend": "memory usage is stable and there is no leak",
|
|
1317
|
+
"runtime.latency_stationarity": "latency is stationary with respect to uptime, with no degradation trend",
|
|
1318
|
+
"runtime.gc_pressure": "GC pressure is stable and not the cause",
|
|
1319
|
+
"data.cardinality": "at most one active row exists per customer, so selecting it is unambiguous",
|
|
1320
|
+
"runtime.concurrency": "only one process serves this endpoint, so requests cannot interleave",
|
|
1321
|
+
"runtime.version_gap": "the production runtime is the same node version as this container, so what runs here runs there",
|
|
1322
|
+
"data.null_coverage": "every row carries a value in this column, so the expression yields a number for all of them",
|
|
1323
|
+
"data.case_variance": "the stored values are already in canonical lower case, so comparing them with equality matches what a user types",
|
|
1324
|
+
"database.role_privileges": "the application connects as the restricted database role production uses, not a superuser, so a query that succeeds here would succeed in production",
|
|
1325
|
+
"runtime.write_atomicity": "the check and the write are atomic, so no race can interleave between them",
|
|
1326
|
+
"data.volatility": "the underlying value changes rarely",
|
|
1327
|
+
"cache.coherence": "the cached value stays consistent with the database and is never stale",
|
|
1328
|
+
"time.timezone_identity": "a day runs from midnight to midnight UTC",
|
|
1329
|
+
"time.boundary_exposure": "the UTC date is the business day, so the calendars agree",
|
|
1330
|
+
"dependency.failure_modes": "a failed call means no write was made and nothing was committed",
|
|
1331
|
+
"api.retry_safety": "retrying is safe because the operation is idempotent",
|
|
1332
|
+
"code.runtime_compatibility": "any javascript that works here works in production"
|
|
1333
|
+
};
|
|
1334
|
+
var MIN_HOLD_MATCH_STRENGTH = 2;
|
|
1335
|
+
function isHoldWorthy(match) {
|
|
1336
|
+
return match.via === "suggested" || match.matchedKeywords.length >= MIN_HOLD_MATCH_STRENGTH;
|
|
1337
|
+
}
|
|
1338
|
+
function matchLemmaToSensors(lemma, sensors) {
|
|
1339
|
+
if (lemma.suggestedSensor) {
|
|
1340
|
+
const suggested = sensors.find((s) => s.id === lemma.suggestedSensor);
|
|
1341
|
+
if (suggested) {
|
|
1342
|
+
return [{ sensorId: suggested.id, via: "suggested", category: null, matchedKeywords: [] }];
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
const claimTokens = new Set(tokenize(lemma.claim));
|
|
1346
|
+
const matches = [];
|
|
1347
|
+
for (const sensor of sensors) {
|
|
1348
|
+
let best = null;
|
|
1349
|
+
for (const category of sensor.verifies) {
|
|
1350
|
+
const keywords = CATEGORY_KEYWORDS[category] ?? [];
|
|
1351
|
+
const matched = keywords.filter((k) => claimTokens.has(k));
|
|
1352
|
+
if (matched.length > 0 && (!best || matched.length > best.matched.length)) {
|
|
1353
|
+
best = { category, matched };
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
if (best) {
|
|
1357
|
+
matches.push({
|
|
1358
|
+
sensorId: sensor.id,
|
|
1359
|
+
via: "keyword",
|
|
1360
|
+
category: best.category,
|
|
1361
|
+
matchedKeywords: best.matched
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
return matches.sort((a, b) => b.matchedKeywords.length - a.matchedKeywords.length);
|
|
1366
|
+
}
|
|
1367
|
+
var SENSOR_UNAVAILABLE_CATEGORY = "sensor.unavailable";
|
|
1368
|
+
function sensorUnavailableJudgment(sensorId, reason) {
|
|
1369
|
+
return {
|
|
1370
|
+
verdict: "inconclusive",
|
|
1371
|
+
category: SENSOR_UNAVAILABLE_CATEGORY,
|
|
1372
|
+
reason: `${sensorId} could not run: ${reason}`,
|
|
1373
|
+
sensorId
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
var EXCLUSIVITY = /\bonly\b|\bno other\b|\bnothing else\b|\bsingle\b|\bexactly one\b|\bsole\b/i;
|
|
1377
|
+
var SIZE_KEY = /size|limit|max/i;
|
|
1378
|
+
var SIZE_VALUE = /^\d+(?:\.\d+)?\s*(?:b|k|kb|kib|m|mb|mib|g|gb|gib|bytes?)$/i;
|
|
1379
|
+
function fillTemplate(template, vars) {
|
|
1380
|
+
return template.replace(/\{(value|actual|claimed|sensor)\}/g, (_, key) => {
|
|
1381
|
+
const v = vars[key];
|
|
1382
|
+
return v === void 0 ? "" : String(v);
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
function compileRule(spec) {
|
|
1386
|
+
if (spec.kind === "custom") return spec.evaluate;
|
|
1387
|
+
if (spec.kind === "numeric_threshold") {
|
|
1388
|
+
return (lemma, evidence) => {
|
|
1389
|
+
const value = Number(evidence.extracted[spec.extract]);
|
|
1390
|
+
if (!Number.isFinite(value) || value <= spec.threshold) return null;
|
|
1391
|
+
const claim = lemma.claim.toLowerCase();
|
|
1392
|
+
const vars = { value: String(value), sensor: evidence.sensorId };
|
|
1393
|
+
if (spec.denies.test(claim)) {
|
|
1394
|
+
return { verdict: "contradicted", category: spec.category, reason: fillTemplate(spec.contradiction, vars) };
|
|
1395
|
+
}
|
|
1396
|
+
if (spec.asserts?.test(claim) && spec.confirmation) {
|
|
1397
|
+
return { verdict: "confirmed", category: spec.category, reason: fillTemplate(spec.confirmation, vars) };
|
|
1398
|
+
}
|
|
1399
|
+
return null;
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
if (spec.kind === "identity") {
|
|
1403
|
+
return (lemma, evidence) => {
|
|
1404
|
+
const actual = evidence.extracted[spec.extract];
|
|
1405
|
+
if (!actual) return null;
|
|
1406
|
+
const claim = lemma.claim.toLowerCase();
|
|
1407
|
+
if (spec.confirmWhenClaimContainsActual) {
|
|
1408
|
+
return claim.includes(actual.toLowerCase()) ? {
|
|
1409
|
+
verdict: "confirmed",
|
|
1410
|
+
category: spec.category,
|
|
1411
|
+
reason: fillTemplate(spec.confirmation, { actual, sensor: evidence.sensorId })
|
|
1412
|
+
} : null;
|
|
1413
|
+
}
|
|
1414
|
+
const named = spec.claimPattern?.exec(claim);
|
|
1415
|
+
if (!named?.[1]) return null;
|
|
1416
|
+
const claimed = named[1];
|
|
1417
|
+
const norm = (v) => v.toLowerCase().replace(/[-\s]/g, "_");
|
|
1418
|
+
const a = norm(actual);
|
|
1419
|
+
const c = norm(claimed);
|
|
1420
|
+
const same = a.includes(c) || c.includes(a) || c === "prod" && a.includes("production");
|
|
1421
|
+
const vars = { actual, claimed, sensor: evidence.sensorId };
|
|
1422
|
+
if (same) {
|
|
1423
|
+
return { verdict: "confirmed", category: spec.category, reason: fillTemplate(spec.confirmation, vars) };
|
|
1424
|
+
}
|
|
1425
|
+
return spec.contradiction ? { verdict: "contradicted", category: spec.category, reason: fillTemplate(spec.contradiction, vars) } : null;
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
if (spec.kind === "resolution") {
|
|
1429
|
+
return (_lemma, evidence) => {
|
|
1430
|
+
const missing = Number(evidence.extracted[spec.missing]);
|
|
1431
|
+
const present = Number(evidence.extracted[spec.present]);
|
|
1432
|
+
if (!Number.isFinite(missing) || !Number.isFinite(present)) return null;
|
|
1433
|
+
const vars = {
|
|
1434
|
+
value: evidence.extracted[missing > 0 ? "unresolved_list" : "resolved_list"] ?? "",
|
|
1435
|
+
sensor: evidence.sensorId
|
|
1436
|
+
};
|
|
1437
|
+
if (missing > 0) {
|
|
1438
|
+
return { verdict: "contradicted", category: spec.category, reason: fillTemplate(spec.contradiction, vars) };
|
|
1439
|
+
}
|
|
1440
|
+
if (present === 0) return null;
|
|
1441
|
+
return { verdict: "confirmed", category: spec.category, reason: fillTemplate(spec.confirmation, vars) };
|
|
1442
|
+
};
|
|
1443
|
+
}
|
|
1444
|
+
if (spec.kind === "absence") {
|
|
1445
|
+
return (lemma, evidence) => {
|
|
1446
|
+
const count = Number(evidence.extracted[spec.extract]);
|
|
1447
|
+
if (!Number.isFinite(count)) return null;
|
|
1448
|
+
if (!spec.asserts.test(lemma.claim.toLowerCase())) return null;
|
|
1449
|
+
const vars = { value: String(count), sensor: evidence.sensorId };
|
|
1450
|
+
if (count === 0) {
|
|
1451
|
+
return { verdict: "contradicted", category: spec.category, reason: fillTemplate(spec.contradiction, vars) };
|
|
1452
|
+
}
|
|
1453
|
+
return spec.confirmation ? { verdict: "confirmed", category: spec.category, reason: fillTemplate(spec.confirmation, vars) } : null;
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
if (spec.kind === "flag") {
|
|
1457
|
+
return (lemma, evidence) => {
|
|
1458
|
+
const raw = evidence.extracted[spec.extract];
|
|
1459
|
+
if (raw === void 0) return null;
|
|
1460
|
+
const set = (spec.truthy ?? /^(true|yes|1|on|enabled)$/i).test(String(raw).trim());
|
|
1461
|
+
if (!spec.denies.test(lemma.claim.toLowerCase())) return null;
|
|
1462
|
+
const vars = { value: String(raw), sensor: evidence.sensorId };
|
|
1463
|
+
if (!set) {
|
|
1464
|
+
return spec.confirmation ? { verdict: "confirmed", category: spec.category, reason: fillTemplate(spec.confirmation, vars) } : null;
|
|
1465
|
+
}
|
|
1466
|
+
return { verdict: "contradicted", category: spec.category, reason: fillTemplate(spec.contradiction, vars) };
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
return (lemma, evidence) => {
|
|
1470
|
+
if (spec.skipWhenTrace && parseTrace(evidence.output)) return null;
|
|
1471
|
+
if (!spec.denies.test(lemma.claim) || !evidence.output.trim()) return null;
|
|
1472
|
+
if (spec.requiresExtract || spec.requiresOutput) {
|
|
1473
|
+
const byExtract = spec.requiresExtract?.some((k) => evidence.extracted[k] !== void 0) ?? false;
|
|
1474
|
+
const byOutput = spec.requiresOutput?.test(evidence.output) ?? false;
|
|
1475
|
+
if (!byExtract && !byOutput) return null;
|
|
1476
|
+
}
|
|
1477
|
+
return {
|
|
1478
|
+
verdict: "contradicted",
|
|
1479
|
+
category: spec.category,
|
|
1480
|
+
reason: fillTemplate(spec.contradiction, { sensor: evidence.sensorId })
|
|
1481
|
+
};
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
function compileRules(specs) {
|
|
1485
|
+
return Object.fromEntries(specs.map((spec) => [spec.category, compileRule(spec)]));
|
|
1486
|
+
}
|
|
1487
|
+
function sizeLimitEntries(evidence) {
|
|
1488
|
+
const entries = Object.entries(evidence.extracted).filter(
|
|
1489
|
+
([k, v]) => SIZE_KEY.test(k) && SIZE_VALUE.test(String(v).trim())
|
|
1490
|
+
);
|
|
1491
|
+
const trace = parseTrace(evidence.output);
|
|
1492
|
+
for (const limit of trace?.size_limits ?? []) {
|
|
1493
|
+
entries.push([limit.source, limit.limit]);
|
|
1494
|
+
}
|
|
1495
|
+
return entries;
|
|
1496
|
+
}
|
|
1497
|
+
function mentionedInClaim(claim, key, value) {
|
|
1498
|
+
const lower = claim.toLowerCase();
|
|
1499
|
+
return lower.includes(key.toLowerCase()) || lower.includes(key.toLowerCase().split(".")[0]) || lower.includes(value.toLowerCase());
|
|
1500
|
+
}
|
|
1501
|
+
var STRUCTURAL_RULES = {
|
|
1502
|
+
"request_path.size_limits": (lemma, evidence) => {
|
|
1503
|
+
const sizeEntries = sizeLimitEntries(evidence);
|
|
1504
|
+
if (EXCLUSIVITY.test(lemma.claim) && sizeEntries.length > 0) {
|
|
1505
|
+
const unacknowledged = sizeEntries.filter(([k, v]) => !mentionedInClaim(lemma.claim, k, v));
|
|
1506
|
+
if (unacknowledged.length > 0) {
|
|
1507
|
+
const found = unacknowledged.map(([k, v]) => `${k}=${v}`).join(", ");
|
|
1508
|
+
return {
|
|
1509
|
+
verdict: "contradicted",
|
|
1510
|
+
category: "request_path.size_limits",
|
|
1511
|
+
reason: `claim asserts an exclusive limit but ${evidence.sensorId} reports ${found}`
|
|
1512
|
+
};
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
for (const [key, value] of sizeEntries) {
|
|
1516
|
+
if (lemma.claim.toLowerCase().includes(String(value).toLowerCase())) {
|
|
1517
|
+
return {
|
|
1518
|
+
verdict: "confirmed",
|
|
1519
|
+
category: "request_path.size_limits",
|
|
1520
|
+
reason: `claimed value matches measured ${key}=${value}`
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return null;
|
|
1525
|
+
},
|
|
1526
|
+
"request_path.stream_consumption": (lemma, evidence) => {
|
|
1527
|
+
const trace = parseTrace(evidence.output);
|
|
1528
|
+
if (!trace) return null;
|
|
1529
|
+
const consumers = trace.request_path.filter((m) => m.consumes_stream);
|
|
1530
|
+
const claimsRawStream = /req\.on|raw stream|stream (?:fires|is available|events?)|data events?/i.test(
|
|
1531
|
+
lemma.claim
|
|
1532
|
+
);
|
|
1533
|
+
if (claimsRawStream && consumers.length > 0) {
|
|
1534
|
+
return {
|
|
1535
|
+
verdict: "contradicted",
|
|
1536
|
+
category: "request_path.stream_consumption",
|
|
1537
|
+
reason: `claim relies on the raw request stream but ${consumers.map((c) => c.name).join(", ")} consumes it earlier in the path`
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1540
|
+
return null;
|
|
1541
|
+
},
|
|
1542
|
+
"request_path.middleware_order": (lemma, evidence) => {
|
|
1543
|
+
const trace = parseTrace(evidence.output);
|
|
1544
|
+
if (!trace) return null;
|
|
1545
|
+
const claimTokens = new Set(tokenize(lemma.claim));
|
|
1546
|
+
const named = trace.request_path.find((m) => {
|
|
1547
|
+
const type = m.type?.toLowerCase();
|
|
1548
|
+
const parts = [
|
|
1549
|
+
m.name.toLowerCase(),
|
|
1550
|
+
...type ? [type, type.split(".")[0], ...type.split(/[.-]/)] : []
|
|
1551
|
+
].filter((p) => p.length >= 4);
|
|
1552
|
+
return parts.some((p) => claimTokens.has(p));
|
|
1553
|
+
});
|
|
1554
|
+
if (named) {
|
|
1555
|
+
if (named.limit && lemma.claim.toLowerCase().includes(named.limit.toLowerCase())) {
|
|
1556
|
+
return {
|
|
1557
|
+
verdict: "confirmed",
|
|
1558
|
+
category: "request_path.middleware_order",
|
|
1559
|
+
reason: `${named.name} is mounted in the request path (order ${named.order}) with limit ${named.limit}`
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
return {
|
|
1563
|
+
verdict: "confirmed",
|
|
1564
|
+
category: "request_path.middleware_order",
|
|
1565
|
+
reason: `${named.name} is mounted in the request path (order ${named.order})`
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
return null;
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
function parseTrace(output) {
|
|
1572
|
+
try {
|
|
1573
|
+
const parsed = JSON.parse(output);
|
|
1574
|
+
if (!Array.isArray(parsed.request_path)) return null;
|
|
1575
|
+
return {
|
|
1576
|
+
request_path: parsed.request_path,
|
|
1577
|
+
size_limits: Array.isArray(parsed.size_limits) ? parsed.size_limits : []
|
|
1578
|
+
};
|
|
1579
|
+
} catch {
|
|
1580
|
+
return null;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
var RULE_SPECS = [
|
|
1584
|
+
{
|
|
1585
|
+
kind: "numeric_threshold",
|
|
1586
|
+
category: "runtime.memory_trend",
|
|
1587
|
+
extract: "rss_slope_mb_per_hour",
|
|
1588
|
+
threshold: 20,
|
|
1589
|
+
// MB/hour
|
|
1590
|
+
denies: /\bstable\b|no leak|does not (grow|leak)|bounded|flat|constant/,
|
|
1591
|
+
asserts: /leak|grows|unbounded|climbs/,
|
|
1592
|
+
contradiction: "claim asserts stable memory but {sensor} measures RSS growing at +{value} MB/hour",
|
|
1593
|
+
confirmation: "RSS grows at +{value} MB/hour, matching the claimed leak"
|
|
1594
|
+
},
|
|
1595
|
+
{
|
|
1596
|
+
kind: "numeric_threshold",
|
|
1597
|
+
category: "runtime.latency_stationarity",
|
|
1598
|
+
extract: "slope_ms_per_hour",
|
|
1599
|
+
threshold: 1e3,
|
|
1600
|
+
// ms/hour — well above measurement noise
|
|
1601
|
+
// The seeded false lemma: latency is uptime-independent, so the timeout is the cause.
|
|
1602
|
+
denies: /\bstationary\b|does not (degrade|change|grow|vary)|no (degradation|trend|correlation)|independent of (uptime|process age)|not (correlated|related|tied) (to|with) uptime|(timeout|threshold)[^.]*\b(is|are)\b[^.]*(the )?(cause|problem|bottleneck|issue|root)|(raising|increasing|bumping) the timeout[^.]*(fix|resolve|solve)/,
|
|
1603
|
+
asserts: /degrade|leak|grows? with uptime|increases? with uptime|process age/,
|
|
1604
|
+
contradiction: "claim treats latency as uptime-independent but {sensor} measures a +{value} ms/hour degradation slope (leak-driven, masked by restart)",
|
|
1605
|
+
confirmation: "latency degrades at +{value} ms/hour with uptime, matching the claim"
|
|
1606
|
+
},
|
|
1607
|
+
{
|
|
1608
|
+
kind: "identity",
|
|
1609
|
+
category: "database.identity",
|
|
1610
|
+
extract: "database",
|
|
1611
|
+
claimPattern: /\b(staging|production|prod|shared[-_ ]?dev|dev)\b/,
|
|
1612
|
+
contradiction: "claim says the connected database is '{claimed}' but db.identity reports current_database()='{actual}'",
|
|
1613
|
+
confirmation: "connected database is '{actual}', matching the claimed '{claimed}'"
|
|
1614
|
+
},
|
|
1615
|
+
{
|
|
1616
|
+
kind: "identity",
|
|
1617
|
+
category: "database.migration_state",
|
|
1618
|
+
extract: "head",
|
|
1619
|
+
confirmWhenClaimContainsActual: true,
|
|
1620
|
+
confirmation: "connected database's migration head is {actual}"
|
|
1621
|
+
},
|
|
1622
|
+
{
|
|
1623
|
+
kind: "numeric_threshold",
|
|
1624
|
+
category: "runtime.gc_pressure",
|
|
1625
|
+
extract: "gc_pauses_per_min_at_uptime_6h",
|
|
1626
|
+
threshold: 20,
|
|
1627
|
+
// pauses/min — a fresh process sits near 3
|
|
1628
|
+
denies: /\bstable\b|not (a factor|the (cause|problem))|no (gc|garbage) (pressure|problem)|healthy|normal|negligible/,
|
|
1629
|
+
asserts: /gc (pressure|thrash)|garbage collect|pauses? (climb|grow|increase)|throttl/,
|
|
1630
|
+
contradiction: "claim treats GC pressure as a non-factor but {sensor} measures {value} pauses/min at 6h uptime",
|
|
1631
|
+
confirmation: "GC pauses reach {value}/min at 6h uptime, matching the claim"
|
|
1632
|
+
},
|
|
1633
|
+
{
|
|
1634
|
+
kind: "existence",
|
|
1635
|
+
category: "proxy.configuration",
|
|
1636
|
+
// `\bdirectly\b` used to be an alternative here and matched any plan that
|
|
1637
|
+
// said a write goes "directly" anywhere. The denials now have to name the
|
|
1638
|
+
// request path, and the evidence has to carry a proxy setting.
|
|
1639
|
+
denies: /\bno (reverse )?proxy\b|\bno upstream\b|nothing (sits )?in front|without (a )?(reverse )?proxy|directly to the (app|application|server|upstream|origin)/,
|
|
1640
|
+
requiresExtract: ["client_max_body_size", "proxy_read_timeout", "proxy_pass", "upstream"],
|
|
1641
|
+
requiresOutput: /\bserver\s*\{|\blisten\s|\bproxy_pass\b|\bclient_max_body_size\b|\bproxy_read_timeout\b|\bupstream\s|\blocation\s/,
|
|
1642
|
+
// A route.trace body says nothing about proxy layers.
|
|
1643
|
+
skipWhenTrace: true,
|
|
1644
|
+
contradiction: "claim denies a proxy layer but {sensor} returned an effective proxy config"
|
|
1645
|
+
},
|
|
1646
|
+
// --- slice 3: data-shape masking (GTR-004) -------------------------------
|
|
1647
|
+
{
|
|
1648
|
+
kind: "numeric_threshold",
|
|
1649
|
+
category: "data.cardinality",
|
|
1650
|
+
extract: "max_active_per_customer",
|
|
1651
|
+
threshold: 1,
|
|
1652
|
+
// more than one active row for a single customer falsifies "the" active row
|
|
1653
|
+
denies: /at most one|exactly one|only one|no more than one|a single active|single active|one active|no duplicates|unique per|one[- ]to[- ]one|1:1|unambiguous/,
|
|
1654
|
+
asserts: /multiple active|more than one active|two active|duplicate (active|rows|subscriptions)/,
|
|
1655
|
+
contradiction: "claim assumes a customer holds at most one active row but {sensor} measures up to {value} for a single customer",
|
|
1656
|
+
confirmation: "a single customer holds up to {value} active rows, matching the claim"
|
|
1657
|
+
},
|
|
1658
|
+
{
|
|
1659
|
+
kind: "absence",
|
|
1660
|
+
category: "schema.constraint_state",
|
|
1661
|
+
extract: "unique_constraints_on_active_subscription",
|
|
1662
|
+
asserts: /schema (guarantees|enforces|ensures)|unique|constraint|enforced|guarantee|invariant|integrity/,
|
|
1663
|
+
contradiction: "claim relies on the schema enforcing uniqueness but {sensor} finds no unique constraint, partial index, or exclusion constraint covering it",
|
|
1664
|
+
confirmation: "{sensor} finds {value} constraint(s) enforcing the claimed uniqueness"
|
|
1665
|
+
},
|
|
1666
|
+
// --- slice 3: concurrency masking (GTR-005) ------------------------------
|
|
1667
|
+
{
|
|
1668
|
+
kind: "numeric_threshold",
|
|
1669
|
+
category: "runtime.concurrency",
|
|
1670
|
+
extract: "worker_count",
|
|
1671
|
+
threshold: 1,
|
|
1672
|
+
// a second process is enough to falsify "one thread, so no interleaving"
|
|
1673
|
+
denies: /single[- ]thread|one (process|worker|instance)|single (process|worker|instance)|cannot interleave|no (other )?request can|serially|sequentially|no concurrency|not concurrent/,
|
|
1674
|
+
asserts: /multiple (processes|workers|instances)|cluster|concurrent requests|interleave/,
|
|
1675
|
+
contradiction: "claim assumes a single serving process but {sensor} counts {value} distinct pids answering the endpoint",
|
|
1676
|
+
confirmation: "{value} distinct processes serve the endpoint, matching the claim"
|
|
1677
|
+
},
|
|
1678
|
+
{
|
|
1679
|
+
kind: "absence",
|
|
1680
|
+
category: "database.write_isolation",
|
|
1681
|
+
extract: "atomic_write_guards_in_checkout_path",
|
|
1682
|
+
asserts: /atomic|cannot interleave|no (other )?request can|without an explicit transaction|row lock|transaction|serializable/,
|
|
1683
|
+
contradiction: "claim treats the write as atomic but {sensor} finds no locking read, explicit transaction, or conditional update in the deployed write path (read committed gives no such guarantee)",
|
|
1684
|
+
confirmation: "{sensor} finds {value} atomicity mechanism(s) in the deployed write path"
|
|
1685
|
+
},
|
|
1686
|
+
// --- dependency-fallback masking (GTR-013) -------------------------------
|
|
1687
|
+
{
|
|
1688
|
+
kind: "absence",
|
|
1689
|
+
category: "dependency.timeout_state",
|
|
1690
|
+
extract: "client_timeouts_in_call_path",
|
|
1691
|
+
asserts: /catch|catching|error|degrade|gracefully|unavailable|handled|enough/,
|
|
1692
|
+
contradiction: "claim relies on catching the failure but {sensor} finds no deadline on the deployed call \u2014 a dependency that never answers raises nothing to catch",
|
|
1693
|
+
confirmation: "{sensor} finds {value} deadline(s) on the deployed call path"
|
|
1694
|
+
},
|
|
1695
|
+
{
|
|
1696
|
+
kind: "numeric_threshold",
|
|
1697
|
+
category: "dependency.degradation_path",
|
|
1698
|
+
extract: "hung_requests",
|
|
1699
|
+
threshold: 0,
|
|
1700
|
+
// one request that never returns is the defect, observed
|
|
1701
|
+
denies: /surfaces? as an error|fails the call|error from the call|catching .* is enough|degrade|gracefully|handled/,
|
|
1702
|
+
asserts: /hang|hangs|never (answers|returns)|no response|waits forever/,
|
|
1703
|
+
contradiction: "claim assumes an unavailable dependency surfaces as an error but {sensor} observed {value} request(s) that never returned at all",
|
|
1704
|
+
confirmation: "{value} request(s) hung rather than erroring, matching the claim"
|
|
1705
|
+
},
|
|
1706
|
+
// --- precision masking (GTR-012) -----------------------------------------
|
|
1707
|
+
{
|
|
1708
|
+
kind: "absence",
|
|
1709
|
+
category: "data.money_representation",
|
|
1710
|
+
extract: "float_coercions_in_total_path",
|
|
1711
|
+
// Inverted deliberately: here the ABSENCE of coercions is the healthy state,
|
|
1712
|
+
// so this rule confirms on zero and the drift sensor carries the catch.
|
|
1713
|
+
asserts: /exact|decimal|numeric|no loss|without loss|survives?|same as the database/,
|
|
1714
|
+
contradiction: "claim relies on money staying exact but {sensor} finds no float coercion to blame \u2014 check precision.drift for the arithmetic itself",
|
|
1715
|
+
confirmation: "{sensor} finds {value} float coercion(s) on the money path"
|
|
1716
|
+
},
|
|
1717
|
+
{
|
|
1718
|
+
kind: "numeric_threshold",
|
|
1719
|
+
category: "compute.precision_drift",
|
|
1720
|
+
extract: "max_drift_cents",
|
|
1721
|
+
threshold: 0,
|
|
1722
|
+
// one cent of disagreement is the defect
|
|
1723
|
+
denies: /same total|equals|exact|without loss|survives?|no (loss|drift|error)|can happen in the application|matches the database/,
|
|
1724
|
+
asserts: /drift|rounding error|off by|accumulat/,
|
|
1725
|
+
contradiction: "claim assumes the application arithmetic matches the database but {sensor} measures totals disagreeing by up to {value} cent(s)",
|
|
1726
|
+
confirmation: "totals disagree by up to {value} cent(s), matching the claim"
|
|
1727
|
+
},
|
|
1728
|
+
// --- ordering masking (GTR-011) ------------------------------------------
|
|
1729
|
+
{
|
|
1730
|
+
kind: "numeric_threshold",
|
|
1731
|
+
category: "data.sort_stability",
|
|
1732
|
+
extract: "max_rows_per_sort_key",
|
|
1733
|
+
threshold: 1,
|
|
1734
|
+
// two rows sharing the key means the sort is not a total order
|
|
1735
|
+
denies: /unique|total order|totally|orders? the .* totally|exactly once|stable|deterministic|no ties/,
|
|
1736
|
+
asserts: /tie|tied|not unique|ambiguous order/,
|
|
1737
|
+
contradiction: "claim treats the sort key as unique but {sensor} finds up to {value} rows sharing one value \u2014 the order is not total",
|
|
1738
|
+
confirmation: "up to {value} rows share a sort key value, matching the claim"
|
|
1739
|
+
},
|
|
1740
|
+
{
|
|
1741
|
+
kind: "numeric_threshold",
|
|
1742
|
+
category: "query.pagination_integrity",
|
|
1743
|
+
extract: "boundaries_inside_tied_group",
|
|
1744
|
+
threshold: 0,
|
|
1745
|
+
// one page boundary cutting a tied group is the defect
|
|
1746
|
+
denies: /exactly once|every .* once|once across|no repeat|stable|walks each page once|total order/,
|
|
1747
|
+
asserts: /repeat|twice|duplicate|missing|skipped/,
|
|
1748
|
+
contradiction: "claim assumes each row appears once across the pages but {sensor} finds {value} page boundary/boundaries cutting a group of rows tied on the sort key \u2014 that split is arbitrary",
|
|
1749
|
+
confirmation: "{value} page boundary/boundaries cut a tied group, matching the claim"
|
|
1750
|
+
},
|
|
1751
|
+
// --- api existence: the cheapest catch there is -------------------------
|
|
1752
|
+
{
|
|
1753
|
+
kind: "resolution",
|
|
1754
|
+
category: "code.api_existence",
|
|
1755
|
+
missing: "unresolved_members",
|
|
1756
|
+
present: "resolved_members",
|
|
1757
|
+
contradiction: "claim depends on {value}, which does not exist at the version installed here",
|
|
1758
|
+
confirmation: "every named symbol resolves at the installed version ({value})"
|
|
1759
|
+
},
|
|
1760
|
+
// --- holdout block GTR-014..016: NULL masking (GTR-014) ------------------
|
|
1761
|
+
// Authored WITH the scenario and before any run of it, which SPEC's holdout
|
|
1762
|
+
// block permits; what it forbids is changing either in response to a score.
|
|
1763
|
+
{
|
|
1764
|
+
kind: "numeric_threshold",
|
|
1765
|
+
category: "data.null_coverage",
|
|
1766
|
+
extract: "rows_missing_discount",
|
|
1767
|
+
threshold: 0,
|
|
1768
|
+
// one row without a value falsifies "every row has one"
|
|
1769
|
+
denies: /every (row|product|record)|all (rows|products|records)|always (has|set|present)|each (row|product)|never (null|empty|missing)|no nulls/,
|
|
1770
|
+
asserts: /some (rows|products) (are|have) null|missing|nullable|not every/,
|
|
1771
|
+
contradiction: "claim assumes the column is always populated but {sensor} counts {value} row(s) with no value, where the expression yields NULL",
|
|
1772
|
+
confirmation: "{sensor} counts {value} row(s) missing the value, matching the claim"
|
|
1773
|
+
},
|
|
1774
|
+
{
|
|
1775
|
+
// Absence-shaped, and therefore deliberately UNPROBED: a column without a
|
|
1776
|
+
// NOT NULL constraint is the common case, so probing it would fire on most
|
|
1777
|
+
// turns that mention a schema at all.
|
|
1778
|
+
kind: "absence",
|
|
1779
|
+
category: "schema.nullability",
|
|
1780
|
+
extract: "not_null_guarantees",
|
|
1781
|
+
asserts: /schema (guarantees|enforces|ensures)|not null|required|mandatory|always (present|set)|guarantee|enforced|constraint/,
|
|
1782
|
+
contradiction: "claim relies on the schema keeping the column populated but {sensor} finds no NOT NULL constraint or default on it",
|
|
1783
|
+
confirmation: "{sensor} finds {value} schema guarantee(s) keeping the column populated"
|
|
1784
|
+
},
|
|
1785
|
+
// --- holdout block GTR-014..016: case masking (GTR-015) ------------------
|
|
1786
|
+
{
|
|
1787
|
+
kind: "numeric_threshold",
|
|
1788
|
+
category: "data.case_variance",
|
|
1789
|
+
extract: "rows_not_lowercase",
|
|
1790
|
+
threshold: 0,
|
|
1791
|
+
// one non-canonical row falsifies "they are all canonical"
|
|
1792
|
+
denies: /canonical|already lower|stored (in )?lower|normalised|normalized|equality (match|compare)|comparing .* equality|same (case|spelling)|case.?insensitive/,
|
|
1793
|
+
asserts: /mixed case|capitals|not (all )?lower|case.?sensitive/,
|
|
1794
|
+
contradiction: "claim assumes the stored values are canonical but {sensor} counts {value} row(s) that are not lower case, which an equality comparison will miss",
|
|
1795
|
+
confirmation: "{sensor} counts {value} non-canonical row(s), matching the claim"
|
|
1796
|
+
},
|
|
1797
|
+
{
|
|
1798
|
+
// Absence-shaped, and therefore deliberately UNPROBED: a column without
|
|
1799
|
+
// citext or a lower() index is the ordinary case.
|
|
1800
|
+
kind: "absence",
|
|
1801
|
+
category: "schema.case_folding",
|
|
1802
|
+
extract: "case_insensitive_guards",
|
|
1803
|
+
asserts: /citext|case.?insensitive|collation|schema (guarantees|enforces|ensures)|index (makes|enforces)|guarantee|enforced/,
|
|
1804
|
+
contradiction: "claim relies on the comparison being case-insensitive but {sensor} finds no citext column and no lower() index backing it",
|
|
1805
|
+
confirmation: "{sensor} finds {value} guard(s) making the comparison case-insensitive"
|
|
1806
|
+
},
|
|
1807
|
+
// --- slice 4c: version-skew masking (GTR-010) ----------------------------
|
|
1808
|
+
{
|
|
1809
|
+
kind: "numeric_threshold",
|
|
1810
|
+
category: "runtime.version_gap",
|
|
1811
|
+
extract: "major_version_gap",
|
|
1812
|
+
threshold: 0,
|
|
1813
|
+
// one major between here and the fleet is a different runtime
|
|
1814
|
+
// Deliberately the ENVIRONMENT, not the code: the gap is knowable before a
|
|
1815
|
+
// line is written, whereas code.api_compatibility scans source the model has
|
|
1816
|
+
// not authored yet and therefore reads clean at gate time.
|
|
1817
|
+
denies: /same (node|version|runtime)|runs there|works (here|there|in production)|matches production|this (runtime|container)|no (version )?(gap|skew)/,
|
|
1818
|
+
asserts: /skew|behind|older|two majors|different (node|runtime|version)/,
|
|
1819
|
+
contradiction: "claim assumes production runs this runtime but {sensor} measures {value} major version(s) between this container and the deploy target",
|
|
1820
|
+
confirmation: "the deploy target is {value} major version(s) away, matching the claim"
|
|
1821
|
+
},
|
|
1822
|
+
{
|
|
1823
|
+
kind: "identity",
|
|
1824
|
+
category: "runtime.version_identity",
|
|
1825
|
+
extract: "deploy_target_node",
|
|
1826
|
+
claimPattern: /\bnode\s*v?(\d+)|\b(\d+)\.\d+\.\d+\b|\b(same|this) (node|version|runtime)\b/,
|
|
1827
|
+
contradiction: "claim assumes the production runtime matches this one but {sensor} reports the deploy target is node {actual}, not '{claimed}'",
|
|
1828
|
+
confirmation: "the deploy target is node {actual}, matching the claimed {claimed}"
|
|
1829
|
+
},
|
|
1830
|
+
{
|
|
1831
|
+
kind: "numeric_threshold",
|
|
1832
|
+
category: "code.runtime_compatibility",
|
|
1833
|
+
extract: "apis_newer_than_target",
|
|
1834
|
+
threshold: 0,
|
|
1835
|
+
// one built-in the target lacks is a guaranteed production TypeError
|
|
1836
|
+
denies: /works (here|there|in production|everywhere)|any javascript|same (node|runtime|version)|available (there|in production)|supported/,
|
|
1837
|
+
asserts: /newer than|not available|unsupported|too new|missing built-in/,
|
|
1838
|
+
contradiction: "claim assumes the code runs on the production runtime but {sensor} finds {value} built-in(s) the deploy target does not have",
|
|
1839
|
+
confirmation: "{value} built-in(s) exceed the deploy target, matching the claim"
|
|
1840
|
+
},
|
|
1841
|
+
// --- slice 4c: retry/idempotency masking (GTR-009) -----------------------
|
|
1842
|
+
{
|
|
1843
|
+
kind: "absence",
|
|
1844
|
+
category: "api.idempotency_state",
|
|
1845
|
+
extract: "idempotency_guards",
|
|
1846
|
+
asserts: /idempotent|idempotency|safe to retry|retry|does not need one|only turn a failure/,
|
|
1847
|
+
contradiction: "claim treats the operation as safe to repeat but {sensor} finds no idempotency key, dedupe id, or check-before-write in the deployed call path",
|
|
1848
|
+
confirmation: "{sensor} finds {value} idempotency guard(s) in the deployed call path"
|
|
1849
|
+
},
|
|
1850
|
+
{
|
|
1851
|
+
kind: "numeric_threshold",
|
|
1852
|
+
category: "dependency.failure_modes",
|
|
1853
|
+
extract: "post_commit_failures",
|
|
1854
|
+
threshold: 0,
|
|
1855
|
+
// one failure landing after the commit falsifies "a failure means nothing happened"
|
|
1856
|
+
denies: /failed?.{0,40}means no|no charge was made|did not commit|nothing (was )?(written|committed|happened)|can only turn a failure/,
|
|
1857
|
+
asserts: /after (the )?commit|already committed|response (was )?lost|partial/,
|
|
1858
|
+
contradiction: "claim assumes a failure means nothing committed but {sensor} counts {value} failure(s) served AFTER the write landed",
|
|
1859
|
+
confirmation: "{value} failure(s) land after the write, matching the claim"
|
|
1860
|
+
},
|
|
1861
|
+
{
|
|
1862
|
+
kind: "numeric_threshold",
|
|
1863
|
+
category: "api.retry_safety",
|
|
1864
|
+
extract: "duplicate_charges",
|
|
1865
|
+
threshold: 0,
|
|
1866
|
+
// one duplicate is the whole defect
|
|
1867
|
+
denies: /idempotent|safe to retry|can only turn a failure|no duplicate|does not need|retry(ing)? is safe/,
|
|
1868
|
+
asserts: /duplicate|charged twice|double[- ]charge|not idempotent/,
|
|
1869
|
+
contradiction: "claim treats retrying as idempotent but {sensor} produced {value} duplicate charge(s) driving the post-commit failure mode",
|
|
1870
|
+
confirmation: "{value} duplicate charge(s) observed on retry, matching the claim"
|
|
1871
|
+
},
|
|
1872
|
+
// --- slice 4: clock masking (GTR-008) ------------------------------------
|
|
1873
|
+
{
|
|
1874
|
+
kind: "identity",
|
|
1875
|
+
category: "time.timezone_identity",
|
|
1876
|
+
extract: "report_timezone",
|
|
1877
|
+
claimPattern: /\b(utc|gmt|america\/[a-z_]+|europe\/[a-z_]+|asia\/[a-z_]+|local|server)\b/,
|
|
1878
|
+
contradiction: "claim groups by '{claimed}' days but {sensor} reports the business calendar is '{actual}' \u2014 a date boundary in one is not a date boundary in the other",
|
|
1879
|
+
confirmation: "the business calendar is '{actual}', matching the claimed '{claimed}'"
|
|
1880
|
+
},
|
|
1881
|
+
{
|
|
1882
|
+
kind: "numeric_threshold",
|
|
1883
|
+
category: "time.boundary_exposure",
|
|
1884
|
+
extract: "rows_in_disputed_hours",
|
|
1885
|
+
threshold: 0,
|
|
1886
|
+
// one row on the wrong side of the boundary is a misfiled row
|
|
1887
|
+
denies: /midnight to midnight|utc date|server (clock|timezone)|calendars? agree|same (calendar|timezone)|day (runs|starts) at midnight|no (timezone|boundary) (issue|problem)/,
|
|
1888
|
+
asserts: /straddle|boundary|disputed|wrong day|misfiled|timezone (issue|problem)/,
|
|
1889
|
+
contradiction: "claim treats the UTC date as the business day but {sensor} finds {value} row(s) whose two calendar dates disagree",
|
|
1890
|
+
confirmation: "{value} row(s) fall on the disputed side of the day boundary, matching the claim"
|
|
1891
|
+
},
|
|
1892
|
+
// --- slice 4: cache masking (GTR-007) ------------------------------------
|
|
1893
|
+
{
|
|
1894
|
+
kind: "absence",
|
|
1895
|
+
category: "cache.invalidation_state",
|
|
1896
|
+
extract: "cache_invalidation_hooks",
|
|
1897
|
+
asserts: /cache|ttl|expire|expiry|invalidat|stale|no invalidation|evict/,
|
|
1898
|
+
contradiction: "claim relies on the cache staying consistent but {sensor} finds no invalidation hook in the deployed write path \u2014 nothing evicts when the value changes",
|
|
1899
|
+
confirmation: "{sensor} finds {value} invalidation hook(s) in the deployed write path"
|
|
1900
|
+
},
|
|
1901
|
+
{
|
|
1902
|
+
kind: "numeric_threshold",
|
|
1903
|
+
category: "data.volatility",
|
|
1904
|
+
extract: "price_changes_per_day",
|
|
1905
|
+
threshold: 1,
|
|
1906
|
+
// anything above "about once a day" falsifies "changes rarely"
|
|
1907
|
+
denies: /rarely|seldom|infrequent|hardly ever|(?:do|does)(?:n't| not) change|static|stable|pretty static|change (?:very )?little|ttl (?:is|will be) (?:sufficient|enough|fine)/,
|
|
1908
|
+
asserts: /change (?:often|frequently|constantly)|volatile|repric/,
|
|
1909
|
+
contradiction: "claim treats the value as rarely changing but {sensor} measures {value} changes per day",
|
|
1910
|
+
confirmation: "the value changes {value} times per day, matching the claim"
|
|
1911
|
+
},
|
|
1912
|
+
{
|
|
1913
|
+
kind: "numeric_threshold",
|
|
1914
|
+
category: "cache.coherence",
|
|
1915
|
+
extract: "stale_reads",
|
|
1916
|
+
threshold: 0,
|
|
1917
|
+
// one stale read after a write is the incoherence, observed
|
|
1918
|
+
denies: /consistent|coherent|fresh|up[- ]to[- ]date|no invalidation is needed|expires on its own|ttl keeps|reflects the database|not stale/,
|
|
1919
|
+
asserts: /stale|incoherent|out of date|serves the old/,
|
|
1920
|
+
contradiction: "claim treats the cached value as consistent with the database but {sensor} observed {value} stale read(s) immediately after a write",
|
|
1921
|
+
confirmation: "{value} stale read(s) observed after a write, matching the claim"
|
|
1922
|
+
},
|
|
1923
|
+
// --- slice 4: permission masking (GTR-006) -------------------------------
|
|
1924
|
+
{
|
|
1925
|
+
// Was an `identity` rule on current_user, and it fabricated catches two ways:
|
|
1926
|
+
// 'service role' sat in claimPattern as a generic PHRASE, which can never
|
|
1927
|
+
// equal a real role name, so any claim using those words contradicted; and
|
|
1928
|
+
// the reason asserted "a superuser bypasses grant checks" without ever
|
|
1929
|
+
// reading is_superuser, on systems where it was false. Both matter more now
|
|
1930
|
+
// that db.role is AMBIENT and runs on every turn. The flag kind reads the
|
|
1931
|
+
// measured value and stays silent when the connection is properly scoped.
|
|
1932
|
+
kind: "flag",
|
|
1933
|
+
category: "database.role_privileges",
|
|
1934
|
+
extract: "is_superuser",
|
|
1935
|
+
// The final clause is negation NEAR "superuser", not the single literal
|
|
1936
|
+
// "not a superuser" this used to require. A live agent declared exactly the
|
|
1937
|
+
// premise this rule exists for — "The connected role does NOT have superuser
|
|
1938
|
+
// privileges" — and the rule stayed silent, so a decisive reading came back
|
|
1939
|
+
// inconclusive and HELD the claim it should have contradicted. "does not
|
|
1940
|
+
// have superuser rights" and "a non-superuser role" missed too. Widening is
|
|
1941
|
+
// safe here because `flag` is value-driven: a claim it newly speaks about is
|
|
1942
|
+
// CONFIRMED when is_superuser is false and contradicted only when it is
|
|
1943
|
+
// true, so this cannot fabricate a catch on a correctly-scoped connection
|
|
1944
|
+
// (COMMON_MISTAKES: ambient sensors need value-driven rules).
|
|
1945
|
+
denies: /restricted (service )?role|service role|least privilege|succeed in production|production access|same (privileges|permissions)|permissions? (are|were) (checked|enforced)|connects as|\b(?:not|non-?|no|never|without|lacks?|lacking)[^.]{0,24}superuser/,
|
|
1946
|
+
contradiction: "claim assumes production-equivalent privileges but {sensor} reports the connection is a SUPERUSER, which bypasses grant checks entirely \u2014 nothing about permissions was actually tested",
|
|
1947
|
+
confirmation: "the connection is not a superuser, so grant checks were genuinely exercised"
|
|
1948
|
+
},
|
|
1949
|
+
{
|
|
1950
|
+
kind: "absence",
|
|
1951
|
+
category: "database.grant_state",
|
|
1952
|
+
extract: "grants_for_service_role",
|
|
1953
|
+
asserts: /grant|privilege|permission|access|allowed|has been granted|can (read|select|query)/,
|
|
1954
|
+
contradiction: "claim relies on the service role holding the privilege but {sensor} reports it has none on the target relation",
|
|
1955
|
+
confirmation: "{sensor} confirms the service role holds the claimed privilege"
|
|
1956
|
+
},
|
|
1957
|
+
{
|
|
1958
|
+
kind: "numeric_threshold",
|
|
1959
|
+
category: "runtime.write_atomicity",
|
|
1960
|
+
extract: "oversold_units",
|
|
1961
|
+
threshold: 0,
|
|
1962
|
+
// one unit sold beyond stock is the interleaving, observed
|
|
1963
|
+
denies: /atomic|cannot interleave|no (race|interleav)|single[- ]thread|check.{0,30}(before|then).{0,30}(write|update|decrement)|guard|never (oversell|sell more)|safe/,
|
|
1964
|
+
asserts: /race|interleav|oversell|lost update|toctou/,
|
|
1965
|
+
contradiction: "claim treats check-then-write as atomic but {sensor} oversold {value} unit(s) driving the same endpoint in parallel",
|
|
1966
|
+
confirmation: "parallel requests oversold {value} unit(s), matching the claimed race"
|
|
1967
|
+
}
|
|
1968
|
+
];
|
|
1969
|
+
var RULES = { ...STRUCTURAL_RULES, ...compileRules(RULE_SPECS) };
|
|
1970
|
+
function sweptFindingClaim(assumption) {
|
|
1971
|
+
return `(surfaced by the coverage sweep, not from a declared premise) ${assumption}`;
|
|
1972
|
+
}
|
|
1973
|
+
var NO_RULE_REACHED_VERDICT = "no judgment rule reached a verdict from the sensor evidence";
|
|
1974
|
+
var FALSIFIER_CATEGORY = "lemma.falsifier";
|
|
1975
|
+
var FALSIFIER_NEGATION = /\b(not|never|other than|anything but|except|unless)\b|n't/i;
|
|
1976
|
+
var FALSIFIER_OP = "(>=|<=|!=|==|=|:|>|<|is|are|was|were|returns?|reports?|equals|shows?)";
|
|
1977
|
+
function escapeForRegex(text) {
|
|
1978
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1979
|
+
}
|
|
1980
|
+
function satisfies(actual, op, stated) {
|
|
1981
|
+
const a = Number(actual);
|
|
1982
|
+
const b = Number(stated);
|
|
1983
|
+
const numeric = Number.isFinite(a) && Number.isFinite(b) && actual.trim() !== "" && stated.trim() !== "";
|
|
1984
|
+
switch (op) {
|
|
1985
|
+
case ">":
|
|
1986
|
+
return numeric && a > b;
|
|
1987
|
+
case "<":
|
|
1988
|
+
return numeric && a < b;
|
|
1989
|
+
case ">=":
|
|
1990
|
+
return numeric && a >= b;
|
|
1991
|
+
case "<=":
|
|
1992
|
+
return numeric && a <= b;
|
|
1993
|
+
case "!=":
|
|
1994
|
+
return numeric ? a !== b : actual.trim().toLowerCase() !== stated.trim().toLowerCase();
|
|
1995
|
+
default:
|
|
1996
|
+
return numeric ? a === b : actual.trim().toLowerCase() === stated.trim().toLowerCase();
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
function judgeFalsifyingObservation(lemma, evidence) {
|
|
2000
|
+
const observation = lemma.falsifyingObservation;
|
|
2001
|
+
if (!observation) return null;
|
|
2002
|
+
if (observation.sensor && observation.sensor !== evidence.sensorId) return null;
|
|
2003
|
+
const actual = evidence.extracted[observation.key];
|
|
2004
|
+
if (actual === void 0) return null;
|
|
2005
|
+
if (!satisfies(actual, observation.operator, observation.value)) return null;
|
|
2006
|
+
return {
|
|
2007
|
+
verdict: "contradicted",
|
|
2008
|
+
category: FALSIFIER_CATEGORY,
|
|
2009
|
+
reason: `the claim's declared falsifying condition is met: ${evidence.sensorId} measured ${observation.key}=${actual}, and the claim is false when ${observation.key} ${observation.operator} ${observation.value}`,
|
|
2010
|
+
sensorId: evidence.sensorId
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
2013
|
+
function findFalsifierClause(falsifier, key) {
|
|
2014
|
+
const clause = new RegExp(`\\b${escapeForRegex(key)}\\b\\s*${FALSIFIER_OP}\\s*"?([A-Za-z0-9_.+-]+)"?`, "i");
|
|
2015
|
+
const match = clause.exec(falsifier);
|
|
2016
|
+
if (!match) return null;
|
|
2017
|
+
const window = falsifier.slice(Math.max(0, match.index - 24), match.index + match[0].length + 8);
|
|
2018
|
+
if (FALSIFIER_NEGATION.test(window)) return null;
|
|
2019
|
+
const raw = match[1].trim().toLowerCase();
|
|
2020
|
+
const operator = [">=", "<=", "!=", "==", "=", ":", ">", "<"].includes(raw) ? raw === "==" || raw === ":" ? "=" : raw : "=";
|
|
2021
|
+
return { operator, value: match[2] };
|
|
2022
|
+
}
|
|
2023
|
+
function judgeFalsifier(lemma, evidence) {
|
|
2024
|
+
const falsifier = lemma.falsifier?.trim();
|
|
2025
|
+
if (!falsifier) return null;
|
|
2026
|
+
for (const [key, actual] of Object.entries(evidence.extracted)) {
|
|
2027
|
+
if (actual === void 0) continue;
|
|
2028
|
+
const clause = findFalsifierClause(falsifier, key);
|
|
2029
|
+
if (!clause) continue;
|
|
2030
|
+
if (!satisfies(actual, clause.operator, clause.value)) continue;
|
|
2031
|
+
return {
|
|
2032
|
+
verdict: "contradicted",
|
|
2033
|
+
category: FALSIFIER_CATEGORY,
|
|
2034
|
+
reason: `the claim's own falsifier is satisfied: ${evidence.sensorId} measured ${key}=${actual} (declared falsifier: "${falsifier.slice(0, 160)}")`,
|
|
2035
|
+
sensorId: evidence.sensorId
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
return null;
|
|
2039
|
+
}
|
|
2040
|
+
function judge(lemma, categories, evidence) {
|
|
2041
|
+
const ordered = [...categories, ...Object.keys(RULES).filter((c) => !categories.includes(c))];
|
|
2042
|
+
for (const category of ordered) {
|
|
2043
|
+
const rule = RULES[category];
|
|
2044
|
+
if (!rule) continue;
|
|
2045
|
+
const judgment = rule(lemma, evidence);
|
|
2046
|
+
if (judgment) return { ...judgment, sensorId: evidence.sensorId };
|
|
2047
|
+
}
|
|
2048
|
+
const byObservation = judgeFalsifyingObservation(lemma, evidence);
|
|
2049
|
+
if (byObservation) return byObservation;
|
|
2050
|
+
const byFalsifier = judgeFalsifier(lemma, evidence);
|
|
2051
|
+
if (byFalsifier) return byFalsifier;
|
|
2052
|
+
return {
|
|
2053
|
+
verdict: "inconclusive",
|
|
2054
|
+
category: categories[0] ?? "unknown",
|
|
2055
|
+
reason: NO_RULE_REACHED_VERDICT,
|
|
2056
|
+
sensorId: evidence.sensorId
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
// ../core/src/gate.ts
|
|
2061
|
+
function evaluateGate(verifications, policy = {}) {
|
|
2062
|
+
const catches = [];
|
|
2063
|
+
const holds = [];
|
|
2064
|
+
const verified = [];
|
|
2065
|
+
const miscalibrations = [];
|
|
2066
|
+
const unverifiable = [];
|
|
2067
|
+
const unjudged = [];
|
|
2068
|
+
for (const verification of verifications) {
|
|
2069
|
+
const { audited, judgments } = verification;
|
|
2070
|
+
if (!audited.lemma.loadBearing) continue;
|
|
2071
|
+
if (audited.downgraded) {
|
|
2072
|
+
miscalibrations.push({
|
|
2073
|
+
claim: audited.lemma.claim,
|
|
2074
|
+
tagged: audited.lemma.provenance,
|
|
2075
|
+
basis: audited.basis
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
const contradiction = judgments.find((j) => j.verdict === "contradicted");
|
|
2079
|
+
if (contradiction) {
|
|
2080
|
+
const existing = catches.find((c) => c.reason === contradiction.reason);
|
|
2081
|
+
if (existing) {
|
|
2082
|
+
existing.alsoClaimed = [...existing.alsoClaimed ?? [], audited.lemma.claim];
|
|
2083
|
+
} else {
|
|
2084
|
+
catches.push({ claim: audited.lemma.claim, reason: contradiction.reason });
|
|
2085
|
+
}
|
|
2086
|
+
continue;
|
|
2087
|
+
}
|
|
2088
|
+
const confirmation = judgments.find((j) => j.verdict === "confirmed");
|
|
2089
|
+
if (confirmation) {
|
|
2090
|
+
verified.push({ claim: audited.lemma.claim, basis: confirmation.reason, via: "sensor" });
|
|
2091
|
+
continue;
|
|
2092
|
+
}
|
|
2093
|
+
if (audited.effectiveProvenance !== "believed") {
|
|
2094
|
+
verified.push({ claim: audited.lemma.claim, basis: audited.basis, via: "provenance" });
|
|
2095
|
+
continue;
|
|
2096
|
+
}
|
|
2097
|
+
if (judgments.length > 0 && verification.matchedSensor !== false) {
|
|
2098
|
+
const unavailable = judgments.find((j) => j.category === SENSOR_UNAVAILABLE_CATEGORY);
|
|
2099
|
+
const noRule = judgments.filter(
|
|
2100
|
+
(j) => j.reason === NO_RULE_REACHED_VERDICT && j.sensorId !== void 0
|
|
2101
|
+
);
|
|
2102
|
+
if (!unavailable && noRule.length > 0) {
|
|
2103
|
+
unjudged.push({
|
|
2104
|
+
claim: audited.lemma.claim,
|
|
2105
|
+
sensorIds: [...new Set(noRule.map((j) => j.sensorId))]
|
|
2106
|
+
});
|
|
2107
|
+
}
|
|
2108
|
+
holds.push({
|
|
2109
|
+
claim: audited.lemma.claim,
|
|
2110
|
+
reason: unavailable ? unavailable.reason : noRule.length > 0 ? `${noRule.map((j) => j.sensorId).join(", ")} measured this, but no judgment rule could read the evidence` : "sensor evidence was inconclusive"
|
|
2111
|
+
});
|
|
2112
|
+
} else {
|
|
2113
|
+
const gap = { claim: audited.lemma.claim, reason: "no registered sensor can verify this claim" };
|
|
2114
|
+
if (policy.holdOnUnverifiable) holds.push(gap);
|
|
2115
|
+
else unverifiable.push(gap);
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
const measured = catches.length > 0 || verified.some((v) => v.via === "sensor");
|
|
2119
|
+
const decision = holds.length > 0 ? "held" : measured ? "released" : "released_unverified";
|
|
2120
|
+
return { decision, catches, holds, verified, miscalibrations, unverifiable, unjudged };
|
|
2121
|
+
}
|
|
2122
|
+
function catchClaims(entry) {
|
|
2123
|
+
return [entry.claim, ...entry.alsoClaimed ?? []];
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
// ../core/src/check.ts
|
|
2127
|
+
async function gather(sensorId, deps, result) {
|
|
2128
|
+
const sensor = deps.registry.sensors.find((s) => s.id === sensorId);
|
|
2129
|
+
if (!sensor) return null;
|
|
2130
|
+
let invocation;
|
|
2131
|
+
try {
|
|
2132
|
+
invocation = await deps.executor.run(sensorId);
|
|
2133
|
+
} catch (err) {
|
|
2134
|
+
result.unrunnableSensors.push({
|
|
2135
|
+
sensorId,
|
|
2136
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
2137
|
+
});
|
|
2138
|
+
return null;
|
|
2139
|
+
}
|
|
2140
|
+
const failure = invocationFailure(invocation);
|
|
2141
|
+
if (failure !== null) {
|
|
2142
|
+
result.unrunnableSensors.push({ sensorId, reason: failure });
|
|
2143
|
+
return null;
|
|
2144
|
+
}
|
|
2145
|
+
const output = invocation.output;
|
|
2146
|
+
const { clean, redactions } = redact(output);
|
|
2147
|
+
result.redactions += redactions.length;
|
|
2148
|
+
result.sensorsRun.push(sensor.id);
|
|
2149
|
+
return {
|
|
2150
|
+
sensor,
|
|
2151
|
+
evidence: { sensorId: sensor.id, output: clean, extracted: extractValues(sensor, clean) }
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2154
|
+
async function checkDeclaration(declaration, deps) {
|
|
2155
|
+
const result = {
|
|
2156
|
+
decision: { decision: "released_unverified", catches: [], holds: [], unverifiable: [], verified: [], miscalibrations: [] },
|
|
2157
|
+
sensorsRun: [],
|
|
2158
|
+
unrunnableSensors: [],
|
|
2159
|
+
redactions: 0,
|
|
2160
|
+
lemmaCount: declaration.lemmas.length,
|
|
2161
|
+
loadBearingCount: declaration.lemmas.filter((l) => l.loadBearing).length,
|
|
2162
|
+
unsubstantiatedProvenance: [],
|
|
2163
|
+
undeclaredCatches: 0
|
|
2164
|
+
};
|
|
2165
|
+
const audited = declaration.lemmas.map((lemma) => {
|
|
2166
|
+
const a = auditProvenance(lemma, { activeFacts: [], userMessages: [] });
|
|
2167
|
+
if (a.downgraded && lemma.loadBearing) {
|
|
2168
|
+
result.unsubstantiatedProvenance.push({ claim: lemma.claim, tagged: lemma.provenance });
|
|
2169
|
+
}
|
|
2170
|
+
return a;
|
|
2171
|
+
});
|
|
2172
|
+
const eligible = (a) => a.lemma.loadBearing && a.effectiveProvenance === "believed";
|
|
2173
|
+
const matchedByClaim = /* @__PURE__ */ new Map();
|
|
2174
|
+
const wanted = [];
|
|
2175
|
+
for (const a of audited.filter(eligible)) {
|
|
2176
|
+
for (const match of matchLemmaToSensors(a.lemma, deps.registry.sensors)) {
|
|
2177
|
+
if (isHoldWorthy(match)) {
|
|
2178
|
+
const forClaim = matchedByClaim.get(a.lemma.claim) ?? /* @__PURE__ */ new Set();
|
|
2179
|
+
forClaim.add(match.sensorId);
|
|
2180
|
+
matchedByClaim.set(a.lemma.claim, forClaim);
|
|
2181
|
+
}
|
|
2182
|
+
if (!wanted.includes(match.sensorId)) wanted.push(match.sensorId);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
const gathered = /* @__PURE__ */ new Map();
|
|
2186
|
+
const definitions = wanted.map((id) => deps.registry.sensors.find((s) => s.id === id)).filter((s) => s !== void 0);
|
|
2187
|
+
for (const batch of planSensorRuns(definitions, deps.concurrency ?? sensorConcurrencyFromEnv())) {
|
|
2188
|
+
const ran = await Promise.all(batch.map((sensor) => gather(sensor.id, deps, result)));
|
|
2189
|
+
for (let i = 0; i < batch.length; i += 1) gathered.set(batch[i].id, ran[i]);
|
|
2190
|
+
}
|
|
2191
|
+
for (const id of wanted) if (!gathered.has(id)) gathered.set(id, null);
|
|
2192
|
+
const evidence = [...gathered.values()].filter((g) => g !== null);
|
|
2193
|
+
const symbolsByClaim = /* @__PURE__ */ new Map();
|
|
2194
|
+
if (deps.apiResolutionCwd) {
|
|
2195
|
+
for (const a of audited.filter(eligible)) {
|
|
2196
|
+
const symbols = [.../* @__PURE__ */ new Set([...a.lemma.symbols ?? [], ...extractSymbols(a.lemma.claim)])];
|
|
2197
|
+
if (symbols.length > 0) symbolsByClaim.set(a.lemma.claim, symbols);
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
const resolutions = symbolsByClaim.size > 0 ? await resolveSymbols([...new Set([...symbolsByClaim.values()].flat())], deps.apiResolutionCwd) : [];
|
|
2201
|
+
const bySymbol = new Map(resolutions.map((r) => [r.symbol, r]));
|
|
2202
|
+
const failed = new Map(result.unrunnableSensors.map((u) => [u.sensorId, u.reason]));
|
|
2203
|
+
const verifications = [];
|
|
2204
|
+
for (const a of audited) {
|
|
2205
|
+
const judgments = [];
|
|
2206
|
+
if (eligible(a)) {
|
|
2207
|
+
const named = symbolsByClaim.get(a.lemma.claim) ?? [];
|
|
2208
|
+
const mine = named.map((s) => bySymbol.get(s)).filter((r) => r !== void 0);
|
|
2209
|
+
if (mine.length > 0) judgments.push(judge(a.lemma, ["code.api_existence"], apiExistenceEvidence(mine)));
|
|
2210
|
+
for (const g of evidence) judgments.push(judge(a.lemma, g.sensor.verifies, g.evidence));
|
|
2211
|
+
for (const sensorId of matchedByClaim.get(a.lemma.claim) ?? []) {
|
|
2212
|
+
const reason = failed.get(sensorId);
|
|
2213
|
+
if (reason !== void 0) judgments.push(sensorUnavailableJudgment(sensorId, reason));
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
verifications.push({
|
|
2217
|
+
audited: a,
|
|
2218
|
+
judgments,
|
|
2219
|
+
matchedSensor: (matchedByClaim.get(a.lemma.claim)?.size ?? 0) > 0
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
const intent = declaration.planSummary.trim();
|
|
2223
|
+
if (intent) {
|
|
2224
|
+
const implicit = { claim: intent, provenance: "believed", loadBearing: true };
|
|
2225
|
+
const alreadyCaught = new Set(
|
|
2226
|
+
verifications.flatMap(
|
|
2227
|
+
(v) => v.judgments.filter((j) => j.verdict === "contradicted" && j.sensorId).map((j) => j.sensorId)
|
|
2228
|
+
)
|
|
2229
|
+
);
|
|
2230
|
+
const keywordMatches = matchLemmaToSensors(implicit, deps.registry.sensors);
|
|
2231
|
+
const matchedIds = new Set(keywordMatches.map((m) => m.sensorId));
|
|
2232
|
+
const ambient = deps.registry.sensors.filter((s) => s.ambient && !matchedIds.has(s.id)).map((s) => ({ sensorId: s.id, category: null }));
|
|
2233
|
+
for (const match of [...keywordMatches, ...ambient]) {
|
|
2234
|
+
if (alreadyCaught.has(match.sensorId)) continue;
|
|
2235
|
+
if (!gathered.has(match.sensorId)) gathered.set(match.sensorId, await gather(match.sensorId, deps, result));
|
|
2236
|
+
const g = gathered.get(match.sensorId);
|
|
2237
|
+
if (!g) continue;
|
|
2238
|
+
const categories = g.sensor.ambient || !match.category ? g.sensor.verifies : [match.category];
|
|
2239
|
+
const probeClaim = categories.map((c) => CATEGORY_PROBES[c]).find(Boolean);
|
|
2240
|
+
let judgment = probeClaim ? judge({ claim: probeClaim, provenance: "believed", loadBearing: true }, categories, g.evidence) : null;
|
|
2241
|
+
const viaProbe = judgment?.verdict === "contradicted";
|
|
2242
|
+
if (!viaProbe) judgment = judge(implicit, categories, g.evidence);
|
|
2243
|
+
if (!judgment || judgment.verdict !== "contradicted") continue;
|
|
2244
|
+
verifications.push({
|
|
2245
|
+
audited: {
|
|
2246
|
+
lemma: {
|
|
2247
|
+
// Name the assumption that was tested, not the plan blob, so a
|
|
2248
|
+
// reviewer can see what the change was taking for granted.
|
|
2249
|
+
claim: sweptFindingClaim(
|
|
2250
|
+
viaProbe && probeClaim ? probeClaim : `an assumption in the plan about ${match.category ?? g.sensor.id}`
|
|
2251
|
+
),
|
|
2252
|
+
provenance: "believed",
|
|
2253
|
+
loadBearing: true
|
|
2254
|
+
},
|
|
2255
|
+
effectiveProvenance: "believed",
|
|
2256
|
+
downgraded: false,
|
|
2257
|
+
basis: "surfaced by the coverage sweep from the plan summary, not from a declared lemma"
|
|
2258
|
+
},
|
|
2259
|
+
judgments: [judgment]
|
|
2260
|
+
});
|
|
2261
|
+
alreadyCaught.add(match.sensorId);
|
|
2262
|
+
result.undeclaredCatches += 1;
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2265
|
+
result.decision = evaluateGate(verifications, deps.policy ?? {});
|
|
2266
|
+
return result;
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
// ../core/src/check-report.ts
|
|
2270
|
+
var CHECK_EXIT_OK = 0;
|
|
2271
|
+
var CHECK_EXIT_GATE = 2;
|
|
2272
|
+
function checkExitCode(result, opts = {}) {
|
|
2273
|
+
const { decision } = result;
|
|
2274
|
+
if (decision.decision === "held") return CHECK_EXIT_GATE;
|
|
2275
|
+
if (decision.catches.length > 0) return CHECK_EXIT_GATE;
|
|
2276
|
+
if (opts.requireEvidence && decision.decision === "released_unverified") return CHECK_EXIT_GATE;
|
|
2277
|
+
return CHECK_EXIT_OK;
|
|
2278
|
+
}
|
|
2279
|
+
function checkOutcome(result) {
|
|
2280
|
+
const d = result.decision;
|
|
2281
|
+
if (d.decision === "held") return "held";
|
|
2282
|
+
if (d.catches.length > 0) return "contradicted";
|
|
2283
|
+
return d.decision === "released" ? "released" : "released, unverified";
|
|
2284
|
+
}
|
|
2285
|
+
function checkCountsLine(result) {
|
|
2286
|
+
const d = result.decision;
|
|
2287
|
+
return [
|
|
2288
|
+
`${result.loadBearingCount} load-bearing of ${result.lemmaCount} declared`,
|
|
2289
|
+
`${d.catches.length} contradicted`,
|
|
2290
|
+
`${d.holds.length} unresolved`,
|
|
2291
|
+
`${d.verified.filter((v) => v.via === "sensor").length} verified by measurement`
|
|
2292
|
+
].join(" \xB7 ");
|
|
2293
|
+
}
|
|
2294
|
+
function checkSummaryLine(result) {
|
|
2295
|
+
return `${checkOutcome(result)} \u2014 ${checkCountsLine(result)}`;
|
|
2296
|
+
}
|
|
2297
|
+
function md(text) {
|
|
2298
|
+
return text.replace(/[`|]/g, "\\$&");
|
|
2299
|
+
}
|
|
2300
|
+
var MAX_ITEMS = 20;
|
|
2301
|
+
function section(title, items) {
|
|
2302
|
+
if (items.length === 0) return [];
|
|
2303
|
+
const shown = items.slice(0, MAX_ITEMS);
|
|
2304
|
+
const rest = items.length - shown.length;
|
|
2305
|
+
return [
|
|
2306
|
+
`#### ${title}`,
|
|
2307
|
+
...shown.map((i) => `- ${i}`),
|
|
2308
|
+
...rest > 0 ? [`- _\u2026and ${rest} more_`] : [],
|
|
2309
|
+
""
|
|
2310
|
+
];
|
|
2311
|
+
}
|
|
2312
|
+
function formatCheckMarkdown(result, opts = {}) {
|
|
2313
|
+
const d = result.decision;
|
|
2314
|
+
const lines = [`### Gettier \u2014 ${checkOutcome(result)}`, ""];
|
|
2315
|
+
if (opts.subject) lines.push(`\`${md(opts.subject)}\``, "");
|
|
2316
|
+
lines.push(checkCountsLine(result), "");
|
|
2317
|
+
lines.push(
|
|
2318
|
+
...section(
|
|
2319
|
+
"Contradicted by measurement",
|
|
2320
|
+
d.catches.map((c) => {
|
|
2321
|
+
const claims = catchClaims(c);
|
|
2322
|
+
const also = claims.length > 1 ? ` _(also claimed: ${claims.length - 1} more)_` : "";
|
|
2323
|
+
return `${md(claims[0])}
|
|
2324
|
+
- ${md(c.reason)}${also}`;
|
|
2325
|
+
})
|
|
2326
|
+
),
|
|
2327
|
+
...section(
|
|
2328
|
+
"Could not be settled \u2014 Confirm / Correct / Waive",
|
|
2329
|
+
d.holds.map((h) => `${md(h.claim)}
|
|
2330
|
+
- ${md(h.reason)}`)
|
|
2331
|
+
),
|
|
2332
|
+
...section(
|
|
2333
|
+
"Verified",
|
|
2334
|
+
d.verified.filter((v) => v.via === "sensor").map((v) => `${md(v.claim)}
|
|
2335
|
+
- ${md(v.basis)}`)
|
|
2336
|
+
),
|
|
2337
|
+
...section(
|
|
2338
|
+
"Declared with evidence this check could not substantiate",
|
|
2339
|
+
result.unsubstantiatedProvenance.map(
|
|
2340
|
+
(m) => `${md(m.claim)}
|
|
2341
|
+
- tagged \`${m.tagged}\`, treated as \`believed\` here`
|
|
2342
|
+
)
|
|
2343
|
+
),
|
|
2344
|
+
...section(
|
|
2345
|
+
"No registered sensor covers these",
|
|
2346
|
+
d.unverifiable.map((u) => md(u.claim))
|
|
2347
|
+
),
|
|
2348
|
+
...section(
|
|
2349
|
+
"Measured, but no judgment rule could read the evidence",
|
|
2350
|
+
(d.unjudged ?? []).map((u) => `${md(u.claim)}
|
|
2351
|
+
- measured by ${md(u.sensorIds.join(", "))} \u2014 this is a gap in the judgment rules, not in the claim`)
|
|
2352
|
+
)
|
|
2353
|
+
);
|
|
2354
|
+
const notes = [
|
|
2355
|
+
`${result.sensorsRun.length} sensor${result.sensorsRun.length === 1 ? "" : "s"} run`,
|
|
2356
|
+
...result.unrunnableSensors.length > 0 ? [`${result.unrunnableSensors.length} could not run`] : [],
|
|
2357
|
+
...result.undeclaredCatches > 0 ? [`${result.undeclaredCatches} found by coverage sweep, undeclared`] : [],
|
|
2358
|
+
...result.redactions > 0 ? [`${result.redactions} secrets redacted before judging`] : []
|
|
2359
|
+
];
|
|
2360
|
+
lines.push(`<sub>${notes.join(" \xB7 ")}</sub>`);
|
|
2361
|
+
return lines.join("\n");
|
|
2362
|
+
}
|
|
2363
|
+
function checkEventPayload(result) {
|
|
2364
|
+
return {
|
|
2365
|
+
// What this check CONCLUDED, in the same words the report uses. The raw
|
|
2366
|
+
// `decision` is kept beside it because a turn's vocabulary is not a pull
|
|
2367
|
+
// request's: evaluateGate calls a caught turn `released`, so an event typed
|
|
2368
|
+
// gate.held carried a payload saying released — the same record answering
|
|
2369
|
+
// its own question two ways.
|
|
2370
|
+
outcome: checkOutcome(result),
|
|
2371
|
+
decision: result.decision.decision,
|
|
2372
|
+
lemmas: result.lemmaCount,
|
|
2373
|
+
loadBearing: result.loadBearingCount,
|
|
2374
|
+
catches: result.decision.catches.length,
|
|
2375
|
+
holds: result.decision.holds.length,
|
|
2376
|
+
verified: result.decision.verified.length,
|
|
2377
|
+
unverifiable: result.decision.unverifiable.length,
|
|
2378
|
+
unjudged: (result.decision.unjudged ?? []).length,
|
|
2379
|
+
undeclaredCatches: result.undeclaredCatches,
|
|
2380
|
+
sensorsRun: result.sensorsRun.length,
|
|
2381
|
+
sensorsUnrunnable: result.unrunnableSensors.length
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
// ../core/src/injection.ts
|
|
2386
|
+
var MARKER_PREFIX = "<<<GETTIER:";
|
|
2387
|
+
var NEUTRALIZED_PREFIX = "<<<GETTIER-ESCAPED:";
|
|
2388
|
+
function escapeFrameMarkers(content) {
|
|
2389
|
+
return content.split(MARKER_PREFIX).join(NEUTRALIZED_PREFIX);
|
|
2390
|
+
}
|
|
2391
|
+
function frameAsData(label, content) {
|
|
2392
|
+
return [
|
|
2393
|
+
`<<<GETTIER:DATA:${escapeFrameMarkers(label)}>>>`,
|
|
2394
|
+
escapeFrameMarkers(content),
|
|
2395
|
+
"<<<GETTIER:END-DATA>>>"
|
|
2396
|
+
].join("\n");
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
// ../core/src/telemetry.ts
|
|
2400
|
+
import { randomUUID } from "node:crypto";
|
|
2401
|
+
|
|
2402
|
+
// ../core/src/control-plane.ts
|
|
2403
|
+
var MAX_ENVELOPE_BYTES = 1048576;
|
|
2404
|
+
var MAX_ENVELOPE_EVENTS = 100;
|
|
2405
|
+
|
|
2406
|
+
// ../core/src/telemetry.ts
|
|
2407
|
+
function redactDeep(value) {
|
|
2408
|
+
if (typeof value === "string") return redact(value).clean;
|
|
2409
|
+
if (Array.isArray(value)) return value.map(redactDeep);
|
|
2410
|
+
if (value && typeof value === "object") {
|
|
2411
|
+
return Object.fromEntries(
|
|
2412
|
+
Object.entries(value).filter(([, v]) => v !== void 0).map(([k, v]) => [redact(k).clean, redactDeep(v)])
|
|
2413
|
+
);
|
|
2414
|
+
}
|
|
2415
|
+
return value;
|
|
2416
|
+
}
|
|
2417
|
+
function createEvent(input) {
|
|
2418
|
+
const event = {
|
|
2419
|
+
eventId: randomUUID(),
|
|
2420
|
+
type: input.type,
|
|
2421
|
+
source: input.source,
|
|
2422
|
+
occurredAt: input.occurredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
2423
|
+
payload: redactDeep(input.payload ?? {})
|
|
2424
|
+
};
|
|
2425
|
+
if (input.sessionId !== void 0) event.sessionId = redactPatternsOnly(input.sessionId).clean;
|
|
2426
|
+
if (input.release !== void 0) event.release = redactPatternsOnly(input.release).clean;
|
|
2427
|
+
if (input.traceId !== void 0) event.traceId = redactPatternsOnly(input.traceId).clean;
|
|
2428
|
+
return event;
|
|
2429
|
+
}
|
|
2430
|
+
var EMPTY_ENVELOPE_BYTES = Buffer.byteLength('{"events":[]}');
|
|
2431
|
+
function eventBytes(event) {
|
|
2432
|
+
return Buffer.byteLength(JSON.stringify(event), "utf8");
|
|
2433
|
+
}
|
|
2434
|
+
function memoryTransport() {
|
|
2435
|
+
const sent = [];
|
|
2436
|
+
return {
|
|
2437
|
+
name: "memory (no ingestion endpoint configured)",
|
|
2438
|
+
sent,
|
|
2439
|
+
async send(events) {
|
|
2440
|
+
const retained = [];
|
|
2441
|
+
let bytes = EMPTY_ENVELOPE_BYTES;
|
|
2442
|
+
sample: for (const candidates of [events, sent]) {
|
|
2443
|
+
for (let i = candidates.length - 1; i >= 0; i -= 1) {
|
|
2444
|
+
const event = candidates[i];
|
|
2445
|
+
let size;
|
|
2446
|
+
try {
|
|
2447
|
+
size = eventBytes(event);
|
|
2448
|
+
} catch {
|
|
2449
|
+
continue;
|
|
2450
|
+
}
|
|
2451
|
+
if (EMPTY_ENVELOPE_BYTES + size > MAX_ENVELOPE_BYTES) continue;
|
|
2452
|
+
if (retained.length === MAX_ENVELOPE_EVENTS || bytes + size + (retained.length ? 1 : 0) > MAX_ENVELOPE_BYTES) break sample;
|
|
2453
|
+
bytes += size + (retained.length ? 1 : 0);
|
|
2454
|
+
retained.unshift(event);
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
sent.splice(0, sent.length, ...retained);
|
|
2458
|
+
}
|
|
2459
|
+
};
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
// ../core/src/transport-http.ts
|
|
2463
|
+
var DEFAULT_INGEST_ENDPOINT = "https://api.gettier.io/api/v1/envelope";
|
|
2464
|
+
var DEFAULTS = { timeoutMs: 5e3, maxAttempts: 3, retryBaseMs: 200 };
|
|
2465
|
+
function retryable(status) {
|
|
2466
|
+
return status === 429 || status >= 500;
|
|
2467
|
+
}
|
|
2468
|
+
function httpTransport(options) {
|
|
2469
|
+
const endpoint = options.endpoint ?? DEFAULT_INGEST_ENDPOINT;
|
|
2470
|
+
const timeoutMs = options.timeoutMs ?? DEFAULTS.timeoutMs;
|
|
2471
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULTS.maxAttempts);
|
|
2472
|
+
const retryBaseMs = options.retryBaseMs ?? DEFAULTS.retryBaseMs;
|
|
2473
|
+
const doFetch = options.fetchImpl ?? globalThis.fetch;
|
|
2474
|
+
const sleep = options.sleep ?? ((ms) => new Promise((r) => {
|
|
2475
|
+
setTimeout(r, ms);
|
|
2476
|
+
}));
|
|
2477
|
+
return {
|
|
2478
|
+
// Names the destination, never the credential.
|
|
2479
|
+
name: `http(${endpoint})`,
|
|
2480
|
+
async send(events) {
|
|
2481
|
+
if (events.length === 0) return;
|
|
2482
|
+
const body = JSON.stringify({ events });
|
|
2483
|
+
let lastError;
|
|
2484
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
2485
|
+
try {
|
|
2486
|
+
const response = await doFetch(endpoint, {
|
|
2487
|
+
method: "POST",
|
|
2488
|
+
// Never follow an ingestion redirect carrying a customer credential.
|
|
2489
|
+
redirect: "error",
|
|
2490
|
+
headers: {
|
|
2491
|
+
"content-type": "application/json",
|
|
2492
|
+
authorization: `Bearer ${options.dsn}`
|
|
2493
|
+
},
|
|
2494
|
+
body,
|
|
2495
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
2496
|
+
});
|
|
2497
|
+
if (response.ok) return;
|
|
2498
|
+
lastError = new Error(`ingestion rejected the batch (HTTP ${response.status})`);
|
|
2499
|
+
if (!retryable(response.status)) throw lastError;
|
|
2500
|
+
} catch (err) {
|
|
2501
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
2502
|
+
if (/HTTP (4\d\d)/.test(lastError.message) && !/HTTP 429/.test(lastError.message)) break;
|
|
2503
|
+
}
|
|
2504
|
+
if (attempt < maxAttempts) await sleep(retryBaseMs * 2 ** (attempt - 1));
|
|
2505
|
+
}
|
|
2506
|
+
throw lastError ?? new Error("ingestion failed");
|
|
2507
|
+
}
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
// src/project.ts
|
|
2512
|
+
import { existsSync, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
|
|
2513
|
+
import path2 from "node:path";
|
|
2514
|
+
var LOCAL_INGEST_ENDPOINT = "http://localhost:3000/api/v1/envelope";
|
|
2515
|
+
var ENDPOINT_ENV_VAR = "GETTIER_ENDPOINT";
|
|
2516
|
+
var CONFIG_DIR = ".gettier";
|
|
2517
|
+
var CONFIG_FILE = "project.json";
|
|
2518
|
+
var DEFAULT_CONFIG = {
|
|
2519
|
+
environment: "development",
|
|
2520
|
+
registry: "sensors.yaml",
|
|
2521
|
+
dsnEnvVar: "GETTIER_DSN"
|
|
2522
|
+
};
|
|
2523
|
+
function configPath(root) {
|
|
2524
|
+
return path2.join(root, CONFIG_DIR, CONFIG_FILE);
|
|
2525
|
+
}
|
|
2526
|
+
function readConfig(root) {
|
|
2527
|
+
const file = configPath(root);
|
|
2528
|
+
if (!existsSync(file)) return null;
|
|
2529
|
+
return JSON.parse(readFileSync2(file, "utf8"));
|
|
2530
|
+
}
|
|
2531
|
+
function writeConfig(root, config, opts = {}) {
|
|
2532
|
+
const file = configPath(root);
|
|
2533
|
+
if (existsSync(file) && !opts.force) {
|
|
2534
|
+
throw new Error(`${path2.relative(root, file)} already exists \u2014 pass --force to overwrite`);
|
|
2535
|
+
}
|
|
2536
|
+
mkdirSync(path2.dirname(file), { recursive: true });
|
|
2537
|
+
writeFileSync(file, `${JSON.stringify(config, null, 2)}
|
|
2538
|
+
`);
|
|
2539
|
+
}
|
|
2540
|
+
function agentEvent(type, _config, payload = {}) {
|
|
2541
|
+
return createEvent({ source: "agent", type, payload });
|
|
2542
|
+
}
|
|
2543
|
+
function resolveEndpoint(config, env = process.env) {
|
|
2544
|
+
if (config.endpoint) return { url: config.endpoint, source: "project config" };
|
|
2545
|
+
const fromEnv = env[ENDPOINT_ENV_VAR];
|
|
2546
|
+
if (fromEnv) return { url: fromEnv, source: ENDPOINT_ENV_VAR };
|
|
2547
|
+
return { url: DEFAULT_INGEST_ENDPOINT, source: "hosted default" };
|
|
2548
|
+
}
|
|
2549
|
+
function projectTransport(config, env = process.env) {
|
|
2550
|
+
const dsn = env[config.dsnEnvVar];
|
|
2551
|
+
if (!dsn) return memoryTransport();
|
|
2552
|
+
return httpTransport({ dsn, endpoint: resolveEndpoint(config, env).url });
|
|
2553
|
+
}
|
|
2554
|
+
function surfaceSource(env = process.env) {
|
|
2555
|
+
return env.CI && env.CI !== "false" && env.CI !== "0" ? "ci" : "agent";
|
|
2556
|
+
}
|
|
2557
|
+
function surfaceEvent(type, payload = {}, env = process.env) {
|
|
2558
|
+
return createEvent({ source: surfaceSource(env), type, payload });
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// src/check.ts
|
|
2562
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
2563
|
+
import path3 from "node:path";
|
|
2564
|
+
var DECLARATION_FILE = path3.join(".gettier", "declaration.json");
|
|
2565
|
+
function readDeclaration(root, from) {
|
|
2566
|
+
const source = from ?? DECLARATION_FILE;
|
|
2567
|
+
let raw;
|
|
2568
|
+
if (source === "-") {
|
|
2569
|
+
raw = readFileSync3(0, "utf8");
|
|
2570
|
+
} else {
|
|
2571
|
+
const file = path3.resolve(root, source);
|
|
2572
|
+
try {
|
|
2573
|
+
raw = readFileSync3(file, "utf8");
|
|
2574
|
+
} catch {
|
|
2575
|
+
throw new Error(
|
|
2576
|
+
`no declaration at ${path3.relative(root, file) || file} \u2014 write the declare_lemmas input there, or pass --declaration <path> (or - for stdin)`
|
|
2577
|
+
);
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
let input;
|
|
2581
|
+
try {
|
|
2582
|
+
input = JSON.parse(raw);
|
|
2583
|
+
} catch {
|
|
2584
|
+
throw new Error(`${source} is not valid JSON`);
|
|
2585
|
+
}
|
|
2586
|
+
const parsed = parseDeclaration(input);
|
|
2587
|
+
return { ...parsed, from: source };
|
|
2588
|
+
}
|
|
2589
|
+
async function runCheck(root, registryPath, opts = {}) {
|
|
2590
|
+
const { declaration, warnings, from } = readDeclaration(root, opts.declaration);
|
|
2591
|
+
const registry = loadRegistry(registryPath);
|
|
2592
|
+
return {
|
|
2593
|
+
result: await checkDeclaration(declaration, {
|
|
2594
|
+
registry,
|
|
2595
|
+
executor: new ProcessSensorExecutor(registry, { cwd: root }),
|
|
2596
|
+
...opts.apiResolutionCwd ? { apiResolutionCwd: opts.apiResolutionCwd } : {},
|
|
2597
|
+
...opts.policy ? { policy: opts.policy } : {}
|
|
2598
|
+
}),
|
|
2599
|
+
warnings,
|
|
2600
|
+
from
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
function formatCheckText(result, opts = {}) {
|
|
2604
|
+
const d = result.decision;
|
|
2605
|
+
const lines = opts.summary === false ? [] : [checkSummaryLine(result), ""];
|
|
2606
|
+
const block = (title, items) => {
|
|
2607
|
+
if (items.length === 0) return;
|
|
2608
|
+
lines.push(title);
|
|
2609
|
+
for (const [head, detail] of items) {
|
|
2610
|
+
lines.push(` ${head}`);
|
|
2611
|
+
if (detail) lines.push(` ${detail}`);
|
|
2612
|
+
}
|
|
2613
|
+
lines.push("");
|
|
2614
|
+
};
|
|
2615
|
+
block("CONTRADICTED", d.catches.map((c) => [c.claim, c.reason]));
|
|
2616
|
+
block("UNRESOLVED \u2014 confirm, correct or waive", d.holds.map((h) => [h.claim, h.reason]));
|
|
2617
|
+
block(
|
|
2618
|
+
"VERIFIED",
|
|
2619
|
+
d.verified.filter((v) => v.via === "sensor").map((v) => [v.claim, v.basis])
|
|
2620
|
+
);
|
|
2621
|
+
block(
|
|
2622
|
+
"DECLARED WITH EVIDENCE THIS CHECK CANNOT SEE",
|
|
2623
|
+
result.unsubstantiatedProvenance.map(
|
|
2624
|
+
(m) => [m.claim, `tagged '${m.tagged}'; no ledger or conversation here, judged as 'believed'`]
|
|
2625
|
+
)
|
|
2626
|
+
);
|
|
2627
|
+
block("NO SENSOR COVERS THESE", d.unverifiable.map((u) => [u.claim]));
|
|
2628
|
+
block(
|
|
2629
|
+
"MEASURED, BUT NO RULE COULD READ IT",
|
|
2630
|
+
(d.unjudged ?? []).map(
|
|
2631
|
+
(u) => [u.claim, `measured by ${u.sensorIds.join(", ")} \u2014 widen a judgment rule, the claim is fine`]
|
|
2632
|
+
)
|
|
2633
|
+
);
|
|
2634
|
+
lines.push(
|
|
2635
|
+
`sensors run ${result.sensorsRun.join(", ") || "(none matched)"}`
|
|
2636
|
+
);
|
|
2637
|
+
for (const u of result.unrunnableSensors) lines.push(` could not run ${u.sensorId}: ${u.reason}`);
|
|
2638
|
+
if (result.undeclaredCatches > 0) {
|
|
2639
|
+
lines.push(` ${result.undeclaredCatches} contradiction(s) the declaration never mentioned`);
|
|
2640
|
+
}
|
|
2641
|
+
if (result.redactions > 0) lines.push(` ${result.redactions} secret(s) redacted before judging`);
|
|
2642
|
+
return lines;
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
// src/mcp.ts
|
|
2646
|
+
import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "node:fs";
|
|
2647
|
+
import path4 from "node:path";
|
|
2648
|
+
|
|
2649
|
+
// src/mcp-stdio.ts
|
|
2650
|
+
var PROTOCOL_VERSIONS = [
|
|
2651
|
+
"2025-11-25",
|
|
2652
|
+
"2025-06-18",
|
|
2653
|
+
"2025-03-26",
|
|
2654
|
+
"2024-11-05",
|
|
2655
|
+
"2024-10-07"
|
|
2656
|
+
];
|
|
2657
|
+
var LATEST_PROTOCOL_VERSION = PROTOCOL_VERSIONS[0];
|
|
2658
|
+
function negotiateProtocol(requested) {
|
|
2659
|
+
return typeof requested === "string" && PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
|
|
2660
|
+
}
|
|
2661
|
+
var JSONRPC_PARSE_ERROR = -32700;
|
|
2662
|
+
var JSONRPC_INVALID_REQUEST = -32600;
|
|
2663
|
+
var JSONRPC_METHOD_NOT_FOUND = -32601;
|
|
2664
|
+
var JSONRPC_INTERNAL_ERROR = -32603;
|
|
2665
|
+
var fail = (id, code, message) => ({
|
|
2666
|
+
jsonrpc: "2.0",
|
|
2667
|
+
id,
|
|
2668
|
+
error: { code, message }
|
|
2669
|
+
});
|
|
2670
|
+
async function handleMessage(message, handlers) {
|
|
2671
|
+
if (Array.isArray(message)) {
|
|
2672
|
+
if (message.length === 0) {
|
|
2673
|
+
return fail(null, JSONRPC_INVALID_REQUEST, "batch is empty");
|
|
2674
|
+
}
|
|
2675
|
+
const answers = [];
|
|
2676
|
+
for (const entry of message) {
|
|
2677
|
+
const answer = await handleMessage(entry, handlers);
|
|
2678
|
+
if (Array.isArray(answer)) answers.push(...answer);
|
|
2679
|
+
else if (answer) answers.push(answer);
|
|
2680
|
+
}
|
|
2681
|
+
return answers.length > 0 ? answers : null;
|
|
2682
|
+
}
|
|
2683
|
+
if (typeof message !== "object" || message === null) {
|
|
2684
|
+
return fail(null, JSONRPC_INVALID_REQUEST, "message is not an object");
|
|
2685
|
+
}
|
|
2686
|
+
const { id, method, params } = message;
|
|
2687
|
+
if (typeof method !== "string") {
|
|
2688
|
+
return id === void 0 ? null : fail(id ?? null, JSONRPC_INVALID_REQUEST, "missing method");
|
|
2689
|
+
}
|
|
2690
|
+
if (id === void 0) return null;
|
|
2691
|
+
if (id === null) return fail(null, JSONRPC_INVALID_REQUEST, "request id must be a string or a number");
|
|
2692
|
+
const ok = (result) => ({ jsonrpc: "2.0", id, result });
|
|
2693
|
+
const args = params ?? {};
|
|
2694
|
+
switch (method) {
|
|
2695
|
+
case "initialize":
|
|
2696
|
+
return ok({
|
|
2697
|
+
protocolVersion: negotiateProtocol(args.protocolVersion),
|
|
2698
|
+
capabilities: { tools: {} },
|
|
2699
|
+
serverInfo: handlers.serverInfo
|
|
2700
|
+
});
|
|
2701
|
+
case "ping":
|
|
2702
|
+
return ok({});
|
|
2703
|
+
case "tools/list":
|
|
2704
|
+
return ok({ tools: handlers.listTools() });
|
|
2705
|
+
case "tools/call": {
|
|
2706
|
+
const name = args.name;
|
|
2707
|
+
if (typeof name !== "string") {
|
|
2708
|
+
return fail(id, JSONRPC_INVALID_REQUEST, "tools/call requires a tool name");
|
|
2709
|
+
}
|
|
2710
|
+
try {
|
|
2711
|
+
return ok(await handlers.callTool(name, args.arguments ?? {}));
|
|
2712
|
+
} catch (err) {
|
|
2713
|
+
return ok({
|
|
2714
|
+
content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
|
|
2715
|
+
isError: true
|
|
2716
|
+
});
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
default:
|
|
2720
|
+
return fail(id, JSONRPC_METHOD_NOT_FOUND, `method not found: ${method}`);
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
var LineBuffer = class {
|
|
2724
|
+
buffer = "";
|
|
2725
|
+
push(chunk) {
|
|
2726
|
+
this.buffer += chunk;
|
|
2727
|
+
const lines = [];
|
|
2728
|
+
let index = this.buffer.indexOf("\n");
|
|
2729
|
+
while (index !== -1) {
|
|
2730
|
+
const line = this.buffer.slice(0, index).trim();
|
|
2731
|
+
this.buffer = this.buffer.slice(index + 1);
|
|
2732
|
+
if (line) lines.push(line);
|
|
2733
|
+
index = this.buffer.indexOf("\n");
|
|
2734
|
+
}
|
|
2735
|
+
return lines;
|
|
2736
|
+
}
|
|
2737
|
+
};
|
|
2738
|
+
async function serve(stdin, stdout, handlers) {
|
|
2739
|
+
const lines = new LineBuffer();
|
|
2740
|
+
const write = (message) => {
|
|
2741
|
+
stdout.write(`${JSON.stringify(message)}
|
|
2742
|
+
`);
|
|
2743
|
+
};
|
|
2744
|
+
let queue = Promise.resolve();
|
|
2745
|
+
stdin.setEncoding("utf8");
|
|
2746
|
+
stdin.on("data", (chunk) => {
|
|
2747
|
+
for (const line of lines.push(chunk)) {
|
|
2748
|
+
queue = queue.then(async () => {
|
|
2749
|
+
let parsed;
|
|
2750
|
+
try {
|
|
2751
|
+
parsed = JSON.parse(line);
|
|
2752
|
+
} catch {
|
|
2753
|
+
write(fail(null, JSONRPC_PARSE_ERROR, "invalid JSON"));
|
|
2754
|
+
return;
|
|
2755
|
+
}
|
|
2756
|
+
try {
|
|
2757
|
+
const response = await handleMessage(parsed, handlers);
|
|
2758
|
+
if (response) write(response);
|
|
2759
|
+
} catch (err) {
|
|
2760
|
+
const id = parsed.id ?? null;
|
|
2761
|
+
write(fail(id, JSONRPC_INTERNAL_ERROR, err instanceof Error ? err.message : String(err)));
|
|
2762
|
+
}
|
|
2763
|
+
});
|
|
2764
|
+
}
|
|
2765
|
+
});
|
|
2766
|
+
await new Promise((resolve) => {
|
|
2767
|
+
stdin.on("end", resolve);
|
|
2768
|
+
stdin.on("close", resolve);
|
|
2769
|
+
});
|
|
2770
|
+
await queue;
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
// src/sensors.ts
|
|
2774
|
+
function listSensors(registryPath) {
|
|
2775
|
+
return loadRegistry(registryPath).sensors;
|
|
2776
|
+
}
|
|
2777
|
+
async function runSensor(registryPath, id, cwd) {
|
|
2778
|
+
const registry = loadRegistry(registryPath);
|
|
2779
|
+
const sensor = registry.sensors.find((s) => s.id === id);
|
|
2780
|
+
if (!sensor) {
|
|
2781
|
+
const known = registry.sensors.map((s) => s.id).join(", ") || "(registry is empty)";
|
|
2782
|
+
throw new Error(`unknown sensor id '${id}' \u2014 the registry allows: ${known}`);
|
|
2783
|
+
}
|
|
2784
|
+
const executor = new ProcessSensorExecutor(registry, { cwd });
|
|
2785
|
+
const result = await executor.run(sensor.id, {});
|
|
2786
|
+
return { id: sensor.id, output: result.output, extracted: extractValues(sensor, result.output) };
|
|
2787
|
+
}
|
|
2788
|
+
|
|
2789
|
+
// src/mcp.ts
|
|
2790
|
+
var MCP_SERVER_NAME = "gettier";
|
|
2791
|
+
function reply(text, isError = false) {
|
|
2792
|
+
return isError ? { content: [{ type: "text", text }], isError: true } : { content: [{ type: "text", text }] };
|
|
2793
|
+
}
|
|
2794
|
+
function toolDefinitions() {
|
|
2795
|
+
return [
|
|
2796
|
+
{
|
|
2797
|
+
name: "list_sensors",
|
|
2798
|
+
description: "List the sensors this project has registered and the assumption categories each can falsify. Call this BEFORE declaring: a premise no sensor covers cannot be checked here, and knowing what is measurable in this repository is what makes a declaration worth making. Sensors run by id from a local registry; there is no way to run anything else.",
|
|
2799
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
2800
|
+
},
|
|
2801
|
+
{
|
|
2802
|
+
// Verbatim Contract 1 — the same tool the proxy forces, so a declaration
|
|
2803
|
+
// made here and one made there are the same object.
|
|
2804
|
+
name: "declare_lemmas",
|
|
2805
|
+
description: DECLARE_LEMMAS_TOOL.description,
|
|
2806
|
+
inputSchema: DECLARE_LEMMAS_TOOL.input_schema
|
|
2807
|
+
},
|
|
2808
|
+
{
|
|
2809
|
+
name: "check_assumptions",
|
|
2810
|
+
description: "Run the registered sensors that bear on the premises you declared, and return what checked out, what was contradicted by measurement, and what could not be settled. A contradiction is the useful outcome: it is a fact about this system you did not have, so revise the plan around it rather than around the claim you made. Requires declare_lemmas first.",
|
|
2811
|
+
inputSchema: {
|
|
2812
|
+
type: "object",
|
|
2813
|
+
properties: {
|
|
2814
|
+
require_evidence: {
|
|
2815
|
+
type: "boolean",
|
|
2816
|
+
description: 'Treat "nothing was measured" as a failure. Off by default: on a change no sensor covers, that would fail every time and mean nothing.'
|
|
2817
|
+
}
|
|
2818
|
+
},
|
|
2819
|
+
additionalProperties: false
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
];
|
|
2823
|
+
}
|
|
2824
|
+
function requireConfig(root) {
|
|
2825
|
+
const config = readConfig(root);
|
|
2826
|
+
if (!config) throw new Error("no .gettier/project.json \u2014 run 'gettier init <project>' in this repository first");
|
|
2827
|
+
return config;
|
|
2828
|
+
}
|
|
2829
|
+
async function callTool(name, args, root) {
|
|
2830
|
+
const config = requireConfig(root);
|
|
2831
|
+
const registryPath = path4.resolve(root, config.registry);
|
|
2832
|
+
if (name === "list_sensors") {
|
|
2833
|
+
const sensors = listSensors(registryPath);
|
|
2834
|
+
if (sensors.length === 0) {
|
|
2835
|
+
return { text: `The registry at ${config.registry} is empty. Nothing can be verified in this repository yet, so any premise you declare will be reported as a coverage gap.`, isError: false };
|
|
2836
|
+
}
|
|
2837
|
+
const lines = sensors.map((s) => `${s.id} ${s.effects ?? "mutates"} falsifies: ${(s.verifies ?? []).join(", ") || "(nothing declared)"}`);
|
|
2838
|
+
return {
|
|
2839
|
+
text: [
|
|
2840
|
+
`${sensors.length} sensor(s) registered in ${config.registry}. Declare premises these can speak to and the gate has something to measure.`,
|
|
2841
|
+
frameAsData("sensor-registry", lines.join("\n"))
|
|
2842
|
+
].join("\n\n"),
|
|
2843
|
+
isError: false
|
|
2844
|
+
};
|
|
2845
|
+
}
|
|
2846
|
+
if (name === "declare_lemmas") {
|
|
2847
|
+
const { declaration, warnings } = parseDeclaration(args);
|
|
2848
|
+
const file = path4.join(root, DECLARATION_FILE);
|
|
2849
|
+
mkdirSync2(path4.dirname(file), { recursive: true });
|
|
2850
|
+
writeFileSync2(file, `${JSON.stringify(args, null, 2)}
|
|
2851
|
+
`);
|
|
2852
|
+
const loadBearing = declaration.lemmas.filter((l) => l.loadBearing).length;
|
|
2853
|
+
return {
|
|
2854
|
+
text: [
|
|
2855
|
+
`Recorded ${declaration.lemmas.length} premise(s), ${loadBearing} load-bearing, to ${DECLARATION_FILE}.`,
|
|
2856
|
+
...warnings.map((w) => `Schema deviation tolerated: ${w}`),
|
|
2857
|
+
loadBearing === 0 ? "None are load-bearing, so the gate has nothing to evaluate. If the plan genuinely fails when a premise is false, mark it load_bearing." : "Now call check_assumptions. Do not author the change until you have."
|
|
2858
|
+
].join("\n"),
|
|
2859
|
+
isError: false
|
|
2860
|
+
};
|
|
2861
|
+
}
|
|
2862
|
+
if (name === "check_assumptions") {
|
|
2863
|
+
const { result, warnings } = await runCheck(root, registryPath);
|
|
2864
|
+
const code = checkExitCode(result, { requireEvidence: args.require_evidence === true });
|
|
2865
|
+
try {
|
|
2866
|
+
await projectTransport(config).send([
|
|
2867
|
+
surfaceEvent(code === 0 ? "gate.released" : "gate.held", checkEventPayload(result))
|
|
2868
|
+
]);
|
|
2869
|
+
} catch {
|
|
2870
|
+
}
|
|
2871
|
+
const guidance = result.decision.catches.length > 0 ? "A measurement contradicts a premise the plan rests on. Revise the plan around the measured fact \u2014 do not restate the claim, and do not proceed as written." : result.decision.holds.length > 0 ? "A premise could not be settled. Confirm it with the user, correct it, or waive it explicitly \u2014 do not assume it." : "Nothing was contradicted. Anything listed as uncovered was not verified, only unchallenged.";
|
|
2872
|
+
return {
|
|
2873
|
+
text: [
|
|
2874
|
+
checkSummaryLine(result),
|
|
2875
|
+
...warnings.map((w) => `Schema deviation tolerated: ${w}`),
|
|
2876
|
+
// Sensor-derived. Framed as data: a reading is evidence, not instruction.
|
|
2877
|
+
frameAsData("verification-report", formatCheckText(result, { summary: false }).join("\n")),
|
|
2878
|
+
guidance
|
|
2879
|
+
].join("\n\n"),
|
|
2880
|
+
isError: code !== 0
|
|
2881
|
+
};
|
|
2882
|
+
}
|
|
2883
|
+
return { text: `unknown tool '${name}'`, isError: true };
|
|
2884
|
+
}
|
|
2885
|
+
function buildHandlers(root, version) {
|
|
2886
|
+
return {
|
|
2887
|
+
serverInfo: { name: MCP_SERVER_NAME, version },
|
|
2888
|
+
listTools: () => toolDefinitions(),
|
|
2889
|
+
callTool: async (name, args) => {
|
|
2890
|
+
const outcome = await callTool(name, args, root);
|
|
2891
|
+
return reply(outcome.text, outcome.isError);
|
|
2892
|
+
}
|
|
2893
|
+
};
|
|
2894
|
+
}
|
|
2895
|
+
function protectProtocolChannel(target = console, stderr = process.stderr) {
|
|
2896
|
+
for (const level of ["log", "info", "warn", "debug", "trace"]) {
|
|
2897
|
+
target[level] = (...args) => {
|
|
2898
|
+
stderr.write(`${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
|
|
2899
|
+
`);
|
|
2900
|
+
};
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
async function serveMcp(root, version) {
|
|
2904
|
+
protectProtocolChannel();
|
|
2905
|
+
await serve(process.stdin, process.stdout, buildHandlers(root, version));
|
|
2906
|
+
}
|
|
2907
|
+
|
|
2908
|
+
// src/cli.ts
|
|
2909
|
+
function packageVersion() {
|
|
2910
|
+
const file = path5.join(path5.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
2911
|
+
return JSON.parse(readFileSync4(file, "utf8")).version;
|
|
2912
|
+
}
|
|
2913
|
+
var USAGE = `gettier \u2014 Gettier for Agents
|
|
2914
|
+
|
|
2915
|
+
gettier init <project> [--environment env] [--registry path]
|
|
2916
|
+
[--endpoint url | --local] [--force]
|
|
2917
|
+
gettier status
|
|
2918
|
+
gettier sensors list
|
|
2919
|
+
gettier sensors run <id>
|
|
2920
|
+
gettier check [--declaration path|-] [--markdown path] [--json]
|
|
2921
|
+
[--require-evidence] [--hold-on-unverifiable] [--api-cwd dir]
|
|
2922
|
+
gettier mcp
|
|
2923
|
+
|
|
2924
|
+
--local points a project at a dashboard on this machine; without it, and without
|
|
2925
|
+
GETTIER_ENDPOINT, events go to the hosted API.
|
|
2926
|
+
|
|
2927
|
+
check reads a declare_lemmas declaration (default ${DECLARATION_FILE}), runs the
|
|
2928
|
+
sensors that bear on it, and exits 0 when the gate allows the change, 2 when it
|
|
2929
|
+
does not, and 1 when the check itself could not run.
|
|
2930
|
+
|
|
2931
|
+
mcp serves three tools over stdio to any MCP-capable agent: list_sensors,
|
|
2932
|
+
declare_lemmas (Contract 1, verbatim) and check_assumptions. Register it with
|
|
2933
|
+
your agent as: gettier mcp
|
|
2934
|
+
|
|
2935
|
+
Not implemented yet: Claude Code hooks, Codex configuration, a packaged GitHub
|
|
2936
|
+
Action. See the repository README for what ships today.`;
|
|
2937
|
+
async function probe(url, dsn) {
|
|
2938
|
+
try {
|
|
2939
|
+
const response = await fetch(url, {
|
|
2940
|
+
method: "POST",
|
|
2941
|
+
signal: AbortSignal.timeout(4e3),
|
|
2942
|
+
headers: {
|
|
2943
|
+
"content-type": "application/json",
|
|
2944
|
+
...dsn ? { authorization: `Bearer ${dsn}` } : {}
|
|
2945
|
+
},
|
|
2946
|
+
// An empty events array: rejected as malformed by a healthy endpoint,
|
|
2947
|
+
// which is a clearer signal than sending a fake event into someone's data.
|
|
2948
|
+
body: JSON.stringify({ events: [] })
|
|
2949
|
+
});
|
|
2950
|
+
if (response.status === 404) return "no \u2014 HTTP 404, check the path";
|
|
2951
|
+
if (response.status === 401) return "reachable, but the credential was REJECTED (401)";
|
|
2952
|
+
if (response.status === 503) return "reachable, but ingestion is not configured there (503)";
|
|
2953
|
+
return `yes (HTTP ${response.status}${response.status === 400 ? " \u2014 endpoint healthy" : ""})`;
|
|
2954
|
+
} catch (err) {
|
|
2955
|
+
return `no (${err instanceof Error ? err.message : String(err)})`;
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
function requireConfig2(root) {
|
|
2959
|
+
const config = readConfig(root);
|
|
2960
|
+
if (!config) throw new Error("no .gettier/project.json \u2014 run 'gettier init <project>' first");
|
|
2961
|
+
return config;
|
|
2962
|
+
}
|
|
2963
|
+
async function main(argv, root = process.cwd(), log = console.log) {
|
|
2964
|
+
const [command, ...rest] = argv;
|
|
2965
|
+
const flag = (name) => {
|
|
2966
|
+
const i = rest.indexOf(`--${name}`);
|
|
2967
|
+
return i === -1 ? void 0 : rest[i + 1];
|
|
2968
|
+
};
|
|
2969
|
+
switch (command) {
|
|
2970
|
+
case "init": {
|
|
2971
|
+
const project = rest[0];
|
|
2972
|
+
if (!project || project.startsWith("--")) throw new Error("usage: gettier init <project>");
|
|
2973
|
+
const endpoint = rest.includes("--local") ? LOCAL_INGEST_ENDPOINT : flag("endpoint");
|
|
2974
|
+
const config = {
|
|
2975
|
+
project,
|
|
2976
|
+
environment: flag("environment") ?? DEFAULT_CONFIG.environment,
|
|
2977
|
+
registry: flag("registry") ?? DEFAULT_CONFIG.registry,
|
|
2978
|
+
dsnEnvVar: DEFAULT_CONFIG.dsnEnvVar,
|
|
2979
|
+
...endpoint ? { endpoint } : {}
|
|
2980
|
+
};
|
|
2981
|
+
writeConfig(root, config, { force: rest.includes("--force") });
|
|
2982
|
+
log(`initialised project '${project}' (environment ${config.environment})`);
|
|
2983
|
+
log(`sensors are read from ${config.registry}, executed by id only`);
|
|
2984
|
+
log(`set ${config.dsnEnvVar} in the environment \u2014 never in this file`);
|
|
2985
|
+
const resolved = resolveEndpoint(config);
|
|
2986
|
+
log(`events go to ${resolved.url} (${resolved.source})`);
|
|
2987
|
+
if (resolved.source === "hosted default") {
|
|
2988
|
+
log(` developing against a local dashboard? re-run with --local`);
|
|
2989
|
+
}
|
|
2990
|
+
return 0;
|
|
2991
|
+
}
|
|
2992
|
+
case "status": {
|
|
2993
|
+
const config = requireConfig2(root);
|
|
2994
|
+
const dsn = process.env[config.dsnEnvVar];
|
|
2995
|
+
log(`project ${config.project}`);
|
|
2996
|
+
log(`environment ${config.environment}`);
|
|
2997
|
+
log(`registry ${config.registry}`);
|
|
2998
|
+
log(`${config.dsnEnvVar} ${dsn ? "set" : "not set"}`);
|
|
2999
|
+
const resolved = resolveEndpoint(config);
|
|
3000
|
+
log(`endpoint ${resolved.url}`);
|
|
3001
|
+
log(` from ${resolved.source}`);
|
|
3002
|
+
log(`transport ${projectTransport(config).name}`);
|
|
3003
|
+
if (!dsn) {
|
|
3004
|
+
log(` set ${config.dsnEnvVar} to transmit`);
|
|
3005
|
+
return 0;
|
|
3006
|
+
}
|
|
3007
|
+
log(`reachable ${await probe(resolved.url, dsn)}`);
|
|
3008
|
+
return 0;
|
|
3009
|
+
}
|
|
3010
|
+
case "mcp": {
|
|
3011
|
+
requireConfig2(root);
|
|
3012
|
+
await serveMcp(root, packageVersion());
|
|
3013
|
+
return 0;
|
|
3014
|
+
}
|
|
3015
|
+
case "check": {
|
|
3016
|
+
const config = requireConfig2(root);
|
|
3017
|
+
const registryPath = path5.resolve(root, config.registry);
|
|
3018
|
+
const { result, warnings, from } = await runCheck(root, registryPath, {
|
|
3019
|
+
...flag("declaration") ? { declaration: flag("declaration") } : {},
|
|
3020
|
+
...flag("api-cwd") ? { apiResolutionCwd: path5.resolve(root, flag("api-cwd")) } : {},
|
|
3021
|
+
...rest.includes("--hold-on-unverifiable") ? { policy: { holdOnUnverifiable: true } } : {}
|
|
3022
|
+
});
|
|
3023
|
+
const code = checkExitCode(result, { requireEvidence: rest.includes("--require-evidence") });
|
|
3024
|
+
if (rest.includes("--json")) {
|
|
3025
|
+
log(JSON.stringify({ ...result, exitCode: code }, null, 2));
|
|
3026
|
+
} else {
|
|
3027
|
+
log(`declaration ${from}`);
|
|
3028
|
+
for (const w of warnings) log(` (schema deviation tolerated: ${w})`);
|
|
3029
|
+
for (const line of formatCheckText(result)) log(line);
|
|
3030
|
+
}
|
|
3031
|
+
const markdown = flag("markdown");
|
|
3032
|
+
if (markdown) {
|
|
3033
|
+
writeFileSync3(path5.resolve(root, markdown), `${formatCheckMarkdown(result)}
|
|
3034
|
+
`);
|
|
3035
|
+
log(`comment written to ${markdown}`);
|
|
3036
|
+
}
|
|
3037
|
+
try {
|
|
3038
|
+
const type = code === 0 ? "gate.released" : "gate.held";
|
|
3039
|
+
await projectTransport(config).send([surfaceEvent(type, checkEventPayload(result))]);
|
|
3040
|
+
} catch (err) {
|
|
3041
|
+
log(`(not reported: ${err instanceof Error ? err.message : String(err)})`);
|
|
3042
|
+
}
|
|
3043
|
+
return code;
|
|
3044
|
+
}
|
|
3045
|
+
case "sensors": {
|
|
3046
|
+
const config = requireConfig2(root);
|
|
3047
|
+
const registryPath = path5.resolve(root, config.registry);
|
|
3048
|
+
if (rest[0] === "list") {
|
|
3049
|
+
for (const s of listSensors(registryPath)) {
|
|
3050
|
+
log(`${s.id} ${s.effects ?? "mutates"} ${(s.verifies ?? []).join(", ")}`);
|
|
3051
|
+
}
|
|
3052
|
+
return 0;
|
|
3053
|
+
}
|
|
3054
|
+
if (rest[0] === "run") {
|
|
3055
|
+
const id = rest[1];
|
|
3056
|
+
if (!id) throw new Error("usage: gettier sensors run <id>");
|
|
3057
|
+
const result = await runSensor(registryPath, id, root);
|
|
3058
|
+
log(result.output.trim());
|
|
3059
|
+
try {
|
|
3060
|
+
await projectTransport(config).send([agentEvent("sensor.completed", config, { sensor: result.id })]);
|
|
3061
|
+
} catch (err) {
|
|
3062
|
+
log(` (not reported: ${err instanceof Error ? err.message : String(err)})`);
|
|
3063
|
+
}
|
|
3064
|
+
return 0;
|
|
3065
|
+
}
|
|
3066
|
+
throw new Error("usage: gettier sensors list | gettier sensors run <id>");
|
|
3067
|
+
}
|
|
3068
|
+
default:
|
|
3069
|
+
log(USAGE);
|
|
3070
|
+
return command === void 0 || command === "--help" ? 0 : 1;
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
function invokedAsEntryPoint() {
|
|
3074
|
+
const entry = process.argv[1];
|
|
3075
|
+
if (!entry) return false;
|
|
3076
|
+
try {
|
|
3077
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(entry);
|
|
3078
|
+
} catch {
|
|
3079
|
+
return false;
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
var invokedDirectly = invokedAsEntryPoint();
|
|
3083
|
+
if (invokedDirectly) {
|
|
3084
|
+
main(process.argv.slice(2)).then((code) => process.exit(code)).catch((err) => {
|
|
3085
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
3086
|
+
process.exit(1);
|
|
3087
|
+
});
|
|
3088
|
+
}
|
|
3089
|
+
export {
|
|
3090
|
+
main
|
|
3091
|
+
};
|