@skillstech/thunderlang 0.4.2 → 0.5.2
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/CHANGELOG.md +28 -0
- package/dist/core.cjs +6082 -3970
- package/dist/index.cjs +2798 -384
- package/package.json +1 -1
- package/src/cli.mjs +130 -4
- package/src/core.d.ts +9 -0
- package/src/core.mjs +5 -0
- package/src/emit.mjs +1 -1
- package/src/expr.mjs +42 -1
- package/src/human-contract.d.mts +20 -0
- package/src/human-contract.mjs +213 -0
- package/src/lift.mjs +7 -0
- package/src/mcp.mjs +120 -22
- package/src/promote.d.mts +6 -0
- package/src/promote.mjs +165 -0
- package/src/read-repo-fs.mjs +29 -0
- package/src/read-repo.d.mts +21 -0
- package/src/read-repo.mjs +139 -0
- package/src/read.d.mts +29 -0
- package/src/read.mjs +1485 -0
- package/src/target-elixir.mjs +79 -0
- package/src/target-go.mjs +95 -0
- package/src/target-kotlin.mjs +91 -0
- package/src/target-rust.mjs +99 -0
- package/src/target-scala.mjs +93 -0
- package/src/target-types.mjs +62 -0
- package/src/target-util.mjs +1 -59
- package/src/translate.d.mts +5 -0
- package/src/translate.mjs +126 -0
package/dist/index.cjs
CHANGED
|
@@ -635,10 +635,10 @@ function parseHandler(trigger, node2) {
|
|
|
635
635
|
}
|
|
636
636
|
var VERIFY_KINDS = /* @__PURE__ */ new Set(["assertion", "static", "runtime", "evidence", "tool", "approval", "formal"]);
|
|
637
637
|
function upsertRule(list, statement, line) {
|
|
638
|
-
const
|
|
639
|
-
let r = list.find((x) => x.id ===
|
|
638
|
+
const id2 = slug(statement);
|
|
639
|
+
let r = list.find((x) => x.id === id2);
|
|
640
640
|
if (!r) {
|
|
641
|
-
r = { id, statement, because: null, verify: [], verifications: [], notes: [], line };
|
|
641
|
+
r = { id: id2, statement, because: null, verify: [], verifications: [], notes: [], line };
|
|
642
642
|
list.push(r);
|
|
643
643
|
}
|
|
644
644
|
return r;
|
|
@@ -1280,8 +1280,8 @@ function toEvidenceEvents(proof) {
|
|
|
1280
1280
|
function verifyDiffToEvidence(verdict2, ctx = {}) {
|
|
1281
1281
|
if (!verdict2 || typeof verdict2 !== "object") return [];
|
|
1282
1282
|
const findings2 = Array.isArray(verdict2.findings) ? verdict2.findings : [];
|
|
1283
|
-
const
|
|
1284
|
-
return [envelope("change.gated",
|
|
1283
|
+
const id2 = `tl-verifydiff-${short(ctx.intentHash)}${ctx.changeHash ? `-${short(ctx.changeHash, 8)}` : ""}`;
|
|
1284
|
+
return [envelope("change.gated", id2, ctx, {
|
|
1285
1285
|
verdict: verdict2.verdict || null,
|
|
1286
1286
|
ok: !!verdict2.ok,
|
|
1287
1287
|
blocking: verdict2.blocking || 0,
|
|
@@ -1317,8 +1317,8 @@ function conformToEvidence(report, ctx = {}) {
|
|
|
1317
1317
|
function driftToEvidence(report, ctx = {}) {
|
|
1318
1318
|
if (!report || typeof report !== "object") return [];
|
|
1319
1319
|
const findings2 = Array.isArray(report.findings) ? report.findings : [];
|
|
1320
|
-
const
|
|
1321
|
-
return [envelope("intent.drift",
|
|
1320
|
+
const id2 = `tl-drift-${short(ctx.intentHash)}${ctx.codeHash ? `-${short(ctx.codeHash, 8)}` : ""}`;
|
|
1321
|
+
return [envelope("intent.drift", id2, ctx, {
|
|
1322
1322
|
status: report.status || null,
|
|
1323
1323
|
total: findings2.length,
|
|
1324
1324
|
blocking: report.summary?.blocking ?? 0,
|
|
@@ -2389,7 +2389,7 @@ function notesSummary(ast) {
|
|
|
2389
2389
|
byLens
|
|
2390
2390
|
};
|
|
2391
2391
|
}
|
|
2392
|
-
var COMPILER_VERSION = "0.
|
|
2392
|
+
var COMPILER_VERSION = "0.5.2";
|
|
2393
2393
|
var PROOF_SCHEMA_VERSION = "0.1.0";
|
|
2394
2394
|
var SOURCE_PRODUCT = "skillstech-compiler";
|
|
2395
2395
|
function buildContractGraph(ast, generatedAt) {
|
|
@@ -3054,7 +3054,7 @@ function renderMarkdown(ast) {
|
|
|
3054
3054
|
function renderLensDoc(ast, lens) {
|
|
3055
3055
|
const m = ast.mission || "mission";
|
|
3056
3056
|
const prefix = `mission.${m}`;
|
|
3057
|
-
const
|
|
3057
|
+
const flat2 = (t) => String(t).replace(/\s+/g, " ").trim();
|
|
3058
3058
|
const notesFor = (path) => (ast.notes || []).filter((n) => n.lens === lens && n.targetPath === path);
|
|
3059
3059
|
const L = [];
|
|
3060
3060
|
L.push(`# ${m} , for the ${lens} reader`, "");
|
|
@@ -3063,7 +3063,7 @@ function renderLensDoc(ast, lens) {
|
|
|
3063
3063
|
`> audience; they are documentation, not verification.`,
|
|
3064
3064
|
""
|
|
3065
3065
|
);
|
|
3066
|
-
for (const nt of notesFor(prefix)) L.push(`_${
|
|
3066
|
+
for (const nt of notesFor(prefix)) L.push(`_${flat2(nt.text)}_`, "");
|
|
3067
3067
|
if (ast.goal) L.push(`**Goal.** ${ast.goal}`, "");
|
|
3068
3068
|
if (ast.why) L.push(`**Why.** ${ast.why}`, "");
|
|
3069
3069
|
const fieldSection = (title, fields, kind) => {
|
|
@@ -3071,7 +3071,7 @@ function renderLensDoc(ast, lens) {
|
|
|
3071
3071
|
L.push(`## ${title}`, "");
|
|
3072
3072
|
for (const f of fields) {
|
|
3073
3073
|
L.push(`- \`${f.name}: ${f.type}\``);
|
|
3074
|
-
for (const nt of notesFor(`${prefix}.${kind}.${f.name}`)) L.push(` , ${
|
|
3074
|
+
for (const nt of notesFor(`${prefix}.${kind}.${f.name}`)) L.push(` , ${flat2(nt.text)}`);
|
|
3075
3075
|
}
|
|
3076
3076
|
L.push("");
|
|
3077
3077
|
};
|
|
@@ -3082,7 +3082,7 @@ function renderLensDoc(ast, lens) {
|
|
|
3082
3082
|
L.push(`## ${title}`, "");
|
|
3083
3083
|
for (const r of rules) {
|
|
3084
3084
|
L.push(`- ${r.statement}${r.because ? ` (because ${r.because})` : ""}`);
|
|
3085
|
-
for (const nt of notesFor(`${prefix}.${kind}.${r.id}`)) L.push(` , ${
|
|
3085
|
+
for (const nt of notesFor(`${prefix}.${kind}.${r.id}`)) L.push(` , ${flat2(nt.text)}`);
|
|
3086
3086
|
}
|
|
3087
3087
|
L.push("");
|
|
3088
3088
|
};
|
|
@@ -3217,7 +3217,7 @@ var LENS_INFO = {
|
|
|
3217
3217
|
};
|
|
3218
3218
|
var BLOCK_KEYWORDS = ["goal", "why", "input", "output", "guarantees", "never", "verify", "target", "examples", "note"];
|
|
3219
3219
|
var SENSITIVE = /payment token|secret|token|password|jwt|credential|ssn|pii|email/i;
|
|
3220
|
-
var item = (
|
|
3220
|
+
var item = (id2, label, insertText, detail, sortText = "050", kind = "snippet") => ({ id: id2, label, kind, detail, insertText, sortText, source: "compiler", confidence: "high" });
|
|
3221
3221
|
var noteItem = (lens) => item(`completion_note_${lens}`, `note ${lens}:`, `note ${lens}:
|
|
3222
3222
|
\${1:${LENS_INFO[lens]}}`, LENS_INFO[lens], "010");
|
|
3223
3223
|
var typeItem = (t) => item(`completion_type_${t}`, t, t, `Semantic type: ${TYPE_INFO[t]?.description || TYPE_INFO[t.replace(/\(.*/, "")]?.description || "A semantic type."}`, "020", "type");
|
|
@@ -3994,6 +3994,11 @@ var ADAPTERS = {
|
|
|
3994
3994
|
ex: extractFactsElixir,
|
|
3995
3995
|
exs: extractFactsElixir
|
|
3996
3996
|
};
|
|
3997
|
+
function extractFacts(source, language, file) {
|
|
3998
|
+
const key = String(language).toLowerCase();
|
|
3999
|
+
const adapter = ADAPTERS[key];
|
|
4000
|
+
return adapter ? adapter(String(source), file || `input.${LANG_EXT[key] || "txt"}`) : null;
|
|
4001
|
+
}
|
|
3997
4002
|
var SUPPORTED_LANGUAGES = ["typescript", "javascript", "python", "java", "csharp", "go", "rust", "cpp", "php", "ruby", "perl", "kotlin", "scala", "elixir"];
|
|
3998
4003
|
var DYNAMIC_LANGUAGES = /* @__PURE__ */ new Set(["perl", "javascript", "python", "ruby", "php", "elixir"]);
|
|
3999
4004
|
var LANG_DISPLAY = {
|
|
@@ -4509,9 +4514,9 @@ function parseSelection(lines) {
|
|
|
4509
4514
|
if (/^require\b/.test(t)) {
|
|
4510
4515
|
require2.push(t.replace(/^require\s+/, ""));
|
|
4511
4516
|
} else if (/^prefer\b/.test(t)) {
|
|
4512
|
-
const
|
|
4513
|
-
const direction = MAX_WORDS.has(
|
|
4514
|
-
prefer.push({ metric: normalizeMetric(
|
|
4517
|
+
const words3 = t.replace(/^prefer\s+/, "").split(/\s+/);
|
|
4518
|
+
const direction = MAX_WORDS.has(words3[0]) ? "max" : MIN_WORDS.has(words3[0]) ? "min" : "min";
|
|
4519
|
+
prefer.push({ metric: normalizeMetric(words3.slice(1).join(" ")), direction });
|
|
4515
4520
|
}
|
|
4516
4521
|
}
|
|
4517
4522
|
return { require: require2, prefer, requireAllChecks: require2.some((r) => /verification|all/.test(r)) };
|
|
@@ -4528,10 +4533,10 @@ var DEFAULT_PREFER = [
|
|
|
4528
4533
|
{ metric: "dependencies", direction: "min" },
|
|
4529
4534
|
{ metric: "size", direction: "min" }
|
|
4530
4535
|
];
|
|
4531
|
-
function selectCandidate(
|
|
4536
|
+
function selectCandidate(candidates2, policy = {}) {
|
|
4532
4537
|
const prefer = policy.prefer && policy.prefer.length ? policy.prefer : DEFAULT_PREFER;
|
|
4533
4538
|
const requireAllChecks = !!policy.requireAllChecks;
|
|
4534
|
-
const eligible = (
|
|
4539
|
+
const eligible = (candidates2 || []).filter((c) => requireAllChecks ? c.checksPassed !== false : true);
|
|
4535
4540
|
const ranked = [...eligible].sort((a, b) => {
|
|
4536
4541
|
for (const p of prefer) {
|
|
4537
4542
|
const av = a.metrics ? a.metrics[p.metric] : void 0;
|
|
@@ -4543,14 +4548,14 @@ function selectCandidate(candidates, policy = {}) {
|
|
|
4543
4548
|
}
|
|
4544
4549
|
return String(a.id).localeCompare(String(b.id));
|
|
4545
4550
|
});
|
|
4546
|
-
return { winner: ranked[0] || null, ranking: ranked, eligibleCount: eligible.length, rejected: (
|
|
4551
|
+
return { winner: ranked[0] || null, ranking: ranked, eligibleCount: eligible.length, rejected: (candidates2 || []).length - eligible.length, prefer };
|
|
4547
4552
|
}
|
|
4548
4553
|
|
|
4549
4554
|
// src/intent-graph.mjs
|
|
4550
4555
|
var INTENT_GRAPH_SCHEMA = "intent-graph-v1";
|
|
4551
|
-
function node(
|
|
4556
|
+
function node(id2, type, title, extra = {}) {
|
|
4552
4557
|
return {
|
|
4553
|
-
id,
|
|
4558
|
+
id: id2,
|
|
4554
4559
|
type,
|
|
4555
4560
|
title: title || null,
|
|
4556
4561
|
description: extra.description ?? null,
|
|
@@ -4578,103 +4583,103 @@ function buildIntentGraph(ast) {
|
|
|
4578
4583
|
}));
|
|
4579
4584
|
for (const [kind, name] of [["persona", ast.persona], ["customer", ast.customer]]) {
|
|
4580
4585
|
if (!name) continue;
|
|
4581
|
-
const
|
|
4582
|
-
nodes2.push(node(
|
|
4583
|
-
relationships.push(rel(mId, "addresses",
|
|
4586
|
+
const id2 = `persona.${slug(name)}`;
|
|
4587
|
+
nodes2.push(node(id2, "Persona", name, { description: kind }));
|
|
4588
|
+
relationships.push(rel(mId, "addresses", id2));
|
|
4584
4589
|
}
|
|
4585
4590
|
for (const e of ast.evidence || []) {
|
|
4586
|
-
const
|
|
4587
|
-
nodes2.push(node(
|
|
4588
|
-
relationships.push(rel(mId, "supported_by",
|
|
4591
|
+
const id2 = `evidence.${slug(e.name || "evidence")}`;
|
|
4592
|
+
nodes2.push(node(id2, "Evidence", e.name, { classification: e.classification, confidence: e.confidence, source: e.source }));
|
|
4593
|
+
relationships.push(rel(mId, "supported_by", id2));
|
|
4589
4594
|
}
|
|
4590
4595
|
for (const o of ast.outcomes || []) {
|
|
4591
|
-
const
|
|
4592
|
-
nodes2.push(node(
|
|
4593
|
-
relationships.push(rel(mId, "targets",
|
|
4596
|
+
const id2 = `outcome.${slug(o.name || "outcome")}`;
|
|
4597
|
+
nodes2.push(node(id2, "Outcome", o.name, { description: o.description }));
|
|
4598
|
+
relationships.push(rel(mId, "targets", id2));
|
|
4594
4599
|
}
|
|
4595
4600
|
for (const m of ast.metrics || []) {
|
|
4596
|
-
const
|
|
4597
|
-
nodes2.push(node(
|
|
4601
|
+
const id2 = `metric.${slug(m.name || "metric")}`;
|
|
4602
|
+
nodes2.push(node(id2, "Metric", m.name, { description: [m.baseline && `baseline ${m.baseline}`, m.target && `target ${m.target}`, m.window && `window ${m.window}`].filter(Boolean).join("; ") || null }));
|
|
4598
4603
|
const ms = slug(m.name || "metric");
|
|
4599
4604
|
const o = (ast.outcomes || []).find((x) => {
|
|
4600
4605
|
const xs = slug(x.name || "outcome");
|
|
4601
4606
|
return xs.includes(ms) || ms.includes(xs);
|
|
4602
4607
|
});
|
|
4603
|
-
relationships.push(rel(o ? `outcome.${slug(o.name || "outcome")}` : mId, "measured_by",
|
|
4608
|
+
relationships.push(rel(o ? `outcome.${slug(o.name || "outcome")}` : mId, "measured_by", id2));
|
|
4604
4609
|
}
|
|
4605
4610
|
(ast.requires || []).forEach((r, i) => {
|
|
4606
|
-
const
|
|
4607
|
-
nodes2.push(node(
|
|
4608
|
-
relationships.push(rel(mId, "requires",
|
|
4611
|
+
const id2 = `requirement.${slug(ast.mission)}.${i + 1}`;
|
|
4612
|
+
nodes2.push(node(id2, "Requirement", r, { classification: "observed" }));
|
|
4613
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4609
4614
|
});
|
|
4610
4615
|
const emittedVerifs = /* @__PURE__ */ new Set();
|
|
4611
4616
|
for (const g of ast.guarantees || []) {
|
|
4612
|
-
const
|
|
4613
|
-
nodes2.push(node(
|
|
4614
|
-
relationships.push(rel(mId, "requires",
|
|
4617
|
+
const id2 = `guarantee.${g.id || slug(g.statement)}`;
|
|
4618
|
+
nodes2.push(node(id2, "Guarantee", g.statement, { status: g.verify && g.verify.length ? "verify-declared" : "unverified" }));
|
|
4619
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4615
4620
|
for (const v of g.verify || []) {
|
|
4616
4621
|
const vid = `verification.${slug(v)}`;
|
|
4617
4622
|
if (!emittedVerifs.has(vid)) {
|
|
4618
4623
|
nodes2.push(node(vid, "VerificationRule", v, { status: "verify-declared" }));
|
|
4619
4624
|
emittedVerifs.add(vid);
|
|
4620
4625
|
}
|
|
4621
|
-
relationships.push(rel(
|
|
4626
|
+
relationships.push(rel(id2, "verified_by", vid));
|
|
4622
4627
|
}
|
|
4623
4628
|
}
|
|
4624
4629
|
for (const n of ast.neverRules || []) {
|
|
4625
|
-
const
|
|
4626
|
-
nodes2.push(node(
|
|
4627
|
-
relationships.push(rel(mId, "constrained_by",
|
|
4630
|
+
const id2 = `never.${n.id || slug(n.statement)}`;
|
|
4631
|
+
nodes2.push(node(id2, "Never", n.statement, { status: n.verify && n.verify.length ? "verify-declared" : "unverified" }));
|
|
4632
|
+
relationships.push(rel(mId, "constrained_by", id2));
|
|
4628
4633
|
for (const v of n.verify || []) {
|
|
4629
4634
|
const vid = `verification.${slug(v)}`;
|
|
4630
4635
|
if (!emittedVerifs.has(vid)) {
|
|
4631
4636
|
nodes2.push(node(vid, "VerificationRule", v, { status: "verify-declared" }));
|
|
4632
4637
|
emittedVerifs.add(vid);
|
|
4633
4638
|
}
|
|
4634
|
-
relationships.push(rel(
|
|
4639
|
+
relationships.push(rel(id2, "verified_by", vid));
|
|
4635
4640
|
}
|
|
4636
4641
|
}
|
|
4637
4642
|
for (const iv of ast.invariants || []) {
|
|
4638
|
-
const
|
|
4639
|
-
nodes2.push(node(
|
|
4643
|
+
const id2 = `invariant.${iv.id || slug(iv.name)}`;
|
|
4644
|
+
nodes2.push(node(id2, "Invariant", iv.statement || iv.name, {
|
|
4640
4645
|
status: iv.verify && iv.verify.length ? "verify-declared" : "unverified",
|
|
4641
4646
|
description: iv.because || null
|
|
4642
4647
|
}));
|
|
4643
|
-
relationships.push(rel(mId, "constrained_by",
|
|
4648
|
+
relationships.push(rel(mId, "constrained_by", id2));
|
|
4644
4649
|
for (const v of iv.verify || []) {
|
|
4645
4650
|
const vid = `verification.${slug(v)}`;
|
|
4646
4651
|
if (!emittedVerifs.has(vid)) {
|
|
4647
4652
|
nodes2.push(node(vid, "VerificationRule", v, { status: "verify-declared" }));
|
|
4648
4653
|
emittedVerifs.add(vid);
|
|
4649
4654
|
}
|
|
4650
|
-
relationships.push(rel(
|
|
4655
|
+
relationships.push(rel(id2, "verified_by", vid));
|
|
4651
4656
|
}
|
|
4652
4657
|
}
|
|
4653
4658
|
const emittedSkills = /* @__PURE__ */ new Set();
|
|
4654
4659
|
for (const sk of ast.skills || []) {
|
|
4655
|
-
const
|
|
4656
|
-
if (!emittedSkills.has(
|
|
4657
|
-
nodes2.push(node(
|
|
4658
|
-
emittedSkills.add(
|
|
4660
|
+
const id2 = sk.id || skillRefId(sk.name);
|
|
4661
|
+
if (!emittedSkills.has(id2)) {
|
|
4662
|
+
nodes2.push(node(id2, "Skill", sk.name, { status: "required" }));
|
|
4663
|
+
emittedSkills.add(id2);
|
|
4659
4664
|
}
|
|
4660
|
-
relationships.push(rel(mId, "requires_skill",
|
|
4665
|
+
relationships.push(rel(mId, "requires_skill", id2));
|
|
4661
4666
|
}
|
|
4662
4667
|
for (const u of ast.unknowns || []) {
|
|
4663
|
-
const
|
|
4664
|
-
nodes2.push(node(
|
|
4665
|
-
relationships.push(rel(mId, "depends_on",
|
|
4666
|
-
if (u.resolveBefore) relationships.push(rel(
|
|
4668
|
+
const id2 = `unknown.${slug(u.name || "unknown")}`;
|
|
4669
|
+
nodes2.push(node(id2, "Unknown", u.name, { classification: "unknown", owner: u.owner, status: "unresolved" }));
|
|
4670
|
+
relationships.push(rel(mId, "depends_on", id2));
|
|
4671
|
+
if (u.resolveBefore) relationships.push(rel(id2, "blocks", `phase.${slug(u.resolveBefore)}`));
|
|
4667
4672
|
}
|
|
4668
4673
|
for (const q of ast.questions || []) {
|
|
4669
|
-
const
|
|
4670
|
-
nodes2.push(node(
|
|
4671
|
-
relationships.push(rel(mId, "depends_on",
|
|
4672
|
-
if (q.blocks) relationships.push(rel(
|
|
4674
|
+
const id2 = `question.${slug(q.name || "question")}`;
|
|
4675
|
+
nodes2.push(node(id2, "Question", q.name, { classification: "unknown", owner: q.askedOf, status: "open" }));
|
|
4676
|
+
relationships.push(rel(mId, "depends_on", id2));
|
|
4677
|
+
if (q.blocks) relationships.push(rel(id2, "blocks", `phase.${slug(q.blocks)}`));
|
|
4673
4678
|
}
|
|
4674
4679
|
for (const a of ast.assumptionDecls || []) {
|
|
4675
|
-
const
|
|
4676
|
-
nodes2.push(node(
|
|
4677
|
-
relationships.push(rel(mId, "depends_on",
|
|
4680
|
+
const id2 = `assumption.${slug(a.name || "assumption")}`;
|
|
4681
|
+
nodes2.push(node(id2, "Assumption", a.name, { classification: "assumed", confidence: a.confidence, status: "unvalidated" }));
|
|
4682
|
+
relationships.push(rel(mId, "depends_on", id2));
|
|
4678
4683
|
}
|
|
4679
4684
|
const patternIds = new Set((ast.patterns || []).map((p) => `pattern.${slug(p.name || "pattern")}`));
|
|
4680
4685
|
for (const exp of ast.experiences || []) {
|
|
@@ -4713,27 +4718,27 @@ function buildIntentGraph(ast) {
|
|
|
4713
4718
|
else relationships.push(rel(mId, "requires", stId));
|
|
4714
4719
|
}
|
|
4715
4720
|
for (const role of ast.approvals || []) {
|
|
4716
|
-
const
|
|
4717
|
-
nodes2.push(node(
|
|
4718
|
-
relationships.push(rel(mId, "approved_by",
|
|
4721
|
+
const id2 = `approval.${slug(ast.mission)}.${slug(role)}`;
|
|
4722
|
+
nodes2.push(node(id2, "Approval", role, { status: "required", owner: role }));
|
|
4723
|
+
relationships.push(rel(mId, "approved_by", id2));
|
|
4719
4724
|
}
|
|
4720
4725
|
(ast.roleConstraints || []).forEach((rc, i) => {
|
|
4721
|
-
const
|
|
4722
|
-
nodes2.push(node(
|
|
4723
|
-
relationships.push(rel(mId, "requires",
|
|
4726
|
+
const id2 = `constraint.${slug(rc.role)}.${i + 1}`;
|
|
4727
|
+
nodes2.push(node(id2, "Constraint", rc.statement, { owner: rc.role }));
|
|
4728
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4724
4729
|
});
|
|
4725
4730
|
const existingIds = new Set(nodes2.map((n) => n.id));
|
|
4726
4731
|
detectConflicts(ast).forEach((c, i) => {
|
|
4727
|
-
const
|
|
4728
|
-
nodes2.push(node(
|
|
4732
|
+
const id2 = `conflict.${slug(c.name || String(i + 1))}`;
|
|
4733
|
+
nodes2.push(node(id2, "Conflict", c.name, { status: c.status, description: c.type }));
|
|
4729
4734
|
for (const b of c.between || []) {
|
|
4730
4735
|
const target = `constraint.${slug(b)}`;
|
|
4731
|
-
if (existingIds.has(target)) relationships.push(rel(
|
|
4736
|
+
if (existingIds.has(target)) relationships.push(rel(id2, "contradicts", target));
|
|
4732
4737
|
}
|
|
4733
|
-
if (c.before) relationships.push(rel(
|
|
4738
|
+
if (c.before) relationships.push(rel(id2, "blocks", `phase.${slug(c.before)}`));
|
|
4734
4739
|
for (const r of c.resolveBy || []) {
|
|
4735
4740
|
const target = `approval.${slug(ast.mission)}.${slug(r)}`;
|
|
4736
|
-
if (existingIds.has(target)) relationships.push(rel(
|
|
4741
|
+
if (existingIds.has(target)) relationships.push(rel(id2, "approved_by", target));
|
|
4737
4742
|
}
|
|
4738
4743
|
});
|
|
4739
4744
|
for (const raw of ast.lifecycles || []) {
|
|
@@ -4769,82 +4774,82 @@ function buildIntentGraph(ast) {
|
|
|
4769
4774
|
}
|
|
4770
4775
|
}
|
|
4771
4776
|
for (const c of ast.commands || []) {
|
|
4772
|
-
const
|
|
4773
|
-
nodes2.push(node(
|
|
4774
|
-
relationships.push(rel(mId, "requires",
|
|
4777
|
+
const id2 = `command.${slug(c.name || "command")}`;
|
|
4778
|
+
nodes2.push(node(id2, "Command", c.name, { description: [c.idempotencyKey && "idempotent", c.timeout && `timeout ${c.timeout}`, c.retry && `retry ${c.retry}`].filter(Boolean).join("; ") || null }));
|
|
4779
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4775
4780
|
}
|
|
4776
4781
|
for (const h of ast.handlers || []) {
|
|
4777
|
-
const
|
|
4778
|
-
nodes2.push(node(
|
|
4779
|
-
relationships.push(rel(mId, "constrained_by",
|
|
4782
|
+
const id2 = `handler.${slug(h.trigger || "handler")}`;
|
|
4783
|
+
nodes2.push(node(id2, "FailureHandler", h.trigger, { description: (h.compensate || []).length ? `compensate ${h.compensate.join(", ")}` : null }));
|
|
4784
|
+
relationships.push(rel(mId, "constrained_by", id2));
|
|
4780
4785
|
}
|
|
4781
4786
|
const nodeIds = new Set(nodes2.map((n) => n.id));
|
|
4782
4787
|
for (const cap of ast.capabilities || []) {
|
|
4783
|
-
const
|
|
4784
|
-
nodes2.push(node(
|
|
4785
|
-
relationships.push(rel(mId, "requires",
|
|
4788
|
+
const id2 = `capability.${slug(cap.name || "capability")}`;
|
|
4789
|
+
nodes2.push(node(id2, "Capability", cap.name, { description: cap.description || null }));
|
|
4790
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4786
4791
|
for (const m of cap.implements || []) {
|
|
4787
4792
|
const target = [`command.${slug(m)}`, `decision.${slug(m)}`, `mission.${slug(m)}`].find((cand) => nodeIds.has(cand));
|
|
4788
|
-
if (target) relationships.push(rel(
|
|
4793
|
+
if (target) relationships.push(rel(id2, "implemented_by", target));
|
|
4789
4794
|
}
|
|
4790
4795
|
}
|
|
4791
4796
|
for (const iface of ast.interfaces || []) {
|
|
4792
|
-
const
|
|
4797
|
+
const id2 = `system-contract.${slug(iface.name || "interface")}`;
|
|
4793
4798
|
const desc = [iface.provides.length && `provides ${iface.provides.join(", ")}`, iface.requires.length && `requires ${iface.requires.join(", ")}`, iface.slo && `slo ${iface.slo}`].filter(Boolean).join("; ") || null;
|
|
4794
|
-
nodes2.push(node(
|
|
4795
|
-
relationships.push(rel(mId, "requires",
|
|
4799
|
+
nodes2.push(node(id2, "SystemContract", iface.name, { description: desc }));
|
|
4800
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4796
4801
|
}
|
|
4797
4802
|
const allIds = nodes2.map((n) => n.id);
|
|
4798
4803
|
const resolveDesignTarget = (name) => {
|
|
4799
4804
|
const s = slug(name);
|
|
4800
|
-
return [`pattern.${s}`, `experience.${s}`].find((c) => nodeIds.has(c)) || allIds.find((
|
|
4805
|
+
return [`pattern.${s}`, `experience.${s}`].find((c) => nodeIds.has(c)) || allIds.find((id2) => id2.startsWith("experience-state.") && id2.endsWith(`.${s}`)) || null;
|
|
4801
4806
|
};
|
|
4802
4807
|
for (const comp of ast.components || []) {
|
|
4803
|
-
const
|
|
4808
|
+
const id2 = `design-component.${slug(comp.name || "component")}`;
|
|
4804
4809
|
const desc = [comp.description, comp.variants.length && `variants: ${comp.variants.join(", ")}`, comp.tokens.length && `tokens: ${comp.tokens.join(", ")}`].filter(Boolean).join("; ") || null;
|
|
4805
|
-
nodes2.push(node(
|
|
4806
|
-
relationships.push(rel(mId, "requires",
|
|
4810
|
+
nodes2.push(node(id2, "DesignComponent", comp.name, { description: desc }));
|
|
4811
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4807
4812
|
for (const m of comp.implements || []) {
|
|
4808
4813
|
const target = resolveDesignTarget(m);
|
|
4809
|
-
if (target) relationships.push(rel(target, "implemented_by",
|
|
4814
|
+
if (target) relationships.push(rel(target, "implemented_by", id2));
|
|
4810
4815
|
}
|
|
4811
4816
|
}
|
|
4812
4817
|
const componentNames = new Set((ast.components || []).map((c) => slug(c.name || "")));
|
|
4813
4818
|
for (const art of ast.artifacts || []) {
|
|
4814
|
-
const
|
|
4815
|
-
nodes2.push(node(
|
|
4816
|
-
relationships.push(rel(mId, "represented_by",
|
|
4819
|
+
const id2 = `design-artifact.${slug(art.name || "artifact")}`;
|
|
4820
|
+
nodes2.push(node(id2, "DesignArtifact", art.name, { source: art.ref || null, description: [art.kind && `kind ${art.kind}`, art.covers.length && `covers ${art.covers.join(", ")}`].filter(Boolean).join("; ") || null }));
|
|
4821
|
+
relationships.push(rel(mId, "represented_by", id2));
|
|
4817
4822
|
for (const c of art.covers || []) {
|
|
4818
|
-
if (componentNames.has(slug(c))) relationships.push(rel(`design-component.${slug(c)}`, "represented_by",
|
|
4823
|
+
if (componentNames.has(slug(c))) relationships.push(rel(`design-component.${slug(c)}`, "represented_by", id2));
|
|
4819
4824
|
}
|
|
4820
4825
|
}
|
|
4821
4826
|
for (const r of ast.releases || []) {
|
|
4822
|
-
const
|
|
4823
|
-
nodes2.push(node(
|
|
4824
|
-
relationships.push(rel(mId, "released_in",
|
|
4827
|
+
const id2 = `release.${slug(r.name || "release")}`;
|
|
4828
|
+
nodes2.push(node(id2, "Release", r.name, { status: r.status || "planned", description: [r.version && `v${r.version}`, r.date && `date ${r.date}`, r.includes.length && `includes ${r.includes.join(", ")}`].filter(Boolean).join("; ") || null }));
|
|
4829
|
+
relationships.push(rel(mId, "released_in", id2));
|
|
4825
4830
|
}
|
|
4826
4831
|
for (const res of ast.results || []) {
|
|
4827
|
-
const
|
|
4828
|
-
nodes2.push(node(
|
|
4832
|
+
const id2 = `outcome-result.${slug(res.name || "result")}`;
|
|
4833
|
+
nodes2.push(node(id2, "OutcomeResult", res.name, { description: [res.metric && `metric ${res.metric}`, res.value && `value ${res.value}`, res.baseline && `baseline ${res.baseline}`].filter(Boolean).join("; ") || null }));
|
|
4829
4834
|
const outId = res.measures ? `outcome.${slug(res.measures)}` : null;
|
|
4830
|
-
relationships.push(rel(nodeIds.has(outId) ? outId : mId, "resulted_in",
|
|
4835
|
+
relationships.push(rel(nodeIds.has(outId) ? outId : mId, "resulted_in", id2));
|
|
4831
4836
|
}
|
|
4832
4837
|
const releaseNames = new Set((ast.releases || []).map((r) => slug(r.name || "")));
|
|
4833
4838
|
for (const l of ast.learnings || []) {
|
|
4834
|
-
const
|
|
4835
|
-
nodes2.push(node(
|
|
4839
|
+
const id2 = `learning.${slug(l.name || "learning")}`;
|
|
4840
|
+
nodes2.push(node(id2, "LearningArtifact", l.name, { description: l.description || null }));
|
|
4836
4841
|
const fromRelease = l.from && releaseNames.has(slug(l.from));
|
|
4837
|
-
relationships.push(rel(
|
|
4842
|
+
relationships.push(rel(id2, "derived_from", fromRelease ? `release.${slug(l.from)}` : mId));
|
|
4838
4843
|
}
|
|
4839
4844
|
for (const c of ast.outcomeContracts || []) {
|
|
4840
|
-
const
|
|
4845
|
+
const id2 = `outcome-contract.${slug(c.name || "contract")}`;
|
|
4841
4846
|
const desc = [c.baseline && `baseline ${c.baseline}`, c.target && `target ${c.target}`, `${c.direction || "higher"} is better`, c.window && `window ${c.window}`].filter(Boolean).join("; ") || null;
|
|
4842
|
-
nodes2.push(node(
|
|
4843
|
-
relationships.push(rel(mId, "requires",
|
|
4847
|
+
nodes2.push(node(id2, "OutcomeContract", c.name, { owner: c.owner || null, description: desc }));
|
|
4848
|
+
relationships.push(rel(mId, "requires", id2));
|
|
4844
4849
|
const outId = c.outcome ? `outcome.${slug(c.outcome)}` : null;
|
|
4845
|
-
if (nodeIds.has(outId)) relationships.push(rel(
|
|
4850
|
+
if (nodeIds.has(outId)) relationships.push(rel(id2, "targets", outId));
|
|
4846
4851
|
const metId = c.metric ? `metric.${slug(c.metric)}` : null;
|
|
4847
|
-
if (nodeIds.has(metId)) relationships.push(rel(
|
|
4852
|
+
if (nodeIds.has(metId)) relationships.push(rel(id2, "measured_by", metId));
|
|
4848
4853
|
}
|
|
4849
4854
|
const byType = {};
|
|
4850
4855
|
for (const n of nodes2) byType[n.type] = (byType[n.type] || 0) + 1;
|
|
@@ -4890,14 +4895,14 @@ function buildAtlas(graphs, opts = {}) {
|
|
|
4890
4895
|
relationships
|
|
4891
4896
|
};
|
|
4892
4897
|
}
|
|
4893
|
-
function atlasNode(atlas,
|
|
4894
|
-
return atlas.nodes.find((n) => n.id ===
|
|
4898
|
+
function atlasNode(atlas, id2) {
|
|
4899
|
+
return atlas.nodes.find((n) => n.id === id2) || null;
|
|
4895
4900
|
}
|
|
4896
|
-
function expandNode(atlas,
|
|
4897
|
-
const node2 = atlasNode(atlas,
|
|
4901
|
+
function expandNode(atlas, id2) {
|
|
4902
|
+
const node2 = atlasNode(atlas, id2);
|
|
4898
4903
|
if (!node2) return null;
|
|
4899
|
-
const out = atlas.relationships.filter((r) => r.from ===
|
|
4900
|
-
const inbound = atlas.relationships.filter((r) => r.to ===
|
|
4904
|
+
const out = atlas.relationships.filter((r) => r.from === id2).map((r) => ({ rel: r.type, node: atlasNode(atlas, r.to) || { id: r.to } }));
|
|
4905
|
+
const inbound = atlas.relationships.filter((r) => r.to === id2).map((r) => ({ rel: r.type, node: atlasNode(atlas, r.from) || { id: r.from } }));
|
|
4901
4906
|
return { node: node2, out, inbound };
|
|
4902
4907
|
}
|
|
4903
4908
|
function searchAtlas(atlas, query, opts = {}) {
|
|
@@ -4905,9 +4910,9 @@ function searchAtlas(atlas, query, opts = {}) {
|
|
|
4905
4910
|
if (!q) return [];
|
|
4906
4911
|
const score = (n) => {
|
|
4907
4912
|
const title = (n.title || "").toLowerCase();
|
|
4908
|
-
const
|
|
4909
|
-
if (title === q ||
|
|
4910
|
-
if (
|
|
4913
|
+
const id2 = n.id.toLowerCase();
|
|
4914
|
+
if (title === q || id2 === q) return 0;
|
|
4915
|
+
if (id2.startsWith(q) || title.startsWith(q)) return 1;
|
|
4911
4916
|
return 2;
|
|
4912
4917
|
};
|
|
4913
4918
|
let hits = atlas.nodes.filter((n) => `${n.id} ${n.title || ""} ${n.description || ""}`.toLowerCase().includes(q));
|
|
@@ -4934,11 +4939,11 @@ function diffGraphs(before, after) {
|
|
|
4934
4939
|
const addedNodes = [];
|
|
4935
4940
|
const removedNodes = [];
|
|
4936
4941
|
const changedNodes = [];
|
|
4937
|
-
for (const [
|
|
4938
|
-
for (const [
|
|
4939
|
-
for (const [
|
|
4940
|
-
const bn = bNodes.get(
|
|
4941
|
-
if (bn && contentKey(bn) !== contentKey(an)) changedNodes.push({ id, type: an.type, before: bn, after: an });
|
|
4942
|
+
for (const [id2, n] of aNodes) if (!bNodes.has(id2)) addedNodes.push(n);
|
|
4943
|
+
for (const [id2, n] of bNodes) if (!aNodes.has(id2)) removedNodes.push(n);
|
|
4944
|
+
for (const [id2, an] of aNodes) {
|
|
4945
|
+
const bn = bNodes.get(id2);
|
|
4946
|
+
if (bn && contentKey(bn) !== contentKey(an)) changedNodes.push({ id: id2, type: an.type, before: bn, after: an });
|
|
4942
4947
|
}
|
|
4943
4948
|
addedNodes.sort((a, b) => a.id.localeCompare(b.id));
|
|
4944
4949
|
removedNodes.sort((a, b) => a.id.localeCompare(b.id));
|
|
@@ -4957,7 +4962,7 @@ function diffGraphs(before, after) {
|
|
|
4957
4962
|
}
|
|
4958
4963
|
const invalidatedApprovals = [];
|
|
4959
4964
|
for (const [mission, contractIds] of Object.entries(missionContract)) {
|
|
4960
|
-
const contractChanged = changedIds.has(mission) || [...contractIds].some((
|
|
4965
|
+
const contractChanged = changedIds.has(mission) || [...contractIds].some((id2) => changedIds.has(id2));
|
|
4961
4966
|
if (contractChanged) for (const ap of missionApprovals[mission] || []) invalidatedApprovals.push(ap);
|
|
4962
4967
|
}
|
|
4963
4968
|
const byType = (arr) => arr.reduce((m, n) => (m[n.type] = (m[n.type] || 0) + 1, m), {});
|
|
@@ -4990,31 +4995,31 @@ function mergeGraphs(base, ours, theirs) {
|
|
|
4990
4995
|
const ids = [.../* @__PURE__ */ new Set([...bN.keys(), ...oN.keys(), ...tN.keys()])].sort();
|
|
4991
4996
|
const merged = /* @__PURE__ */ new Map();
|
|
4992
4997
|
const conflicts = [];
|
|
4993
|
-
for (const
|
|
4994
|
-
const b = bN.get(
|
|
4995
|
-
const o = oN.get(
|
|
4996
|
-
const t = tN.get(
|
|
4998
|
+
for (const id2 of ids) {
|
|
4999
|
+
const b = bN.get(id2) || null;
|
|
5000
|
+
const o = oN.get(id2) || null;
|
|
5001
|
+
const t = tN.get(id2) || null;
|
|
4997
5002
|
const oChanged = key(o) !== key(b);
|
|
4998
5003
|
const tChanged = key(t) !== key(b);
|
|
4999
5004
|
if (!oChanged && !tChanged) {
|
|
5000
|
-
if (b) merged.set(
|
|
5005
|
+
if (b) merged.set(id2, b);
|
|
5001
5006
|
continue;
|
|
5002
5007
|
}
|
|
5003
5008
|
if (oChanged && !tChanged) {
|
|
5004
|
-
if (o) merged.set(
|
|
5009
|
+
if (o) merged.set(id2, o);
|
|
5005
5010
|
continue;
|
|
5006
5011
|
}
|
|
5007
5012
|
if (!oChanged && tChanged) {
|
|
5008
|
-
if (t) merged.set(
|
|
5013
|
+
if (t) merged.set(id2, t);
|
|
5009
5014
|
continue;
|
|
5010
5015
|
}
|
|
5011
5016
|
if (key(o) === key(t)) {
|
|
5012
|
-
if (o) merged.set(
|
|
5017
|
+
if (o) merged.set(id2, o);
|
|
5013
5018
|
continue;
|
|
5014
5019
|
}
|
|
5015
|
-
conflicts.push({ id, type: (o || t || b).type, base: b, ours: o, theirs: t });
|
|
5016
|
-
if (o) merged.set(
|
|
5017
|
-
else if (t) merged.set(
|
|
5020
|
+
conflicts.push({ id: id2, type: (o || t || b).type, base: b, ours: o, theirs: t });
|
|
5021
|
+
if (o) merged.set(id2, o);
|
|
5022
|
+
else if (t) merged.set(id2, t);
|
|
5018
5023
|
}
|
|
5019
5024
|
const bR = new Set((base?.relationships || []).map(relKey));
|
|
5020
5025
|
const oR = new Set((ours?.relationships || []).map(relKey));
|
|
@@ -5132,11 +5137,11 @@ function toDMN(ast) {
|
|
|
5132
5137
|
const inputCols = inputs.map((inp) => ` <input id="in_${decId}_${xmlId(inp)}" label="${esc(inp)}">
|
|
5133
5138
|
<inputExpression id="ie_${decId}_${xmlId(inp)}" typeRef="string"><text>${esc(inp)}</text></inputExpression>
|
|
5134
5139
|
</input>`).join("\n");
|
|
5135
|
-
const ruleRow = (when, result,
|
|
5136
|
-
const entries = inputs.map((_inp, i) => ` <inputEntry id="ien_${
|
|
5137
|
-
return ` <rule id="rule_${
|
|
5140
|
+
const ruleRow = (when, result, id2) => {
|
|
5141
|
+
const entries = inputs.map((_inp, i) => ` <inputEntry id="ien_${id2}_${i}"><text>${esc(i === 0 ? when ?? "-" : "-")}</text></inputEntry>`).join("\n");
|
|
5142
|
+
return ` <rule id="rule_${id2}">
|
|
5138
5143
|
${entries}
|
|
5139
|
-
<outputEntry id="oen_${
|
|
5144
|
+
<outputEntry id="oen_${id2}"><text>${esc(result != null ? `"${result}"` : "-")}</text></outputEntry>
|
|
5140
5145
|
</rule>`;
|
|
5141
5146
|
};
|
|
5142
5147
|
const rules = dec.rules.map((r, i) => ruleRow(r.when, r.result, `${decId}_${i}`)).join("\n");
|
|
@@ -5226,7 +5231,7 @@ ${reachSpecs ? "\n" + reachSpecs : ""}${tempSpecs ? "\n" + tempSpecs : ""}`;
|
|
|
5226
5231
|
function toMermaid(ast) {
|
|
5227
5232
|
const graph = buildIntentGraph(ast);
|
|
5228
5233
|
const L = ["graph TD"];
|
|
5229
|
-
const mid = (
|
|
5234
|
+
const mid = (id2) => `n_${String(id2).replace(/[^A-Za-z0-9]+/g, "_")}`;
|
|
5230
5235
|
const lbl = (s) => String(s ?? "").replace(/"/g, "'").replace(/[[\]{}()<>|#]/g, " ").replace(/\s+/g, " ").trim();
|
|
5231
5236
|
const shape = (type) => {
|
|
5232
5237
|
if (/State$/.test(type) || type === "Lifecycle" || type === "Journey") return ['(["', '"])'];
|
|
@@ -5459,12 +5464,12 @@ function dmnToIntent(xml, warn = NOOP_WARN) {
|
|
|
5459
5464
|
}
|
|
5460
5465
|
const inputEls = childrenNamed(table, "input");
|
|
5461
5466
|
const inputExprs = inputEls.map((inp) => textOf(find(inp, "inputExpression")) || inp.attrs.label || "");
|
|
5462
|
-
const
|
|
5467
|
+
const inputNames2 = inputExprs.map((e, i) => (e || `in${i + 1}`).replace(/\s+/g, ""));
|
|
5463
5468
|
if (childrenNamed(table, "output").length > 1) warn("IL-IMP-DMN-004", `Decision "${dname}" has multiple output columns; only the first is imported.`, dname);
|
|
5464
5469
|
lines.push(`decision ${dname}`);
|
|
5465
|
-
if (
|
|
5470
|
+
if (inputNames2.length) {
|
|
5466
5471
|
lines.push(" inputs");
|
|
5467
|
-
for (const n of
|
|
5472
|
+
for (const n of inputNames2) lines.push(` ${n}`);
|
|
5468
5473
|
}
|
|
5469
5474
|
let defaultReturn = null;
|
|
5470
5475
|
let ruleN = 0;
|
|
@@ -5587,9 +5592,9 @@ function graphToSource(graph) {
|
|
|
5587
5592
|
const byType = (t) => nodes2.filter((n) => n.type === t);
|
|
5588
5593
|
const first = (t) => byType(t)[0] || null;
|
|
5589
5594
|
const title = (n) => n && n.title != null ? String(n.title) : "";
|
|
5590
|
-
const out = (
|
|
5591
|
-
const inTo = (
|
|
5592
|
-
const phaseOut = (
|
|
5595
|
+
const out = (id2, type) => rels2.filter((r) => r.from === id2 && r.type === type).map((r) => byId.get(r.to)).filter(Boolean);
|
|
5596
|
+
const inTo = (id2, type) => rels2.filter((r) => r.to === id2 && r.type === type).map((r) => byId.get(r.from)).filter(Boolean);
|
|
5597
|
+
const phaseOut = (id2) => rels2.filter((r) => r.from === id2 && r.type === "blocks" && String(r.to).startsWith("phase.")).map((r) => String(r.to).slice("phase.".length));
|
|
5593
5598
|
const L = [];
|
|
5594
5599
|
const push = (s = "") => L.push(s);
|
|
5595
5600
|
const mission = first("Mission");
|
|
@@ -6060,9 +6065,9 @@ var VERIFICATION_RULES = [
|
|
|
6060
6065
|
var ALL_DIAGNOSTICS = [...DIAGNOSTIC_RULES, ...CORE_DIAGNOSTICS, ...VERIFICATION_RULES];
|
|
6061
6066
|
var IL_CORE_IDS = new Set(IL_CORE_RULE_ROWS.map((r) => r.ruleId));
|
|
6062
6067
|
function ruleNamespace(ruleId) {
|
|
6063
|
-
const
|
|
6064
|
-
for (const ns of RULE_NAMESPACES) if (
|
|
6065
|
-
if (IL_CORE_IDS.has(
|
|
6068
|
+
const id2 = String(ruleId || "");
|
|
6069
|
+
for (const ns of RULE_NAMESPACES) if (id2.startsWith(ns.prefix)) return { owner: ns.owner, phase: ns.phase };
|
|
6070
|
+
if (IL_CORE_IDS.has(id2)) return { owner: "IL", phase: "author" };
|
|
6066
6071
|
return null;
|
|
6067
6072
|
}
|
|
6068
6073
|
|
|
@@ -6194,15 +6199,15 @@ function tokenize(src) {
|
|
|
6194
6199
|
}
|
|
6195
6200
|
if (isIdStart(c)) {
|
|
6196
6201
|
let j = i;
|
|
6197
|
-
let
|
|
6202
|
+
let id2 = "";
|
|
6198
6203
|
while (j < s.length && isId(s[j])) {
|
|
6199
|
-
|
|
6204
|
+
id2 += s[j];
|
|
6200
6205
|
j++;
|
|
6201
6206
|
}
|
|
6202
|
-
const lower2 =
|
|
6207
|
+
const lower2 = id2.toLowerCase();
|
|
6203
6208
|
if (lower2 === "and" || lower2 === "or" || lower2 === "not" || lower2 === "in") toks.push({ t: "kw", v: lower2 });
|
|
6204
6209
|
else if (lower2 === "true" || lower2 === "false") toks.push({ t: "bool", v: lower2 === "true" });
|
|
6205
|
-
else toks.push({ t: "id", v:
|
|
6210
|
+
else toks.push({ t: "id", v: id2 });
|
|
6206
6211
|
i = j;
|
|
6207
6212
|
continue;
|
|
6208
6213
|
}
|
|
@@ -6418,7 +6423,14 @@ var DIALECTS = {
|
|
|
6418
6423
|
js: { ...C_LOGIC, eq: (a, b) => `${a} === ${b}`, neq: (a, b) => `${a} !== ${b}`, inList: (list, x) => `[${list.join(", ")}].includes(${x})`, nil: "undefined" },
|
|
6419
6424
|
csharp: { ...C_LOGIC, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `new[]{${list.join(", ")}}.Contains(${x})`, nil: "null" },
|
|
6420
6425
|
java: { ...C_LOGIC, eq: (a, b) => `java.util.Objects.equals(${a}, ${b})`, neq: (a, b) => `!java.util.Objects.equals(${a}, ${b})`, inList: (list, x) => `java.util.List.of(${list.join(", ")}).contains(${x})`, nil: "null" },
|
|
6421
|
-
python: { and: (a, b) => `(${a} and ${b})`, or: (a, b) => `(${a} or ${b})`, not: (a) => `(not ${a})`, bool: (v) => v ? "True" : "False", eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in [${list.join(", ")}]`, nil: "None" }
|
|
6426
|
+
python: { and: (a, b) => `(${a} and ${b})`, or: (a, b) => `(${a} or ${b})`, not: (a) => `(not ${a})`, bool: (v) => v ? "True" : "False", eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in [${list.join(", ")}]`, nil: "None" },
|
|
6427
|
+
// Go has no built-in membership operator, so `in` becomes a parenthesized chain of equalities
|
|
6428
|
+
// (an empty list is an impossible match -> false). Booleans and logic are C-family.
|
|
6429
|
+
go: { ...C_LOGIC, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => list.length ? `(${list.map((e) => `${x} == ${e}`).join(" || ")})` : "false", nil: "nil" },
|
|
6430
|
+
rust: { ...C_LOGIC, num: (v) => `${v}f64`, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `[${list.join(", ")}].contains(&${x})`, nil: "Default::default()" },
|
|
6431
|
+
kotlin: { ...C_LOGIC, num: (v) => Number.isInteger(v) ? `${v}.0` : String(v), eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in listOf(${list.join(", ")})`, nil: "null" },
|
|
6432
|
+
scala: { ...C_LOGIC, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `List(${list.join(", ")}).contains(${x})`, nil: "null" },
|
|
6433
|
+
elixir: { and: (a, b) => `(${a} and ${b})`, or: (a, b) => `(${a} or ${b})`, not: (a) => `(not ${a})`, bool: (v) => String(v), eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in [${list.join(", ")}]`, nil: "nil" }
|
|
6422
6434
|
};
|
|
6423
6435
|
function renderExpr(src, inputs, D) {
|
|
6424
6436
|
const known = new Set(inputs);
|
|
@@ -6443,7 +6455,7 @@ function renderExpr(src, inputs, D) {
|
|
|
6443
6455
|
case "list":
|
|
6444
6456
|
return `[${n.items.map(r).join(", ")}]`;
|
|
6445
6457
|
case "lit":
|
|
6446
|
-
return typeof n.v === "string" ? JSON.stringify(n.v) : typeof n.v === "boolean" ? D.bool(n.v) : String(n.v);
|
|
6458
|
+
return typeof n.v === "string" ? JSON.stringify(n.v) : typeof n.v === "boolean" ? D.bool(n.v) : D.num ? D.num(n.v) : String(n.v);
|
|
6447
6459
|
case "ref":
|
|
6448
6460
|
return known.has(n.path) || known.has(n.path.split(".")[0]) ? n.path : JSON.stringify(n.path);
|
|
6449
6461
|
default:
|
|
@@ -6452,6 +6464,48 @@ function renderExpr(src, inputs, D) {
|
|
|
6452
6464
|
};
|
|
6453
6465
|
return r(parse(tokenize(src)));
|
|
6454
6466
|
}
|
|
6467
|
+
function simplifyExpr(src) {
|
|
6468
|
+
const PREC = { or: 1, and: 2, not: 3, cmp: 4, arith: 5, neg: 6, lit: 7, ref: 7 };
|
|
6469
|
+
let unsupported = false;
|
|
6470
|
+
const p = (n, parent = 0) => {
|
|
6471
|
+
const me = PREC[n.k];
|
|
6472
|
+
if (me == null) {
|
|
6473
|
+
unsupported = true;
|
|
6474
|
+
return "";
|
|
6475
|
+
}
|
|
6476
|
+
let out;
|
|
6477
|
+
switch (n.k) {
|
|
6478
|
+
// `and` inside `or` keeps its parentheses: correct without them, but easy to misread.
|
|
6479
|
+
case "or":
|
|
6480
|
+
out = `${p(n.a, n.a.k === "and" ? 9 : me)} or ${p(n.b, n.b.k === "and" ? 9 : me + 0.5)}`;
|
|
6481
|
+
break;
|
|
6482
|
+
case "and":
|
|
6483
|
+
out = `${p(n.a, me)} and ${p(n.b, me + 0.5)}`;
|
|
6484
|
+
break;
|
|
6485
|
+
case "not":
|
|
6486
|
+
out = `not ${p(n.a, me)}`;
|
|
6487
|
+
break;
|
|
6488
|
+
case "cmp":
|
|
6489
|
+
out = `${p(n.a, me + 0.5)} ${n.op} ${p(n.b, me + 0.5)}`;
|
|
6490
|
+
break;
|
|
6491
|
+
case "arith":
|
|
6492
|
+
out = `${p(n.a, me)} ${n.op} ${p(n.b, me + 0.5)}`;
|
|
6493
|
+
break;
|
|
6494
|
+
case "neg":
|
|
6495
|
+
out = `-${p(n.a, me)}`;
|
|
6496
|
+
break;
|
|
6497
|
+
case "lit":
|
|
6498
|
+
out = typeof n.v === "string" ? JSON.stringify(n.v) : String(n.v);
|
|
6499
|
+
break;
|
|
6500
|
+
case "ref":
|
|
6501
|
+
out = n.path;
|
|
6502
|
+
break;
|
|
6503
|
+
}
|
|
6504
|
+
return me < parent ? `(${out})` : out;
|
|
6505
|
+
};
|
|
6506
|
+
const text = p(parse(tokenize(src)));
|
|
6507
|
+
return unsupported ? src : text;
|
|
6508
|
+
}
|
|
6455
6509
|
function exprToCode(src, { inputs = [], dialect = "js" } = {}) {
|
|
6456
6510
|
return renderExpr(src, inputs, DIALECTS[dialect] || DIALECTS.js);
|
|
6457
6511
|
}
|
|
@@ -6459,6 +6513,8 @@ var exprToJs = (src, opts = {}) => exprToCode(src, { ...opts, dialect: "js" });
|
|
|
6459
6513
|
var exprToCSharp = (src, opts = {}) => exprToCode(src, { ...opts, dialect: "csharp" });
|
|
6460
6514
|
var exprToJava = (src, opts = {}) => exprToCode(src, { ...opts, dialect: "java" });
|
|
6461
6515
|
var exprToPython = (src, opts = {}) => exprToCode(src, { ...opts, dialect: "python" });
|
|
6516
|
+
var exprToGo = (src, opts = {}) => exprToCode(src, { ...opts, dialect: "go" });
|
|
6517
|
+
var exprToRust = (src, opts = {}) => exprToCode(src, { ...opts, dialect: "rust" });
|
|
6462
6518
|
|
|
6463
6519
|
// src/runtime.mjs
|
|
6464
6520
|
var RUNTIME_SCHEMA = "intent-runtime-v1";
|
|
@@ -6507,14 +6563,14 @@ function simulateLifecycle(lc, events = []) {
|
|
|
6507
6563
|
const steps = [];
|
|
6508
6564
|
let valid = true;
|
|
6509
6565
|
for (const ev of events) {
|
|
6510
|
-
const
|
|
6511
|
-
if (
|
|
6566
|
+
const candidates2 = (ir.transitions || []).filter((t2) => t2.from === state && (t2.name === ev || t2.to === ev));
|
|
6567
|
+
if (candidates2.length === 0) {
|
|
6512
6568
|
valid = false;
|
|
6513
6569
|
const reason = terminals.has(state) ? `state "${state}" is terminal` : `no transition "${ev}" from "${state}"`;
|
|
6514
6570
|
steps.push({ event: ev, from: state, to: state, ok: false, reason });
|
|
6515
6571
|
continue;
|
|
6516
6572
|
}
|
|
6517
|
-
const t =
|
|
6573
|
+
const t = candidates2[0];
|
|
6518
6574
|
steps.push({ event: ev, from: state, to: t.to, ok: true, transition: t.name });
|
|
6519
6575
|
state = t.to;
|
|
6520
6576
|
path.push(state);
|
|
@@ -7632,8 +7688,8 @@ function buildFocusGraph(atlas, { seeds = [], depth = 2, scope = null } = {}) {
|
|
|
7632
7688
|
let frontier = [...seedSet];
|
|
7633
7689
|
for (let d = 1; d <= depth && frontier.length; d += 1) {
|
|
7634
7690
|
const next = [];
|
|
7635
|
-
for (const
|
|
7636
|
-
const edges = adj.get(
|
|
7691
|
+
for (const id2 of frontier) {
|
|
7692
|
+
const edges = adj.get(id2);
|
|
7637
7693
|
if (!edges) continue;
|
|
7638
7694
|
for (const { neighborId, via } of edges) {
|
|
7639
7695
|
if (included.has(neighborId)) continue;
|
|
@@ -8389,7 +8445,7 @@ function blastRadius(graph, changedIds, maxDepth = 3) {
|
|
|
8389
8445
|
let frontier = [...changedIds];
|
|
8390
8446
|
for (let d = 0; d < maxDepth && frontier.length; d += 1) {
|
|
8391
8447
|
const next = [];
|
|
8392
|
-
for (const
|
|
8448
|
+
for (const id2 of frontier) for (const nb of adj.get(id2) ?? []) if (!reached.has(nb)) {
|
|
8393
8449
|
reached.add(nb);
|
|
8394
8450
|
next.push(nb);
|
|
8395
8451
|
}
|
|
@@ -8411,7 +8467,7 @@ function simulateChange(baseFiles, proposedFiles) {
|
|
|
8411
8467
|
const union = { nodes: [...unionNodes.values()], relationships: [...baseGraph.relationships, ...proposedGraph.relationships] };
|
|
8412
8468
|
const changedIds = [.../* @__PURE__ */ new Set([...diff.addedNodes.map((n) => n.id), ...diff.removedNodes.map((n) => n.id), ...diff.changedNodes.map((c) => c.id)])];
|
|
8413
8469
|
const reached = blastRadius(union, changedIds);
|
|
8414
|
-
const affectedNodes = [...reached].map((
|
|
8470
|
+
const affectedNodes = [...reached].map((id2) => unionNodes.get(id2)).filter(Boolean);
|
|
8415
8471
|
const changedSet = new Set(changedIds);
|
|
8416
8472
|
const dependents = affectedNodes.filter((n) => !changedSet.has(n.id));
|
|
8417
8473
|
const baseScan = scanProject(baseFiles);
|
|
@@ -8665,8 +8721,8 @@ function identifierWords(text) {
|
|
|
8665
8721
|
return String(text).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
|
|
8666
8722
|
}
|
|
8667
8723
|
var lineHitsTerm = (text, terms) => {
|
|
8668
|
-
const
|
|
8669
|
-
return terms.some((term) =>
|
|
8724
|
+
const words3 = identifierWords(text);
|
|
8725
|
+
return terms.some((term) => words3.some((w) => w === term || w.endsWith(term)));
|
|
8670
8726
|
};
|
|
8671
8727
|
function addedLines(before, after) {
|
|
8672
8728
|
const afterLines = String(after ?? "").split(/\r?\n/);
|
|
@@ -8718,8 +8774,8 @@ function verifyDiff(intentText, { before = null, after, language = "typescript"
|
|
|
8718
8774
|
|
|
8719
8775
|
// src/mcp.mjs
|
|
8720
8776
|
var import_node_child_process = require("node:child_process");
|
|
8721
|
-
var
|
|
8722
|
-
var
|
|
8777
|
+
var import_node_fs2 = require("node:fs");
|
|
8778
|
+
var import_node_path2 = require("node:path");
|
|
8723
8779
|
|
|
8724
8780
|
// src/conformance.mjs
|
|
8725
8781
|
function buildConformance(ast, { targets = [], results = null } = {}) {
|
|
@@ -8770,9 +8826,9 @@ var SECRET_TYPES2 = /* @__PURE__ */ new Set(["secret", "password", "passwd", "jw
|
|
|
8770
8826
|
var SECRET_NAME = /pass(word|wd)?|secret|token|jwt|ssn|api[-_]?key|apikey|credential|cvv|private[-_]?key|card/i;
|
|
8771
8827
|
var isSecretField = (f) => f && (SECRET_TYPES2.has(String(f.type || "").toLowerCase()) || SECRET_NAME.test(f.name || ""));
|
|
8772
8828
|
function pascalish(text) {
|
|
8773
|
-
const
|
|
8774
|
-
if (
|
|
8775
|
-
return
|
|
8829
|
+
const words3 = String(text || "Mission").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/);
|
|
8830
|
+
if (words3.length === 1) return words3[0].charAt(0).toUpperCase() + words3[0].slice(1);
|
|
8831
|
+
return words3.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
|
|
8776
8832
|
}
|
|
8777
8833
|
var normRules = (list) => (Array.isArray(list) ? list : []).map((r) => typeof r === "string" ? { statement: r } : { ...r }).filter((r) => r.statement);
|
|
8778
8834
|
function draftIntent(brief = {}) {
|
|
@@ -8852,196 +8908,2472 @@ function draftIntent(brief = {}) {
|
|
|
8852
8908
|
return { schema: DRAFT_SCHEMA, source, review, diagnostics };
|
|
8853
8909
|
}
|
|
8854
8910
|
|
|
8855
|
-
// src/
|
|
8856
|
-
var
|
|
8857
|
-
var
|
|
8858
|
-
|
|
8859
|
-
|
|
8860
|
-
|
|
8861
|
-
|
|
8862
|
-
|
|
8863
|
-
|
|
8911
|
+
// src/read.mjs
|
|
8912
|
+
var READ_SCHEMA = "thunder-reading-v1";
|
|
8913
|
+
var READ_LANGUAGES = ["typescript", "javascript", "python", "go", "rust", "csharp", "java", "kotlin", "php", "ruby"];
|
|
8914
|
+
var KEYWORDS_NOT_FN = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "new", "else", "using", "lock", "foreach", "match", "loop", "sizeof", "typeof", "nameof"]);
|
|
8915
|
+
function detectLanguage(source, file = "") {
|
|
8916
|
+
if (file) return languageForFile(file);
|
|
8917
|
+
const s = String(source);
|
|
8918
|
+
if (/^\s*<\?php\b/.test(s) || /\bfunction\s+\w+\s*\([^)]*\$\w+/.test(s)) return "php";
|
|
8919
|
+
if (/\bfun\s+(<[^>]*>\s*)?[\w.]*\w+\s*\(/.test(s)) return "kotlin";
|
|
8920
|
+
if (/^\s*def\s+[\w.?!]+(\s*\(.*\))?\s*$/m.test(s) && /^\s*end\s*$/m.test(s)) return "ruby";
|
|
8921
|
+
if (/^\s*package\s+\w+\s*$/m.test(s) || /\bfunc\s+(\([^)]*\)\s*)?\w+\s*\(/.test(s)) return "go";
|
|
8922
|
+
if (/\bfn\s+\w+\s*(<[^>]*>)?\s*\(/.test(s) || /\blet\s+mut\b|->\s*&'static/.test(s)) return "rust";
|
|
8923
|
+
if (/^\s*def\s+\w+\s*\(.*\)\s*(->\s*[^:]+)?:\s*$/m.test(s)) return "python";
|
|
8924
|
+
if (/\bnamespace\s+[\w.]+|\busing\s+System\b|\bpublic\s+static\s+string\b|\bstring\s+\w+\s*[,)]/.test(s)) return "csharp";
|
|
8925
|
+
if (/\bpublic\s+(static\s+)?(class|String|boolean|int|double|void)\b|\bString\s+\w+\s*[,)]|\bboolean\b/.test(s)) return "java";
|
|
8926
|
+
if (/:\s*(number|string|boolean)\b|\binterface\s+\w+|\bexport\s+(function|const)\b/.test(s)) return "typescript";
|
|
8927
|
+
return "javascript";
|
|
8928
|
+
}
|
|
8929
|
+
var lineAt = (src, idx) => src.slice(0, idx).split("\n").length;
|
|
8930
|
+
function matchClose(src, open) {
|
|
8931
|
+
const pairs = { "{": "}", "(": ")", "[": "]" };
|
|
8932
|
+
const stack = [pairs[src[open]]];
|
|
8933
|
+
for (let i = open + 1; i < src.length; i++) {
|
|
8934
|
+
const c = src[i];
|
|
8935
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
8936
|
+
i = skipString(src, i);
|
|
8937
|
+
continue;
|
|
8938
|
+
}
|
|
8939
|
+
if (c === "/" && src[i + 1] === "/") {
|
|
8940
|
+
i = src.indexOf("\n", i);
|
|
8941
|
+
if (i < 0) return -1;
|
|
8942
|
+
continue;
|
|
8943
|
+
}
|
|
8944
|
+
if (c === "/" && src[i + 1] === "*") {
|
|
8945
|
+
i = src.indexOf("*/", i + 2);
|
|
8946
|
+
if (i < 0) return -1;
|
|
8947
|
+
i++;
|
|
8948
|
+
continue;
|
|
8949
|
+
}
|
|
8950
|
+
if (pairs[c]) stack.push(pairs[c]);
|
|
8951
|
+
else if (c === stack[stack.length - 1]) {
|
|
8952
|
+
stack.pop();
|
|
8953
|
+
if (!stack.length) return i;
|
|
8954
|
+
}
|
|
8864
8955
|
}
|
|
8865
|
-
|
|
8866
|
-
|
|
8867
|
-
|
|
8868
|
-
|
|
8869
|
-
|
|
8870
|
-
|
|
8871
|
-
|
|
8956
|
+
return -1;
|
|
8957
|
+
}
|
|
8958
|
+
var READING_RUST = false;
|
|
8959
|
+
function skipString(src, i) {
|
|
8960
|
+
const q = src[i];
|
|
8961
|
+
if (q === "'" && !READING_RUST) {
|
|
8962
|
+
for (let j = i + 1; j < src.length; j++) {
|
|
8963
|
+
if (src[j] === "\\") {
|
|
8964
|
+
j++;
|
|
8965
|
+
continue;
|
|
8966
|
+
}
|
|
8967
|
+
if (src[j] === q || src[j] === "\n") return j;
|
|
8872
8968
|
}
|
|
8873
|
-
return
|
|
8969
|
+
return src.length;
|
|
8970
|
+
}
|
|
8971
|
+
if (q === "'" && /[A-Za-z_]/.test(src[i + 1] || "")) {
|
|
8972
|
+
let j = i + 1;
|
|
8973
|
+
while (/\w/.test(src[j] || "")) j++;
|
|
8974
|
+
if (src[j] !== "'") return i;
|
|
8975
|
+
}
|
|
8976
|
+
for (let j = i + 1; j < src.length; j++) {
|
|
8977
|
+
if (src[j] === "\\") {
|
|
8978
|
+
j++;
|
|
8979
|
+
continue;
|
|
8980
|
+
}
|
|
8981
|
+
if (src[j] === q) return j;
|
|
8982
|
+
if (src[j] === "\n" && q !== "`") return j;
|
|
8983
|
+
}
|
|
8984
|
+
return src.length;
|
|
8985
|
+
}
|
|
8986
|
+
function parseParams2(raw, language) {
|
|
8987
|
+
const parts = [];
|
|
8988
|
+
let depth = 0, cur = "";
|
|
8989
|
+
for (const ch of raw) {
|
|
8990
|
+
if ("<([{".includes(ch)) depth++;
|
|
8991
|
+
else if (">)]}".includes(ch)) depth--;
|
|
8992
|
+
if (ch === "," && depth === 0) {
|
|
8993
|
+
parts.push(cur);
|
|
8994
|
+
cur = "";
|
|
8995
|
+
} else cur += ch;
|
|
8996
|
+
}
|
|
8997
|
+
if (cur.trim()) parts.push(cur);
|
|
8998
|
+
const out = [];
|
|
8999
|
+
let pendingGo = [];
|
|
9000
|
+
for (let p of parts.map((x) => x.trim()).filter(Boolean)) {
|
|
9001
|
+
p = p.replace(/=.*$/, "").trim();
|
|
9002
|
+
if (/^&?\s*(mut\s+)?self$|^self$|^cls$|^this$/.test(p)) continue;
|
|
9003
|
+
if (language === "ruby") {
|
|
9004
|
+
if (/^&/.test(p)) continue;
|
|
9005
|
+
out.push({ name: p.replace(/^\*+/, "").replace(/:.*$/, "").trim(), type: null });
|
|
9006
|
+
continue;
|
|
9007
|
+
}
|
|
9008
|
+
let name = p, type = null, m;
|
|
9009
|
+
if (language === "go") {
|
|
9010
|
+
m = p.match(/^(\w+)\s+(.+)$/);
|
|
9011
|
+
if (!m) {
|
|
9012
|
+
pendingGo.push(p);
|
|
9013
|
+
continue;
|
|
9014
|
+
}
|
|
9015
|
+
[, name, type] = m;
|
|
9016
|
+
for (const g of pendingGo) out.push({ name: g, type: simpleType(type) });
|
|
9017
|
+
pendingGo = [];
|
|
9018
|
+
} else if (language === "java" || language === "csharp" || language === "php") {
|
|
9019
|
+
m = p.replace(/^(final|ref|in|out|params|public|private|protected|readonly)\s+/g, "").replace(/^(public|private|protected|readonly)\s+/g, "").match(/^(.+?)\s+&?(?:\.\.\.)?(\w+)$/);
|
|
9020
|
+
if (m) [, type, name] = m;
|
|
9021
|
+
} else if (m = p.match(/^(\w+)\??\s*:\s*(.+)$/)) {
|
|
9022
|
+
[, name, type] = m;
|
|
9023
|
+
}
|
|
9024
|
+
out.push({ name: name.replace(/^(mut|val|var|vararg)\s+/, "").replace(/^[&$]+/, ""), type: simpleType(type ? type.replace(/^\?/, "") : type) });
|
|
9025
|
+
}
|
|
9026
|
+
for (const g of pendingGo) out.push({ name: g, type: null });
|
|
9027
|
+
return out;
|
|
9028
|
+
}
|
|
9029
|
+
function simpleType(t) {
|
|
9030
|
+
if (!t) return null;
|
|
9031
|
+
const s = String(t).trim().replace(/^&(mut\s+)?/, "");
|
|
9032
|
+
if (/^(number|int|long|short|float|double|decimal|f32|f64|i\d+|u\d+|usize|isize|float64|float32|int\d*|uint\d*|Integer|Double|Long|BigDecimal|Int|Float|Short|Byte)$/.test(s)) return "number";
|
|
9033
|
+
if (/^(bool|boolean|Boolean)$/.test(s)) return "boolean";
|
|
9034
|
+
if (/^(str|string|String|&str|char)$/.test(s)) return "string";
|
|
9035
|
+
return s;
|
|
9036
|
+
}
|
|
9037
|
+
function findFunctions(src, language) {
|
|
9038
|
+
const fns = [];
|
|
9039
|
+
if (language === "python") {
|
|
9040
|
+
const lines = src.split("\n");
|
|
9041
|
+
lines.forEach((l, i) => {
|
|
9042
|
+
const m = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\((.*)\)\s*(?:->\s*([^:]+))?:\s*(.*)$/);
|
|
9043
|
+
if (!m) return;
|
|
9044
|
+
const indent = m[1].length;
|
|
9045
|
+
const body = [];
|
|
9046
|
+
if (m[5].trim()) body.push({ text: m[5].trim(), line: i + 1, indent: indent + 4 });
|
|
9047
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
9048
|
+
const t = lines[j];
|
|
9049
|
+
if (!t.trim() || /^\s*#/.test(t)) continue;
|
|
9050
|
+
const ind = t.match(/^\s*/)[0].length;
|
|
9051
|
+
if (ind <= indent) break;
|
|
9052
|
+
body.push({ text: t.trim(), line: j + 1, indent: ind });
|
|
9053
|
+
}
|
|
9054
|
+
fns.push({ name: m[2], line: i + 1, params: parseParams2(m[3], language), returns: m[4]?.trim() || null, pyBody: body });
|
|
9055
|
+
});
|
|
9056
|
+
annotateRoutes(fns, src);
|
|
9057
|
+
return fns;
|
|
9058
|
+
}
|
|
9059
|
+
if (language === "ruby") return findRubyFunctions(src);
|
|
9060
|
+
const patterns = {
|
|
9061
|
+
typescript: [
|
|
9062
|
+
/(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(\w+)\s*(?:<[^>]*>)?\s*\(/g,
|
|
9063
|
+
/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:<[^>]*>)?\(/g,
|
|
9064
|
+
/^\s*(?:public\s+|private\s+|protected\s+|static\s+|async\s+|readonly\s+)*(\w+)\s*(?:<[^>]*>)?\s*\(/gm
|
|
9065
|
+
],
|
|
9066
|
+
go: [/func\s+(?:\([^)]*\)\s*)?(\w+)\s*(?:\[[^\]]*\])?\s*\(/g],
|
|
9067
|
+
rust: [/(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)\s*(?:<[^>]*>)?\s*\(/g],
|
|
9068
|
+
java: [/(?:(?:public|private|protected|static|final|synchronized|abstract)\s+)*(?:<[^>]+>\s+)?[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g],
|
|
9069
|
+
kotlin: [/\bfun\s+(?:<[^>]*>\s*)?(?:[\w.]+\.)?(\w+)\s*\(/g],
|
|
9070
|
+
php: [/\bfunction\s+&?(\w+)\s*\(/g]
|
|
8874
9071
|
};
|
|
8875
|
-
|
|
8876
|
-
|
|
8877
|
-
|
|
8878
|
-
|
|
8879
|
-
|
|
8880
|
-
|
|
8881
|
-
|
|
8882
|
-
|
|
8883
|
-
|
|
8884
|
-
|
|
9072
|
+
patterns.javascript = patterns.typescript;
|
|
9073
|
+
patterns.csharp = [/(?:(?:public|private|protected|internal|static|virtual|override|async|sealed|abstract|readonly)\s+)*[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g];
|
|
9074
|
+
const seen = /* @__PURE__ */ new Set();
|
|
9075
|
+
for (const re of patterns[language] || []) {
|
|
9076
|
+
let m;
|
|
9077
|
+
re.lastIndex = 0;
|
|
9078
|
+
while (m = re.exec(src)) {
|
|
9079
|
+
const name = m[1];
|
|
9080
|
+
const open = src.indexOf("(", m.index + m[0].length - 1);
|
|
9081
|
+
if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
|
|
9082
|
+
const close = matchClose(src, open);
|
|
9083
|
+
if (close < 0) continue;
|
|
9084
|
+
const after = src.slice(close + 1);
|
|
9085
|
+
const head = language === "kotlin" ? after.match(/^\s*(?::\s*([^{=]+?))?()()\s*(?:where\s+[^{=]+)?(=(?![=>])|\{)/) : after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/);
|
|
9086
|
+
if (!head || head[4] === ";") continue;
|
|
9087
|
+
if (language === "kotlin" && head[4] === "=") {
|
|
9088
|
+
const markerAt2 = close + 1 + head[0].length - 1;
|
|
9089
|
+
const fnLine2 = lineAt(src, m.index + m[0].lastIndexOf(name));
|
|
9090
|
+
if (seen.has(name + ":" + fnLine2)) continue;
|
|
9091
|
+
seen.add(name + ":" + fnLine2);
|
|
9092
|
+
const rest2 = src.slice(markerAt2 + 1);
|
|
9093
|
+
const lead = rest2.match(/^\s*/)[0].length;
|
|
9094
|
+
const end = kotlinExprEnd(rest2, lead);
|
|
9095
|
+
fns.push({ key: `${name}@${m.index}`, name, line: fnLine2, params: parseParams2(src.slice(open + 1, close), language), returns: (head[1] || "").trim() || null, bodyStart: markerAt2 + 1 + lead, body: `return ${rest2.slice(lead, end).trim()}` });
|
|
9096
|
+
continue;
|
|
9097
|
+
}
|
|
9098
|
+
const key = `${name}@${m.index}`;
|
|
9099
|
+
const fnLine = lineAt(src, m.index + m[0].lastIndexOf(name));
|
|
9100
|
+
if (seen.has(name + ":" + fnLine)) continue;
|
|
9101
|
+
seen.add(name + ":" + fnLine);
|
|
9102
|
+
const returns = (head[1] || head[2] || head[3] || "").trim() || null;
|
|
9103
|
+
const params = parseParams2(src.slice(open + 1, close), language);
|
|
9104
|
+
const markerAt = close + 1 + head[0].length - head[4].length;
|
|
9105
|
+
if (head[4] === "=>") {
|
|
9106
|
+
const rest2 = src.slice(markerAt + 2);
|
|
9107
|
+
const lead = rest2.match(/^\s*/)[0].length;
|
|
9108
|
+
if (rest2[lead] === "{") {
|
|
9109
|
+
const bo = markerAt + 2 + lead, bc = matchClose(src, bo);
|
|
9110
|
+
if (bc > 0) fns.push({ key, name, line: fnLine, params, returns, bodyStart: bo + 1, body: src.slice(bo + 1, bc) });
|
|
9111
|
+
} else {
|
|
9112
|
+
const semi = topLevelIndex(rest2, ";");
|
|
9113
|
+
const blank = rest2.search(/\n\s*\n/);
|
|
9114
|
+
const end = semi < 0 ? blank : blank < 0 ? semi : Math.min(semi, blank);
|
|
9115
|
+
const expr = (end < 0 ? rest2 : rest2.slice(0, end)).trim();
|
|
9116
|
+
fns.push({ key, name, line: fnLine, params, returns, bodyStart: markerAt + 2 + lead, body: `return ${expr};` });
|
|
8885
9117
|
}
|
|
9118
|
+
} else {
|
|
9119
|
+
const bc = matchClose(src, markerAt);
|
|
9120
|
+
if (bc > 0) fns.push({ key, name, line: fnLine, params, returns, bodyStart: markerAt + 1, body: src.slice(markerAt + 1, bc) });
|
|
8886
9121
|
}
|
|
8887
|
-
if (m) {
|
|
8888
|
-
status = m.pass ? "verified" : "failed";
|
|
8889
|
-
provenBy = m.name;
|
|
8890
|
-
} else status = "declared";
|
|
8891
9122
|
}
|
|
8892
|
-
return { kind, id: o.id, status, provenBy };
|
|
8893
|
-
};
|
|
8894
|
-
const obligations = [...ast.guarantees.map((g) => build("guarantee", g)), ...ast.neverRules.map((n) => build("prohibition", n))];
|
|
8895
|
-
return { obligations, tests: t, failed: obligations.filter((o) => o.status === "failed").length };
|
|
8896
|
-
}
|
|
8897
|
-
var LOCKFILES = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "poetry.lock", "Pipfile.lock", "Cargo.lock", "go.sum", "Gemfile.lock", "composer.lock"];
|
|
8898
|
-
function proofFreshness(proof, environment) {
|
|
8899
|
-
let head = null;
|
|
8900
|
-
try {
|
|
8901
|
-
head = (0, import_node_child_process.execSync)("git rev-parse HEAD", { encoding: "utf8", stdio: ["pipe", "pipe", "ignore"] }).trim() || null;
|
|
8902
|
-
} catch {
|
|
8903
|
-
head = null;
|
|
8904
9123
|
}
|
|
8905
|
-
|
|
8906
|
-
|
|
8907
|
-
|
|
8908
|
-
|
|
8909
|
-
|
|
8910
|
-
|
|
9124
|
+
if (language === "kotlin") {
|
|
9125
|
+
const re = /\b(get|post|put|patch|delete)\(\s*"([^"]+)"\s*\)\s*\{/g;
|
|
9126
|
+
let m;
|
|
9127
|
+
while (m = re.exec(src)) {
|
|
9128
|
+
const brace = m.index + m[0].length - 1;
|
|
9129
|
+
const bc = matchClose(src, brace);
|
|
9130
|
+
if (bc < 0) continue;
|
|
9131
|
+
fns.push({ name: `${m[1].toUpperCase()} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method: m[1].toUpperCase(), path: m[2] } });
|
|
9132
|
+
}
|
|
9133
|
+
}
|
|
9134
|
+
const routeRes = language === "php" ? [/\bRoute::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]\s*,\s*(?:static\s+)?function\s*\(/g] : language === "go" ? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g] : language === "typescript" || language === "javascript" ? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:async\s*)?(?:function\s*\w*\s*)?\(/g] : [];
|
|
9135
|
+
for (const re of routeRes) {
|
|
9136
|
+
let m;
|
|
9137
|
+
while (m = re.exec(src)) {
|
|
9138
|
+
const open = src.indexOf("(", m.index + m[0].length - 1);
|
|
9139
|
+
const close = matchClose(src, open);
|
|
9140
|
+
if (close < 0) continue;
|
|
9141
|
+
const brace = src.indexOf("{", close);
|
|
9142
|
+
if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) continue;
|
|
9143
|
+
const bc = matchClose(src, brace);
|
|
9144
|
+
if (bc < 0) continue;
|
|
9145
|
+
const method = /^handle/i.test(m[1]) ? "ANY" : m[1].toUpperCase();
|
|
9146
|
+
fns.push({ name: `${method} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method, path: m[2] } });
|
|
9147
|
+
}
|
|
9148
|
+
}
|
|
9149
|
+
annotateRoutes(fns, src);
|
|
9150
|
+
return fns.sort((a, b) => a.line - b.line);
|
|
9151
|
+
}
|
|
9152
|
+
function annotateRoutes(fns, src) {
|
|
9153
|
+
const lines = src.split("\n");
|
|
9154
|
+
for (const fn of fns) {
|
|
9155
|
+
if (fn.route) continue;
|
|
9156
|
+
for (let k = fn.line - 2; k >= Math.max(0, fn.line - 6); k--) {
|
|
9157
|
+
const l = lines[k].trim();
|
|
9158
|
+
let m;
|
|
9159
|
+
if (m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i)) {
|
|
9160
|
+
fn.route = { method: m[1].toUpperCase(), path: m[2] };
|
|
9161
|
+
break;
|
|
9162
|
+
}
|
|
9163
|
+
if (m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/)) {
|
|
9164
|
+
fn.route = { method: (m[2] || "GET").toUpperCase(), path: m[1] };
|
|
9165
|
+
break;
|
|
9166
|
+
}
|
|
9167
|
+
if (m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?["']([^"']*)["'])?/)) {
|
|
9168
|
+
fn.route = { method: m[1] === "Request" ? "ANY" : m[1].toUpperCase(), path: m[2] || "/" };
|
|
8911
9169
|
break;
|
|
8912
9170
|
}
|
|
9171
|
+
if (m = l.match(/^#\[Route\(\s*(?:path:\s*)?['"]([^'"]*)['"](?:.*methods:\s*\[\s*['"](\w+)['"])?/)) {
|
|
9172
|
+
fn.route = { method: (m[2] || "ANY").toUpperCase(), path: m[1] };
|
|
9173
|
+
break;
|
|
9174
|
+
}
|
|
9175
|
+
if (m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/)) {
|
|
9176
|
+
fn.route = { method: m[1].toUpperCase(), path: m[2] || "" };
|
|
9177
|
+
break;
|
|
9178
|
+
}
|
|
9179
|
+
if (m = l.match(/^@(Get|Post|Put|Patch|Delete)\(\s*(?:['"]([^'"]*)['"])?\s*\)/)) {
|
|
9180
|
+
fn.route = { method: m[1].toUpperCase(), path: m[2] || "" };
|
|
9181
|
+
break;
|
|
9182
|
+
}
|
|
9183
|
+
if (!/^(@|\[|\/\/|#|\*|\/\*)/.test(l) && l) break;
|
|
8913
9184
|
}
|
|
8914
|
-
const parent = (0, import_node_path.dirname)(dir);
|
|
8915
|
-
if (parent === dir) break;
|
|
8916
|
-
dir = parent;
|
|
8917
9185
|
}
|
|
8918
|
-
return {
|
|
8919
|
-
intentHash: proof.sourceHash,
|
|
8920
|
-
compilerVersion: proof.compilerVersion,
|
|
8921
|
-
implementation: head,
|
|
8922
|
-
dependencies: lock ? { file: (0, import_node_path.basename)(lock), hash: sha256((0, import_node_fs.readFileSync)(lock, "utf8")) } : null,
|
|
8923
|
-
environment: environment || null,
|
|
8924
|
-
generatedAt: proof.generatedAt
|
|
8925
|
-
};
|
|
8926
9186
|
}
|
|
8927
|
-
var
|
|
8928
|
-
|
|
8929
|
-
|
|
8930
|
-
|
|
8931
|
-
|
|
8932
|
-
|
|
8933
|
-
|
|
8934
|
-
|
|
9187
|
+
var KT_CONTINUES_NEXT = /^\s*(\.|\?\.|\?:|&&|\|\||[+\-*/%]|else\b(?!\s*->)|->|\)|\]|:)/;
|
|
9188
|
+
var KT_CONTINUES_LINE = /(&&|\|\||[=+\-*/%(,.:[]|->|\belse|\bif\s*\([^)]*\))\s*$/;
|
|
9189
|
+
function kotlinExprEnd(src, from) {
|
|
9190
|
+
let depth = 0;
|
|
9191
|
+
for (let i = from; i < src.length; i++) {
|
|
9192
|
+
const c = src[i];
|
|
9193
|
+
if (c === '"' || c === "'") {
|
|
9194
|
+
i = skipString(src, i);
|
|
9195
|
+
continue;
|
|
8935
9196
|
}
|
|
8936
|
-
|
|
8937
|
-
|
|
8938
|
-
|
|
8939
|
-
|
|
8940
|
-
|
|
8941
|
-
type: "object",
|
|
8942
|
-
required: ["intent", "after"],
|
|
8943
|
-
properties: {
|
|
8944
|
-
intent: { ...str, description: "the .intent source (the contract)" },
|
|
8945
|
-
after: { ...str, description: "the proposed/changed code" },
|
|
8946
|
-
before: { ...str, description: "the code before the change (optional; enables regression detection)" },
|
|
8947
|
-
language: { ...str, description: `source language (default typescript). One of: ${SUPPORTED_LANGUAGES.join(", ")}` }
|
|
8948
|
-
}
|
|
8949
|
-
},
|
|
8950
|
-
run: ({ intent, after, before = null, language = "typescript" }) => verifyDiff(String(intent), { before: before == null ? null : String(before), after: String(after), language })
|
|
8951
|
-
},
|
|
8952
|
-
{
|
|
8953
|
-
name: "intent_prove",
|
|
8954
|
-
description: "Emit the durable intent-proof-v1 artifact for .intent source: per-claim verdicts (verified / failed / planned / needs_verification, each bound to the named test that proves it) plus the freshness tuple (intent hash, compiler version, commit, dependency lockfile) that lets `thunder verify` mark the proof STALE later. Mirrors `thunder prove`; an unverified claim never reads as passed. Call it after the gate passes to record WHAT was proven.",
|
|
8955
|
-
inputSchema: {
|
|
8956
|
-
type: "object",
|
|
8957
|
-
required: ["source"],
|
|
8958
|
-
properties: {
|
|
8959
|
-
source: { ...str, description: "the .intent source" },
|
|
8960
|
-
sourceFile: { ...str, description: "file name to record in the proof (default intent.thunder)" },
|
|
8961
|
-
environment: { ...str, description: "environment name to bind into the freshness tuple (optional)" }
|
|
8962
|
-
}
|
|
8963
|
-
},
|
|
8964
|
-
run: ({ source, sourceFile = "intent.thunder", environment }) => {
|
|
8965
|
-
const text = String(source);
|
|
8966
|
-
const ast = parseIntent(text);
|
|
8967
|
-
const diagnostics = semanticDiagnostics(ast);
|
|
8968
|
-
const resolved = resolveObligations(ast);
|
|
8969
|
-
const proof = buildProof(ast, {
|
|
8970
|
-
sourceFile: String(sourceFile),
|
|
8971
|
-
sourceHash: sha256(text),
|
|
8972
|
-
targetsRequested: ast.targets || [],
|
|
8973
|
-
targetsGenerated: [],
|
|
8974
|
-
diagnostics,
|
|
8975
|
-
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
8976
|
-
});
|
|
8977
|
-
const CLAIM_MAP = { verified: "verified", failed: "failed", declared: "planned", unverified: "needs_verification" };
|
|
8978
|
-
const byId = new Map(resolved.obligations.map((o) => [o.id, o]));
|
|
8979
|
-
const applyStatus = (claim) => {
|
|
8980
|
-
const o = byId.get(claim.id);
|
|
8981
|
-
return o ? { ...claim, status: CLAIM_MAP[o.status], provenBy: o.provenBy || null } : claim;
|
|
8982
|
-
};
|
|
8983
|
-
proof.guarantees = proof.guarantees.map(applyStatus);
|
|
8984
|
-
proof.neverRules = proof.neverRules.map(applyStatus);
|
|
8985
|
-
proof.freshness = proofFreshness(proof, environment);
|
|
8986
|
-
const ok = proof.verification.semanticPassed && resolved.tests.ok !== false && resolved.failed === 0;
|
|
8987
|
-
return { ok, proofId: `proof-${proof.sourceHash.replace("sha256:", "").slice(0, 6)}`, ...proof, tests: resolved.tests };
|
|
9197
|
+
if (c === "/" && src[i + 1] === "/") {
|
|
9198
|
+
const n = src.indexOf("\n", i);
|
|
9199
|
+
if (n < 0) return src.length;
|
|
9200
|
+
i = n - 1;
|
|
9201
|
+
continue;
|
|
8988
9202
|
}
|
|
8989
|
-
|
|
8990
|
-
|
|
8991
|
-
|
|
8992
|
-
|
|
8993
|
-
|
|
8994
|
-
|
|
8995
|
-
|
|
8996
|
-
|
|
8997
|
-
source: { ...str, description: "the .intent source (with test blocks)" },
|
|
8998
|
-
targets: { type: "array", items: str, description: "target languages to grade (default: the targets the intent declares)" },
|
|
8999
|
-
results: { type: "object", description: 'per-target actual outputs to grade: {target: {"Test / case": result}}' }
|
|
9000
|
-
}
|
|
9001
|
-
},
|
|
9002
|
-
run: ({ source, targets = [], results = null }) => {
|
|
9003
|
-
const rep = buildConformance(parseIntent(String(source)), { targets: Array.isArray(targets) ? targets.map(String) : [], results });
|
|
9004
|
-
return { ok: rep.semanticFailures === 0 && rep.failures.length === 0, ...rep };
|
|
9203
|
+
if ("([{".includes(c)) depth++;
|
|
9204
|
+
else if (")]}".includes(c)) {
|
|
9205
|
+
if (--depth < 0) return i;
|
|
9206
|
+
} else if (c === "\n" && depth === 0) {
|
|
9207
|
+
const line = src.slice(src.lastIndexOf("\n", i - 1) + 1, i);
|
|
9208
|
+
const next = src.slice(i + 1);
|
|
9209
|
+
if (/^\s*\n/.test(next) || !next.trim()) return i;
|
|
9210
|
+
if (!KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) return i;
|
|
9005
9211
|
}
|
|
9006
|
-
}
|
|
9007
|
-
|
|
9008
|
-
|
|
9009
|
-
|
|
9010
|
-
|
|
9011
|
-
|
|
9012
|
-
|
|
9013
|
-
|
|
9014
|
-
|
|
9015
|
-
|
|
9016
|
-
|
|
9212
|
+
}
|
|
9213
|
+
return src.length;
|
|
9214
|
+
}
|
|
9215
|
+
function kotlinTerminate(body) {
|
|
9216
|
+
const src = stripCommentsKeepLayout(body);
|
|
9217
|
+
let out = "", depth = 0, last = 0;
|
|
9218
|
+
for (let i = 0; i < src.length; i++) {
|
|
9219
|
+
const c = src[i];
|
|
9220
|
+
if (c === '"' || c === "'") {
|
|
9221
|
+
i = skipString(src, i);
|
|
9222
|
+
continue;
|
|
9223
|
+
}
|
|
9224
|
+
if ("([{".includes(c)) depth++;
|
|
9225
|
+
else if (")]}".includes(c)) depth--;
|
|
9226
|
+
else if (c === "\n" && depth === 0) {
|
|
9227
|
+
const line = src.slice(src.lastIndexOf("\n", i - 1) + 1, i);
|
|
9228
|
+
const next = src.slice(i + 1);
|
|
9229
|
+
if (line.trim() && !/[{;]\s*$/.test(line) && !KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) {
|
|
9230
|
+
out += src.slice(last, i) + ";";
|
|
9231
|
+
last = i;
|
|
9017
9232
|
}
|
|
9018
|
-
},
|
|
9019
|
-
run: ({ intent, code, language = "typescript" }) => checkDrift(String(intent), String(code), { language })
|
|
9020
|
-
},
|
|
9021
|
-
{
|
|
9022
|
-
name: "intent_draft",
|
|
9023
|
-
description: "Turn a STRUCTURED brief into a rigorous, canonically-formatted ThunderLang draft plus a review checklist of what a human must still fill in (unverified guarantees, unguarded secrets, missing goal). Use this after distilling a user request into structured fields; the draft is a proposal for human approval, never verified.",
|
|
9024
|
-
inputSchema: {
|
|
9025
|
-
type: "object",
|
|
9026
|
-
required: ["brief"],
|
|
9027
|
-
properties: { brief: { type: "object", description: "fields: mission, goal, actor, problem, guarantees[], neverRules[], inputs[{name,type}], outputs[], decisions[]" } }
|
|
9028
|
-
},
|
|
9029
|
-
run: ({ brief }) => draftIntent(brief || {})
|
|
9030
|
-
},
|
|
9031
|
-
{
|
|
9032
|
-
name: "intent_lift",
|
|
9033
|
-
description: "Lift source code into an inferred, humble ThunderLang draft (never claims verified). Covers the top languages. Use it to bootstrap intent from code you already have.",
|
|
9034
|
-
inputSchema: {
|
|
9035
|
-
type: "object",
|
|
9036
|
-
required: ["source"],
|
|
9037
|
-
properties: { source: { ...str, description: "the source code" }, language: { ...str, description: `source language (default typescript). One of: ${SUPPORTED_LANGUAGES.join(", ")}` } }
|
|
9038
|
-
},
|
|
9039
|
-
run: ({ source, language = "typescript" }) => {
|
|
9040
|
-
const r = liftSource(String(source), { language });
|
|
9041
|
-
return r.ok ? { ok: true, intent: r.intentText, summary: r.summary, diagnostics: r.diagnostics } : { ok: false, error: r.error };
|
|
9042
9233
|
}
|
|
9043
|
-
}
|
|
9044
|
-
|
|
9234
|
+
}
|
|
9235
|
+
return out + src.slice(last);
|
|
9236
|
+
}
|
|
9237
|
+
function mapCode(src, fn) {
|
|
9238
|
+
let out = "", start = 0;
|
|
9239
|
+
for (let i = 0; i < src.length; i++) {
|
|
9240
|
+
const c = src[i];
|
|
9241
|
+
let end = -1;
|
|
9242
|
+
if (c === '"' || c === "'") end = skipString(src, i);
|
|
9243
|
+
else if (c === "/" && src[i + 1] === "/") {
|
|
9244
|
+
const n = src.indexOf("\n", i);
|
|
9245
|
+
end = n < 0 ? src.length - 1 : n - 1;
|
|
9246
|
+
} else if (c === "/" && src[i + 1] === "*") {
|
|
9247
|
+
const n = src.indexOf("*/", i + 2);
|
|
9248
|
+
end = n < 0 ? src.length - 1 : n + 1;
|
|
9249
|
+
}
|
|
9250
|
+
if (end < 0) continue;
|
|
9251
|
+
end = Math.max(end, i);
|
|
9252
|
+
out += fn(src.slice(start, i)) + src.slice(i, end + 1);
|
|
9253
|
+
start = i = end + 1;
|
|
9254
|
+
i--;
|
|
9255
|
+
}
|
|
9256
|
+
return out + fn(src.slice(start));
|
|
9257
|
+
}
|
|
9258
|
+
function normalizePhp(src) {
|
|
9259
|
+
return mapCode(src.replace(/(^|[^\[])#(?!\[)/gm, "$1//"), (code) => code.replace(/\$this\s*->/g, "this.").replace(/\$(?=[A-Za-z_])/g, "").replace(/(\w|\))\s*(?:\?)?->\s*(?=[A-Za-z_])/g, "$1.").replace(/\belseif\b/g, "else if"));
|
|
9260
|
+
}
|
|
9261
|
+
function readKotlinIf(text, inputs, rules, unread, line, setOtherwise) {
|
|
9262
|
+
let s = text.trim().replace(/;$/, "");
|
|
9263
|
+
if (!/^if\s*\(/.test(s)) return false;
|
|
9264
|
+
const local = [];
|
|
9265
|
+
const value = (v) => {
|
|
9266
|
+
v = v.trim();
|
|
9267
|
+
if (v.startsWith("{")) {
|
|
9268
|
+
const c = matchClose(v, 0);
|
|
9269
|
+
return c === v.length - 1 ? v.slice(1, -1).trim() : null;
|
|
9270
|
+
}
|
|
9271
|
+
return v;
|
|
9272
|
+
};
|
|
9273
|
+
while (/^if\s*\(/.test(s)) {
|
|
9274
|
+
const open = s.indexOf("(");
|
|
9275
|
+
const close = matchClose(s, open);
|
|
9276
|
+
if (close < 0) return false;
|
|
9277
|
+
const cond = s.slice(open + 1, close);
|
|
9278
|
+
const rest2 = s.slice(close + 1).trim();
|
|
9279
|
+
const elseAt = rest2.startsWith("{") ? matchClose(rest2, 0) + 1 : rest2.search(/\belse\b/);
|
|
9280
|
+
if (elseAt <= 0) return false;
|
|
9281
|
+
const thenPart = value(rest2.slice(0, elseAt));
|
|
9282
|
+
const after = rest2.slice(elseAt).trim();
|
|
9283
|
+
if (!/^else\b/.test(after)) return false;
|
|
9284
|
+
const when = toThunderCondition(cond, inputs), result = thenPart == null ? null : toThunderOutcome(thenPart);
|
|
9285
|
+
if (!when || !result) {
|
|
9286
|
+
unread.push({ line, text: `if (${cond.trim()})`, reason: "This choice uses a condition or answer that is not a fixed value." });
|
|
9287
|
+
return true;
|
|
9288
|
+
}
|
|
9289
|
+
local.push({ when, result, line });
|
|
9290
|
+
s = after.replace(/^else\s*/, "");
|
|
9291
|
+
}
|
|
9292
|
+
const fb = value(s);
|
|
9293
|
+
const fallback = fb == null ? null : toThunderOutcome(fb);
|
|
9294
|
+
if (!fallback) {
|
|
9295
|
+
unread.push({ line, text: s.slice(0, 120), reason: "The fallback answer is computed, not a fixed value." });
|
|
9296
|
+
return true;
|
|
9297
|
+
}
|
|
9298
|
+
rules.push(...local);
|
|
9299
|
+
setOtherwise({ result: fallback, line });
|
|
9300
|
+
return true;
|
|
9301
|
+
}
|
|
9302
|
+
function kotlinWhenArms(body, baseLine) {
|
|
9303
|
+
const arms = [];
|
|
9304
|
+
const src = stripCommentsKeepLayout(body);
|
|
9305
|
+
let i = 0;
|
|
9306
|
+
while (i < src.length) {
|
|
9307
|
+
while (i < src.length && /[\s;]/.test(src[i])) i++;
|
|
9308
|
+
if (i >= src.length) break;
|
|
9309
|
+
const arrow = (() => {
|
|
9310
|
+
let depth = 0;
|
|
9311
|
+
for (let j2 = i; j2 < src.length; j2++) {
|
|
9312
|
+
const c = src[j2];
|
|
9313
|
+
if (c === '"' || c === "'") {
|
|
9314
|
+
j2 = skipString(src, j2);
|
|
9315
|
+
continue;
|
|
9316
|
+
}
|
|
9317
|
+
if ("([{".includes(c)) depth++;
|
|
9318
|
+
else if (")]}".includes(c)) depth--;
|
|
9319
|
+
else if (c === "-" && src[j2 + 1] === ">" && depth === 0) return j2;
|
|
9320
|
+
}
|
|
9321
|
+
return -1;
|
|
9322
|
+
})();
|
|
9323
|
+
if (arrow < 0) return null;
|
|
9324
|
+
const pattern = src.slice(i, arrow).trim();
|
|
9325
|
+
let j = arrow + 2;
|
|
9326
|
+
while (/[ \t]/.test(src[j] || "")) j++;
|
|
9327
|
+
let value, end;
|
|
9328
|
+
if (src[j] === "{") {
|
|
9329
|
+
const c = matchClose(src, j);
|
|
9330
|
+
if (c < 0) return null;
|
|
9331
|
+
const inner = src.slice(j + 1, c).trim();
|
|
9332
|
+
value = /[;\n]/.test(inner) ? null : inner;
|
|
9333
|
+
end = c + 1;
|
|
9334
|
+
} else {
|
|
9335
|
+
end = kotlinExprEnd(src, j);
|
|
9336
|
+
const semi = topLevelIndex(src.slice(j, end), ";");
|
|
9337
|
+
if (semi >= 0) end = j + semi;
|
|
9338
|
+
value = src.slice(j, end).trim();
|
|
9339
|
+
}
|
|
9340
|
+
if (value) value = value.replace(/^return\s+/, "");
|
|
9341
|
+
arms.push({ pattern: pattern === "else" ? null : pattern, guard: null, value, line: baseLine + lineAt(src, i) - 1 });
|
|
9342
|
+
i = end;
|
|
9343
|
+
}
|
|
9344
|
+
return arms;
|
|
9345
|
+
}
|
|
9346
|
+
function kotlinPattern(p) {
|
|
9347
|
+
return p.split(/,(?![^(]*\))/).map((x) => x.trim().replace(/^in\s+(-?[\d.]+)\s*\.\.\s*(-?[\d.]+)$/, "$1..=$2").replace(/^in\s+(-?[\d.]+)\s*(?:until|\.\.<)\s*(-?[\d.]+)$/, "$1..$2")).join(", ");
|
|
9348
|
+
}
|
|
9349
|
+
var EXPR_TOKEN = /\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|===|!==|==|!=|>=|<=|&&|\|\||->|::|[<>!()?:,.]|\d+(?:\.\d+)?(?:f64|f32|[fFdDmMlL])?|[A-Za-z_$][\w$]*)/y;
|
|
9350
|
+
function lex(text) {
|
|
9351
|
+
const out = [];
|
|
9352
|
+
EXPR_TOKEN.lastIndex = 0;
|
|
9353
|
+
let i = 0;
|
|
9354
|
+
const s = text.trim();
|
|
9355
|
+
while (i < s.length) {
|
|
9356
|
+
EXPR_TOKEN.lastIndex = i;
|
|
9357
|
+
const m = EXPR_TOKEN.exec(s);
|
|
9358
|
+
if (!m) return null;
|
|
9359
|
+
out.push(m[1]);
|
|
9360
|
+
i = EXPR_TOKEN.lastIndex;
|
|
9361
|
+
while (i < s.length && /\s/.test(s[i])) i++;
|
|
9362
|
+
}
|
|
9363
|
+
return out;
|
|
9364
|
+
}
|
|
9365
|
+
var unquote = (t) => t.slice(1, -1);
|
|
9366
|
+
function toThunderCondition(text, inputs = []) {
|
|
9367
|
+
const toks = lex(text);
|
|
9368
|
+
if (!toks || !toks.length) return null;
|
|
9369
|
+
const out = [];
|
|
9370
|
+
for (let i = 0; i < toks.length; i++) {
|
|
9371
|
+
let t = toks[i];
|
|
9372
|
+
const next = toks[i + 1];
|
|
9373
|
+
if (t === "this" || t === "self") {
|
|
9374
|
+
if (next === ".") i++;
|
|
9375
|
+
continue;
|
|
9376
|
+
}
|
|
9377
|
+
if (t === "&&" || t === "and") {
|
|
9378
|
+
out.push("and");
|
|
9379
|
+
continue;
|
|
9380
|
+
}
|
|
9381
|
+
if (t === "||" || t === "or") {
|
|
9382
|
+
out.push("or");
|
|
9383
|
+
continue;
|
|
9384
|
+
}
|
|
9385
|
+
if (t === "!" || t === "not") {
|
|
9386
|
+
out.push("not");
|
|
9387
|
+
continue;
|
|
9388
|
+
}
|
|
9389
|
+
if (t === "===" || t === "==") {
|
|
9390
|
+
out.push("==");
|
|
9391
|
+
continue;
|
|
9392
|
+
}
|
|
9393
|
+
if (t === "!==" || t === "!=") {
|
|
9394
|
+
out.push("!=");
|
|
9395
|
+
continue;
|
|
9396
|
+
}
|
|
9397
|
+
if ([">", "<", ">=", "<=", "(", ")"].includes(t)) {
|
|
9398
|
+
out.push(t);
|
|
9399
|
+
continue;
|
|
9400
|
+
}
|
|
9401
|
+
if (t === "True" || t === "true") {
|
|
9402
|
+
out.push("true");
|
|
9403
|
+
continue;
|
|
9404
|
+
}
|
|
9405
|
+
if (t === "False" || t === "false") {
|
|
9406
|
+
out.push("false");
|
|
9407
|
+
continue;
|
|
9408
|
+
}
|
|
9409
|
+
if (/^["']/.test(t)) {
|
|
9410
|
+
if (t[0] === '"' && /#\{|\$\{|\$[A-Za-z_]/.test(t)) return null;
|
|
9411
|
+
out.push(JSON.stringify(unquote(t)));
|
|
9412
|
+
continue;
|
|
9413
|
+
}
|
|
9414
|
+
if (/^\d/.test(t)) {
|
|
9415
|
+
out.push(t.replace(/(f64|f32|[fFdDmMlL])$/, ""));
|
|
9416
|
+
continue;
|
|
9417
|
+
}
|
|
9418
|
+
if (/^[A-Za-z_$]/.test(t)) {
|
|
9419
|
+
if ((t === "Objects" || t === "string" || t === "String") && next === "." && /^(equals|Equals)$/.test(toks[i + 2] || "") && toks[i + 3] === "(") {
|
|
9420
|
+
const close = findClose(toks, i + 3);
|
|
9421
|
+
const args = splitArgs(toks.slice(i + 4, close));
|
|
9422
|
+
if (args.length !== 2) return null;
|
|
9423
|
+
const a = toThunderCondition(args[0].join(" "), inputs), b = toThunderCondition(args[1].join(" "), inputs);
|
|
9424
|
+
if (!a || !b) return null;
|
|
9425
|
+
out.push(`${a} == ${b}`);
|
|
9426
|
+
i = close;
|
|
9427
|
+
continue;
|
|
9428
|
+
}
|
|
9429
|
+
let path = t;
|
|
9430
|
+
while (toks[i + 1] === "." && /^[A-Za-z_$]/.test(toks[i + 2] || "")) {
|
|
9431
|
+
if (/^(equals|Equals)$/.test(toks[i + 2]) && toks[i + 3] === "(") break;
|
|
9432
|
+
path += "." + toks[i + 2];
|
|
9433
|
+
i += 2;
|
|
9434
|
+
}
|
|
9435
|
+
if (toks[i + 1] === "." && /^(equals|Equals)$/.test(toks[i + 2] || "") && toks[i + 3] === "(") {
|
|
9436
|
+
const close = findClose(toks, i + 3);
|
|
9437
|
+
if (/(^|\.)(Objects|String|string)$/.test(path)) {
|
|
9438
|
+
const args = splitArgs(toks.slice(i + 4, close));
|
|
9439
|
+
if (args.length !== 2) return null;
|
|
9440
|
+
const a = toThunderCondition(args[0].join(" "), inputs), b = toThunderCondition(args[1].join(" "), inputs);
|
|
9441
|
+
if (!a || !b) return null;
|
|
9442
|
+
out.push(`${a} == ${b}`);
|
|
9443
|
+
i = close;
|
|
9444
|
+
continue;
|
|
9445
|
+
}
|
|
9446
|
+
const arg = toThunderCondition(toks.slice(i + 4, close).join(" "), inputs);
|
|
9447
|
+
if (!arg) return null;
|
|
9448
|
+
out.push(`${path} == ${arg}`);
|
|
9449
|
+
i = close;
|
|
9450
|
+
continue;
|
|
9451
|
+
}
|
|
9452
|
+
while (toks[i + 1] === "::" && /^[A-Za-z_]/.test(toks[i + 2] || "")) {
|
|
9453
|
+
path = toks[i + 2];
|
|
9454
|
+
i += 2;
|
|
9455
|
+
}
|
|
9456
|
+
if (toks[i + 1] === "(") {
|
|
9457
|
+
if (toks[i + 2] !== ")") return null;
|
|
9458
|
+
i += 2;
|
|
9459
|
+
}
|
|
9460
|
+
if (/^(null|nil|None|undefined)$/.test(path)) return null;
|
|
9461
|
+
out.push(path);
|
|
9462
|
+
continue;
|
|
9463
|
+
}
|
|
9464
|
+
return null;
|
|
9465
|
+
}
|
|
9466
|
+
for (let k = 0; k < out.length; k++) if (/^[<>]=?$/.test(out[k]) && (/^"/.test(out[k - 1] || "") || /^"/.test(out[k + 1] || ""))) return null;
|
|
9467
|
+
const expr = out.join(" ").replace(/\( /g, "(").replace(/ \)/g, ")").replace(/not \(/g, "not (").replace(/\bnot not /g, "");
|
|
9468
|
+
try {
|
|
9469
|
+
compileExpr(expr, { inputs });
|
|
9470
|
+
} catch {
|
|
9471
|
+
return null;
|
|
9472
|
+
}
|
|
9473
|
+
return simplifyExpr(expr);
|
|
9474
|
+
}
|
|
9475
|
+
function findClose(toks, open) {
|
|
9476
|
+
let depth = 0;
|
|
9477
|
+
for (let i = open; i < toks.length; i++) {
|
|
9478
|
+
if (toks[i] === "(") depth++;
|
|
9479
|
+
else if (toks[i] === ")" && --depth === 0) return i;
|
|
9480
|
+
}
|
|
9481
|
+
return toks.length - 1;
|
|
9482
|
+
}
|
|
9483
|
+
function splitArgs(toks) {
|
|
9484
|
+
const args = [[]];
|
|
9485
|
+
let depth = 0;
|
|
9486
|
+
for (const t of toks) {
|
|
9487
|
+
if (t === "(") depth++;
|
|
9488
|
+
if (t === ")") depth--;
|
|
9489
|
+
if (t === "," && depth === 0) args.push([]);
|
|
9490
|
+
else args[args.length - 1].push(t);
|
|
9491
|
+
}
|
|
9492
|
+
return args;
|
|
9493
|
+
}
|
|
9494
|
+
function toThunderOutcome(text) {
|
|
9495
|
+
let s = String(text).trim().replace(/;$/, "").trim();
|
|
9496
|
+
s = s.replace(/^Ok\((.*)\)$/, "$1").replace(/\.(to_string|into|to_owned)\(\)$/, "").replace(/^String::from\((.*)\)$/, "$1").trim();
|
|
9497
|
+
if (/^(None|null|nil|undefined|Nothing)$/.test(s)) return null;
|
|
9498
|
+
let m;
|
|
9499
|
+
if (m = s.match(/^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/)) {
|
|
9500
|
+
if (m[1] != null && /#\{|\$\{|\$[A-Za-z_]/.test(m[1])) return null;
|
|
9501
|
+
const v = m[1] ?? m[2] ?? m[3];
|
|
9502
|
+
if (v === "") return null;
|
|
9503
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(v) ? v : JSON.stringify(v);
|
|
9504
|
+
}
|
|
9505
|
+
if (/^-?\d+(\.\d+)?(f64|f32|[fFdDmMlL])?$/.test(s)) return s.replace(/(f64|f32|[fFdDmMlL])$/, "");
|
|
9506
|
+
if (/^(true|false|True|False)$/.test(s)) return s.toLowerCase();
|
|
9507
|
+
if (m = s.match(/^(?:[A-Za-z_][\w]*(?:\.|::))+([A-Z][A-Za-z0-9_]*)$/)) return m[1];
|
|
9508
|
+
if (/^[A-Z][A-Za-z0-9_]*$/.test(s)) return s;
|
|
9509
|
+
return null;
|
|
9510
|
+
}
|
|
9511
|
+
var lastSeg = (s) => String(s).split(/\.|::/).pop();
|
|
9512
|
+
var firstString = (s) => (String(s).match(/^\s*(?:f|r|b)?["'`]([^"'`]{1,80})["'`]/) || [])[1] || null;
|
|
9513
|
+
function splitTop(str2, delim) {
|
|
9514
|
+
const out = [];
|
|
9515
|
+
let depth = 0, cur = "";
|
|
9516
|
+
for (let i = 0; i < str2.length; i++) {
|
|
9517
|
+
const ch = str2[i];
|
|
9518
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
9519
|
+
const j = skipString(str2, i);
|
|
9520
|
+
cur += str2.slice(i, j + 1);
|
|
9521
|
+
i = j;
|
|
9522
|
+
continue;
|
|
9523
|
+
}
|
|
9524
|
+
if ("([{".includes(ch)) depth++;
|
|
9525
|
+
else if (")]}".includes(ch)) depth--;
|
|
9526
|
+
if (ch === delim && depth === 0) {
|
|
9527
|
+
out.push(cur);
|
|
9528
|
+
cur = "";
|
|
9529
|
+
} else cur += ch;
|
|
9530
|
+
}
|
|
9531
|
+
out.push(cur);
|
|
9532
|
+
return out;
|
|
9533
|
+
}
|
|
9534
|
+
function terminatorEffect(stmt, language) {
|
|
9535
|
+
const s = String(stmt).trim().replace(/;$/, "").trim();
|
|
9536
|
+
let m;
|
|
9537
|
+
if (m = s.match(/^throw\s+new\s+([\w.$]+)\s*\(([\s\S]*)\)$/)) return { kind: "fails", name: lastSeg(m[1]), detail: firstString(m[2]) };
|
|
9538
|
+
if (m = s.match(/^throw\s+([\w.$]+)$/)) return { kind: "fails", name: lastSeg(m[1]) };
|
|
9539
|
+
if (m = s.match(/^throw\s+([A-Z][\w.$]*)\s*\(([\s\S]*)\)$/)) return { kind: "fails", name: lastSeg(m[1]), detail: firstString(m[2]) };
|
|
9540
|
+
if ((m = s.match(/^error\(([\s\S]*)\)$/)) && language === "kotlin") return { kind: "fails", name: "IllegalStateException", detail: firstString(m[1]) };
|
|
9541
|
+
if (m = s.match(/^abort\(\s*(\d{3})\b/)) return { kind: "responds", name: m[1] };
|
|
9542
|
+
if (m = s.match(/^raise\s+([\w.]+)(?:\(([\s\S]*)\))?$/)) return { kind: "fails", name: lastSeg(m[1]), detail: m[2] ? firstString(m[2]) : null };
|
|
9543
|
+
if (language === "ruby") {
|
|
9544
|
+
if (m = s.match(/^raise\s+([A-Z][\w:]*)(?:\.new)?\s*(?:,\s*|\(\s*)?([\s\S]*?)\)?$/)) return { kind: "fails", name: lastSeg(m[1]), detail: firstString(m[2] || "") };
|
|
9545
|
+
if (m = s.match(/^(?:raise|fail)\s+(["'][\s\S]*)$/)) return { kind: "fails", name: "RuntimeError", detail: firstString(m[1]) };
|
|
9546
|
+
if (m = s.match(/^(?:head|halt)\s+(?::|")?(\w+)"?/)) return { kind: "responds", name: m[1] };
|
|
9547
|
+
}
|
|
9548
|
+
if (m = s.match(/^panic!?\(([\s\S]*)\)$/)) return { kind: "fails", name: "panic", detail: firstString(m[1]) };
|
|
9549
|
+
if (m = s.match(/^return\s+Err\(([\s\S]*)\)$/)) {
|
|
9550
|
+
const inner = m[1].trim();
|
|
9551
|
+
return { kind: "fails", name: firstString(inner) ? "error" : lastSeg(inner.replace(/\(.*$/s, "")), detail: firstString(inner) };
|
|
9552
|
+
}
|
|
9553
|
+
if (s === "return") return { kind: "stops" };
|
|
9554
|
+
if ((m = s.match(/^render\b.*\bstatus:\s*(?::|")?(\w+)/)) && language === "ruby") return { kind: "responds", name: m[1] };
|
|
9555
|
+
if (!(m = s.match(/^return\s+([\s\S]+)$/))) return null;
|
|
9556
|
+
const v = m[1].trim();
|
|
9557
|
+
if (language === "go") {
|
|
9558
|
+
const parts = splitTop(v, ",").map((x) => x.trim());
|
|
9559
|
+
const last = parts[parts.length - 1];
|
|
9560
|
+
if (last === "err" || /^fmt\.Errorf\([^)]*%w/.test(last)) return { kind: "passes-error" };
|
|
9561
|
+
if (m = last.match(/^(?:errors\.New|fmt\.Errorf)\(\s*"([^"]*)"/)) return { kind: "fails", name: "error", detail: m[1] };
|
|
9562
|
+
if (/^Err[A-Z]\w*$/.test(last)) return { kind: "fails", name: last };
|
|
9563
|
+
if (parts.length === 1 && last === "nil") return { kind: "nothing" };
|
|
9564
|
+
}
|
|
9565
|
+
if (/^(null|undefined|None|nil|void 0)$/.test(v)) return { kind: "nothing" };
|
|
9566
|
+
if ((m = v.match(/(?:\b(?:status|Status|StatusCode|HttpStatus|sendStatus)|\.code)\s*\(\s*(\d{3})\s*\)/)) || (m = v.match(/^\{\s*status\s*:\s*(\d{3})\b/))) return { kind: "responds", name: m[1] };
|
|
9567
|
+
if (m = v.match(/^(BadRequest|Unauthorized|Forbid|Forbidden|NotFound|Conflict|UnprocessableEntity)\s*\(/)) return { kind: "responds", name: m[1] };
|
|
9568
|
+
const fixed = toThunderOutcome(v);
|
|
9569
|
+
if (fixed) return { kind: "returns", name: fixed };
|
|
9570
|
+
return { kind: "returns-computed" };
|
|
9571
|
+
}
|
|
9572
|
+
function sayGuard(effect, condText) {
|
|
9573
|
+
const when = `if ${condText}`;
|
|
9574
|
+
switch (effect.kind) {
|
|
9575
|
+
case "fails":
|
|
9576
|
+
return `Fails with ${effect.name}${effect.detail ? ` ("${effect.detail}")` : ""} ${when}.`;
|
|
9577
|
+
case "responds":
|
|
9578
|
+
return `Responds ${effect.name} ${when}.`;
|
|
9579
|
+
case "nothing":
|
|
9580
|
+
return `Stops early and returns nothing ${when}.`;
|
|
9581
|
+
case "stops":
|
|
9582
|
+
return `Stops early ${when}.`;
|
|
9583
|
+
case "returns":
|
|
9584
|
+
return `Returns ${effect.name} early ${when}.`;
|
|
9585
|
+
default:
|
|
9586
|
+
return `Returns early ${when}.`;
|
|
9587
|
+
}
|
|
9588
|
+
}
|
|
9589
|
+
function makeGuard(cond, branch, language, inputs, line) {
|
|
9590
|
+
const stmts = splitTop(branch.trim().replace(/;\s*$/, ""), ";").map((x) => x.trim()).filter(Boolean);
|
|
9591
|
+
if (stmts.length !== 1 || /\n\s*\S[\s\S]*\n/.test(stmts[0]) && !/^(throw|raise|return)/.test(stmts[0])) return null;
|
|
9592
|
+
const effect = terminatorEffect(stmts[0], language);
|
|
9593
|
+
if (!effect) return null;
|
|
9594
|
+
if (effect.kind === "passes-error") return "skip";
|
|
9595
|
+
const when = toThunderCondition(cond, inputs);
|
|
9596
|
+
const code = cond.trim().replace(/\s+/g, " ");
|
|
9597
|
+
return { when, code, effect, line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${code}\``) };
|
|
9598
|
+
}
|
|
9599
|
+
function splitIf(text, language) {
|
|
9600
|
+
let rest2 = text.replace(/^if\b\s*/, "");
|
|
9601
|
+
let cond, after;
|
|
9602
|
+
if (language === "go" || language === "rust" || rest2[0] !== "(") {
|
|
9603
|
+
const b = findTopBrace(rest2);
|
|
9604
|
+
if (b < 0) return null;
|
|
9605
|
+
cond = rest2.slice(0, b).trim();
|
|
9606
|
+
after = rest2.slice(b);
|
|
9607
|
+
} else {
|
|
9608
|
+
const close = matchClose(rest2, 0);
|
|
9609
|
+
if (close < 0) return null;
|
|
9610
|
+
cond = rest2.slice(1, close);
|
|
9611
|
+
after = rest2.slice(close + 1).trimStart();
|
|
9612
|
+
}
|
|
9613
|
+
let branch, remaining;
|
|
9614
|
+
if (after[0] === "{") {
|
|
9615
|
+
const bc = matchClose(after, 0);
|
|
9616
|
+
if (bc < 0) return null;
|
|
9617
|
+
branch = after.slice(1, bc).trim();
|
|
9618
|
+
remaining = after.slice(bc + 1).trim();
|
|
9619
|
+
} else {
|
|
9620
|
+
const semi = topLevelIndex(after, ";");
|
|
9621
|
+
branch = (semi < 0 ? after : after.slice(0, semi)).trim();
|
|
9622
|
+
remaining = semi < 0 ? "" : after.slice(semi + 1).trim();
|
|
9623
|
+
}
|
|
9624
|
+
return { cond: cond.trim(), branch, remaining };
|
|
9625
|
+
}
|
|
9626
|
+
function patternCondition(pattern, subject, inputs, language) {
|
|
9627
|
+
const p = pattern.trim();
|
|
9628
|
+
let m;
|
|
9629
|
+
if (subject == null) return toThunderCondition(p, inputs);
|
|
9630
|
+
if (m = p.match(/^(-?\d+(?:\.\d+)?)\s*\.\.(=?)\s*(-?\d+(?:\.\d+)?)$/)) return `${subject} >= ${m[1]} and ${subject} ${m[2] ? "<=" : "<"} ${m[3]}`;
|
|
9631
|
+
if (m = p.match(/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/)) return `${subject} ${m[1]} ${m[2]}`;
|
|
9632
|
+
if ((m = p.match(/^not\s+(.+)$/)) && language === "csharp") {
|
|
9633
|
+
const v2 = toThunderOutcome(m[1]);
|
|
9634
|
+
return v2 ? `${subject} != ${/^[A-Za-z_]/.test(v2) && !/^(true|false)$/.test(v2) ? v2 : v2}` : null;
|
|
9635
|
+
}
|
|
9636
|
+
const parts = splitTop(p.replace(/\s+or\s+/g, "|"), language === "rust" || language === "csharp" || language === "python" ? "|" : ",").map((x) => x.trim()).filter(Boolean);
|
|
9637
|
+
if (parts.length > 1) {
|
|
9638
|
+
const each = parts.map((x) => patternCondition(x, subject, inputs, language));
|
|
9639
|
+
return each.every(Boolean) ? each.map((c) => /\s(and|or)\s/.test(c) ? `(${c})` : c).join(" or ") : null;
|
|
9640
|
+
}
|
|
9641
|
+
const v = valueLiteral(p);
|
|
9642
|
+
return v == null ? null : `${subject} == ${v}`;
|
|
9643
|
+
}
|
|
9644
|
+
function valueLiteral(text) {
|
|
9645
|
+
const s = text.trim();
|
|
9646
|
+
let m;
|
|
9647
|
+
if (/^(nil|null|None|undefined)$/.test(s)) return null;
|
|
9648
|
+
if (m = s.match(/^"([^"\\]*)"$|^'([^'\\]*)'$/)) return m[1] != null && /#\{|\$\{|\$[A-Za-z_]/.test(m[1]) ? null : JSON.stringify(m[1] ?? m[2]);
|
|
9649
|
+
if (/^-?\d+(\.\d+)?$/.test(s)) return s;
|
|
9650
|
+
if (/^(true|false|True|False)$/.test(s)) return s.toLowerCase();
|
|
9651
|
+
if (m = s.match(/^(?:[A-Za-z_]\w*(?:\.|::))*([A-Za-z_]\w*)$/)) return m[1];
|
|
9652
|
+
return null;
|
|
9653
|
+
}
|
|
9654
|
+
var rebind = (guard, name, subject) => guard.replace(new RegExp(`\\b${name}\\b`, "g"), subject);
|
|
9655
|
+
function switchArms(body, language, baseLine) {
|
|
9656
|
+
const arms = [];
|
|
9657
|
+
const lineOf2 = (idx) => baseLine + lineAt(body, idx) - 1;
|
|
9658
|
+
if (language === "rust" || language === "csharp-expr") {
|
|
9659
|
+
let i = 0;
|
|
9660
|
+
while (i < body.length) {
|
|
9661
|
+
while (i < body.length && /[\s,]/.test(body[i])) i++;
|
|
9662
|
+
if (i >= body.length) break;
|
|
9663
|
+
const arrow = body.indexOf("=>", i);
|
|
9664
|
+
if (arrow < 0) return null;
|
|
9665
|
+
const head = body.slice(i, arrow).trim();
|
|
9666
|
+
let j = arrow + 2;
|
|
9667
|
+
while (/\s/.test(body[j] || "")) j++;
|
|
9668
|
+
let value, end;
|
|
9669
|
+
if (body[j] === "{") {
|
|
9670
|
+
const c = matchClose(body, j);
|
|
9671
|
+
if (c < 0) return null;
|
|
9672
|
+
value = blockOnlyValue(body.slice(j + 1, c), language);
|
|
9673
|
+
end = c + 1;
|
|
9674
|
+
} else {
|
|
9675
|
+
const c = topLevelIndex(body, ",", j);
|
|
9676
|
+
end = c < 0 ? body.length : c;
|
|
9677
|
+
value = body.slice(j, end).trim();
|
|
9678
|
+
}
|
|
9679
|
+
const g = head.match(/^(.*?)\s+(?:if|when)\s+(.+)$/s);
|
|
9680
|
+
arms.push({ pattern: (g ? g[1] : head).trim(), guard: g ? g[2].trim() : null, value, line: lineOf2(i) });
|
|
9681
|
+
i = end + 1;
|
|
9682
|
+
}
|
|
9683
|
+
return arms;
|
|
9684
|
+
}
|
|
9685
|
+
const starts = [];
|
|
9686
|
+
const re = /(^|[\s;{}:])(case\b|default\b)/g;
|
|
9687
|
+
let m;
|
|
9688
|
+
while (m = re.exec(body)) {
|
|
9689
|
+
const at = m.index + m[1].length;
|
|
9690
|
+
if (depthAt(body, at) === 0) starts.push(at);
|
|
9691
|
+
}
|
|
9692
|
+
let pending = [];
|
|
9693
|
+
for (let k = 0; k < starts.length; k++) {
|
|
9694
|
+
const clause = body.slice(starts[k], starts[k + 1] ?? body.length).trim();
|
|
9695
|
+
const isDefault = clause.startsWith("default");
|
|
9696
|
+
const afterKw = clause.replace(/^(case|default)\b/, "");
|
|
9697
|
+
const arrowAt = topLevelIndex(afterKw, "-") >= 0 && /->/.test(afterKw) ? afterKw.indexOf("->") : -1;
|
|
9698
|
+
const colonAt = topLevelIndex(afterKw, ":");
|
|
9699
|
+
const useArrow = arrowAt >= 0 && (colonAt < 0 || arrowAt < colonAt);
|
|
9700
|
+
const cut = useArrow ? arrowAt : colonAt;
|
|
9701
|
+
if (cut < 0) return null;
|
|
9702
|
+
const label = afterKw.slice(0, cut).trim();
|
|
9703
|
+
let rest2 = afterKw.slice(cut + (useArrow ? 2 : 1)).trim();
|
|
9704
|
+
const g = label.match(/^(.*?)\s+when\s+(.+)$/s);
|
|
9705
|
+
const pattern = isDefault ? null : g ? g[1] : label;
|
|
9706
|
+
if (!useArrow && !rest2) {
|
|
9707
|
+
pending.push(pattern);
|
|
9708
|
+
continue;
|
|
9709
|
+
}
|
|
9710
|
+
let value;
|
|
9711
|
+
if (rest2.startsWith("{")) value = blockOnlyValue(rest2.slice(1, matchClose(rest2, 0)), language);
|
|
9712
|
+
else {
|
|
9713
|
+
rest2 = rest2.replace(/;?\s*break\s*;?\s*$/, "").replace(/;\s*$/, "").trim();
|
|
9714
|
+
value = useArrow ? rest2 : (rest2.match(/^return\s+([\s\S]+)$/) || [])[1] ?? null;
|
|
9715
|
+
if (value && /;/.test(value)) value = null;
|
|
9716
|
+
}
|
|
9717
|
+
const patterns = [...pending, pattern];
|
|
9718
|
+
pending = [];
|
|
9719
|
+
if (patterns.includes(null)) arms.push({ pattern: null, guard: null, value, line: lineOf2(starts[k]) });
|
|
9720
|
+
else arms.push({ pattern: patterns.join(language === "go" && patterns.length === 1 ? "" : ", ") || patterns[0], guard: g ? g[2].trim() : null, value, line: lineOf2(starts[k]) });
|
|
9721
|
+
}
|
|
9722
|
+
return arms;
|
|
9723
|
+
}
|
|
9724
|
+
function depthAt(s, idx) {
|
|
9725
|
+
let d = 0;
|
|
9726
|
+
for (let i = 0; i < idx; i++) {
|
|
9727
|
+
const c = s[i];
|
|
9728
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
9729
|
+
i = skipString(s, i);
|
|
9730
|
+
continue;
|
|
9731
|
+
}
|
|
9732
|
+
if ("({[".includes(c)) d++;
|
|
9733
|
+
else if (")}]".includes(c)) d--;
|
|
9734
|
+
}
|
|
9735
|
+
return d;
|
|
9736
|
+
}
|
|
9737
|
+
function blockOnlyValue(inner, language) {
|
|
9738
|
+
const t = inner.trim().replace(/;\s*$/, "");
|
|
9739
|
+
if (/;/.test(t)) return null;
|
|
9740
|
+
const m = t.match(/^return\s+([\s\S]+)$/);
|
|
9741
|
+
if (m) return m[1].trim();
|
|
9742
|
+
return language === "rust" || language === "csharp-expr" ? t : null;
|
|
9743
|
+
}
|
|
9744
|
+
function readSwitch(text, language, inputs, line) {
|
|
9745
|
+
let subjectText, body, kind = language;
|
|
9746
|
+
let m;
|
|
9747
|
+
const t = text.trim();
|
|
9748
|
+
if ((m = t.match(/^switch\s*\(([\s\S]*?)\)\s*\{/)) && language !== "go" && language !== "rust") {
|
|
9749
|
+
const open = t.indexOf("{", m[0].length - 1);
|
|
9750
|
+
subjectText = m[1];
|
|
9751
|
+
body = t.slice(open + 1, matchClose(t, open));
|
|
9752
|
+
} else if (language === "go" && (m = t.match(/^switch\b([^{]*)\{/))) {
|
|
9753
|
+
const open = t.indexOf("{");
|
|
9754
|
+
subjectText = m[1].trim() || null;
|
|
9755
|
+
body = t.slice(open + 1, matchClose(t, open));
|
|
9756
|
+
} else if (language === "rust" && (m = t.match(/^match\s+([^{]+?)\s*\{/))) {
|
|
9757
|
+
const open = t.indexOf("{", m[0].length - 1);
|
|
9758
|
+
subjectText = m[1];
|
|
9759
|
+
body = t.slice(open + 1, matchClose(t, open));
|
|
9760
|
+
} else if (language === "php" && (m = t.match(/^match\s*\(([\s\S]*?)\)\s*\{/))) {
|
|
9761
|
+
const open = t.indexOf("{", m[0].length - 1);
|
|
9762
|
+
subjectText = /^\s*true\s*$/.test(m[1]) ? null : m[1];
|
|
9763
|
+
body = t.slice(open + 1, matchClose(t, open));
|
|
9764
|
+
kind = "csharp-expr";
|
|
9765
|
+
} else if (language === "kotlin" && (m = t.match(/^when\s*(?:\(([\s\S]*?)\))?\s*\{/))) {
|
|
9766
|
+
const open = t.indexOf("{", m[0].length - 1);
|
|
9767
|
+
subjectText = m[1] ?? null;
|
|
9768
|
+
body = t.slice(open + 1, matchClose(t, open));
|
|
9769
|
+
kind = "kotlin-when";
|
|
9770
|
+
} else if (language === "csharp" && (m = t.match(/^([\w.]+)\s+switch\s*\{/))) {
|
|
9771
|
+
const open = t.indexOf("{");
|
|
9772
|
+
subjectText = m[1];
|
|
9773
|
+
body = t.slice(open + 1, matchClose(t, open));
|
|
9774
|
+
kind = "csharp-expr";
|
|
9775
|
+
} else return null;
|
|
9776
|
+
if (body == null) return null;
|
|
9777
|
+
const subject = subjectText == null ? null : toThunderCondition(subjectText, inputs);
|
|
9778
|
+
if (subjectText != null && (!subject || /\s/.test(subject))) return { unread: [{ line, text: t.split("\n")[0].slice(0, 120), reason: "This switch compares something other than an input or field." }] };
|
|
9779
|
+
const arms = kind === "kotlin-when" ? (kotlinWhenArms(body, line) || null)?.map((a) => a.pattern == null || subjectText == null ? a : { ...a, pattern: kotlinPattern(a.pattern) }) : switchArms(body, kind, line)?.map((a) => language === "php" && a.pattern === "default" ? { ...a, pattern: null } : a);
|
|
9780
|
+
if (!arms || !arms.length) return { unread: [{ line, text: t.split("\n")[0].slice(0, 120), reason: "This switch has a shape the reader does not recognize yet." }] };
|
|
9781
|
+
return armsToRules(arms, subject, inputs, language);
|
|
9782
|
+
}
|
|
9783
|
+
function armsToRules(arms, subject, inputs, language) {
|
|
9784
|
+
const rules = [];
|
|
9785
|
+
let otherwise = null;
|
|
9786
|
+
for (const a of arms) {
|
|
9787
|
+
const result = a.value == null ? null : toThunderOutcome(a.value);
|
|
9788
|
+
if (!result) return { unread: [{ line: a.line, text: (a.pattern ?? "default") + " => " + String(a.value ?? "...").slice(0, 60), reason: "This case does more than give a fixed answer, so the switch is not shown as rules." }] };
|
|
9789
|
+
const isDefault = a.pattern == null || a.pattern === "_" || language === "rust" && /^[a-z_]\w*$/.test(a.pattern) && !a.guard && !inputs.includes(a.pattern);
|
|
9790
|
+
if (isDefault && !a.guard) {
|
|
9791
|
+
otherwise = { result, line: a.line };
|
|
9792
|
+
break;
|
|
9793
|
+
}
|
|
9794
|
+
let when = isDefault ? null : patternCondition(a.pattern, subject, inputs, language);
|
|
9795
|
+
if (a.guard) {
|
|
9796
|
+
const binding = (a.pattern || "").match(/^([a-z_]\w*)$/);
|
|
9797
|
+
const g = toThunderCondition(binding && subject ? rebind(a.guard, binding[1], subject) : a.guard, inputs);
|
|
9798
|
+
if (!g) return { unread: [{ line: a.line, text: `${a.pattern} if ${a.guard}`, reason: "This case guard uses something besides comparisons and and/or/not." }] };
|
|
9799
|
+
when = when && !binding ? `(${when}) and (${g})` : g;
|
|
9800
|
+
}
|
|
9801
|
+
if (!when) return { unread: [{ line: a.line, text: String(a.pattern).slice(0, 80), reason: "This case pattern is not a value, range, or comparison the reader recognizes." }] };
|
|
9802
|
+
try {
|
|
9803
|
+
compileExpr(when, { inputs });
|
|
9804
|
+
} catch {
|
|
9805
|
+
return { unread: [{ line: a.line, text: String(a.pattern), reason: "This case pattern could not be read as a condition." }] };
|
|
9806
|
+
}
|
|
9807
|
+
rules.push({ when: simplifyExpr(when), result, line: a.line });
|
|
9808
|
+
}
|
|
9809
|
+
return { rules, otherwise };
|
|
9810
|
+
}
|
|
9811
|
+
function splitStatements(body, baseLine) {
|
|
9812
|
+
const src = stripCommentsKeepLayout(body);
|
|
9813
|
+
const out = [];
|
|
9814
|
+
let i = 0;
|
|
9815
|
+
while (i < src.length) {
|
|
9816
|
+
while (i < src.length && /[\s;]/.test(src[i])) i++;
|
|
9817
|
+
if (i >= src.length) break;
|
|
9818
|
+
const start = i;
|
|
9819
|
+
let depth = 0;
|
|
9820
|
+
for (; i < src.length; i++) {
|
|
9821
|
+
const c = src[i];
|
|
9822
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
9823
|
+
i = skipString(src, i);
|
|
9824
|
+
continue;
|
|
9825
|
+
}
|
|
9826
|
+
if (c === "(" || c === "[") depth++;
|
|
9827
|
+
else if (c === ")" || c === "]") depth--;
|
|
9828
|
+
else if (c === "{") {
|
|
9829
|
+
const close = matchClose(src, i);
|
|
9830
|
+
if (close < 0) {
|
|
9831
|
+
i = src.length;
|
|
9832
|
+
break;
|
|
9833
|
+
}
|
|
9834
|
+
i = close;
|
|
9835
|
+
if (depth === 0) {
|
|
9836
|
+
const rest2 = src.slice(i + 1).match(/^\s*else\b/);
|
|
9837
|
+
if (!rest2) {
|
|
9838
|
+
i++;
|
|
9839
|
+
break;
|
|
9840
|
+
}
|
|
9841
|
+
}
|
|
9842
|
+
} else if (c === ";" && depth === 0) {
|
|
9843
|
+
i++;
|
|
9844
|
+
break;
|
|
9845
|
+
}
|
|
9846
|
+
}
|
|
9847
|
+
const text = src.slice(start, i).trim();
|
|
9848
|
+
if (text) out.push({ text, line: baseLine + lineAt(src, start) - 1 });
|
|
9849
|
+
}
|
|
9850
|
+
return out;
|
|
9851
|
+
}
|
|
9852
|
+
var stripCommentsKeepLayout = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/(^|[^:])\/\/.*$/gm, "$1");
|
|
9853
|
+
function readBraceStatements(stmts, language, inputs) {
|
|
9854
|
+
const rules = [], unread = [], guards = [];
|
|
9855
|
+
let otherwise = null;
|
|
9856
|
+
const take = (cond, outcomeText, line) => {
|
|
9857
|
+
const when = cond == null ? null : toThunderCondition(cond, inputs);
|
|
9858
|
+
const result = toThunderOutcome(outcomeText);
|
|
9859
|
+
if (cond != null && !when) {
|
|
9860
|
+
unread.push({ line, text: `if ${cond}`, reason: "This condition uses something besides comparisons and and/or/not." });
|
|
9861
|
+
return false;
|
|
9862
|
+
}
|
|
9863
|
+
if (!result) {
|
|
9864
|
+
unread.push({ line, text: outcomeText.trim(), reason: "This answer is computed, not a fixed value." });
|
|
9865
|
+
return false;
|
|
9866
|
+
}
|
|
9867
|
+
if (when == null) otherwise = { result, line };
|
|
9868
|
+
else rules.push({ when, result, line });
|
|
9869
|
+
return true;
|
|
9870
|
+
};
|
|
9871
|
+
const blockValue = (block) => {
|
|
9872
|
+
const inner = block.trim().replace(/^\{|\}$/g, "").trim();
|
|
9873
|
+
const m = inner.match(/^return\s+([\s\S]+?);?$/) || (language === "rust" && !/;/.test(inner) ? [null, inner] : null);
|
|
9874
|
+
return m && !/\n\s*\S/.test(m[1].trim()) ? m[1].trim() : null;
|
|
9875
|
+
};
|
|
9876
|
+
for (const st of stmts) {
|
|
9877
|
+
const t = st.text;
|
|
9878
|
+
let m;
|
|
9879
|
+
if (/^if\b/.test(t)) {
|
|
9880
|
+
const head = splitIf(t, language);
|
|
9881
|
+
if (head && !/^else\b/.test(head.remaining)) {
|
|
9882
|
+
const single = head.branch.replace(/^return\s+/, "").replace(/;\s*$/, "");
|
|
9883
|
+
const looksLikeError = /^(Err[A-Z]\w*|\w*(Error|Exception))$/.test(lastSeg(single));
|
|
9884
|
+
const isFixedReturn = /^return\s/.test(head.branch) && toThunderOutcome(single) && !looksLikeError && (language !== "go" || !single.includes(","));
|
|
9885
|
+
if (!isFixedReturn) {
|
|
9886
|
+
const g = makeGuard(head.cond, head.branch, language, inputs, st.line);
|
|
9887
|
+
if (g === "skip") continue;
|
|
9888
|
+
if (g) {
|
|
9889
|
+
guards.push(g);
|
|
9890
|
+
continue;
|
|
9891
|
+
}
|
|
9892
|
+
}
|
|
9893
|
+
}
|
|
9894
|
+
let rest2 = t;
|
|
9895
|
+
let ok = true;
|
|
9896
|
+
while (rest2) {
|
|
9897
|
+
const head2 = rest2.match(/^(?:else\s+)?if\b\s*/);
|
|
9898
|
+
if (!head2) break;
|
|
9899
|
+
rest2 = rest2.slice(head2[0].length);
|
|
9900
|
+
let cond, after;
|
|
9901
|
+
if (rest2[0] === "(" && (language !== "go" && language !== "rust" || true)) {
|
|
9902
|
+
const close = matchClose(rest2, 0);
|
|
9903
|
+
const tail = rest2.slice(close + 1).trimStart();
|
|
9904
|
+
if (language === "go" || language === "rust") {
|
|
9905
|
+
const brace = findTopBrace(rest2);
|
|
9906
|
+
cond = rest2.slice(0, brace).trim();
|
|
9907
|
+
after = rest2.slice(brace);
|
|
9908
|
+
} else {
|
|
9909
|
+
cond = rest2.slice(1, close);
|
|
9910
|
+
after = tail;
|
|
9911
|
+
}
|
|
9912
|
+
} else {
|
|
9913
|
+
const brace = findTopBrace(rest2);
|
|
9914
|
+
if (brace < 0) {
|
|
9915
|
+
ok = false;
|
|
9916
|
+
break;
|
|
9917
|
+
}
|
|
9918
|
+
cond = rest2.slice(0, brace).trim();
|
|
9919
|
+
after = rest2.slice(brace);
|
|
9920
|
+
}
|
|
9921
|
+
let value, remaining;
|
|
9922
|
+
if (after[0] === "{") {
|
|
9923
|
+
const bc = matchClose(after, 0);
|
|
9924
|
+
value = blockValue(after.slice(0, bc + 1));
|
|
9925
|
+
remaining = after.slice(bc + 1).trim();
|
|
9926
|
+
} else {
|
|
9927
|
+
const semi = after.indexOf(";");
|
|
9928
|
+
const single = (semi < 0 ? after : after.slice(0, semi)).trim();
|
|
9929
|
+
value = single.startsWith("return ") ? single.slice(7) : null;
|
|
9930
|
+
remaining = (semi < 0 ? "" : after.slice(semi + 1)).trim();
|
|
9931
|
+
}
|
|
9932
|
+
if (value == null) {
|
|
9933
|
+
unread.push({ line: st.line, text: `if ${cond.trim()}`, reason: "This branch does more than choose an answer." });
|
|
9934
|
+
ok = false;
|
|
9935
|
+
break;
|
|
9936
|
+
}
|
|
9937
|
+
if (!take(cond, value, st.line)) {
|
|
9938
|
+
ok = false;
|
|
9939
|
+
break;
|
|
9940
|
+
}
|
|
9941
|
+
if (/^else\s+if\b/.test(remaining)) {
|
|
9942
|
+
rest2 = remaining;
|
|
9943
|
+
continue;
|
|
9944
|
+
}
|
|
9945
|
+
if (/^else\b/.test(remaining)) {
|
|
9946
|
+
const elseBody = remaining.replace(/^else\s*/, "");
|
|
9947
|
+
const v = elseBody.startsWith("{") ? blockValue(elseBody) : elseBody.startsWith("return ") ? elseBody.slice(7).replace(/;$/, "") : null;
|
|
9948
|
+
if (v == null) {
|
|
9949
|
+
unread.push({ line: st.line, text: "else", reason: "The fallback branch does more than choose an answer." });
|
|
9950
|
+
ok = false;
|
|
9951
|
+
} else take(null, v, st.line);
|
|
9952
|
+
}
|
|
9953
|
+
rest2 = "";
|
|
9954
|
+
}
|
|
9955
|
+
if (!ok) continue;
|
|
9956
|
+
continue;
|
|
9957
|
+
}
|
|
9958
|
+
if (language === "kotlin" && (m = t.match(/^(require|check|requireNotNull|checkNotNull)\s*\(/))) {
|
|
9959
|
+
const open = t.indexOf("(");
|
|
9960
|
+
const close = matchClose(t, open);
|
|
9961
|
+
const cond = t.slice(open + 1, close);
|
|
9962
|
+
const name = m[1].startsWith("require") ? "IllegalArgumentException" : "IllegalStateException";
|
|
9963
|
+
const detail = firstString(t.slice(close + 1).replace(/^\s*\{/, "")) || null;
|
|
9964
|
+
const when = /NotNull$/.test(m[1]) ? null : toThunderCondition(`!(${cond})`, inputs);
|
|
9965
|
+
const effect = { kind: "fails", name, detail };
|
|
9966
|
+
const condSaid = when ? sayCondition(when) : `\`${/NotNull$/.test(m[1]) ? `${cond.trim()} is null` : `not (${cond.trim()})`}\``;
|
|
9967
|
+
guards.push({ when, code: `${m[1]}(${cond.trim()})`, effect, line: st.line, readable: !!when, says: sayGuard(effect, condSaid) });
|
|
9968
|
+
continue;
|
|
9969
|
+
}
|
|
9970
|
+
if (language === "php" && (m = t.match(/^abort_(if|unless)\s*\(([\s\S]*)\)\s*;?$/))) {
|
|
9971
|
+
const args = splitTop(m[2], ",").map((x) => x.trim());
|
|
9972
|
+
if (args.length >= 2 && /^\d{3}$/.test(args[1])) {
|
|
9973
|
+
const cond = m[1] === "if" ? args[0] : `!(${args[0]})`;
|
|
9974
|
+
const when = toThunderCondition(cond, inputs);
|
|
9975
|
+
const effect = { kind: "responds", name: args[1] };
|
|
9976
|
+
guards.push({ when, code: `abort_${m[1]}(${args[0]})`, effect, line: st.line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${cond}\``) });
|
|
9977
|
+
continue;
|
|
9978
|
+
}
|
|
9979
|
+
}
|
|
9980
|
+
{
|
|
9981
|
+
const isLast = st === stmts[stmts.length - 1];
|
|
9982
|
+
const val = (t.match(/^return\s+([\s\S]+?);?$/) || [])[1];
|
|
9983
|
+
const candidate = /^(switch|match|when)\b/.test(t) && (language === "kotlin" || !/^when\b/.test(t)) ? t : val && /^(switch\b|match\b|when\b|[\w.]+\s+switch\s*\{)/.test(val) && (language === "kotlin" || !/^when\b/.test(val)) ? val : null;
|
|
9984
|
+
const sw = candidate && (candidate === t ? !(language === "rust" && !isLast && /^match/.test(t) && false) : true) ? readSwitch(candidate, language, inputs, st.line) : null;
|
|
9985
|
+
if (sw) {
|
|
9986
|
+
if (sw.unread) {
|
|
9987
|
+
unread.push(...sw.unread);
|
|
9988
|
+
continue;
|
|
9989
|
+
}
|
|
9990
|
+
rules.push(...sw.rules);
|
|
9991
|
+
if (sw.otherwise) otherwise = sw.otherwise;
|
|
9992
|
+
continue;
|
|
9993
|
+
}
|
|
9994
|
+
}
|
|
9995
|
+
const ret = t.match(/^return\s+([\s\S]+?);?$/) || (language === "rust" && st === stmts[stmts.length - 1] && !/;\s*$/.test(t) ? [null, t] : null);
|
|
9996
|
+
if (ret) {
|
|
9997
|
+
if (language === "kotlin" && readKotlinIf(ret[1], inputs, rules, unread, st.line, (o) => {
|
|
9998
|
+
otherwise = o;
|
|
9999
|
+
})) continue;
|
|
10000
|
+
if (readTernary(ret[1], inputs, rules, unread, st.line, (o) => {
|
|
10001
|
+
otherwise = o;
|
|
10002
|
+
})) continue;
|
|
10003
|
+
take(null, ret[1], st.line);
|
|
10004
|
+
continue;
|
|
10005
|
+
}
|
|
10006
|
+
unread.push({ line: st.line, text: t.split("\n")[0].slice(0, 120), reason: "This statement does work besides choosing an answer." });
|
|
10007
|
+
}
|
|
10008
|
+
return { rules, otherwise, unread, guards };
|
|
10009
|
+
}
|
|
10010
|
+
function findTopBrace(s) {
|
|
10011
|
+
let depth = 0;
|
|
10012
|
+
for (let i = 0; i < s.length; i++) {
|
|
10013
|
+
const c = s[i];
|
|
10014
|
+
if (c === '"' || c === "'") {
|
|
10015
|
+
i = skipString(s, i);
|
|
10016
|
+
continue;
|
|
10017
|
+
}
|
|
10018
|
+
if (c === "(" || c === "[") depth++;
|
|
10019
|
+
else if (c === ")" || c === "]") depth--;
|
|
10020
|
+
else if (c === "{" && depth === 0) return i;
|
|
10021
|
+
}
|
|
10022
|
+
return -1;
|
|
10023
|
+
}
|
|
10024
|
+
function readTernary(text, inputs, rules, unread, line, setOtherwise) {
|
|
10025
|
+
let s = text.trim().replace(/;$/, "");
|
|
10026
|
+
if (!/\?/.test(s)) return false;
|
|
10027
|
+
const local = [];
|
|
10028
|
+
while (true) {
|
|
10029
|
+
while (s.startsWith("(") && matchClose(s, 0) === s.length - 1) s = s.slice(1, -1).trim();
|
|
10030
|
+
const q = topLevelIndex(s, "?");
|
|
10031
|
+
if (q < 0) break;
|
|
10032
|
+
const c = topLevelIndex(s, ":", q + 1);
|
|
10033
|
+
if (c < 0) return false;
|
|
10034
|
+
const when = toThunderCondition(s.slice(0, q), inputs);
|
|
10035
|
+
const result = toThunderOutcome(s.slice(q + 1, c));
|
|
10036
|
+
if (!when || !result) {
|
|
10037
|
+
unread.push({ line, text: s.slice(0, 120), reason: "This choice uses a condition or answer that is not a fixed value." });
|
|
10038
|
+
return true;
|
|
10039
|
+
}
|
|
10040
|
+
local.push({ when, result, line });
|
|
10041
|
+
s = s.slice(c + 1).trim();
|
|
10042
|
+
}
|
|
10043
|
+
const fallback = toThunderOutcome(s);
|
|
10044
|
+
if (!fallback) {
|
|
10045
|
+
unread.push({ line, text: s.slice(0, 120), reason: "The fallback answer is computed, not a fixed value." });
|
|
10046
|
+
return true;
|
|
10047
|
+
}
|
|
10048
|
+
rules.push(...local);
|
|
10049
|
+
setOtherwise({ result: fallback, line });
|
|
10050
|
+
return true;
|
|
10051
|
+
}
|
|
10052
|
+
function topLevelIndex(s, ch, from = 0) {
|
|
10053
|
+
let depth = 0;
|
|
10054
|
+
for (let i = from; i < s.length; i++) {
|
|
10055
|
+
const c = s[i];
|
|
10056
|
+
if (c === '"' || c === "'") {
|
|
10057
|
+
i = skipString(s, i);
|
|
10058
|
+
continue;
|
|
10059
|
+
}
|
|
10060
|
+
if (c === "(" || c === "[") depth++;
|
|
10061
|
+
else if (c === ")" || c === "]") depth--;
|
|
10062
|
+
else if (c === ":" && s[i + 1] === ":") {
|
|
10063
|
+
i++;
|
|
10064
|
+
continue;
|
|
10065
|
+
} else if (c === ch && depth === 0) return i;
|
|
10066
|
+
}
|
|
10067
|
+
return -1;
|
|
10068
|
+
}
|
|
10069
|
+
function readPythonBody(body, inputs) {
|
|
10070
|
+
const rules = [], unread = [], guards = [];
|
|
10071
|
+
let otherwise = null;
|
|
10072
|
+
const base = body[0]?.indent ?? 0;
|
|
10073
|
+
for (let i = 0; i < body.length; i++) {
|
|
10074
|
+
const { text, line, indent } = body[i];
|
|
10075
|
+
if (indent !== base) continue;
|
|
10076
|
+
let m;
|
|
10077
|
+
if (m = text.match(/^match\s+(.+?):\s*$/)) {
|
|
10078
|
+
const subject = toThunderCondition(m[1], inputs);
|
|
10079
|
+
const block = [];
|
|
10080
|
+
for (let k = i + 1; k < body.length && body[k].indent > base; k++) block.push(body[k]);
|
|
10081
|
+
i += block.length;
|
|
10082
|
+
const caseIndent = block[0]?.indent;
|
|
10083
|
+
const arms = [];
|
|
10084
|
+
for (let k = 0; k < block.length; k++) {
|
|
10085
|
+
const c = block[k];
|
|
10086
|
+
if (c.indent !== caseIndent) continue;
|
|
10087
|
+
const cm = c.text.match(/^case\s+(.+?)(?:\s+if\s+(.+?))?:\s*(.*)$/);
|
|
10088
|
+
if (!cm) {
|
|
10089
|
+
arms.length = 0;
|
|
10090
|
+
break;
|
|
10091
|
+
}
|
|
10092
|
+
const inner = block.slice(k + 1).filter((x, n, arr) => x.indent > caseIndent && arr.slice(0, n).every((y) => y.indent > caseIndent));
|
|
10093
|
+
const valueLine = cm[3].trim() || (inner.length === 1 ? inner[0].text : "");
|
|
10094
|
+
const r = valueLine.match(/^return\s+(.+)$/);
|
|
10095
|
+
arms.push({ pattern: cm[1].trim(), guard: cm[2]?.trim() || null, value: r ? r[1] : null, line: c.line });
|
|
10096
|
+
}
|
|
10097
|
+
let ok = !!subject && !/\s/.test(subject) && arms.length > 0;
|
|
10098
|
+
const local = [];
|
|
10099
|
+
let fallback = null;
|
|
10100
|
+
for (const a of ok ? arms : []) {
|
|
10101
|
+
const result = a.value == null ? null : toThunderOutcome(a.value);
|
|
10102
|
+
if (!result) {
|
|
10103
|
+
ok = false;
|
|
10104
|
+
break;
|
|
10105
|
+
}
|
|
10106
|
+
if (a.pattern === "_" && !a.guard) {
|
|
10107
|
+
fallback = { result, line: a.line };
|
|
10108
|
+
break;
|
|
10109
|
+
}
|
|
10110
|
+
const binding = a.pattern.match(/^([a-z_]\w*)$/) && a.pattern !== "_" ? a.pattern : null;
|
|
10111
|
+
let when = a.pattern === "_" || binding ? null : patternCondition(a.pattern, subject, inputs, "python");
|
|
10112
|
+
if (a.guard) {
|
|
10113
|
+
const g = toThunderCondition(binding ? rebind(a.guard, binding, subject) : a.guard, inputs);
|
|
10114
|
+
if (!g) {
|
|
10115
|
+
ok = false;
|
|
10116
|
+
break;
|
|
10117
|
+
}
|
|
10118
|
+
when = when ? `(${when}) and (${g})` : g;
|
|
10119
|
+
}
|
|
10120
|
+
if (!when) {
|
|
10121
|
+
ok = false;
|
|
10122
|
+
break;
|
|
10123
|
+
}
|
|
10124
|
+
local.push({ when: simplifyExpr(when), result, line: a.line });
|
|
10125
|
+
}
|
|
10126
|
+
if (!ok) {
|
|
10127
|
+
unread.push({ line, text: text.slice(0, 120), reason: "This match has a case that does more than give a fixed answer." });
|
|
10128
|
+
continue;
|
|
10129
|
+
}
|
|
10130
|
+
rules.push(...local);
|
|
10131
|
+
if (fallback) otherwise = fallback;
|
|
10132
|
+
continue;
|
|
10133
|
+
}
|
|
10134
|
+
if (m = text.match(/^(?:if|elif)\s+(.+?):\s*(.*)$/)) {
|
|
10135
|
+
const inline = m[2].trim();
|
|
10136
|
+
const next = body[i + 1];
|
|
10137
|
+
const valueText = inline ? inline : next && next.indent > base ? next.text : "";
|
|
10138
|
+
const deeper = body.slice(i + 1).filter((b, k, arr) => b.indent > base && arr.slice(0, k).every((x) => x.indent > base));
|
|
10139
|
+
const r = valueText.match(/^return\s+(.+)$/);
|
|
10140
|
+
if (/^if\s/.test(text) && (inline || deeper.length === 1) && !body.slice(i + 1).find((b) => b.indent === base && /^(elif|else)\b/.test(b.text) && b.line > line && body.slice(i + 1, body.indexOf(b)).every((x) => x.indent > base)) && !(r && toThunderOutcome(r[1]))) {
|
|
10141
|
+
const g = makeGuard(m[1], valueText, "python", inputs, line);
|
|
10142
|
+
if (g && g !== "skip") {
|
|
10143
|
+
guards.push(g);
|
|
10144
|
+
continue;
|
|
10145
|
+
}
|
|
10146
|
+
}
|
|
10147
|
+
if (!r || !inline && deeper.length > 1) {
|
|
10148
|
+
unread.push({ line, text: text.slice(0, 120), reason: "This branch does more than choose an answer." });
|
|
10149
|
+
continue;
|
|
10150
|
+
}
|
|
10151
|
+
const when = toThunderCondition(m[1], inputs), result = toThunderOutcome(r[1]);
|
|
10152
|
+
if (!when) {
|
|
10153
|
+
unread.push({ line, text: `if ${m[1]}`, reason: "This condition uses something besides comparisons and and/or/not." });
|
|
10154
|
+
continue;
|
|
10155
|
+
}
|
|
10156
|
+
if (!result) {
|
|
10157
|
+
unread.push({ line, text: r[1], reason: "This answer is computed, not a fixed value." });
|
|
10158
|
+
continue;
|
|
10159
|
+
}
|
|
10160
|
+
rules.push({ when, result, line });
|
|
10161
|
+
continue;
|
|
10162
|
+
}
|
|
10163
|
+
if (m = text.match(/^else:\s*(.*)$/)) {
|
|
10164
|
+
const v = (m[1].trim() || body[i + 1]?.text || "").match(/^return\s+(.+)$/);
|
|
10165
|
+
const result = v && toThunderOutcome(v[1]);
|
|
10166
|
+
if (result) otherwise = { result, line };
|
|
10167
|
+
else unread.push({ line, text: "else", reason: "The fallback branch does more than choose an answer." });
|
|
10168
|
+
continue;
|
|
10169
|
+
}
|
|
10170
|
+
if (m = text.match(/^return\s+(.+)$/)) {
|
|
10171
|
+
const tern = m[1].match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/);
|
|
10172
|
+
if (tern) {
|
|
10173
|
+
const when = toThunderCondition(tern[2], inputs), a = toThunderOutcome(tern[1]), b = toThunderOutcome(tern[3]);
|
|
10174
|
+
if (when && a && b) {
|
|
10175
|
+
rules.push({ when, result: a, line });
|
|
10176
|
+
otherwise = { result: b, line };
|
|
10177
|
+
} else unread.push({ line, text: m[1].slice(0, 120), reason: "This choice uses a condition or answer that is not a fixed value." });
|
|
10178
|
+
continue;
|
|
10179
|
+
}
|
|
10180
|
+
const result = toThunderOutcome(m[1]);
|
|
10181
|
+
if (result) otherwise = { result, line };
|
|
10182
|
+
else unread.push({ line, text: m[1].slice(0, 120), reason: "This answer is computed, not a fixed value." });
|
|
10183
|
+
continue;
|
|
10184
|
+
}
|
|
10185
|
+
if (/^("""|''')/.test(text)) continue;
|
|
10186
|
+
unread.push({ line, text: text.slice(0, 120), reason: "This statement does work besides choosing an answer." });
|
|
10187
|
+
}
|
|
10188
|
+
return { rules, otherwise, unread, guards };
|
|
10189
|
+
}
|
|
10190
|
+
var RB_OPENER = /^(if|unless|while|until|case|begin|for|def|class|module)\b/;
|
|
10191
|
+
var rbCodeOnly = (l) => l.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""').replace(/(^|\s)#.*$/, "$1");
|
|
10192
|
+
function rbNoComment(l) {
|
|
10193
|
+
for (let i = 0; i < l.length; i++) {
|
|
10194
|
+
const c = l[i];
|
|
10195
|
+
if (c === '"' || c === "'") {
|
|
10196
|
+
i = skipString(l, i);
|
|
10197
|
+
continue;
|
|
10198
|
+
}
|
|
10199
|
+
if (c === "#" && l[i + 1] !== "{" && (i === 0 || /\s/.test(l[i - 1]))) return l.slice(0, i);
|
|
10200
|
+
}
|
|
10201
|
+
return l;
|
|
10202
|
+
}
|
|
10203
|
+
function rbDelta(raw) {
|
|
10204
|
+
const l = rbCodeOnly(raw).trim();
|
|
10205
|
+
if (!l) return 0;
|
|
10206
|
+
let d = 0;
|
|
10207
|
+
if (RB_OPENER.test(l) && !/^def\s+[\w.?!]+(\([^)]*\))?\s*=/.test(l)) d++;
|
|
10208
|
+
if (/\bdo\s*(\|[^|]*\|)?\s*$/.test(l)) d++;
|
|
10209
|
+
if (/[=(,]\s*(if|unless|case|begin)\b/.test(l) && !RB_OPENER.test(l)) d++;
|
|
10210
|
+
d -= (l.match(/(^|[^.\w])end\b(?![?!:])/g) || []).length;
|
|
10211
|
+
return d;
|
|
10212
|
+
}
|
|
10213
|
+
function findRubyFunctions(src) {
|
|
10214
|
+
const lines = src.split("\n");
|
|
10215
|
+
const fns = [];
|
|
10216
|
+
const collect = (from, headIndent) => {
|
|
10217
|
+
const body = [];
|
|
10218
|
+
let depth = 0;
|
|
10219
|
+
for (let j = from; j < lines.length; j++) {
|
|
10220
|
+
const t = lines[j];
|
|
10221
|
+
const code = rbCodeOnly(t).trim();
|
|
10222
|
+
if (!code) continue;
|
|
10223
|
+
if (depth === 0 && /^end\b/.test(code)) return body;
|
|
10224
|
+
body.push({ text: t.trim(), line: j + 1, depth });
|
|
10225
|
+
depth += rbDelta(t);
|
|
10226
|
+
if (depth < 0) return body;
|
|
10227
|
+
}
|
|
10228
|
+
return body;
|
|
10229
|
+
};
|
|
10230
|
+
lines.forEach((l, i) => {
|
|
10231
|
+
let m;
|
|
10232
|
+
if (m = l.match(/^(\s*)def\s+(?:self\.)?([\w]+[?!=]?)\s*(?:\((.*?)\)|\s+([^=#][^#]*?))?\s*(=\s*(.+))?\s*$/)) {
|
|
10233
|
+
const params = parseParams2(m[3] ?? m[4] ?? "", "ruby");
|
|
10234
|
+
const body = m[5] ? [{ text: m[6].trim(), line: i + 1, depth: 0 }] : collect(i + 1, m[1].length);
|
|
10235
|
+
fns.push({ name: m[2], line: i + 1, params, returns: null, rbBody: body });
|
|
10236
|
+
return;
|
|
10237
|
+
}
|
|
10238
|
+
if (m = l.match(/^\s*(get|post|put|patch|delete)\s+['"]([^'"]+)['"]\s+do\b/)) {
|
|
10239
|
+
const method = m[1].toUpperCase();
|
|
10240
|
+
fns.push({ name: `${method} ${m[2]}`, line: i + 1, params: [], returns: null, rbBody: collect(i + 1), route: { method, path: m[2] } });
|
|
10241
|
+
}
|
|
10242
|
+
});
|
|
10243
|
+
return fns;
|
|
10244
|
+
}
|
|
10245
|
+
var RB_PREDICATE_NOT_FIELD = /^(nil|empty|zero|blank|present|any|none|all|include|key|is_a|kind_of|respond_to|start_with|end_with|between|positive|negative|even|odd)$/;
|
|
10246
|
+
function rbExpr(text) {
|
|
10247
|
+
let bad = false;
|
|
10248
|
+
const bare = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
|
|
10249
|
+
if (/===/.test(bare) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare.replace(/<=>/g, "")) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare)) return null;
|
|
10250
|
+
const out = mapCode(String(text), (code) => code.replace(/@(?=[A-Za-z_])/g, "").replace(/(^|[\s(,=!<>[])::?([A-Za-z_]\w*)\b(?!:)/g, (all, pre, name) => all.includes("::") ? all : `${pre}"${name}"`).replace(/\.(\w+)\?/g, (all, name) => {
|
|
10251
|
+
if (RB_PREDICATE_NOT_FIELD.test(name)) bad = true;
|
|
10252
|
+
return `.${name}`;
|
|
10253
|
+
}).replace(/\bunless\b/g, "if not"));
|
|
10254
|
+
return bad ? null : out;
|
|
10255
|
+
}
|
|
10256
|
+
var rbCond = (text, inputs, negate = false) => {
|
|
10257
|
+
const e = rbExpr(text);
|
|
10258
|
+
return e == null ? null : toThunderCondition(negate ? `!(${e})` : e, inputs);
|
|
10259
|
+
};
|
|
10260
|
+
var rbOutcome = (text) => {
|
|
10261
|
+
const e = rbExpr(String(text).replace(/^return\s+/, ""));
|
|
10262
|
+
return e == null ? null : toThunderOutcome(e);
|
|
10263
|
+
};
|
|
10264
|
+
function rbRange(p) {
|
|
10265
|
+
return p.split(/,(?![^(]*\))/).map((x) => x.trim().replace(
|
|
10266
|
+
/^\(?(-?\d+(?:\.\d+)?)\s*(\.\.\.?)\s*(-?\d+(?:\.\d+)?)\)?$/,
|
|
10267
|
+
(_, a, dots, b) => dots === "..." ? `${a}..${b}` : `${a}..=${b}`
|
|
10268
|
+
)).join(", ");
|
|
10269
|
+
}
|
|
10270
|
+
function readRubyBody(body, inputs) {
|
|
10271
|
+
const rules = [], unread = [], guards = [];
|
|
10272
|
+
let otherwise = null;
|
|
10273
|
+
let top = body.map((b, k) => ({ ...b, k })).filter((b) => b.depth === 0);
|
|
10274
|
+
const rescueAt = top.findIndex((b) => /^(rescue|ensure)\b/.test(rbNoComment(b.text).trim()));
|
|
10275
|
+
if (rescueAt >= 0) {
|
|
10276
|
+
unread.push({ line: top[rescueAt].line, text: rbNoComment(top[rescueAt].text).trim().slice(0, 120), reason: "Error handling (rescue) is not read as rules." });
|
|
10277
|
+
top = top.slice(0, rescueAt);
|
|
10278
|
+
}
|
|
10279
|
+
const blockOf = (start) => {
|
|
10280
|
+
const out = [];
|
|
10281
|
+
for (let k = start + 1; k < body.length && body[k].depth > 0; k++) if (!(body[k].depth === 1 && /^end\b/.test(rbNoComment(body[k].text).trim()))) out.push(body[k]);
|
|
10282
|
+
return out;
|
|
10283
|
+
};
|
|
10284
|
+
const sole = (lines) => lines.length === 1 ? lines[0].text : null;
|
|
10285
|
+
top.forEach((st, n) => {
|
|
10286
|
+
const t = rbNoComment(st.text).trim();
|
|
10287
|
+
const isLast = n === top.length - 1;
|
|
10288
|
+
let m;
|
|
10289
|
+
if (m = t.match(/^(return\b.*?|raise\b.*?|fail\b.*?|head\b.*?|halt\b.*?|render\b.*?)\s+(if|unless)\s+(.+)$/)) {
|
|
10290
|
+
const when = rbCond(m[3], inputs, m[2] === "unless");
|
|
10291
|
+
const stmt = m[1].trim();
|
|
10292
|
+
const fixed = /^return\s+\S/.test(stmt) ? rbOutcome(stmt) : null;
|
|
10293
|
+
if (fixed) {
|
|
10294
|
+
if (!when) unread.push({ line: st.line, text: t.slice(0, 120), reason: "This condition uses something besides comparisons and and/or/not." });
|
|
10295
|
+
else rules.push({ when, result: fixed, line: st.line });
|
|
10296
|
+
return;
|
|
10297
|
+
}
|
|
10298
|
+
const effect = terminatorEffect(rbExpr(stmt) ?? stmt, "ruby");
|
|
10299
|
+
if (effect) {
|
|
10300
|
+
const code = (m[2] === "unless" ? "unless " : "") + m[3].trim();
|
|
10301
|
+
guards.push({ when, code, effect, line: st.line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${code}\``) });
|
|
10302
|
+
return;
|
|
10303
|
+
}
|
|
10304
|
+
}
|
|
10305
|
+
if (m = t.match(/^(if|unless)\s+(.+?)(?:\s+then)?$/)) {
|
|
10306
|
+
const block = blockOf(st.k);
|
|
10307
|
+
const parts = [];
|
|
10308
|
+
let cur = { cond: m[2], negate: m[1] === "unless", lines: [], line: st.line };
|
|
10309
|
+
for (const b of block) {
|
|
10310
|
+
const bt = rbNoComment(b.text).trim();
|
|
10311
|
+
let e;
|
|
10312
|
+
if (b.depth === 1 && (e = bt.match(/^elsif\s+(.+?)(?:\s+then)?$/))) {
|
|
10313
|
+
parts.push(cur);
|
|
10314
|
+
cur = { cond: e[1], negate: false, lines: [], line: b.line };
|
|
10315
|
+
continue;
|
|
10316
|
+
}
|
|
10317
|
+
if (b.depth === 1 && /^else$/.test(bt)) {
|
|
10318
|
+
parts.push(cur);
|
|
10319
|
+
cur = { cond: null, lines: [], line: b.line };
|
|
10320
|
+
continue;
|
|
10321
|
+
}
|
|
10322
|
+
cur.lines.push({ ...b, text: bt });
|
|
10323
|
+
}
|
|
10324
|
+
parts.push(cur);
|
|
10325
|
+
const hasElse = parts.some((p) => p.cond == null);
|
|
10326
|
+
if (parts.length === 1 && !hasElse) {
|
|
10327
|
+
const only = sole(parts[0].lines);
|
|
10328
|
+
const fixed = only && /^return\s/.test(only) ? rbOutcome(only) : null;
|
|
10329
|
+
if (only && !fixed) {
|
|
10330
|
+
const effect = terminatorEffect(rbExpr(only) ?? only, "ruby");
|
|
10331
|
+
if (effect && effect.kind !== "returns-computed") {
|
|
10332
|
+
const when = rbCond(parts[0].cond, inputs, parts[0].negate);
|
|
10333
|
+
const code = (parts[0].negate ? "unless " : "") + parts[0].cond;
|
|
10334
|
+
guards.push({ when, code, effect, line: st.line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${code}\``) });
|
|
10335
|
+
return;
|
|
10336
|
+
}
|
|
10337
|
+
}
|
|
10338
|
+
}
|
|
10339
|
+
const local = [];
|
|
10340
|
+
let fallback = null;
|
|
10341
|
+
for (const p of parts) {
|
|
10342
|
+
const v = sole(p.lines);
|
|
10343
|
+
const valueText = v && (/^return\s/.test(v) || isLast) ? v : null;
|
|
10344
|
+
const result = valueText ? rbOutcome(valueText) : null;
|
|
10345
|
+
if (!result) {
|
|
10346
|
+
unread.push({ line: p.line, text: p.cond ? `${p.negate ? "unless" : "if"} ${p.cond}` : "else", reason: "This branch does more than choose an answer." });
|
|
10347
|
+
return;
|
|
10348
|
+
}
|
|
10349
|
+
if (p.cond == null) {
|
|
10350
|
+
fallback = { result, line: p.line };
|
|
10351
|
+
continue;
|
|
10352
|
+
}
|
|
10353
|
+
const when = rbCond(p.cond, inputs, p.negate);
|
|
10354
|
+
if (!when) {
|
|
10355
|
+
unread.push({ line: p.line, text: `if ${p.cond}`, reason: "This condition uses something besides comparisons and and/or/not." });
|
|
10356
|
+
return;
|
|
10357
|
+
}
|
|
10358
|
+
local.push({ when, result, line: p.line });
|
|
10359
|
+
}
|
|
10360
|
+
rules.push(...local);
|
|
10361
|
+
if (fallback) otherwise = fallback;
|
|
10362
|
+
return;
|
|
10363
|
+
}
|
|
10364
|
+
if (m = t.match(/^(?:return\s+)?case(?:\s+(.+))?$/)) {
|
|
10365
|
+
const subject = m[1] ? rbCond(m[1], inputs) : null;
|
|
10366
|
+
if (m[1] && (!subject || /\s/.test(subject))) {
|
|
10367
|
+
unread.push({ line: st.line, text: t.slice(0, 120), reason: "This case compares something other than an input or field." });
|
|
10368
|
+
return;
|
|
10369
|
+
}
|
|
10370
|
+
const block = blockOf(st.k);
|
|
10371
|
+
const arms = [];
|
|
10372
|
+
let cur = null;
|
|
10373
|
+
for (const b of block) {
|
|
10374
|
+
const bt = rbNoComment(b.text).trim();
|
|
10375
|
+
let w;
|
|
10376
|
+
if (b.depth === 1 && (w = bt.match(/^when\s+(.+?)(?:\s+then\s+(.+))?$/))) {
|
|
10377
|
+
cur = { pattern: w[1], value: w[2] ?? null, lines: [], line: b.line };
|
|
10378
|
+
arms.push(cur);
|
|
10379
|
+
continue;
|
|
10380
|
+
}
|
|
10381
|
+
if (b.depth === 1 && (w = bt.match(/^else(?:\s+(.+))?$/))) {
|
|
10382
|
+
cur = { pattern: null, value: w[1] ?? null, lines: [], line: b.line };
|
|
10383
|
+
arms.push(cur);
|
|
10384
|
+
continue;
|
|
10385
|
+
}
|
|
10386
|
+
if (cur) cur.lines.push(bt);
|
|
10387
|
+
}
|
|
10388
|
+
const answerable = isLast || /^return\s/.test(t);
|
|
10389
|
+
const ready = arms.map((a) => {
|
|
10390
|
+
const v = a.value ?? (a.lines.length === 1 ? a.lines[0] : null);
|
|
10391
|
+
const ok = v && (answerable || /^return\s/.test(v));
|
|
10392
|
+
const conv = ok ? rbExpr(v.replace(/^return\s+/, "")) : null;
|
|
10393
|
+
const typeCheck = m[1] && a.pattern != null && a.pattern.split(",").some((x) => /^[A-Z][\w:]*$/.test(x.trim()) && !/^[A-Z][A-Z0-9_]*$/.test(x.trim().split("::").pop()));
|
|
10394
|
+
const pattern = a.pattern == null ? null : typeCheck ? null : m[1] ? rbExpr(rbRange(a.pattern)) : rbExpr(a.pattern);
|
|
10395
|
+
return { pattern: a.pattern != null && pattern == null ? "\0" : pattern, guard: null, value: conv, line: a.line };
|
|
10396
|
+
});
|
|
10397
|
+
const sw = arms.length ? armsToRules(ready, subject, inputs, "ruby") : { unread: [{ line: st.line, text: t, reason: "This case has no when branches the reader recognizes." }] };
|
|
10398
|
+
if (sw.unread) {
|
|
10399
|
+
unread.push(...sw.unread);
|
|
10400
|
+
return;
|
|
10401
|
+
}
|
|
10402
|
+
rules.push(...sw.rules);
|
|
10403
|
+
if (sw.otherwise) otherwise = sw.otherwise;
|
|
10404
|
+
return;
|
|
10405
|
+
}
|
|
10406
|
+
if (/^return\s/.test(t) || isLast) {
|
|
10407
|
+
const v = t.replace(/^return\s+/, "");
|
|
10408
|
+
const e = rbExpr(v);
|
|
10409
|
+
if (e && readTernary(e, inputs, rules, unread, st.line, (o) => {
|
|
10410
|
+
otherwise = o;
|
|
10411
|
+
})) return;
|
|
10412
|
+
const result = rbOutcome(v);
|
|
10413
|
+
if (result) {
|
|
10414
|
+
otherwise = { result, line: st.line };
|
|
10415
|
+
return;
|
|
10416
|
+
}
|
|
10417
|
+
unread.push({ line: st.line, text: t.slice(0, 120), reason: "This answer is computed, not a fixed value." });
|
|
10418
|
+
return;
|
|
10419
|
+
}
|
|
10420
|
+
unread.push({ line: st.line, text: t.slice(0, 120), reason: "This statement does work besides choosing an answer." });
|
|
10421
|
+
});
|
|
10422
|
+
return { rules, otherwise, unread, guards };
|
|
10423
|
+
}
|
|
10424
|
+
var OP_WORDS = { ">=": "is at least", ">": "is more than", "<=": "is at most", "<": "is less than", "==": "is", "!=": "is not" };
|
|
10425
|
+
var NOT_OP_WORDS = { ">=": "is less than", ">": "is at most", "<=": "is more than", "<": "is at least", "==": "is not", "!=": "is" };
|
|
10426
|
+
function sayCondition(cond) {
|
|
10427
|
+
return cond.replace(/\bnot\s+([A-Za-z_][\w.]*)\s*(>=|<=|==|!=|>|<)\s*("[^"]*"|-?[\w.]+)/g, (_, a, op, b) => `${a} ${NOT_OP_WORDS[op]} ${b}`).replace(/\s*(>=|<=|==|!=|>|<)\s*/g, (_, op) => ` ${OP_WORDS[op]} `).replace(/\bnot\s+/g, "not ").replace(/\s+/g, " ").trim();
|
|
10428
|
+
}
|
|
10429
|
+
function sayDecision(rules, otherwise) {
|
|
10430
|
+
const parts = rules.map((r, i) => `${i === 0 ? "If" : "Otherwise, if"} ${sayCondition(r.when)}, the answer is ${r.result}.`);
|
|
10431
|
+
if (otherwise) parts.push(rules.length ? `Otherwise, the answer is ${otherwise.result}.` : `The answer is always ${otherwise.result}.`);
|
|
10432
|
+
return parts.join(" ");
|
|
10433
|
+
}
|
|
10434
|
+
function decisionSource(name, inputs, rules, otherwise) {
|
|
10435
|
+
const L = [`decision ${name}`, " inputs"];
|
|
10436
|
+
for (const p of inputs) L.push(` ${p.name}${["number", "boolean", "string"].includes(p.type) ? `: ${p.type}` : ""}`);
|
|
10437
|
+
rules.forEach((r, i) => L.push(` rule rule_${i + 1}`, ` when ${r.when}`, ` return ${r.result}`));
|
|
10438
|
+
if (otherwise) L.push(" default", ` return ${otherwise.result}`);
|
|
10439
|
+
return L.join("\n");
|
|
10440
|
+
}
|
|
10441
|
+
function readCode(source, { language, file = "" } = {}) {
|
|
10442
|
+
const src = String(source ?? "");
|
|
10443
|
+
if (src.length > 4e5) throw new Error("Source is larger than 400 KB. Read one file or module at a time.");
|
|
10444
|
+
const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, "typescript").replace(/^js$/, "javascript").replace(/^py$/, "python").replace(/^(cs|c#)$/, "csharp").replace(/^rs$/, "rust").replace(/^golang$/, "go").replace(/^kts?$/, "kotlin").replace(/^rb$/, "ruby");
|
|
10445
|
+
if (!READ_LANGUAGES.includes(lang)) throw new Error(`Reading rules supports ${READ_LANGUAGES.join(", ")}. Got "${lang}".`);
|
|
10446
|
+
READING_RUST = lang === "rust";
|
|
10447
|
+
const code = lang === "php" ? normalizePhp(src) : src;
|
|
10448
|
+
const items = [];
|
|
10449
|
+
for (const fn of findFunctions(code, lang)) {
|
|
10450
|
+
const inputs = fn.params;
|
|
10451
|
+
const names = inputs.map((p) => p.name);
|
|
10452
|
+
const read = lang === "python" ? readPythonBody(fn.pyBody, names) : lang === "ruby" ? readRubyBody(fn.rbBody, names) : readBraceStatements(splitStatements(lang === "kotlin" ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), lang, names);
|
|
10453
|
+
const isDecision = read.rules.length > 0 && !!read.otherwise;
|
|
10454
|
+
const guards = read.guards || [];
|
|
10455
|
+
if (!isDecision) {
|
|
10456
|
+
for (const r of read.rules) guards.push({ when: r.when, code: r.when, effect: { kind: "returns", name: r.result }, line: r.line, readable: true, says: sayGuard({ kind: "returns", name: r.result }, sayCondition(r.when)) });
|
|
10457
|
+
guards.sort((a, b) => a.line - b.line);
|
|
10458
|
+
}
|
|
10459
|
+
const guardNote = guards.length ? ` It checks ${guards.length} condition${guards.length === 1 ? "" : "s"} first: ${guards.map((g) => g.says.replace(/\.$/, "")).join("; ")}.` : "";
|
|
10460
|
+
const base = {
|
|
10461
|
+
id: `${fn.name}:${fn.line}`,
|
|
10462
|
+
name: fn.name,
|
|
10463
|
+
line: fn.line,
|
|
10464
|
+
inputs,
|
|
10465
|
+
returns: simpleType(fn.returns),
|
|
10466
|
+
...fn.route ? { route: fn.route } : {},
|
|
10467
|
+
provenance: "inferred-from-code"
|
|
10468
|
+
};
|
|
10469
|
+
if (isDecision) {
|
|
10470
|
+
items.push({
|
|
10471
|
+
...base,
|
|
10472
|
+
kind: "decision",
|
|
10473
|
+
status: read.unread.length ? "partial" : "read",
|
|
10474
|
+
rules: read.rules.map((r) => ({ ...r, says: sayCondition(r.when) })),
|
|
10475
|
+
otherwise: read.otherwise,
|
|
10476
|
+
says: (fn.route ? `Handles ${fn.route.method} ${fn.route.path}. ` : "") + sayDecision(read.rules, read.otherwise) + guardNote,
|
|
10477
|
+
guards,
|
|
10478
|
+
thunder: decisionSource(fn.name, inputs, read.rules, read.otherwise),
|
|
10479
|
+
unread: read.unread
|
|
10480
|
+
});
|
|
10481
|
+
} else {
|
|
10482
|
+
items.push({
|
|
10483
|
+
...base,
|
|
10484
|
+
kind: "function",
|
|
10485
|
+
status: "signature-only",
|
|
10486
|
+
says: fn.route ? `Handles ${fn.route.method} ${fn.route.path || "(this controller's path)"}.${guardNote}` : `${fn.name} takes ${inputs.length ? inputs.map((p) => p.type && !/[<>\[\]]/.test(p.type) ? `${p.name} (${p.type})` : p.name).join(", ") : "no inputs"}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ""}. ${guards.length ? "" : " Its body does more than choose between fixed answers, so no rules are shown."}${guardNote}`,
|
|
10487
|
+
guards,
|
|
10488
|
+
unread: read.unread
|
|
10489
|
+
});
|
|
10490
|
+
}
|
|
10491
|
+
}
|
|
10492
|
+
const facts = extractFacts(src, lang, file || void 0);
|
|
10493
|
+
for (const e of facts?.errors || []) items.push({ id: `error:${e.name}:${e.line}`, kind: "error", name: e.name, line: e.line, status: "read", says: /\s/.test(e.name) ? `Can fail with the error "${e.name}".` : `Raises ${e.name}.`, provenance: "inferred-from-code" });
|
|
10494
|
+
for (const t of facts?.tests || []) items.push({ id: `test:${t.name}:${t.line}`, kind: "test", name: t.name, line: t.line, status: "read", says: `A test named "${t.name}".`, provenance: "inferred-from-code" });
|
|
10495
|
+
items.sort((a, b) => a.line - b.line);
|
|
10496
|
+
const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
10497
|
+
for (const it of items) {
|
|
10498
|
+
counts[it.kind]++;
|
|
10499
|
+
if (it.status === "partial") counts.partial++;
|
|
10500
|
+
if (it.guards?.length) counts.guarded++;
|
|
10501
|
+
if (it.route) counts.route++;
|
|
10502
|
+
}
|
|
10503
|
+
return {
|
|
10504
|
+
schema: READ_SCHEMA,
|
|
10505
|
+
language: lang,
|
|
10506
|
+
detected: !language,
|
|
10507
|
+
items,
|
|
10508
|
+
counts,
|
|
10509
|
+
limitations: [
|
|
10510
|
+
"Inferred from code by pattern, not by running it. Confirm a reading before relying on it.",
|
|
10511
|
+
"Rules are shown only for functions that choose between fixed answers; other logic is listed as not read."
|
|
10512
|
+
]
|
|
10513
|
+
};
|
|
10514
|
+
}
|
|
10515
|
+
function searchReading(reading, { query = "", kinds = [], status = [] } = {}) {
|
|
10516
|
+
const q = String(query).trim().toLowerCase();
|
|
10517
|
+
const terms = q ? q.split(/\s+/) : [];
|
|
10518
|
+
return reading.items.filter((it) => {
|
|
10519
|
+
if (kinds.length && !kinds.includes(it.kind) && !(kinds.includes("guard") && it.guards?.length) && !(kinds.includes("route") && it.route)) return false;
|
|
10520
|
+
if (status.length && !status.includes(it.status)) return false;
|
|
10521
|
+
if (!terms.length) return true;
|
|
10522
|
+
const hay = [it.name, it.route && `${it.route.method} ${it.route.path}`, it.says, it.thunder, ...(it.guards || []).flatMap((g) => [g.code, g.effect.name, g.says]), ...(it.inputs || []).map((p) => `${p.name} ${p.type ?? ""}`), ...(it.rules || []).flatMap((r) => [r.when, r.result, r.says]), it.otherwise?.result].filter(Boolean).join(" ").toLowerCase();
|
|
10523
|
+
return terms.every((t) => hay.includes(t));
|
|
10524
|
+
});
|
|
10525
|
+
}
|
|
10526
|
+
|
|
10527
|
+
// src/read-repo.mjs
|
|
10528
|
+
var READ_REPO_SCHEMA = "thunder-repo-reading-v1";
|
|
10529
|
+
var EXT_LANG = [
|
|
10530
|
+
[/\.d\.ts$/i, null],
|
|
10531
|
+
[/\.min\.js$/i, null],
|
|
10532
|
+
[/\.(ts|tsx|mts|cts)$/i, "typescript"],
|
|
10533
|
+
[/\.(js|jsx|mjs|cjs)$/i, "javascript"],
|
|
10534
|
+
[/\.pyi?$/i, "python"],
|
|
10535
|
+
[/\.go$/i, "go"],
|
|
10536
|
+
[/\.rs$/i, "rust"],
|
|
10537
|
+
[/\.cs$/i, "csharp"],
|
|
10538
|
+
[/\.java$/i, "java"],
|
|
10539
|
+
[/\.kts?$/i, "kotlin"],
|
|
10540
|
+
[/\.php$/i, "php"],
|
|
10541
|
+
[/\.rb$/i, "ruby"]
|
|
10542
|
+
];
|
|
10543
|
+
var READ_SKIP_DIRS = /* @__PURE__ */ new Set([
|
|
10544
|
+
"node_modules",
|
|
10545
|
+
".git",
|
|
10546
|
+
"dist",
|
|
10547
|
+
"build",
|
|
10548
|
+
"out",
|
|
10549
|
+
".next",
|
|
10550
|
+
".nuxt",
|
|
10551
|
+
".vercel",
|
|
10552
|
+
".turbo",
|
|
10553
|
+
"coverage",
|
|
10554
|
+
"vendor",
|
|
10555
|
+
"target",
|
|
10556
|
+
"bin",
|
|
10557
|
+
"obj",
|
|
10558
|
+
"__pycache__",
|
|
10559
|
+
".venv",
|
|
10560
|
+
"venv",
|
|
10561
|
+
"env",
|
|
10562
|
+
".tox",
|
|
10563
|
+
".mypy_cache",
|
|
10564
|
+
".gradle",
|
|
10565
|
+
".idea",
|
|
10566
|
+
".vscode",
|
|
10567
|
+
".intent",
|
|
10568
|
+
"third_party",
|
|
10569
|
+
"Pods",
|
|
10570
|
+
".terraform"
|
|
10571
|
+
]);
|
|
10572
|
+
function readableLanguage(path) {
|
|
10573
|
+
const p = String(path).replace(/\\/g, "/");
|
|
10574
|
+
if (p.split("/").some((seg) => READ_SKIP_DIRS.has(seg))) return null;
|
|
10575
|
+
for (const [re, lang] of EXT_LANG) if (re.test(p)) return lang;
|
|
10576
|
+
return null;
|
|
10577
|
+
}
|
|
10578
|
+
function looksGenerated(source) {
|
|
10579
|
+
const lines = source.split("\n");
|
|
10580
|
+
if (/^\s*(\/\/|#)\s*(Code generated|@generated|<auto-generated)/im.test(lines.slice(0, 5).join("\n"))) return true;
|
|
10581
|
+
const long = lines.filter((l) => l.length > 400).length;
|
|
10582
|
+
return long > 3 && long / lines.length > 0.2;
|
|
10583
|
+
}
|
|
10584
|
+
var topFolder = (path) => {
|
|
10585
|
+
const parts = String(path).replace(/\\/g, "/").split("/");
|
|
10586
|
+
return parts.length > 1 ? parts[0] : ".";
|
|
10587
|
+
};
|
|
10588
|
+
function readRepo(files, { maxFileBytes = 4e5, maxFiles = 5e3 } = {}) {
|
|
10589
|
+
const items = [], fileSummaries = [], skipped = [];
|
|
10590
|
+
let considered = 0;
|
|
10591
|
+
for (const f of files || []) {
|
|
10592
|
+
const path = String(f.path).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
10593
|
+
const language = readableLanguage(path);
|
|
10594
|
+
if (!language) continue;
|
|
10595
|
+
considered++;
|
|
10596
|
+
if (considered > maxFiles) {
|
|
10597
|
+
skipped.push({ path, reason: `More than ${maxFiles} files; read a smaller folder to include this one.` });
|
|
10598
|
+
continue;
|
|
10599
|
+
}
|
|
10600
|
+
const source = String(f.source ?? "");
|
|
10601
|
+
if (source.length > maxFileBytes || (f.size ?? 0) > maxFileBytes) {
|
|
10602
|
+
skipped.push({ path, reason: `Larger than ${Math.round(maxFileBytes / 1e3)} KB.` });
|
|
10603
|
+
continue;
|
|
10604
|
+
}
|
|
10605
|
+
if (looksGenerated(source)) {
|
|
10606
|
+
skipped.push({ path, reason: "Looks generated or minified." });
|
|
10607
|
+
continue;
|
|
10608
|
+
}
|
|
10609
|
+
let reading;
|
|
10610
|
+
try {
|
|
10611
|
+
reading = readCode(source, { language, file: path });
|
|
10612
|
+
} catch (e) {
|
|
10613
|
+
skipped.push({ path, reason: e instanceof Error ? e.message : "Could not be read." });
|
|
10614
|
+
continue;
|
|
10615
|
+
}
|
|
10616
|
+
for (const it of reading.items) items.push({ ...it, id: `${path}#${it.id}`, file: path, language });
|
|
10617
|
+
fileSummaries.push({ path, language, counts: reading.counts });
|
|
10618
|
+
}
|
|
10619
|
+
return { schema: READ_REPO_SCHEMA, ...summarize(items, fileSummaries), skipped };
|
|
10620
|
+
}
|
|
10621
|
+
function summarize(items, files) {
|
|
10622
|
+
const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
10623
|
+
const languages = {}, folders = {}, answers = /* @__PURE__ */ new Map(), inputs = /* @__PURE__ */ new Map();
|
|
10624
|
+
for (const f of files) {
|
|
10625
|
+
languages[f.language] = (languages[f.language] || 0) + 1;
|
|
10626
|
+
const top = topFolder(f.path);
|
|
10627
|
+
folders[top] = (folders[top] || 0) + 1;
|
|
10628
|
+
}
|
|
10629
|
+
for (const it of items) {
|
|
10630
|
+
counts[it.kind]++;
|
|
10631
|
+
if (it.status === "partial") counts.partial++;
|
|
10632
|
+
if (it.guards?.length) counts.guarded++;
|
|
10633
|
+
if (it.route) counts.route++;
|
|
10634
|
+
const guardAnswers = (it.guards || []).filter((g) => ["fails", "responds", "returns"].includes(g.effect.kind)).map((g) => g.effect.name);
|
|
10635
|
+
if (it.kind !== "decision" && !guardAnswers.length) continue;
|
|
10636
|
+
for (const result of new Set([...(it.rules || []).map((r) => r.result), it.otherwise?.result, ...guardAnswers].filter(Boolean))) {
|
|
10637
|
+
if (!answers.has(result)) answers.set(result, []);
|
|
10638
|
+
answers.get(result).push(it.id);
|
|
10639
|
+
}
|
|
10640
|
+
if (it.kind !== "decision") continue;
|
|
10641
|
+
for (const p of it.inputs || []) {
|
|
10642
|
+
if (!inputs.has(p.name)) inputs.set(p.name, []);
|
|
10643
|
+
inputs.get(p.name).push(it.id);
|
|
10644
|
+
}
|
|
10645
|
+
}
|
|
10646
|
+
const byUse = (m) => [...m].map(([name, ids]) => ({ name, decisions: ids })).sort((a, b) => b.decisions.length - a.decisions.length || a.name.localeCompare(b.name));
|
|
10647
|
+
return { files, items, counts, languages, folders, answers: byUse(answers), inputs: byUse(inputs) };
|
|
10648
|
+
}
|
|
10649
|
+
function searchRepo(index, { query = "", kinds = [], status = [], languages = [], path = "", answer = "", input = "" } = {}) {
|
|
10650
|
+
const terms = String(query).trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
10651
|
+
const prefix = String(path).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
10652
|
+
return index.items.filter((it) => {
|
|
10653
|
+
if (kinds.length && !kinds.includes(it.kind) && !(kinds.includes("guard") && it.guards?.length) && !(kinds.includes("route") && it.route)) return false;
|
|
10654
|
+
if (status.length && !status.includes(it.status)) return false;
|
|
10655
|
+
if (languages.length && !languages.includes(it.language)) return false;
|
|
10656
|
+
if (prefix && !it.file.startsWith(prefix)) return false;
|
|
10657
|
+
if (answer && !((it.rules || []).some((r) => r.result === answer) || it.otherwise?.result === answer || (it.guards || []).some((g) => g.effect.name === answer))) return false;
|
|
10658
|
+
if (input && !(it.inputs || []).some((p) => p.name === input)) return false;
|
|
10659
|
+
if (!terms.length) return true;
|
|
10660
|
+
const hay = [it.file, it.name, it.route && `${it.route.method} ${it.route.path}`, it.says, it.thunder, ...(it.guards || []).flatMap((g) => [g.code, g.effect.name, g.says]), ...(it.inputs || []).map((p) => `${p.name} ${p.type ?? ""}`), ...(it.rules || []).flatMap((r) => [r.when, r.result, r.says]), it.otherwise?.result].filter(Boolean).join(" ").toLowerCase();
|
|
10661
|
+
return terms.every((t) => hay.includes(t));
|
|
10662
|
+
});
|
|
10663
|
+
}
|
|
10664
|
+
|
|
10665
|
+
// src/promote.mjs
|
|
10666
|
+
var PROMOTE_SCHEMA = "thunder-promotion-v1";
|
|
10667
|
+
var pascal3 = (s) => String(s).replace(/(^|[_\s-]+)([a-zA-Z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/[^A-Za-z0-9]/g, "") || "Rule";
|
|
10668
|
+
var flat = (path) => path.split(".").map((seg, i) => i ? seg[0].toUpperCase() + seg.slice(1) : seg).join("");
|
|
10669
|
+
var OUTCOME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
10670
|
+
var STRING_LIT = /^[A-Za-z0-9 _-]*$/;
|
|
10671
|
+
function usage(conditions, params) {
|
|
10672
|
+
const isInput = (name) => params.size ? params.has(name.split(".")[0]) : !/^[A-Z]/.test(name);
|
|
10673
|
+
const refs = /* @__PURE__ */ new Map();
|
|
10674
|
+
const entry = (name) => {
|
|
10675
|
+
if (!refs.has(name)) refs.set(name, { numbers: /* @__PURE__ */ new Set(), strings: /* @__PURE__ */ new Set(), bare: false });
|
|
10676
|
+
return refs.get(name);
|
|
10677
|
+
};
|
|
10678
|
+
for (const cond of conditions) {
|
|
10679
|
+
const toks = tokenize(cond);
|
|
10680
|
+
toks.forEach((t, i) => {
|
|
10681
|
+
if (t.t !== "id" || !isInput(t.v)) return;
|
|
10682
|
+
const u = entry(t.v);
|
|
10683
|
+
const after = toks[i + 1]?.t === "op";
|
|
10684
|
+
const op = after ? toks[i + 1] : toks[i - 1]?.t === "op" ? toks[i - 1] : null;
|
|
10685
|
+
const other = after ? toks[i + 2] : toks[i - 1]?.t === "op" ? toks[i - 2] : null;
|
|
10686
|
+
if (op && other?.t === "num") u.numbers.add(other.v);
|
|
10687
|
+
else if (op && other?.t === "str") u.strings.add(other.v);
|
|
10688
|
+
else if (op && other?.t === "id" && !isInput(other.v)) u.strings.add(other.v);
|
|
10689
|
+
else if (op && other?.t === "id") u.numbers.add(0);
|
|
10690
|
+
else if (!op) u.bare = true;
|
|
10691
|
+
});
|
|
10692
|
+
}
|
|
10693
|
+
return refs;
|
|
10694
|
+
}
|
|
10695
|
+
function candidates(type, u) {
|
|
10696
|
+
if (type === "boolean") return [false, true];
|
|
10697
|
+
if (type === "string") return [...u.strings].concat("other").filter((s, i, a) => a.indexOf(s) === i);
|
|
10698
|
+
const out = /* @__PURE__ */ new Set();
|
|
10699
|
+
for (const n of u.numbers) {
|
|
10700
|
+
const step = Number.isInteger(n) ? 1 : 0.01;
|
|
10701
|
+
for (const v of [n - step, n, n + step]) out.add(Math.round(v * 100) / 100);
|
|
10702
|
+
}
|
|
10703
|
+
if (!out.size) out.add(0);
|
|
10704
|
+
return [...out].sort((a, b) => a - b);
|
|
10705
|
+
}
|
|
10706
|
+
function assignments(inputs, values, cap = 4096) {
|
|
10707
|
+
const total = inputs.reduce((n, i) => n * values[i].length, 1);
|
|
10708
|
+
if (total <= cap) {
|
|
10709
|
+
let acc = [{}];
|
|
10710
|
+
for (const name of inputs) acc = acc.flatMap((a) => values[name].map((v) => ({ ...a, [name]: v })));
|
|
10711
|
+
return acc;
|
|
10712
|
+
}
|
|
10713
|
+
const base = Object.fromEntries(inputs.map((n) => [n, values[n][0]]));
|
|
10714
|
+
return [base, ...inputs.flatMap((n) => values[n].map((v) => ({ ...base, [n]: v })))];
|
|
10715
|
+
}
|
|
10716
|
+
var lit = (v) => typeof v === "string" ? JSON.stringify(v) : String(v);
|
|
10717
|
+
function promoteDecision(item2, { file = item2.file || "" } = {}) {
|
|
10718
|
+
if (!item2 || item2.kind !== "decision" || !item2.rules?.length || !item2.otherwise) return { ok: false, reason: "Only decisions (functions that choose between fixed answers) can become a contract." };
|
|
10719
|
+
const results = [...item2.rules.map((r) => r.result), item2.otherwise.result];
|
|
10720
|
+
const bad = results.find((r) => !OUTCOME.test(r));
|
|
10721
|
+
if (bad) return { ok: false, reason: `The answer ${bad} is not a name. Contracts answer with names such as Approve or Review.` };
|
|
10722
|
+
const notes = [];
|
|
10723
|
+
const renames = /* @__PURE__ */ new Map();
|
|
10724
|
+
const conditions = item2.rules.map((r) => r.when);
|
|
10725
|
+
const refs = usage(conditions, new Set((item2.inputs || []).map((p) => p.name)));
|
|
10726
|
+
for (const path of refs.keys()) if (path.includes(".")) {
|
|
10727
|
+
renames.set(path, flat(path));
|
|
10728
|
+
notes.push(`${flat(path)} stands for ${path} in the code.`);
|
|
10729
|
+
}
|
|
10730
|
+
const rewrite = (cond) => tokenize(cond).map((t) => {
|
|
10731
|
+
if (t.t === "id") return refs.has(t.v) ? renames.get(t.v) ?? t.v : JSON.stringify(t.v);
|
|
10732
|
+
if (t.t === "str") return JSON.stringify(t.v);
|
|
10733
|
+
if (t.t === "num" || t.t === "bool") return String(t.v);
|
|
10734
|
+
return t.v;
|
|
10735
|
+
}).join(" ").replace(/\( /g, "(").replace(/ \)/g, ")");
|
|
10736
|
+
const declared = new Map((item2.inputs || []).map((p) => [p.name, p.type]));
|
|
10737
|
+
const order = (path) => {
|
|
10738
|
+
const i = (item2.inputs || []).findIndex((p) => p.name === path.split(".")[0]);
|
|
10739
|
+
return i < 0 ? 999 : i;
|
|
10740
|
+
};
|
|
10741
|
+
const names = [...refs.keys()].sort((a, b) => order(a) - order(b)).map((p) => renames.get(p) ?? p);
|
|
10742
|
+
if (!names.length) return { ok: false, reason: "The rules do not depend on any input, so there is nothing to give examples for." };
|
|
10743
|
+
const types = {}, values = {};
|
|
10744
|
+
for (const [path, u] of refs) {
|
|
10745
|
+
const name = renames.get(path) ?? path;
|
|
10746
|
+
const t = declared.get(path);
|
|
10747
|
+
types[name] = ["number", "boolean", "string"].includes(t) && !(t !== "string" && u.strings.size) ? t : u.strings.size ? "string" : u.numbers.size ? "number" : "boolean";
|
|
10748
|
+
for (const s of u.strings) if (!STRING_LIT.test(s)) return { ok: false, reason: `The text "${s}" has characters a contract example cannot hold yet.` };
|
|
10749
|
+
values[name] = candidates(types[name], u);
|
|
10750
|
+
}
|
|
10751
|
+
const rules = item2.rules.map((r) => ({ when: rewrite(r.when), result: r.result }));
|
|
10752
|
+
const decisionName = pascal3(item2.name);
|
|
10753
|
+
const canonical = parseIntent([
|
|
10754
|
+
`decision ${decisionName}`,
|
|
10755
|
+
" inputs",
|
|
10756
|
+
...names.map((n) => ` ${n}`),
|
|
10757
|
+
...rules.flatMap((r, i) => [` rule r${i + 1}`, ` when ${r.when}`, ` return ${r.result}`]),
|
|
10758
|
+
" default",
|
|
10759
|
+
` return ${item2.otherwise.result}`
|
|
10760
|
+
].join("\n")).decisions[0];
|
|
10761
|
+
const run = (a) => evaluateDecision(canonical, a);
|
|
10762
|
+
const all = assignments(names, values).map((a) => ({ a, r: run(a) }));
|
|
10763
|
+
const chosen = [];
|
|
10764
|
+
const key = (a) => names.map((n) => lit(a[n])).join("|");
|
|
10765
|
+
const add = (a, label) => {
|
|
10766
|
+
if (chosen.length >= 10 || chosen.some((c) => key(c.a) === key(a) || c.label === label)) return;
|
|
10767
|
+
chosen.push({ a, label, result: run(a).result });
|
|
10768
|
+
};
|
|
10769
|
+
rules.forEach((r, i) => {
|
|
10770
|
+
const hit = all.find((x) => x.r.matched === `r${i + 1}`);
|
|
10771
|
+
if (hit) add(hit.a, `when ${sayCondition(r.when)}`);
|
|
10772
|
+
});
|
|
10773
|
+
const fallback = all.find((x) => x.r.matched === "default");
|
|
10774
|
+
if (fallback) add(fallback.a, "when no rule matches");
|
|
10775
|
+
for (const [path, u] of refs) {
|
|
10776
|
+
const name = renames.get(path) ?? path;
|
|
10777
|
+
if (types[name] !== "number") continue;
|
|
10778
|
+
for (const n of u.numbers) {
|
|
10779
|
+
const step = Number.isInteger(n) ? 1 : 0.01;
|
|
10780
|
+
for (const x of all) {
|
|
10781
|
+
if (x.a[name] !== n) continue;
|
|
10782
|
+
for (const [v, word] of [[Math.round((n - step) * 100) / 100, "just below"], [Math.round((n + step) * 100) / 100, "just above"]]) {
|
|
10783
|
+
const y = all.find((z) => z.a[name] === v && names.every((m) => m === name || z.a[m] === x.a[m]));
|
|
10784
|
+
if (y && y.r.result !== x.r.result) {
|
|
10785
|
+
add(x.a, `${name} exactly ${n}`);
|
|
10786
|
+
add(y.a, `${name} ${word} ${n}`);
|
|
10787
|
+
}
|
|
10788
|
+
}
|
|
10789
|
+
if (chosen.some((c) => c.label === `${name} exactly ${n}`)) break;
|
|
10790
|
+
}
|
|
10791
|
+
}
|
|
10792
|
+
}
|
|
10793
|
+
const unreached = rules.filter((_, i) => !all.some((x) => x.r.matched === `r${i + 1}`)).map((r) => r.when);
|
|
10794
|
+
for (const w of unreached) notes.push(`No example reaches the rule "${sayCondition(w)}"; an earlier rule always answers first, or the examples need other values.`);
|
|
10795
|
+
const outcomes = [...new Set(results)];
|
|
10796
|
+
const sig = names.map((n) => `${n}: ${types[n]}`).join(", ");
|
|
10797
|
+
const where = file ? `${file} line ${item2.line}` : `line ${item2.line}`;
|
|
10798
|
+
const source = [
|
|
10799
|
+
`# Recovered from ${where} by thunder read. Inferred from code, not written by a person.`,
|
|
10800
|
+
"# The examples record what the code does today. Confirm each answer, or change it where the code is wrong.",
|
|
10801
|
+
...notes.map((n) => `# ${n}`),
|
|
10802
|
+
`contract ${decisionName}`,
|
|
10803
|
+
`purpose ${decisionName} decides between ${outcomes.length === 2 ? outcomes.join(" and ") : `${outcomes.slice(0, -1).join(", ")}, and ${outcomes[outcomes.length - 1]}`}. Confirm what it is for.`,
|
|
10804
|
+
"",
|
|
10805
|
+
`decision ${decisionName}(${sig})`,
|
|
10806
|
+
...rules.map((r) => ` when ${r.when} -> ${r.result}`),
|
|
10807
|
+
` otherwise -> ${item2.otherwise.result}`,
|
|
10808
|
+
"",
|
|
10809
|
+
`examples ${decisionName}`,
|
|
10810
|
+
...chosen.map((c) => ` case "${c.label.replace(/"/g, "")}": (${names.map((n) => `${n}: ${lit(c.a[n])}`).join(", ")}) -> ${c.result}`),
|
|
10811
|
+
""
|
|
10812
|
+
].join("\n");
|
|
10813
|
+
return { schema: PROMOTE_SCHEMA, ok: true, name: decisionName, source, examples: chosen.length, notes };
|
|
10814
|
+
}
|
|
10815
|
+
|
|
10816
|
+
// src/read-repo-fs.mjs
|
|
10817
|
+
var import_node_fs = require("node:fs");
|
|
10818
|
+
var import_node_path = require("node:path");
|
|
10819
|
+
function collectReadableFiles(root, { maxFiles = 5e3, maxFileBytes = 4e5 } = {}) {
|
|
10820
|
+
const out = [];
|
|
10821
|
+
const walk = (dir) => {
|
|
10822
|
+
let names;
|
|
10823
|
+
try {
|
|
10824
|
+
names = (0, import_node_fs.readdirSync)(dir).sort();
|
|
10825
|
+
} catch {
|
|
10826
|
+
return;
|
|
10827
|
+
}
|
|
10828
|
+
for (const name of names) {
|
|
10829
|
+
if (out.length > maxFiles) return;
|
|
10830
|
+
if (READ_SKIP_DIRS.has(name) || name.startsWith(".")) continue;
|
|
10831
|
+
const full = (0, import_node_path.join)(dir, name);
|
|
10832
|
+
let st;
|
|
10833
|
+
try {
|
|
10834
|
+
st = (0, import_node_fs.statSync)(full);
|
|
10835
|
+
} catch {
|
|
10836
|
+
continue;
|
|
10837
|
+
}
|
|
10838
|
+
if (st.isDirectory()) walk(full);
|
|
10839
|
+
else if (readableLanguage(name)) {
|
|
10840
|
+
const path = (0, import_node_path.relative)(root, full).split("\\").join("/");
|
|
10841
|
+
out.push(st.size > maxFileBytes ? { path, source: "", size: st.size } : { path, source: (0, import_node_fs.readFileSync)(full, "utf8") });
|
|
10842
|
+
}
|
|
10843
|
+
}
|
|
10844
|
+
};
|
|
10845
|
+
walk(root);
|
|
10846
|
+
return out;
|
|
10847
|
+
}
|
|
10848
|
+
|
|
10849
|
+
// src/mcp.mjs
|
|
10850
|
+
var import_node_path3 = require("node:path");
|
|
10851
|
+
|
|
10852
|
+
// src/target-types.mjs
|
|
10853
|
+
var inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(":")[0].trim()).filter(Boolean);
|
|
10854
|
+
function coerceVal(v) {
|
|
10855
|
+
if (v == null || typeof v !== "string") return v;
|
|
10856
|
+
const s = v.trim();
|
|
10857
|
+
if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
|
|
10858
|
+
if (s === "true") return true;
|
|
10859
|
+
if (s === "false") return false;
|
|
10860
|
+
return v;
|
|
10861
|
+
}
|
|
10862
|
+
function inferInputTypes(ast, dec) {
|
|
10863
|
+
const names = inputNames(dec);
|
|
10864
|
+
const types = {};
|
|
10865
|
+
for (const n of names) {
|
|
10866
|
+
let t = "string";
|
|
10867
|
+
for (const test of (ast.tests || []).filter((x) => x.name === dec.name)) {
|
|
10868
|
+
for (const c of test.cases || []) {
|
|
10869
|
+
const raw = (c.given || {})[n];
|
|
10870
|
+
if (raw == null) continue;
|
|
10871
|
+
const cv = coerceVal(raw);
|
|
10872
|
+
if (typeof cv === "number") {
|
|
10873
|
+
t = "number";
|
|
10874
|
+
break;
|
|
10875
|
+
}
|
|
10876
|
+
if (typeof cv === "boolean" && t !== "number") t = "bool";
|
|
10877
|
+
}
|
|
10878
|
+
if (t === "number") break;
|
|
10879
|
+
}
|
|
10880
|
+
types[n] = t;
|
|
10881
|
+
}
|
|
10882
|
+
return types;
|
|
10883
|
+
}
|
|
10884
|
+
var strLit = (s) => JSON.stringify(String(s));
|
|
10885
|
+
|
|
10886
|
+
// src/translate.mjs
|
|
10887
|
+
var RELATIONAL = /^(<=|>=|<|>)$/;
|
|
10888
|
+
function typesFor(ast, dec) {
|
|
10889
|
+
const names = inputNames(dec);
|
|
10890
|
+
const types = inferInputTypes(ast, dec);
|
|
10891
|
+
const hasExample = (n) => (ast.tests || []).some((t) => t.name === dec.name && (t.cases || []).some((c) => (c.given || {})[n] != null));
|
|
10892
|
+
const declared = {};
|
|
10893
|
+
for (const raw of dec.inputs || []) {
|
|
10894
|
+
const m = String(raw).match(/^\s*(\w+)\s*:\s*(number|boolean|bool|string)\s*$/);
|
|
10895
|
+
if (m) declared[m[1]] = m[2] === "boolean" ? "bool" : m[2];
|
|
10896
|
+
}
|
|
10897
|
+
for (const n of names) {
|
|
10898
|
+
if (declared[n]) {
|
|
10899
|
+
types[n] = declared[n];
|
|
10900
|
+
continue;
|
|
10901
|
+
}
|
|
10902
|
+
if (hasExample(n)) continue;
|
|
10903
|
+
let guess = "string";
|
|
10904
|
+
for (const r of dec.rules || []) {
|
|
10905
|
+
const toks = String(r.when || "").split(/\s+|(?=[()])|(?<=[()])/).filter(Boolean);
|
|
10906
|
+
toks.forEach((t, i) => {
|
|
10907
|
+
if (t !== n) return;
|
|
10908
|
+
if (RELATIONAL.test(toks[i - 1] || "") || RELATIONAL.test(toks[i + 1] || "")) guess = "number";
|
|
10909
|
+
else if (guess === "string" && !/^(==|!=|in)$/.test(toks[i + 1] || "") && !/^(==|!=)$/.test(toks[i - 1] || "")) guess = "bool";
|
|
10910
|
+
});
|
|
10911
|
+
}
|
|
10912
|
+
types[n] = guess;
|
|
10913
|
+
}
|
|
10914
|
+
return types;
|
|
10915
|
+
}
|
|
10916
|
+
var tryExpr = (fn, when, inputs, fallback) => {
|
|
10917
|
+
try {
|
|
10918
|
+
return fn(when, { inputs });
|
|
10919
|
+
} catch {
|
|
10920
|
+
return fallback;
|
|
10921
|
+
}
|
|
10922
|
+
};
|
|
10923
|
+
var LANGS = {
|
|
10924
|
+
typescript: {
|
|
10925
|
+
label: "TypeScript",
|
|
10926
|
+
types: { number: "number", bool: "boolean", string: "string" },
|
|
10927
|
+
emit(d, names, types) {
|
|
10928
|
+
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(", ");
|
|
10929
|
+
const L = [`export function ${d.name}(${params}): string {`];
|
|
10930
|
+
for (const r of d.rules || []) L.push(` if (${tryExpr(exprToJs, r.when, names, "false")}) return ${strLit(r.result)};`);
|
|
10931
|
+
L.push(` return ${strLit(d.default ?? "")};`, "}");
|
|
10932
|
+
return L;
|
|
10933
|
+
}
|
|
10934
|
+
},
|
|
10935
|
+
python: {
|
|
10936
|
+
label: "Python",
|
|
10937
|
+
types: { number: "float", bool: "bool", string: "str" },
|
|
10938
|
+
emit(d, names, types) {
|
|
10939
|
+
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(", ");
|
|
10940
|
+
const L = [`def ${d.name}(${params}) -> str:`];
|
|
10941
|
+
for (const r of d.rules || []) L.push(` if ${tryExpr(exprToPython, r.when, names, "False")}:`, ` return ${strLit(r.result)}`);
|
|
10942
|
+
L.push(` return ${strLit(d.default ?? "")}`);
|
|
10943
|
+
return L;
|
|
10944
|
+
}
|
|
10945
|
+
},
|
|
10946
|
+
go: {
|
|
10947
|
+
label: "Go",
|
|
10948
|
+
types: { number: "float64", bool: "bool", string: "string" },
|
|
10949
|
+
emit(d, names, types) {
|
|
10950
|
+
const params = names.map((n) => `${n} ${this.types[types[n]]}`).join(", ");
|
|
10951
|
+
const L = [`func ${d.name}(${params}) string {`];
|
|
10952
|
+
for (const r of d.rules || []) L.push(` if ${tryExpr(exprToGo, r.when, names, "false")} {`, ` return ${strLit(r.result)}`, " }");
|
|
10953
|
+
L.push(` return ${strLit(d.default ?? "")}`, "}");
|
|
10954
|
+
return L;
|
|
10955
|
+
}
|
|
10956
|
+
},
|
|
10957
|
+
rust: {
|
|
10958
|
+
label: "Rust",
|
|
10959
|
+
types: { number: "f64", bool: "bool", string: "&str" },
|
|
10960
|
+
emit(d, names, types) {
|
|
10961
|
+
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(", ");
|
|
10962
|
+
const L = [`fn ${d.name}(${params}) -> &'static str {`];
|
|
10963
|
+
for (const r of d.rules || []) L.push(` if ${tryExpr(exprToRust, r.when, names, "false")} {`, ` return ${strLit(r.result)};`, " }");
|
|
10964
|
+
L.push(` ${strLit(d.default ?? "")}`, "}");
|
|
10965
|
+
return L;
|
|
10966
|
+
}
|
|
10967
|
+
},
|
|
10968
|
+
csharp: {
|
|
10969
|
+
label: "C#",
|
|
10970
|
+
types: { number: "double", bool: "bool", string: "string" },
|
|
10971
|
+
emit(d, names, types) {
|
|
10972
|
+
const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(", ");
|
|
10973
|
+
const L = [`public static string ${d.name}(${params})`, "{"];
|
|
10974
|
+
for (const r of d.rules || []) L.push(` if (${tryExpr(exprToCSharp, r.when, names, "false")}) return ${strLit(r.result)};`);
|
|
10975
|
+
L.push(` return ${strLit(d.default ?? "")};`, "}");
|
|
10976
|
+
return L;
|
|
10977
|
+
}
|
|
10978
|
+
},
|
|
10979
|
+
java: {
|
|
10980
|
+
label: "Java",
|
|
10981
|
+
types: { number: "double", bool: "boolean", string: "String" },
|
|
10982
|
+
emit(d, names, types) {
|
|
10983
|
+
const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(", ");
|
|
10984
|
+
const L = [`public static String ${d.name}(${params}) {`];
|
|
10985
|
+
for (const r of d.rules || []) L.push(` if (${tryExpr(exprToJava, r.when, names, "false")}) return ${strLit(r.result)};`);
|
|
10986
|
+
L.push(` return ${strLit(d.default ?? "")};`, "}");
|
|
10987
|
+
return L;
|
|
10988
|
+
}
|
|
10989
|
+
}
|
|
10990
|
+
};
|
|
10991
|
+
var TRANSLATE_LANGUAGES = Object.entries(LANGS).map(([key, l]) => ({ key, label: l.label }));
|
|
10992
|
+
function translateDecisions(ast, lang) {
|
|
10993
|
+
const L = LANGS[lang];
|
|
10994
|
+
if (!L) throw new Error(`Unknown language ${lang}. Use one of: ${Object.keys(LANGS).join(", ")}.`);
|
|
10995
|
+
const comment = lang === "python" ? "#" : "//";
|
|
10996
|
+
const out = [`${comment} Generated from ThunderLang. Deterministic, no AI. The first matching rule wins.`];
|
|
10997
|
+
for (const d of ast.decisions || []) {
|
|
10998
|
+
out.push("", ...L.emit(d, inputNames(d), typesFor(ast, d)));
|
|
10999
|
+
}
|
|
11000
|
+
return out.join("\n");
|
|
11001
|
+
}
|
|
11002
|
+
|
|
11003
|
+
// src/human-contract.mjs
|
|
11004
|
+
var ID = "[A-Za-z_][A-Za-z0-9_]*";
|
|
11005
|
+
var id = new RegExp(`^${ID}$`);
|
|
11006
|
+
var literal = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?|true|false|"[A-Za-z0-9 _-]*")$/;
|
|
11007
|
+
var fail = (line, text) => {
|
|
11008
|
+
throw new Error(`Line ${line}: ${text}`);
|
|
11009
|
+
};
|
|
11010
|
+
function namedCase(text, line, decision) {
|
|
11011
|
+
const match = text.match(new RegExp(`^case "([^"\\\\]+)":\\s*\\((.*)\\)\\s*->\\s*(${ID})$`));
|
|
11012
|
+
if (!match) fail(line, 'Use case "name": (input: value, otherInput: value) -> Outcome. Use -> for both rules and examples.');
|
|
11013
|
+
const values = /* @__PURE__ */ new Map();
|
|
11014
|
+
const entries = match[2].trim().replace(/,\s*$/, "").split(",");
|
|
11015
|
+
for (const entry of entries) {
|
|
11016
|
+
const arg = entry.trim().match(new RegExp(`^(${ID})\\s*:\\s*(.+)$`));
|
|
11017
|
+
if (!arg) fail(line, "Name every example input, such as amount: 100.");
|
|
11018
|
+
if (!decision.inputs.includes(arg[1])) fail(line, `Unknown input ${arg[1]}. Expected: ${decision.inputs.join(", ")}.`);
|
|
11019
|
+
if (values.has(arg[1])) fail(line, `Duplicate input ${arg[1]}. Provide each input once.`);
|
|
11020
|
+
values.set(arg[1], arg[2].trim());
|
|
11021
|
+
}
|
|
11022
|
+
const missing = decision.inputs.filter((input) => !values.has(input));
|
|
11023
|
+
if (missing.length) fail(line, `Missing input ${missing.join(", ")}. Missing is not the same as false.`);
|
|
11024
|
+
return { cells: [match[1].trim(), ...decision.inputs.map((input) => values.get(input)), match[3]], line };
|
|
11025
|
+
}
|
|
11026
|
+
function compileHumanContract(source) {
|
|
11027
|
+
if (typeof source !== "string" || source.length > 2e5) throw new Error("A human contract must be text of at most 200 KB.");
|
|
11028
|
+
const rows = source.split(/\r?\n/).map((text, i) => ({ text: text.trim(), indented: /^\s/.test(text), line: i + 1 })).filter((r) => r.text && !r.text.startsWith("#"));
|
|
11029
|
+
let mission = null, purpose = null, active = null;
|
|
11030
|
+
const decisions = [], tables = /* @__PURE__ */ new Map();
|
|
11031
|
+
for (let index = 0; index < rows.length; index++) {
|
|
11032
|
+
const row = rows[index];
|
|
11033
|
+
const { text, line } = row;
|
|
11034
|
+
if (!row.indented) {
|
|
11035
|
+
active = null;
|
|
11036
|
+
let match;
|
|
11037
|
+
if (match = text.match(new RegExp(`^contract (${ID})$`))) {
|
|
11038
|
+
if (mission || decisions.length) fail(line, "Declare one contract before its decisions.");
|
|
11039
|
+
mission = match[1];
|
|
11040
|
+
} else if (text.startsWith("purpose ")) {
|
|
11041
|
+
if (!mission || purpose) fail(line, "Declare one purpose after the contract name.");
|
|
11042
|
+
purpose = text.slice(8).trim();
|
|
11043
|
+
} else if (match = text.match(new RegExp(`^decision (${ID})\\(([^)]*)\\)$`))) {
|
|
11044
|
+
const signature = match[2].split(",").map((x) => x.trim().match(new RegExp(`^(${ID})(?:\\s*:\\s*(number|boolean|string))?$`)));
|
|
11045
|
+
if (signature.some((input) => !input)) fail(line, "Use input names, optionally typed as number, boolean, or string.");
|
|
11046
|
+
const inputs = signature.map((input) => input[1]);
|
|
11047
|
+
const inputTypes = Object.fromEntries(signature.filter((input) => input[2]).map((input) => [input[1], input[2]]));
|
|
11048
|
+
if (!mission || !purpose) fail(line, "Start with contract and purpose before a decision.");
|
|
11049
|
+
if (!inputs.length || inputs.some((x) => !id.test(x) || ["case", "expect", "true", "false", "and", "or", "not", "in"].includes(x)) || new Set(inputs).size !== inputs.length) fail(line, "Use unique input names, such as decision RefundPolicy(amount, withinWindow).");
|
|
11050
|
+
if (decisions.some((d) => d.name === match[1])) fail(line, "Decision names must be unique.");
|
|
11051
|
+
active = { kind: "decision", name: match[1], inputs, inputTypes, rules: [], otherwise: null, line };
|
|
11052
|
+
decisions.push(active);
|
|
11053
|
+
} else if (match = text.match(new RegExp(`^examples (${ID})$`))) {
|
|
11054
|
+
if (tables.has(match[1]) || !decisions.some((d) => d.name === match[1])) fail(line, "Examples must name one preceding decision exactly, with one examples block per decision.");
|
|
11055
|
+
active = { kind: "examples", name: match[1], rows: [], format: null, line };
|
|
11056
|
+
tables.set(match[1], active);
|
|
11057
|
+
} else fail(line, "Expected contract, purpose, decision Name(inputs), or examples Name. This preview does not guess unknown syntax.");
|
|
11058
|
+
} else if (active?.kind === "decision") {
|
|
11059
|
+
let match;
|
|
11060
|
+
if (match = text.match(new RegExp(`^when (.+) -> (${ID})$`))) {
|
|
11061
|
+
if (active.otherwise) fail(line, "Put conditional rules before otherwise.");
|
|
11062
|
+
try {
|
|
11063
|
+
compileExpr(match[1]);
|
|
11064
|
+
for (const token of tokenize(match[1])) {
|
|
11065
|
+
if (token.t === "id" && !active.inputs.includes(token.v)) fail(line, `Unknown input ${token.v}. Declare it, or quote it if it is a text value.`);
|
|
11066
|
+
if (token.t === "num" && !Number.isFinite(token.v)) fail(line, "Use a finite number in the condition.");
|
|
11067
|
+
}
|
|
11068
|
+
} catch (e) {
|
|
11069
|
+
fail(line, e.message);
|
|
11070
|
+
}
|
|
11071
|
+
active.rules.push({ condition: match[1], result: match[2], line });
|
|
11072
|
+
} else if (match = text.match(new RegExp(`^otherwise -> (${ID})$`))) {
|
|
11073
|
+
if (active.otherwise) fail(line, "Use one otherwise result.");
|
|
11074
|
+
active.otherwise = match[1];
|
|
11075
|
+
} else fail(line, "Use when <condition> -> Outcome or otherwise -> Outcome.");
|
|
11076
|
+
} else if (active?.kind === "examples") {
|
|
11077
|
+
const format = text.startsWith("|") ? "table" : "named";
|
|
11078
|
+
if (active.format && active.format !== format) fail(line, "Use named cases or a table within one examples block, not both.");
|
|
11079
|
+
active.format = format;
|
|
11080
|
+
if (format === "table") {
|
|
11081
|
+
if (!text.endsWith("|")) fail(line, "Write an examples table row with | around every cell.");
|
|
11082
|
+
active.rows.push({ cells: text.slice(1, -1).split("|").map((s) => s.trim()), line });
|
|
11083
|
+
} else {
|
|
11084
|
+
let statement = text;
|
|
11085
|
+
while (!/\)\s*(?:->|=>)/.test(statement) && index + 1 < rows.length && rows[index + 1].indented && !/^(case |\|)/.test(rows[index + 1].text)) {
|
|
11086
|
+
statement += ` ${rows[++index].text}`;
|
|
11087
|
+
}
|
|
11088
|
+
active.rows.push(namedCase(statement, line, decisions.find((d) => d.name === active.name)));
|
|
11089
|
+
}
|
|
11090
|
+
} else fail(line, "This indented line has no decision or examples block.");
|
|
11091
|
+
}
|
|
11092
|
+
if (!mission || !purpose || !decisions.length) throw new Error("Include a contract, purpose, and at least one decision with examples.");
|
|
11093
|
+
const out = [`mission ${mission}`, "", "goal", ` ${purpose}`];
|
|
11094
|
+
for (const d of decisions) {
|
|
11095
|
+
if (!d.rules.length || !d.otherwise) fail(d.line, "Each decision needs at least one when rule and an otherwise result.");
|
|
11096
|
+
out.push("", `decision ${d.name}`, " inputs", ...d.inputs.map((i) => ` ${i}`));
|
|
11097
|
+
d.rules.forEach((r, i) => out.push(` rule condition_${i + 1}`, ` when ${r.condition}`, ` return ${r.result}`));
|
|
11098
|
+
out.push(" default", ` return ${d.otherwise}`);
|
|
11099
|
+
const table = tables.get(d.name);
|
|
11100
|
+
if (!table || !table.rows.length) fail(d.line, `Add examples ${d.name} with at least one case.`);
|
|
11101
|
+
const expectedHeader = ["case", ...d.inputs, "expect"];
|
|
11102
|
+
const header = table.format === "table" ? table.rows[0].cells : expectedHeader;
|
|
11103
|
+
if (JSON.stringify(header) !== JSON.stringify(expectedHeader)) fail(table.rows[0].line, `Use this header: | ${expectedHeader.join(" | ")} |`);
|
|
11104
|
+
const names = /* @__PURE__ */ new Set();
|
|
11105
|
+
out.push("", `test ${d.name}`);
|
|
11106
|
+
for (const row of table.rows.slice(table.format === "table" ? 1 : 0)) {
|
|
11107
|
+
if (row.cells.every((c) => /^:?-+:?$/.test(c))) continue;
|
|
11108
|
+
const [name, ...values] = row.cells;
|
|
11109
|
+
if (row.cells.length !== header.length || !name || names.has(name)) fail(row.line, "Use a unique case name and fill every column.");
|
|
11110
|
+
names.add(name);
|
|
11111
|
+
const expected = values.pop();
|
|
11112
|
+
if (!id.test(expected)) fail(row.line, "The expected outcome must be a named result, such as Approve or Review.");
|
|
11113
|
+
const outcomes = [...d.rules.map((r) => r.result), d.otherwise];
|
|
11114
|
+
if (!outcomes.includes(expected)) fail(row.line, `Unknown outcome ${expected}. Use one of: ${[...new Set(outcomes)].join(", ")}.`);
|
|
11115
|
+
values.forEach((v, i) => {
|
|
11116
|
+
if (!literal.test(v) || !v.startsWith('"') && !["true", "false"].includes(v) && !Number.isFinite(Number(v))) fail(row.line, "Inputs must be finite numbers, true/false, or quoted simple text. Complex values need ordinary ThunderLang.");
|
|
11117
|
+
const type = v.startsWith('"') ? "string" : ["true", "false"].includes(v) ? "boolean" : "number";
|
|
11118
|
+
if (d.inputTypes[d.inputs[i]] && type !== d.inputTypes[d.inputs[i]]) fail(row.line, `${d.inputs[i]} expects ${d.inputTypes[d.inputs[i]]}, received ${type}. Values are not coerced.`);
|
|
11119
|
+
});
|
|
11120
|
+
out.push(` case ${name}`, ` given ${d.inputs.map((input, i) => `${input} ${values[i]}`).join(", ")}`, ` expect ${expected}`);
|
|
11121
|
+
}
|
|
11122
|
+
if (!names.size) fail(table.line, "The table has no examples; add a row with inputs and an expected outcome.");
|
|
11123
|
+
}
|
|
11124
|
+
return out.join("\n") + "\n";
|
|
11125
|
+
}
|
|
11126
|
+
var words2 = (s) => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, " ");
|
|
11127
|
+
var operators = { ">=": "is at least", "<=": "is at most", ">": "is greater than", "<": "is less than", "==": "equals", "=": "equals", "!=": "does not equal", "&&": "and", "||": "or", "!": "not" };
|
|
11128
|
+
function readCondition(expression) {
|
|
11129
|
+
try {
|
|
11130
|
+
return tokenize(expression).map((t) => t.t === "str" ? JSON.stringify(t.v) : t.t === "id" ? words2(t.v) : operators[t.v] ?? String(t.v)).join(" ");
|
|
11131
|
+
} catch {
|
|
11132
|
+
return expression;
|
|
11133
|
+
}
|
|
11134
|
+
}
|
|
11135
|
+
function readUnknowns(ast, source) {
|
|
11136
|
+
const notes = (ast.unknowns ?? []).filter((u) => u.name).map((u) => u.name);
|
|
11137
|
+
let block = false;
|
|
11138
|
+
for (const line of source.split(/\r?\n/)) {
|
|
11139
|
+
if (/^unknown\s*$/.test(line)) {
|
|
11140
|
+
block = true;
|
|
11141
|
+
continue;
|
|
11142
|
+
}
|
|
11143
|
+
if (/^\S/.test(line)) block = false;
|
|
11144
|
+
if (block && /^\s+\S/.test(line)) notes.push(line.trim());
|
|
11145
|
+
}
|
|
11146
|
+
return notes;
|
|
11147
|
+
}
|
|
11148
|
+
function previewHumanContract(source) {
|
|
11149
|
+
const first = source.split(/\r?\n/).find((l) => l.trim() && !l.trim().startsWith("#"))?.trim() ?? "";
|
|
11150
|
+
const compact = first.startsWith("contract ");
|
|
11151
|
+
const canonicalSource = compact ? compileHumanContract(source) : source;
|
|
11152
|
+
const ast = parseIntent(canonicalSource);
|
|
11153
|
+
const tests = runTests(ast);
|
|
11154
|
+
const declared = (ast.tests ?? []).flatMap((t) => t.cases);
|
|
11155
|
+
const results = tests.results.map((r, i) => ({ ...r, given: declared[i]?.given ?? {}, pass: !!r.pass && !r.error && !r.note && declared[i]?.expect != null }));
|
|
11156
|
+
const passed = results.filter((r) => r.pass).length;
|
|
11157
|
+
const report = {
|
|
11158
|
+
schema: "thunder-human-preview-v1",
|
|
11159
|
+
experimental: true,
|
|
11160
|
+
origin: ast.lift?.inferred ? "inferred-code" : compact ? "human-v1" : "thunderlang",
|
|
11161
|
+
mission: ast.mission,
|
|
11162
|
+
purpose: ast.goal,
|
|
11163
|
+
canonicalSource,
|
|
11164
|
+
signatureInputs: ast.inputs ?? [],
|
|
11165
|
+
sourceReferences: ast.lift?.maps_to ?? [],
|
|
11166
|
+
needsReview: ast.lift?.needs_review ?? [],
|
|
11167
|
+
unknowns: readUnknowns(ast, canonicalSource),
|
|
11168
|
+
decisions: (ast.decisions ?? []).map((d) => ({
|
|
11169
|
+
name: d.name,
|
|
11170
|
+
inputs: d.inputs,
|
|
11171
|
+
order: "first matching rule wins",
|
|
11172
|
+
rules: d.rules.map((r) => ({ condition: r.when, readAs: readCondition(r.when ?? ""), outcome: r.result })),
|
|
11173
|
+
otherwise: d.default
|
|
11174
|
+
})),
|
|
11175
|
+
tests: { total: results.length, passed, failed: results.length - passed, results },
|
|
11176
|
+
application: "not_checked",
|
|
11177
|
+
limitations: [
|
|
11178
|
+
"This reading view covers authored decisions and examples. Other constructs remain in the full source.",
|
|
11179
|
+
"Purpose is author-stated intent, not inferred from code or established by tests.",
|
|
11180
|
+
"Passing examples check those contract inputs only. Use OpenThunder intent test-app to exercise the application."
|
|
11181
|
+
]
|
|
11182
|
+
};
|
|
11183
|
+
return report;
|
|
11184
|
+
}
|
|
11185
|
+
|
|
11186
|
+
// src/mcp.mjs
|
|
11187
|
+
var PROTOCOL_VERSION = "2024-11-05";
|
|
11188
|
+
var SUPPORTED_PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
11189
|
+
var str = { type: "string" };
|
|
11190
|
+
function resolveObligations(ast) {
|
|
11191
|
+
const t = runTests(ast);
|
|
11192
|
+
const testPass = /* @__PURE__ */ new Map();
|
|
11193
|
+
for (const res of t.results || []) {
|
|
11194
|
+
const cur = testPass.get(res.target);
|
|
11195
|
+
testPass.set(res.target, cur === void 0 ? !!res.pass : cur && !!res.pass);
|
|
11196
|
+
}
|
|
11197
|
+
const norm4 = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
11198
|
+
const matchTest = (verifyText) => {
|
|
11199
|
+
const v = norm4(verifyText);
|
|
11200
|
+
if (!v) return null;
|
|
11201
|
+
for (const [name, pass] of testPass) {
|
|
11202
|
+
const n = norm4(name);
|
|
11203
|
+
if (n && (n === v || n.includes(v) || v.includes(n))) return { name, pass };
|
|
11204
|
+
}
|
|
11205
|
+
return null;
|
|
11206
|
+
};
|
|
11207
|
+
const build = (kind, o) => {
|
|
11208
|
+
const verify = o.verify || [];
|
|
11209
|
+
let status = "unverified", provenBy = null;
|
|
11210
|
+
if (verify.length) {
|
|
11211
|
+
let m = null;
|
|
11212
|
+
for (const vt of verify) {
|
|
11213
|
+
const x = matchTest(vt);
|
|
11214
|
+
if (x) {
|
|
11215
|
+
m = x;
|
|
11216
|
+
if (!x.pass) break;
|
|
11217
|
+
}
|
|
11218
|
+
}
|
|
11219
|
+
if (m) {
|
|
11220
|
+
status = m.pass ? "verified" : "failed";
|
|
11221
|
+
provenBy = m.name;
|
|
11222
|
+
} else status = "declared";
|
|
11223
|
+
}
|
|
11224
|
+
return { kind, id: o.id, status, provenBy };
|
|
11225
|
+
};
|
|
11226
|
+
const obligations = [...ast.guarantees.map((g) => build("guarantee", g)), ...ast.neverRules.map((n) => build("prohibition", n))];
|
|
11227
|
+
return { obligations, tests: t, failed: obligations.filter((o) => o.status === "failed").length };
|
|
11228
|
+
}
|
|
11229
|
+
var LOCKFILES = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "poetry.lock", "Pipfile.lock", "Cargo.lock", "go.sum", "Gemfile.lock", "composer.lock"];
|
|
11230
|
+
function proofFreshness(proof, environment) {
|
|
11231
|
+
let head = null;
|
|
11232
|
+
try {
|
|
11233
|
+
head = (0, import_node_child_process.execSync)("git rev-parse HEAD", { encoding: "utf8", stdio: ["pipe", "pipe", "ignore"] }).trim() || null;
|
|
11234
|
+
} catch {
|
|
11235
|
+
head = null;
|
|
11236
|
+
}
|
|
11237
|
+
let lock = null, dir = process.cwd();
|
|
11238
|
+
for (let i = 0; i < 6 && !lock; i++) {
|
|
11239
|
+
for (const lf of LOCKFILES) {
|
|
11240
|
+
const p = (0, import_node_path2.join)(dir, lf);
|
|
11241
|
+
if ((0, import_node_fs2.existsSync)(p)) {
|
|
11242
|
+
lock = p;
|
|
11243
|
+
break;
|
|
11244
|
+
}
|
|
11245
|
+
}
|
|
11246
|
+
const parent = (0, import_node_path2.dirname)(dir);
|
|
11247
|
+
if (parent === dir) break;
|
|
11248
|
+
dir = parent;
|
|
11249
|
+
}
|
|
11250
|
+
return {
|
|
11251
|
+
intentHash: proof.sourceHash,
|
|
11252
|
+
compilerVersion: proof.compilerVersion,
|
|
11253
|
+
implementation: head,
|
|
11254
|
+
dependencies: lock ? { file: (0, import_node_path2.basename)(lock), hash: sha256((0, import_node_fs2.readFileSync)(lock, "utf8")) } : null,
|
|
11255
|
+
environment: environment || null,
|
|
11256
|
+
generatedAt: proof.generatedAt
|
|
11257
|
+
};
|
|
11258
|
+
}
|
|
11259
|
+
var TOOLS = [
|
|
11260
|
+
{
|
|
11261
|
+
name: "intent_check",
|
|
11262
|
+
description: "Run ThunderLang semantic diagnostics on .intent source. Returns the diagnostics (codes, severity, messages) , the deterministic checks that catch missing verification, secrets on the bus, contradictions, and more.",
|
|
11263
|
+
inputSchema: { type: "object", required: ["source"], properties: { source: { ...str, description: "the .intent source" } } },
|
|
11264
|
+
run: ({ source }) => {
|
|
11265
|
+
const diagnostics = semanticDiagnostics(parseIntent(String(source)));
|
|
11266
|
+
return { ok: !diagnostics.some((d) => d.level === "error"), count: diagnostics.length, diagnostics };
|
|
11267
|
+
}
|
|
11268
|
+
},
|
|
11269
|
+
{
|
|
11270
|
+
name: "intent_verify_diff",
|
|
11271
|
+
description: "THE AI-LOOP GATE. Prove, deterministically, which of an intent's guarantees and never-rules a code change upholds or breaks. Returns verdict PASS or BLOCK. Blocks on regressions (a claim that held on `before` and broke on `after`) and guardrail hits (an added line pushing a protected secret into a log/response). Call this on your own proposed change before shipping it.",
|
|
11272
|
+
inputSchema: {
|
|
11273
|
+
type: "object",
|
|
11274
|
+
required: ["intent", "after"],
|
|
11275
|
+
properties: {
|
|
11276
|
+
intent: { ...str, description: "the .intent source (the contract)" },
|
|
11277
|
+
after: { ...str, description: "the proposed/changed code" },
|
|
11278
|
+
before: { ...str, description: "the code before the change (optional; enables regression detection)" },
|
|
11279
|
+
language: { ...str, description: `source language (default typescript). One of: ${SUPPORTED_LANGUAGES.join(", ")}` }
|
|
11280
|
+
}
|
|
11281
|
+
},
|
|
11282
|
+
run: ({ intent, after, before = null, language = "typescript" }) => verifyDiff(String(intent), { before: before == null ? null : String(before), after: String(after), language })
|
|
11283
|
+
},
|
|
11284
|
+
{
|
|
11285
|
+
name: "intent_prove",
|
|
11286
|
+
description: "Emit the durable intent-proof-v1 artifact for .intent source: per-claim verdicts (verified / failed / planned / needs_verification, each bound to the named test that proves it) plus the freshness tuple (intent hash, compiler version, commit, dependency lockfile) that lets `thunder verify` mark the proof STALE later. Mirrors `thunder prove`; an unverified claim never reads as passed. Call it after the gate passes to record WHAT was proven.",
|
|
11287
|
+
inputSchema: {
|
|
11288
|
+
type: "object",
|
|
11289
|
+
required: ["source"],
|
|
11290
|
+
properties: {
|
|
11291
|
+
source: { ...str, description: "the .intent source" },
|
|
11292
|
+
sourceFile: { ...str, description: "file name to record in the proof (default intent.thunder)" },
|
|
11293
|
+
environment: { ...str, description: "environment name to bind into the freshness tuple (optional)" }
|
|
11294
|
+
}
|
|
11295
|
+
},
|
|
11296
|
+
run: ({ source, sourceFile = "intent.thunder", environment }) => {
|
|
11297
|
+
const text = String(source);
|
|
11298
|
+
const ast = parseIntent(text);
|
|
11299
|
+
const diagnostics = semanticDiagnostics(ast);
|
|
11300
|
+
const resolved = resolveObligations(ast);
|
|
11301
|
+
const proof = buildProof(ast, {
|
|
11302
|
+
sourceFile: String(sourceFile),
|
|
11303
|
+
sourceHash: sha256(text),
|
|
11304
|
+
targetsRequested: ast.targets || [],
|
|
11305
|
+
targetsGenerated: [],
|
|
11306
|
+
diagnostics,
|
|
11307
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
11308
|
+
});
|
|
11309
|
+
const CLAIM_MAP = { verified: "verified", failed: "failed", declared: "planned", unverified: "needs_verification" };
|
|
11310
|
+
const byId = new Map(resolved.obligations.map((o) => [o.id, o]));
|
|
11311
|
+
const applyStatus = (claim) => {
|
|
11312
|
+
const o = byId.get(claim.id);
|
|
11313
|
+
return o ? { ...claim, status: CLAIM_MAP[o.status], provenBy: o.provenBy || null } : claim;
|
|
11314
|
+
};
|
|
11315
|
+
proof.guarantees = proof.guarantees.map(applyStatus);
|
|
11316
|
+
proof.neverRules = proof.neverRules.map(applyStatus);
|
|
11317
|
+
proof.freshness = proofFreshness(proof, environment);
|
|
11318
|
+
const ok = proof.verification.semanticPassed && resolved.tests.ok !== false && resolved.failed === 0;
|
|
11319
|
+
return { ok, proofId: `proof-${proof.sourceHash.replace("sha256:", "").slice(0, 6)}`, ...proof, tests: resolved.tests };
|
|
11320
|
+
}
|
|
11321
|
+
},
|
|
11322
|
+
{
|
|
11323
|
+
name: "intent_conform",
|
|
11324
|
+
description: 'Grade cross-target conformance (thunder-conformance-v1): the deterministic engine defines the canonical result every in-file test case must produce, and each target\'s outputs (passed via `results`) are graded against it. Same tests, every implementation , a diverging target case is a CONFORMANCE FAILURE. Mirrors `thunder conform`. Without `results`, targets honestly stay "declared", never "pass".',
|
|
11325
|
+
inputSchema: {
|
|
11326
|
+
type: "object",
|
|
11327
|
+
required: ["source"],
|
|
11328
|
+
properties: {
|
|
11329
|
+
source: { ...str, description: "the .intent source (with test blocks)" },
|
|
11330
|
+
targets: { type: "array", items: str, description: "target languages to grade (default: the targets the intent declares)" },
|
|
11331
|
+
results: { type: "object", description: 'per-target actual outputs to grade: {target: {"Test / case": result}}' }
|
|
11332
|
+
}
|
|
11333
|
+
},
|
|
11334
|
+
run: ({ source, targets = [], results = null }) => {
|
|
11335
|
+
const rep = buildConformance(parseIntent(String(source)), { targets: Array.isArray(targets) ? targets.map(String) : [], results });
|
|
11336
|
+
return { ok: rep.semanticFailures === 0 && rep.failures.length === 0, ...rep };
|
|
11337
|
+
}
|
|
11338
|
+
},
|
|
11339
|
+
{
|
|
11340
|
+
name: "intent_drift",
|
|
11341
|
+
description: "Check whether real code, as it exists TODAY, still satisfies its intent , the standing-guard complement to intent_verify_diff (no diff needed). Re-lifts the code and reports drift findings: guarantees with no matching evidence, never-rules with no guard, declared inputs missing from the signature, and new behavior the intent never declared. Mirrors `thunder drift`.",
|
|
11342
|
+
inputSchema: {
|
|
11343
|
+
type: "object",
|
|
11344
|
+
required: ["intent", "code"],
|
|
11345
|
+
properties: {
|
|
11346
|
+
intent: { ...str, description: "the approved .intent source (the contract)" },
|
|
11347
|
+
code: { ...str, description: "the implementation source as it exists now" },
|
|
11348
|
+
language: { ...str, description: `source language (default typescript). One of: ${SUPPORTED_LANGUAGES.join(", ")}` }
|
|
11349
|
+
}
|
|
11350
|
+
},
|
|
11351
|
+
run: ({ intent, code, language = "typescript" }) => checkDrift(String(intent), String(code), { language })
|
|
11352
|
+
},
|
|
11353
|
+
{
|
|
11354
|
+
name: "intent_draft",
|
|
11355
|
+
description: "Turn a STRUCTURED brief into a rigorous, canonically-formatted ThunderLang draft plus a review checklist of what a human must still fill in (unverified guarantees, unguarded secrets, missing goal). Use this after distilling a user request into structured fields; the draft is a proposal for human approval, never verified.",
|
|
11356
|
+
inputSchema: {
|
|
11357
|
+
type: "object",
|
|
11358
|
+
required: ["brief"],
|
|
11359
|
+
properties: { brief: { type: "object", description: "fields: mission, goal, actor, problem, guarantees[], neverRules[], inputs[{name,type}], outputs[], decisions[]" } }
|
|
11360
|
+
},
|
|
11361
|
+
run: ({ brief }) => draftIntent(brief || {})
|
|
11362
|
+
},
|
|
11363
|
+
{
|
|
11364
|
+
name: "intent_lift",
|
|
11365
|
+
description: "Lift source code into an inferred, humble ThunderLang draft (never claims verified). Covers the top languages. Use it to bootstrap intent from code you already have.",
|
|
11366
|
+
inputSchema: {
|
|
11367
|
+
type: "object",
|
|
11368
|
+
required: ["source"],
|
|
11369
|
+
properties: { source: { ...str, description: "the source code" }, language: { ...str, description: `source language (default typescript). One of: ${SUPPORTED_LANGUAGES.join(", ")}` } }
|
|
11370
|
+
},
|
|
11371
|
+
run: ({ source, language = "typescript" }) => {
|
|
11372
|
+
const r = liftSource(String(source), { language });
|
|
11373
|
+
return r.ok ? { ok: true, intent: r.intentText, summary: r.summary, diagnostics: r.diagnostics } : { ok: false, error: r.error };
|
|
11374
|
+
}
|
|
11375
|
+
},
|
|
11376
|
+
{
|
|
9045
11377
|
name: "intent_run",
|
|
9046
11378
|
description: "Evaluate a decision in .intent source against concrete inputs (FIRST-hit, with a per-rule trace). Deterministic , the intent itself decides.",
|
|
9047
11379
|
inputSchema: {
|
|
@@ -9073,50 +11405,132 @@ var TOOLS = [
|
|
|
9073
11405
|
description: "Explain a diagnostic code (area, severity, what it blocks). Accepts any code the compiler emits.",
|
|
9074
11406
|
inputSchema: { type: "object", required: ["code"], properties: { code: { ...str, description: "e.g. IL-SEC-001" } } },
|
|
9075
11407
|
run: ({ code }) => ALL_DIAGNOSTICS.find((r) => r.ruleId.toLowerCase() === String(code).toLowerCase()) || { code, found: false }
|
|
11408
|
+
},
|
|
11409
|
+
{
|
|
11410
|
+
name: "intent_read",
|
|
11411
|
+
description: `READ CODE YOU DON'T KNOW. Given source code (${READ_LANGUAGES.join(", ")}), returns each function and the decision rules it makes, as ThunderLang and plain English, plus errors raised and tests found. Inferred from code by pattern (no AI); anything it could not read is listed, never guessed. Optional search text and kind filters. Pass \`in\` to also rewrite each decision in a language the reader knows.`,
|
|
11412
|
+
inputSchema: {
|
|
11413
|
+
type: "object",
|
|
11414
|
+
required: ["source"],
|
|
11415
|
+
properties: {
|
|
11416
|
+
source: { ...str, description: "the source code" },
|
|
11417
|
+
language: { ...str, description: `source language; detected when omitted. One of: ${READ_LANGUAGES.join(", ")}` },
|
|
11418
|
+
query: { ...str, description: "free-text search over names, inputs, conditions, and answers" },
|
|
11419
|
+
kinds: { type: "array", items: { type: "string", enum: ["decision", "function", "error", "test"] }, description: "only these kinds" },
|
|
11420
|
+
in: { ...str, description: `rewrite decisions in this language: ${TRANSLATE_LANGUAGES.map((l) => l.key).join(", ")}` }
|
|
11421
|
+
}
|
|
11422
|
+
},
|
|
11423
|
+
run: ({ source, language, query = "", kinds = [], in: inLang }) => {
|
|
11424
|
+
const reading = readCode(String(source), { language });
|
|
11425
|
+
const items = searchReading(reading, { query, kinds }).map((it) => inLang && it.thunder ? { ...it, rewritten: { language: inLang, code: translateDecisions(parseIntent(it.thunder), inLang) } } : it);
|
|
11426
|
+
return { ...reading, items };
|
|
11427
|
+
}
|
|
11428
|
+
},
|
|
11429
|
+
{
|
|
11430
|
+
name: "intent_read_repo",
|
|
11431
|
+
description: `READ A WHOLE REPOSITORY (local only). Reads every ${READ_LANGUAGES.join(", ")} file under a folder (skipping dependency and build folders) into one index: HTTP routes, decisions, checks that fail or respond early, errors, and tests, each with file and line. Filter by text, kind (route, decision, guard, function, error, test), language, folder prefix, an answer the code gives or fails with (e.g. "Decline", "401", "NotFoundError"), or an input a rule uses. Answers "what does this app do?" and "where does it decide X?" without guessing.`,
|
|
11432
|
+
inputSchema: {
|
|
11433
|
+
type: "object",
|
|
11434
|
+
required: ["path"],
|
|
11435
|
+
properties: {
|
|
11436
|
+
path: { ...str, description: "folder to read (absolute, or relative to the server working directory)" },
|
|
11437
|
+
query: str,
|
|
11438
|
+
kinds: { type: "array", items: { type: "string", enum: ["route", "decision", "guard", "function", "error", "test"] } },
|
|
11439
|
+
languages: { type: "array", items: { type: "string", enum: READ_LANGUAGES } },
|
|
11440
|
+
folder: { ...str, description: "only files under this relative path prefix" },
|
|
11441
|
+
answer: { ...str, description: "only items that answer, fail, or respond with this value" },
|
|
11442
|
+
input: { ...str, description: "only decisions that use this input" },
|
|
11443
|
+
limit: { type: "number", description: "max items to return (default 50)" }
|
|
11444
|
+
}
|
|
11445
|
+
},
|
|
11446
|
+
run: ({ path, query = "", kinds = [], languages = [], folder = "", answer = "", input = "", limit = 50 }) => {
|
|
11447
|
+
const index = readRepo(collectReadableFiles((0, import_node_path3.resolve)(String(path))));
|
|
11448
|
+
const items = searchRepo(index, { query, kinds, languages, path: folder, answer, input });
|
|
11449
|
+
const { files, ...rest2 } = index;
|
|
11450
|
+
return { ...rest2, files: files.length, matched: items.length, items: items.slice(0, Math.max(1, Math.min(500, Number(limit) || 50))) };
|
|
11451
|
+
}
|
|
11452
|
+
},
|
|
11453
|
+
{
|
|
11454
|
+
name: "intent_promote",
|
|
11455
|
+
description: "Turn a decision recovered from code into a readable ThunderLang contract with starter examples chosen at every rule and threshold. The examples record what the code does TODAY (computed from the recovered rule), so a person must confirm each answer; after that, intent_verify_diff can hold every change to it. Give the source code and the decision (function) name.",
|
|
11456
|
+
inputSchema: {
|
|
11457
|
+
type: "object",
|
|
11458
|
+
required: ["source", "name"],
|
|
11459
|
+
properties: { source: { ...str, description: "the source code" }, name: { ...str, description: "the function whose decision to promote" }, language: { ...str, description: `one of: ${READ_LANGUAGES.join(", ")} (detected when omitted)` } }
|
|
11460
|
+
},
|
|
11461
|
+
run: ({ source, name, language }) => {
|
|
11462
|
+
const item2 = readCode(String(source), { language }).items.find((i) => i.name === name);
|
|
11463
|
+
if (!item2) return { ok: false, reason: `No function named ${name} was found.` };
|
|
11464
|
+
const p = promoteDecision(item2);
|
|
11465
|
+
return p.ok ? { ...p, examplesPass: previewHumanContract(p.source).tests } : p;
|
|
11466
|
+
}
|
|
11467
|
+
},
|
|
11468
|
+
{
|
|
11469
|
+
name: "intent_translate",
|
|
11470
|
+
description: `Generate readable, typed code for every decision in ThunderLang source, in ${TRANSLATE_LANGUAGES.map((l) => l.label).join(", ")}. Deterministic, no AI; the first matching rule wins in every language. Accepts canonical .thunder source or the readable contract notation.`,
|
|
11471
|
+
inputSchema: {
|
|
11472
|
+
type: "object",
|
|
11473
|
+
required: ["source", "language"],
|
|
11474
|
+
properties: { source: str, language: { type: "string", enum: TRANSLATE_LANGUAGES.map((l) => l.key) } }
|
|
11475
|
+
},
|
|
11476
|
+
run: ({ source, language }) => {
|
|
11477
|
+
const text = String(source);
|
|
11478
|
+
const canonical = /^\s*contract\s/m.test(text.split("\n").find((l) => l.trim() && !l.trim().startsWith("#")) || "") ? previewHumanContract(text).canonicalSource : text;
|
|
11479
|
+
return translateDecisions(parseIntent(canonical), language);
|
|
11480
|
+
}
|
|
11481
|
+
},
|
|
11482
|
+
{
|
|
11483
|
+
name: "intent_human",
|
|
11484
|
+
description: "Check a contract written in the readable notation (contract / purpose / decision Name(inputs) / when ... -> Outcome / examples). Runs every example and returns pass/fail per case plus the canonical .thunder source. Use it to write or review business rules with a person.",
|
|
11485
|
+
inputSchema: { type: "object", required: ["source"], properties: { source: str } },
|
|
11486
|
+
run: ({ source }) => previewHumanContract(String(source))
|
|
9076
11487
|
}
|
|
9077
11488
|
];
|
|
9078
11489
|
var MCP_TOOLS = TOOLS.map((t) => t.name);
|
|
9079
|
-
function
|
|
9080
|
-
const
|
|
9081
|
-
|
|
9082
|
-
const
|
|
9083
|
-
|
|
9084
|
-
|
|
9085
|
-
const { id, method, params } = msg || {};
|
|
11490
|
+
function createMcpHandler({ tools = MCP_TOOLS } = {}) {
|
|
11491
|
+
const allowed = TOOLS.filter((t) => tools.includes(t.name));
|
|
11492
|
+
const ok = (id2, result) => ({ jsonrpc: "2.0", id: id2, result });
|
|
11493
|
+
const err = (id2, code, message) => ({ jsonrpc: "2.0", id: id2 ?? null, error: { code, message } });
|
|
11494
|
+
return function handle(msg) {
|
|
11495
|
+
const { id: id2, method, params } = msg || {};
|
|
9086
11496
|
switch (method) {
|
|
9087
|
-
case "initialize":
|
|
9088
|
-
|
|
9089
|
-
|
|
11497
|
+
case "initialize": {
|
|
11498
|
+
const asked = params?.protocolVersion;
|
|
11499
|
+
const protocolVersion = SUPPORTED_PROTOCOLS.includes(asked) ? asked : PROTOCOL_VERSION;
|
|
11500
|
+
return ok(id2, { protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "thunderlang", version: COMPILER_VERSION } });
|
|
11501
|
+
}
|
|
9090
11502
|
case "notifications/initialized":
|
|
9091
11503
|
case "initialized":
|
|
9092
11504
|
case "notifications/cancelled":
|
|
9093
|
-
|
|
11505
|
+
return null;
|
|
9094
11506
|
// notifications , no response
|
|
9095
11507
|
case "ping":
|
|
9096
|
-
|
|
9097
|
-
break;
|
|
11508
|
+
return ok(id2, {});
|
|
9098
11509
|
case "tools/list":
|
|
9099
|
-
|
|
9100
|
-
break;
|
|
11510
|
+
return ok(id2, { tools: allowed.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });
|
|
9101
11511
|
case "tools/call": {
|
|
9102
|
-
const tool =
|
|
9103
|
-
if (!tool) {
|
|
9104
|
-
fail(id, -32602, `Unknown tool: ${params?.name}`);
|
|
9105
|
-
break;
|
|
9106
|
-
}
|
|
11512
|
+
const tool = allowed.find((t) => t.name === params?.name);
|
|
11513
|
+
if (!tool) return err(id2, -32602, `Unknown tool: ${params?.name}`);
|
|
9107
11514
|
try {
|
|
9108
11515
|
const result = tool.run(params.arguments || {});
|
|
9109
11516
|
const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
|
|
9110
|
-
|
|
11517
|
+
return ok(id2, { content: [{ type: "text", text }] });
|
|
9111
11518
|
} catch (e) {
|
|
9112
|
-
|
|
11519
|
+
return ok(id2, { content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true });
|
|
9113
11520
|
}
|
|
9114
|
-
break;
|
|
9115
11521
|
}
|
|
9116
11522
|
default:
|
|
9117
|
-
|
|
11523
|
+
return id2 != null ? err(id2, -32601, `Method not found: ${method}`) : null;
|
|
9118
11524
|
}
|
|
9119
|
-
}
|
|
11525
|
+
};
|
|
11526
|
+
}
|
|
11527
|
+
function startMcpServer({ readable = process.stdin, writable = process.stdout } = {}) {
|
|
11528
|
+
const respondTo = createMcpHandler();
|
|
11529
|
+
const handle = (msg) => {
|
|
11530
|
+
const reply = respondTo(msg);
|
|
11531
|
+
if (reply) writable.write(`${JSON.stringify(reply)}
|
|
11532
|
+
`);
|
|
11533
|
+
};
|
|
9120
11534
|
let buffer = "";
|
|
9121
11535
|
readable.on("data", (chunk) => {
|
|
9122
11536
|
buffer += chunk.toString("utf8");
|
|
@@ -9287,11 +11701,11 @@ function implementationHash(regionCode) {
|
|
|
9287
11701
|
}
|
|
9288
11702
|
function buildImplementationPrompt(ast, { language = "typescript" } = {}) {
|
|
9289
11703
|
const impl = ast.implementation || {};
|
|
9290
|
-
const
|
|
9291
|
-
const { open, close } = renderMarker({ id, mission: ast.mission, status: "generated" }, language);
|
|
11704
|
+
const id2 = impl.id || slug(ast.mission || "implementation");
|
|
11705
|
+
const { open, close } = renderMarker({ id: id2, mission: ast.mission, status: "generated" }, language);
|
|
9292
11706
|
const list = (arr) => arr && arr.length ? arr.map((x) => `- ${x}`).join("\n") : "- (none)";
|
|
9293
11707
|
return [
|
|
9294
|
-
`# Implement: ${ast.mission} (id: ${
|
|
11708
|
+
`# Implement: ${ast.mission} (id: ${id2})`,
|
|
9295
11709
|
"",
|
|
9296
11710
|
`You are implementing one function/region for the mission "${ast.mission}". Follow the contract EXACTLY.`,
|
|
9297
11711
|
"",
|
|
@@ -9375,14 +11789,14 @@ var APPROVALS_SCHEMA_VERSION = "1.0";
|
|
|
9375
11789
|
function emptyApprovals() {
|
|
9376
11790
|
return { schemaVersion: APPROVALS_SCHEMA_VERSION, approvals: {} };
|
|
9377
11791
|
}
|
|
9378
|
-
function approvalFor(store,
|
|
9379
|
-
return store && store.approvals && store.approvals[
|
|
11792
|
+
function approvalFor(store, id2) {
|
|
11793
|
+
return store && store.approvals && store.approvals[id2] || null;
|
|
9380
11794
|
}
|
|
9381
|
-
function recordDecision2(store,
|
|
11795
|
+
function recordDecision2(store, id2, { decision, by, role, note, contractHash: cH, implementationHash: iH, at }) {
|
|
9382
11796
|
if (!["approved", "rejected"].includes(decision)) return { error: `Unknown decision "${decision}".` };
|
|
9383
11797
|
if (!cH || !iH) return { error: "Cannot record a decision without current contract + implementation hashes." };
|
|
9384
11798
|
const record2 = { decision, by: by || null, role: role || null, note: note || null, contractHash: cH, implementationHash: iH, at: at || null };
|
|
9385
|
-
const next = { ...emptyApprovals(), ...store, approvals: { ...store?.approvals || {}, [
|
|
11799
|
+
const next = { ...emptyApprovals(), ...store, approvals: { ...store?.approvals || {}, [id2]: record2 } };
|
|
9386
11800
|
return { store: next, record: record2 };
|
|
9387
11801
|
}
|
|
9388
11802
|
function productionGate(resolved, { allowPending = false } = {}) {
|
|
@@ -9392,19 +11806,19 @@ function productionGate(resolved, { allowPending = false } = {}) {
|
|
|
9392
11806
|
});
|
|
9393
11807
|
return { ok: blocking.length === 0, blocking, total: resolved.length };
|
|
9394
11808
|
}
|
|
9395
|
-
function adoptRegion(code,
|
|
11809
|
+
function adoptRegion(code, id2, language = "typescript") {
|
|
9396
11810
|
const { regions } = parseMarkers(code);
|
|
9397
|
-
const region = regions.find((r) => r.id ===
|
|
11811
|
+
const region = regions.find((r) => r.id === id2 && r.token === OPEN_TOKEN);
|
|
9398
11812
|
if (!region) return null;
|
|
9399
11813
|
const lines = String(code).split("\n");
|
|
9400
11814
|
const { open, close } = renderMarker(
|
|
9401
|
-
{ id, mission: region.attrs.mission, origin: "ai", ownership: "human" },
|
|
11815
|
+
{ id: id2, mission: region.attrs.mission, origin: "ai", ownership: "human" },
|
|
9402
11816
|
language,
|
|
9403
11817
|
{ token: ADOPTED_TOKEN }
|
|
9404
11818
|
);
|
|
9405
11819
|
lines[region.startLine - 1] = open;
|
|
9406
11820
|
lines[region.endLine - 1] = close;
|
|
9407
|
-
return { code: lines.join("\n"), adopted:
|
|
11821
|
+
return { code: lines.join("\n"), adopted: id2 };
|
|
9408
11822
|
}
|
|
9409
11823
|
var MANIFEST_SCHEMA_VERSION = "1.0";
|
|
9410
11824
|
function defaultApproval(impl) {
|
|
@@ -9416,9 +11830,9 @@ function buildManifest(files, opts = {}) {
|
|
|
9416
11830
|
for (const f of files) {
|
|
9417
11831
|
const impl = f.ast?.implementation;
|
|
9418
11832
|
if (!impl) continue;
|
|
9419
|
-
const
|
|
11833
|
+
const id2 = impl.id || slug(f.ast.mission || "unnamed");
|
|
9420
11834
|
implementations.push({
|
|
9421
|
-
id,
|
|
11835
|
+
id: id2,
|
|
9422
11836
|
mission: f.ast.mission || null,
|
|
9423
11837
|
sourceLocation: f.path || null,
|
|
9424
11838
|
targetLocation: impl.target || impl.targetLocation || null,
|
|
@@ -9431,7 +11845,7 @@ function buildManifest(files, opts = {}) {
|
|
|
9431
11845
|
contractHash: contractHash(f.ast),
|
|
9432
11846
|
implementationHash: null,
|
|
9433
11847
|
generationId: null,
|
|
9434
|
-
proofLocation: `.intent/proofs/${
|
|
11848
|
+
proofLocation: `.intent/proofs/${id2}.json`,
|
|
9435
11849
|
mayModify: impl.mayModify || [`${f.ast.mission}.body`],
|
|
9436
11850
|
mustNotModify: impl.mustNotModify || [`${f.ast.mission}.contract`]
|
|
9437
11851
|
});
|
|
@@ -9504,7 +11918,7 @@ function startLspServer({ readable = process.stdin, writable = process.stdout }
|
|
|
9504
11918
|
`);
|
|
9505
11919
|
writable.write(payload);
|
|
9506
11920
|
};
|
|
9507
|
-
const respond = (
|
|
11921
|
+
const respond = (id2, result) => send({ jsonrpc: "2.0", id: id2, result });
|
|
9508
11922
|
const notify = (method, params) => send({ jsonrpc: "2.0", method, params });
|
|
9509
11923
|
const publish = (uri) => {
|
|
9510
11924
|
const lines = (docs.get(uri) || "").split("\n");
|