yichus 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -16
- package/dist/cli.js +17 -2123
- package/dist/cli.js.map +1 -1
- package/dist/main.js +3762 -0
- package/dist/main.js.map +1 -0
- package/dist/studio-page/dom.js +22 -0
- package/dist/studio-page/label-fit.js +7 -0
- package/dist/studio-page/layer-diagram.js +458 -0
- package/dist/studio-page/layer-groups.js +129 -0
- package/dist/studio-page/source-link.js +17 -0
- package/dist/studio-page/studio-views.js +256 -0
- package/dist/studio-page/system-map-record.js +124 -10
- package/dist/studio-page/system-map.js +476 -87
- package/dist/studio-page/what-happens-record.js +224 -0
- package/dist/studio-page/what-happens.js +771 -0
- package/dist/studio-reference/balance-listed-laws.bosatsu +29 -0
- package/dist/studio-reference/balance.bosatsu +7 -0
- package/dist/studio-reference/calculator.md +20 -0
- package/dist/studio-reference/consent-laws.bosatsu +37 -0
- package/dist/studio-reference/consent.bosatsu +15 -0
- package/dist/studio-reference/deploy-platforms.md +79 -0
- package/dist/studio-reference/laws.md +62 -0
- package/dist/studio-reference/portable-programs.md +58 -0
- package/dist/studio-reference/porting.md +34 -0
- package/dist/studio-reference/protocol-cases.md +11 -0
- package/dist/studio-reference/{protocol-specification.txt → protocol-specification.md} +16 -18
- package/dist/studio-reference/refund-desk-one-round.bosatsu +196 -0
- package/dist/studio-reference/refund-desk.bosatsu +194 -0
- package/dist/studio-reference/refund-policy.bosatsu +97 -0
- package/dist/studio-reference/refund-test.bosatsu +75 -0
- package/dist/studio-reference/render.yaml +42 -0
- package/dist/studio-reference/server.mjs +33 -0
- package/dist/studio-reference/store.mjs +16 -0
- package/dist/studio-reference/the-page.md +130 -0
- package/dist/studio-reference/worker-authority.md +159 -0
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,2132 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
// src/run.ts
|
|
8
|
-
import fs5 from "fs";
|
|
9
|
-
import path6 from "path";
|
|
10
|
-
import { isDeepStrictEqual, parseArgs as parseArgs2 } from "util";
|
|
11
|
-
import { z as z7 } from "zod";
|
|
12
|
-
|
|
13
|
-
// src/engine-results.ts
|
|
14
|
-
import { z } from "zod";
|
|
15
|
-
var PropertyStatus = z.enum(["proven", "warning", "violated", "blocked"]);
|
|
16
|
-
var Property = z.looseObject({
|
|
17
|
-
id: z.string(),
|
|
18
|
-
title: z.string().optional(),
|
|
19
|
-
status: PropertyStatus,
|
|
20
|
-
details: z.array(z.string()),
|
|
21
|
-
// The declared assumption an accepted warning rests on, e.g. "instances=1".
|
|
22
|
-
accepted: z.string().optional()
|
|
23
|
-
});
|
|
24
|
-
var VerifyResult = z.looseObject({
|
|
25
|
-
topology: z.string().optional(),
|
|
26
|
-
verdict: z.looseObject({
|
|
27
|
-
properties: z.array(Property),
|
|
28
|
-
errors: z.array(z.string()).default([]),
|
|
29
|
-
// Present only when the caller passed block_on_warnings: the warnings
|
|
30
|
-
// among the listed properties, which made the verdict not proven.
|
|
31
|
-
blockedWarnings: z.array(z.string()).optional()
|
|
32
|
-
})
|
|
33
|
-
});
|
|
34
|
-
var VerdictErrors = z.object({ verdict: z.object({ errors: z.array(z.string()) }) });
|
|
35
|
-
var EngineError = z.object({ error: z.string(), errorKinds: z.array(z.string()).optional() });
|
|
36
|
-
var Count = z.int().nonnegative();
|
|
37
|
-
var AbstractionMap = z.looseObject({
|
|
38
|
-
measures: z.looseObject({
|
|
39
|
-
definitions: Count,
|
|
40
|
-
edges: Count,
|
|
41
|
-
layers: Count,
|
|
42
|
-
layerSkips: Count,
|
|
43
|
-
usedOnce: Count,
|
|
44
|
-
usedMany: Count,
|
|
45
|
-
clonePairs: Count,
|
|
46
|
-
duplicatedMass: Count,
|
|
47
|
-
maxSize: Count,
|
|
48
|
-
largestDefinition: z.string().optional()
|
|
49
|
-
})
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
// src/verdict.ts
|
|
53
|
-
var title = (p) => p.title ?? p.id;
|
|
54
|
-
var MEANING = {
|
|
55
|
-
proven: "holds for every input",
|
|
56
|
-
warning: "holds only under the acceptance its details name",
|
|
57
|
-
violated: "is broken; the details are the evidence",
|
|
58
|
-
blocked: "was not checked: the check could not run, could not finish, or could not see its subject"
|
|
59
|
-
};
|
|
60
|
-
var ACCEPTANCE = {
|
|
61
|
-
"instances=1": "Safe while you run one instance (--instances 1). Before running more than one:"
|
|
3
|
+
// package.json
|
|
4
|
+
var engines = {
|
|
5
|
+
node: ">=20"
|
|
62
6
|
};
|
|
63
|
-
var acceptance = (a) => ACCEPTANCE[a] ?? `Safe under the declared ${a}. Before dropping it:`;
|
|
64
|
-
var label = (p) => p.status === "warning" && p.accepted !== void 0 ? "accepted" : p.status;
|
|
65
|
-
var indent = (text3, prefix) => text3.split("\n").map((line) => prefix + line).join("\n");
|
|
66
|
-
function count(props) {
|
|
67
|
-
const order = [];
|
|
68
|
-
const counts = /* @__PURE__ */ new Map();
|
|
69
|
-
for (const p of props) {
|
|
70
|
-
const status = label(p);
|
|
71
|
-
if (!counts.has(status)) order.push(status);
|
|
72
|
-
counts.set(status, (counts.get(status) ?? 0) + 1);
|
|
73
|
-
}
|
|
74
|
-
return order.map((status) => `${counts.get(status)} ${status}`).join(", ");
|
|
75
|
-
}
|
|
76
|
-
function verifySummary(result, proven, artifact) {
|
|
77
|
-
const parsed = VerifyResult.safeParse(result);
|
|
78
|
-
if (!parsed.success) {
|
|
79
|
-
const said = EngineError.safeParse(result);
|
|
80
|
-
const reason = said.success ? ` The engine said: ${said.data.error}` : "";
|
|
81
|
-
const errors2 = VerdictErrors.safeParse(result);
|
|
82
|
-
const lines2 = [
|
|
83
|
-
proven ? "Proven, but the verdict has no readable property list." : `Not proven. The engine returned no readable verdict.${reason}`
|
|
84
|
-
];
|
|
85
|
-
if (errors2.success && errors2.data.verdict.errors.length)
|
|
86
|
-
lines2.push("Errors:", ...errors2.data.verdict.errors.map((e) => indent(e, " ")));
|
|
87
|
-
lines2.push(`The full result is in ${artifact}.`);
|
|
88
|
-
return `${lines2.join("\n")}
|
|
89
|
-
`;
|
|
90
|
-
}
|
|
91
|
-
const checked = parsed.data.verdict.properties;
|
|
92
|
-
const errors = parsed.data.verdict.errors;
|
|
93
|
-
const topology2 = parsed.data.topology !== void 0 ? ` Topology: ${parsed.data.topology}.` : "";
|
|
94
|
-
const lines = [];
|
|
95
|
-
if (proven) {
|
|
96
|
-
lines.push(`Proven: ${checked.length} properties checked (${count(checked)}).${topology2}`);
|
|
97
|
-
} else {
|
|
98
|
-
lines.push(`Not proven: ${checked.length} properties checked (${count(checked)}).${topology2}`);
|
|
99
|
-
const blocking = new Set(parsed.data.verdict.blockedWarnings ?? []);
|
|
100
|
-
const first = checked.find((p) => p.status === "violated") ?? checked.find((p) => p.status !== "proven" && p.status !== "warning") ?? checked.find((p) => blocking.has(p.id));
|
|
101
|
-
if (first) {
|
|
102
|
-
const why = blocking.has(first.id) && first.status === "warning" ? " It blocks because --block-on-warning named it." : "";
|
|
103
|
-
lines.push(`First failure (${first.status}): ${title(first)}. This property ${MEANING[first.status]}.${why}`);
|
|
104
|
-
for (const detail of first.details) lines.push(indent(detail, " "));
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
lines.push("Every property:");
|
|
108
|
-
const width = Math.max(...checked.map((p) => label(p).length));
|
|
109
|
-
for (const p of checked) {
|
|
110
|
-
lines.push(` ${label(p).padEnd(width)} ${title(p)}`);
|
|
111
|
-
const pad = ` ${" ".repeat(width)} `;
|
|
112
|
-
if (p.status === "warning" && p.accepted !== void 0) lines.push(pad + acceptance(p.accepted));
|
|
113
|
-
if (p.status === "warning") for (const detail of p.details) lines.push(indent(detail, pad));
|
|
114
|
-
}
|
|
115
|
-
const shown2 = new Set(checked.flatMap((p) => p.details));
|
|
116
|
-
const unshown = errors.filter((e) => !shown2.has(e));
|
|
117
|
-
if (unshown.length) lines.push("Errors:", ...unshown.map((e) => indent(e, " ")));
|
|
118
|
-
lines.push(`The full verdict, with every property's details, is in ${artifact}.`);
|
|
119
|
-
return `${lines.join("\n")}
|
|
120
|
-
`;
|
|
121
|
-
}
|
|
122
7
|
|
|
123
|
-
// src/
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
"axiom-audit": "checker",
|
|
131
|
-
"not-admitted": "checker",
|
|
132
|
-
"runtime-missing": "harness",
|
|
133
|
-
timeout: "harness",
|
|
134
|
-
"runtime-error": "harness"
|
|
135
|
-
};
|
|
136
|
-
var DEFAULT_TIMEOUT_MS = 18e4;
|
|
137
|
-
var MAX_TIMEOUT_MS = 3e5;
|
|
138
|
-
function remedy(cause, timeoutMs, files) {
|
|
139
|
-
const sources = files.map((f) => `--source ${f}`).join(" ");
|
|
140
|
-
switch (cause) {
|
|
141
|
-
case "runtime-missing":
|
|
142
|
-
return [
|
|
143
|
-
"Install the pinned runtime once (about 290 MB to download), then pass that folder as --lean-wasm-root:",
|
|
144
|
-
` ${LEAN_WASM_INSTALL_COMMAND.replace("NEW_DIRECTORY", "/absolute/new/folder")}`
|
|
145
|
-
];
|
|
146
|
-
case "timeout":
|
|
147
|
-
return [timeoutMs < MAX_TIMEOUT_MS ? `The ${timeoutMs} ms budget ran out before Lean finished. Rerun with a larger --timeout-ms (the default is ${DEFAULT_TIMEOUT_MS}, the most is ${MAX_TIMEOUT_MS}).` : `The ${timeoutMs} ms budget, the most allowed, ran out before Lean finished. Split the laws across separate files and check them one at a time.`];
|
|
148
|
-
case "runtime-error":
|
|
149
|
-
return [
|
|
150
|
-
"The Lean Wasm runtime could not run. If it was changed or only partly installed, install a fresh copy into a new folder:",
|
|
151
|
-
` ${LEAN_WASM_INSTALL_COMMAND.replace("NEW_DIRECTORY", "/absolute/new/folder")}`
|
|
152
|
-
];
|
|
153
|
-
case "rejected":
|
|
154
|
-
return [
|
|
155
|
-
"A rejected theorem means the law fails for some input, its witness matches no value, or the generated Lean is wrong; Lean's words above say which.",
|
|
156
|
-
`To see a failing input, run: yichus call api_law_check ${sources}. Fix the code, not the law.`
|
|
157
|
-
];
|
|
158
|
-
case "axiom-audit":
|
|
159
|
-
return ["Lean accepted the theorem, but its axiom audit was missing or named an axiom other than propext, Classical.choice and Quot.sound, so it is not counted as proven."];
|
|
160
|
-
case "not-admitted":
|
|
161
|
-
return [`Lean Wasm proves Bool and structural List[Bool] laws with one direct witness. Check other laws with: yichus call api_law_check ${sources}`];
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
var unreadable = (artifact, why) => ({
|
|
165
|
-
exit: 2,
|
|
166
|
-
text: `Not checked: the Lean result could not be read (${why}). The full result is in ${artifact}.
|
|
167
|
-
`
|
|
168
|
-
});
|
|
169
|
-
var EngineError2 = z2.object({ ok: z2.literal(false), error: z2.string().min(1), proof: z2.undefined().optional() });
|
|
170
|
-
var issue = (error) => {
|
|
171
|
-
const first = error.issues[0];
|
|
172
|
-
return first.path.length ? `${first.path.join(".")}: ${first.message}` : first.message;
|
|
173
|
-
};
|
|
174
|
-
function leanSummary(raw, artifact, timeoutMs, files) {
|
|
175
|
-
const refused = EngineError2.safeParse(raw);
|
|
176
|
-
if (refused.success) return unreadable(artifact, `the engine said: ${refused.data.error}`);
|
|
177
|
-
const parsed = LeanCheckResult.safeParse(raw);
|
|
178
|
-
if (!parsed.success) return unreadable(artifact, issue(parsed.error));
|
|
179
|
-
const proof = parsed.data.proof;
|
|
180
|
-
const laws = proof.obligations;
|
|
181
|
-
const lines = [];
|
|
182
|
-
if (proof.status === "verified") {
|
|
183
|
-
lines.push(`Proven: ${plural(laws.length, "law")} verified by the pinned Lean Wasm kernel.`);
|
|
184
|
-
for (const row of laws) {
|
|
185
|
-
if (row.status !== "verified") continue;
|
|
186
|
-
const { check, witness, domain } = row.proof.subject;
|
|
187
|
-
lines.push(` ${row.binding}: ${check} holds for ${domain}, and ${witness} holds for at least one.`);
|
|
188
|
-
}
|
|
189
|
-
lines.push(`The proof receipt is in ${artifact}. It is a local Wasm kernel check (independentKernelReplay: false).`);
|
|
190
|
-
return { exit: 0, text: `${lines.join("\n")}
|
|
191
|
-
` };
|
|
192
|
-
}
|
|
193
|
-
if (!laws.length) {
|
|
194
|
-
const cause = proof.cause;
|
|
195
|
-
const checker2 = SIDE[cause] === "checker";
|
|
196
|
-
lines.push(`${checker2 ? "Not proven" : "Not checked"}: ${proof.reason}.`);
|
|
197
|
-
if (cause === "not-admitted") lines.push("Fix the source, or add a Yichus/Law Obligation for lean to prove.");
|
|
198
|
-
else lines.push(...remedy(cause, timeoutMs, files));
|
|
199
|
-
lines.push(`The full result is in ${artifact}.`);
|
|
200
|
-
return { exit: checker2 ? 1 : 2, text: `${lines.join("\n")}
|
|
201
|
-
` };
|
|
202
|
-
}
|
|
203
|
-
const failed = laws.flatMap((row) => row.status === "inconclusive" ? [row] : []);
|
|
204
|
-
const causes = [...new Set(failed.map((row) => row.cause))];
|
|
205
|
-
const checker = causes.some((cause) => SIDE[cause] === "checker");
|
|
206
|
-
lines.push(checker ? `Not proven: ${failed.length} of ${plural(laws.length, "law")} did not verify.` : `Not checked: ${failed.length} of ${plural(laws.length, "law")} could not be checked.`);
|
|
207
|
-
for (const row of laws) {
|
|
208
|
-
if (row.status === "verified") {
|
|
209
|
-
lines.push(` verified ${row.binding}`);
|
|
210
|
-
continue;
|
|
211
|
-
}
|
|
212
|
-
lines.push(` ${row.cause.padEnd(12)} ${row.binding}: ${row.reason}.`);
|
|
213
|
-
if (row.diagnostics?.length) lines.push(" Lean said:", ...row.diagnostics.map((d) => indent2(d, " ")));
|
|
214
|
-
}
|
|
215
|
-
for (const cause of causes) lines.push(...remedy(cause, timeoutMs, files));
|
|
216
|
-
lines.push(`The full result is in ${artifact}.`);
|
|
217
|
-
return { exit: checker ? 1 : 2, text: `${lines.join("\n")}
|
|
218
|
-
` };
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// src/call-summary.ts
|
|
222
|
-
var plural2 = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
223
|
-
function mapSummary(result) {
|
|
224
|
-
const parsed = AbstractionMap.safeParse(result);
|
|
225
|
-
if (!parsed.success) return ["The map has no readable measures block; read the JSON for its contents."];
|
|
226
|
-
const m = parsed.data.measures;
|
|
227
|
-
const lines = [
|
|
228
|
-
`Layers: ${plural2(m.definitions, "definition")} stacked ${plural2(m.layers, "layer")} deep (a definition sits one layer above the highest one it uses).`,
|
|
229
|
-
m.layerSkips === 0 ? `Layer skips: none of the ${plural2(m.edges, "dependency edge")} reaches past the layer just below.` : `Layer skips: ${m.layerSkips} of ${plural2(m.edges, "dependency edge")} reach past the layer just below, using a definition two or more layers down; they are the "edges" with "span" above 1.`,
|
|
230
|
-
`Reuse: ${plural2(m.usedMany, "definition is", "definitions are")} used by several others, ${m.usedOnce} by exactly one (each node's "fanIn").`,
|
|
231
|
-
m.clonePairs === 0 ? "Copies: no two definitions have the same compiled body." : `Copies: ${plural2(m.clonePairs, "pair")} of definitions have the same compiled body; see "clonePairs".`,
|
|
232
|
-
m.duplicatedMass === 0 ? "Repeats: no block of code repeats inside a definition." : `Repeats: blocks repeated inside one definition add ${plural2(m.duplicatedMass, "node")}; nodes with "repeatedBlockMass" above 0 list each block's places in "repeatedBlocks".`
|
|
233
|
-
];
|
|
234
|
-
if (m.largestDefinition !== void 0)
|
|
235
|
-
lines.push(`Largest definition: ${m.largestDefinition} (${m.maxSize} nodes).`);
|
|
236
|
-
return lines;
|
|
237
|
-
}
|
|
238
|
-
var SUMMARIES = {
|
|
239
|
-
api_abstraction_map: {
|
|
240
|
-
noun: "the abstraction map",
|
|
241
|
-
progress: (files) => `Mapping ${files === void 0 ? "the program" : plural2(files, "Bosatsu file")}: compiling it and measuring every definition, which can take half a minute or more for a large program...`,
|
|
242
|
-
summary: mapSummary
|
|
243
|
-
}
|
|
244
|
-
};
|
|
245
|
-
function callProgress(tool, files) {
|
|
246
|
-
const known = SUMMARIES[tool];
|
|
247
|
-
return known ? `${known.progress(files)}
|
|
248
|
-
` : void 0;
|
|
249
|
-
}
|
|
250
|
-
function callSummary(tool, result, output) {
|
|
251
|
-
const known = SUMMARIES[tool];
|
|
252
|
-
const lines = [];
|
|
253
|
-
if (output) lines.push(`Wrote ${known?.noun ?? `the ${tool} result`} to ${output}.`);
|
|
254
|
-
if (known) lines.push(...known.summary(result));
|
|
255
|
-
return lines.length ? `${lines.join("\n")}
|
|
256
|
-
` : void 0;
|
|
257
|
-
}
|
|
258
|
-
var NEXT_STEP = {
|
|
259
|
-
"duplicate-package": "Each package can be declared by only one file. Give each file its own package name, or pass only one of them."
|
|
260
|
-
};
|
|
261
|
-
function callFailure(tool, result, artifact) {
|
|
262
|
-
const said = EngineError.safeParse(result);
|
|
263
|
-
const lines = said.success ? [`${tool} failed:`, said.data.error] : [`${tool} failed without saying why.`];
|
|
264
|
-
if (said.success) {
|
|
265
|
-
for (const kind of said.data.errorKinds ?? []) if (Object.hasOwn(NEXT_STEP, kind)) lines.push(`Next: ${NEXT_STEP[kind]}`);
|
|
266
|
-
}
|
|
267
|
-
lines.push(`The full result is in ${artifact}.`);
|
|
268
|
-
return `${lines.join("\n")}
|
|
269
|
-
`;
|
|
8
|
+
// src/node-version.ts
|
|
9
|
+
function nodeVersionProblem(running, required) {
|
|
10
|
+
const floor = /^>=(\d+)$/.exec(required);
|
|
11
|
+
if (!floor) throw new Error(`engines.node must read >=N, not ${required}`);
|
|
12
|
+
const needed = Number(floor[1]);
|
|
13
|
+
if (Number(running.split(".")[0]) >= needed) return void 0;
|
|
14
|
+
return `yichus needs Node ${needed} or newer; this is Node ${running}. Install Node ${needed} or newer and run the command again.`;
|
|
270
15
|
}
|
|
271
16
|
|
|
272
|
-
// src/
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
// src/studio/director.ts
|
|
277
|
-
import fs3 from "fs";
|
|
278
|
-
import path3 from "path";
|
|
279
|
-
import { z as z5 } from "zod";
|
|
280
|
-
|
|
281
|
-
// ../../web/system-map-record.js
|
|
282
|
-
var MARKS_VERSION = "yichus-marks-2";
|
|
283
|
-
var VOCABULARY = {
|
|
284
|
-
version: MARKS_VERSION,
|
|
285
|
-
fixedPlaces: {
|
|
286
|
-
callers: "left of the wall: one glyph per transport kind, HTTP above, importer below, each with a bracket over the openings it calls; the kind the program lacks is the same glyph struck through <- callers[], ghostCallers[]",
|
|
287
|
-
openings: "the left wall: one opening per entry <- entries[]",
|
|
288
|
-
hullBand: "the middle band of the wall: wrappers sit here and nowhere else; empty band = no entry goes through a shared wrapper <- wrappers[]",
|
|
289
|
-
afterBand: "between the hull band and the reply bars: work an entry does after its wrapper returns, with its stations and checks; empty = none <- entries[].beside",
|
|
290
|
-
replyBars: "one bar per entry at the same x, past the hull band <- entries[]",
|
|
291
|
-
rail: "the bottom of the wall: a handle handed in from outside, with a riser to each use; a ? on the rail where a use is handed in on some paths only <- uses[how=handed|mixed]",
|
|
292
|
-
rack: "right of the wall: db, model, net, always in this order; struck = the engine checked and found none <- resources[], ghostResources[]",
|
|
293
|
-
quietLine: "bottom inside the wall: parts on no entry path, one stretch per package, with their forks, sockets, generic letters and steps <- keyed[], library.applied[], steps[]"
|
|
294
|
-
},
|
|
295
|
-
marks: {
|
|
296
|
-
entryHead: "arrowhead at an opening; solid = the entry writes, hollow = it only reads <- entries[].writes",
|
|
297
|
-
lock: "closed padlock by the path: sign-in with a secret key; open padlock with a raised shackle: a publishable key may call it <- entries[].authority",
|
|
298
|
-
role: "red word beside the lock: a role beyond sign-in <- entries[].roles",
|
|
299
|
-
limit: "gauge beside the path: a declared rate limit <- entries[].limits",
|
|
300
|
-
station: "ring on a path: code touching a table, with the verb and table beside it; filled = writes <- entries[].reach, wrappers[].effects, entries[].beside.effects",
|
|
301
|
-
modelRing: "violet ring: the entry reaches the model; the count under the model says how many entries do <- entries[].model",
|
|
302
|
-
netRing: "orange ring: the entry reaches the network <- entries[].net",
|
|
303
|
-
guard: "red diamond on the path where the check happens, its name above, failure stem below <- entries[].guards, wrappers[].guards, entries[].passed[].guards, entries[].beside.guards",
|
|
304
|
-
hull: "translucent region in the hull band: paths merge into it, run one shared stretch, and split; everything inside it runs inside the wrapper <- wrappers[]",
|
|
305
|
-
socket: "broken-rim ring: a function the caller hands in runs here; its centre fills like a station <- entries[].passed[]",
|
|
306
|
-
token: "small grey word under a path: the value the caller fixes for the wrapper <- entries[].policy",
|
|
307
|
-
afterDot: "dot in the after band: a call the entry makes after its wrapper returns <- entries[].beside.calls",
|
|
308
|
-
builder: "plus-disc under a station with the call that builds the handle there <- uses[how=local].builtBy",
|
|
309
|
-
unknown: "a ? in a circle on the rail: the engine traced the handle only on some paths <- uses[how=mixed]",
|
|
310
|
-
fork: "three prongs and a type: a choice keyed on a plain String or Int; under the mark that makes it, else on the quiet line <- keyed[]",
|
|
311
|
-
bundle: "one cable with a count: entries with the same wrapper and identical marks; its title names every route; opening it draws each one <- bundles[]",
|
|
312
|
-
anchor: "where the rail starts: platform when no definition of the program can make the handle; ? when the trace stops and the program could <- uses[].anchor",
|
|
313
|
-
step: "loop arc with a type on the quiet line: functions of the package take that type and return it <- steps[]",
|
|
314
|
-
loop: "loop arc with package names: packages whose types lead back to themselves <- phases.cycles",
|
|
315
|
-
composes: "hull round a chain: a definition takes the type the chain hands in at each step and applies it <- library.applied[].fedBy",
|
|
316
|
-
port: "plug strip on the right: a record of functions; each adapter a plug, hollow when nothing plugs it in <- library.ports[]",
|
|
317
|
-
generic: "the letter \u2200 with its variables over a part that never looks inside what it carries <- library.generic[]"
|
|
318
|
-
},
|
|
319
|
-
rule: "every guard, wrapper, socket, fork, handle, station, step and resource the engine records is drawn at its fixed place, in every view; where nothing is drawn, the engine checked and found none."
|
|
320
|
-
};
|
|
321
|
-
var bare = (id) => String(id).split("::").pop();
|
|
322
|
-
var pkgOf = (id) => String(id).split("::")[0];
|
|
323
|
-
var uniq = (xs) => [...new Set(xs)];
|
|
324
|
-
var OPS = { read: "read", query: "read", delete: "delete" };
|
|
325
|
-
function effectsOf(steps) {
|
|
326
|
-
return (steps || []).filter((e) => e.resource === "db").flatMap((e) => e.tables.map((table) => ({ op: OPS[e.op] || "write", table })));
|
|
327
|
-
}
|
|
328
|
-
var isWrite = (op) => op !== "read";
|
|
329
|
-
var uniqBy = (xs, key) => {
|
|
330
|
-
const seen = /* @__PURE__ */ new Set();
|
|
331
|
-
return xs.filter((x) => !seen.has(key(x)) && seen.add(key(x)));
|
|
332
|
-
};
|
|
333
|
-
var outsideResourcesOf = (steps) => uniq((steps || []).map((e) => e.resource).filter((r) => r === "model" || r === "net"));
|
|
334
|
-
function buildSystemMap(engine, { program }) {
|
|
335
|
-
for (const [k, v] of Object.entries(engine)) if (!v.ok) throw new Error(`${k}: ${v.error}`);
|
|
336
|
-
const report = engine.report, st = engine.structure, abs = engine.abstractions.abstractions, layers = engine.layers.layers;
|
|
337
|
-
const routes = (report.surface.routes || []).slice().sort((a, b) => a.path.localeCompare(b.path));
|
|
338
|
-
const engEntry = new Map(st.entries.map((e) => [e.entry, e]));
|
|
339
|
-
const shapes = new Map(abs.routeShapes.map((r) => [r.path, r]));
|
|
340
|
-
const gens = new Map(abs.generators.map((g) => [g.id, g]));
|
|
341
|
-
const insts = abs.instantiations;
|
|
342
|
-
const besideOf = (inst) => ({
|
|
343
|
-
calls: inst.besideCalls.map(bare),
|
|
344
|
-
callIds: inst.besideCalls,
|
|
345
|
-
guards: inst.besideGuards.map(bare),
|
|
346
|
-
guardIds: inst.besideGuards,
|
|
347
|
-
effects: effectsOf(inst.besideEffectSteps),
|
|
348
|
-
resources: outsideResourcesOf(inst.besideEffectSteps),
|
|
349
|
-
from: "abstractions.instantiations[].beside*"
|
|
350
|
-
});
|
|
351
|
-
const entries = routes.map((r) => {
|
|
352
|
-
const key = `route:${r.path}`;
|
|
353
|
-
const ee = engEntry.get(key);
|
|
354
|
-
const rs = shapes.get(r.path);
|
|
355
|
-
const wrapper = rs.shapedByGenerator;
|
|
356
|
-
const inst = wrapper ? insts.find((i) => i.callerId === rs.handlerId && i.generatorId === wrapper) : null;
|
|
357
|
-
const passed = (inst ? inst.slotBindings : []).filter((sb) => ["function", "effect"].includes(sb.slotRole)).map((sb) => ({
|
|
358
|
-
slot: sb.slotName,
|
|
359
|
-
id: sb.targetId || null,
|
|
360
|
-
label: sb.targetId ? bare(sb.targetId) : null,
|
|
361
|
-
kind: sb.passedKind,
|
|
362
|
-
guards: (sb.guards || []).map(bare),
|
|
363
|
-
guardIds: sb.guards || [],
|
|
364
|
-
effects: effectsOf(sb.effectSteps),
|
|
365
|
-
from: "abstractions.instantiations[].slotBindings[slotRole=function|effect]"
|
|
366
|
-
}));
|
|
367
|
-
const reach = wrapper ? [
|
|
368
|
-
...effectsOf(rs.effectsInGeneratorSteps).map((e) => ({ ...e, where: "wrapper", from: "abstractions.routeShapes[].effectsInGeneratorSteps" })),
|
|
369
|
-
...effectsOf(rs.effectsInPassedFunctionSteps).map((e) => ({ ...e, where: "passed", from: "abstractions.routeShapes[].effectsInPassedFunctionSteps" })),
|
|
370
|
-
...effectsOf(rs.effectsDirectOrBesideSteps).map((e) => ({ ...e, where: "beside", from: "abstractions.routeShapes[].effectsDirectOrBesideSteps" }))
|
|
371
|
-
] : uniqBy([
|
|
372
|
-
...effectsOf(r.inferredSteps).map((e) => ({ ...e, where: "direct", from: "report.surface.routes[].inferredSteps" })),
|
|
373
|
-
...effectsOf(rs.effectsDirectOrBesideSteps).map((e) => ({ ...e, where: "direct", from: "abstractions.routeShapes[].effectsDirectOrBesideSteps" }))
|
|
374
|
-
], (e) => `${e.op} ${e.table}`);
|
|
375
|
-
const limits = ee.limits.written === "literal" ? ee.limits.each.map((l) => ({ requests: +l.requests, seconds: +l.seconds, by: l.by })) : [];
|
|
376
|
-
return {
|
|
377
|
-
key,
|
|
378
|
-
path: r.path,
|
|
379
|
-
handler: r.handler,
|
|
380
|
-
handlerId: rs.handlerId,
|
|
381
|
-
transport: ee.transport,
|
|
382
|
-
authority: ee.authority,
|
|
383
|
-
signedIn: !["public", "anonymous"].includes(ee.authority),
|
|
384
|
-
roles: r.requiredRoles || [],
|
|
385
|
-
limits,
|
|
386
|
-
limitComputed: ee.limits.written === "computed",
|
|
387
|
-
reachKinds: ee.reaches,
|
|
388
|
-
model: ee.resources.includes("model"),
|
|
389
|
-
net: ee.resources.includes("net"),
|
|
390
|
-
writes: reach.some((e) => isWrite(e.op)),
|
|
391
|
-
guards: rs.handlerGuards.map(bare),
|
|
392
|
-
guardIds: rs.handlerGuards,
|
|
393
|
-
wrapper,
|
|
394
|
-
via: rs.viaSpecialization ? bare(rs.viaSpecialization) : null,
|
|
395
|
-
policy: (inst ? inst.slotBindings : []).filter((s) => s.slotRole === "semantic-object").map((s) => s.value).filter(Boolean),
|
|
396
|
-
passed,
|
|
397
|
-
beside: inst ? besideOf(inst) : null,
|
|
398
|
-
reach,
|
|
399
|
-
from: { entry: "report.surface.routes[]", transport: "structure.entries[]", shape: "abstractions.routeShapes[]", head: "entries[].reach (writes)" }
|
|
400
|
-
};
|
|
401
|
-
});
|
|
402
|
-
const partOf = (g) => {
|
|
403
|
-
const own = insts.filter((i) => i.generatorId === g.id);
|
|
404
|
-
return {
|
|
405
|
-
id: g.id,
|
|
406
|
-
label: g.name || bare(g.id),
|
|
407
|
-
pkg: pkgOf(g.id),
|
|
408
|
-
guards: g.envelope.guards.map(bare),
|
|
409
|
-
guardIds: g.envelope.guards,
|
|
410
|
-
effects: effectsOf(g.envelope.effectSteps),
|
|
411
|
-
groups: (g.parameterGroups || []).map((grp) => grp.map((sl) => ({ name: sl.name, role: sl.role, type: sl.type, guardsFed: (sl.guardsFed || []).map(bare) }))),
|
|
412
|
-
instantiationCount: own.length,
|
|
413
|
-
instantiatingPackages: uniq(own.map((i) => pkgOf(i.callerId))).sort(),
|
|
414
|
-
besideEmpty: own.every((i) => !i.besideCalls.length && !i.besideGuards.length && !i.besideEffects.length),
|
|
415
|
-
callers: own.map((i) => ({
|
|
416
|
-
id: i.callerId,
|
|
417
|
-
label: i.callerName || bare(i.callerId),
|
|
418
|
-
pkg: pkgOf(i.callerId),
|
|
419
|
-
routes: i.routes || [],
|
|
420
|
-
via: i.viaSpecialization ? bare(i.viaSpecialization) : null,
|
|
421
|
-
tokens: i.slotBindings.filter((s) => s.slotRole === "semantic-object").map((s) => s.value).filter(Boolean),
|
|
422
|
-
passed: i.slotBindings.filter((s) => ["function", "effect"].includes(s.slotRole)).map((s) => ({
|
|
423
|
-
slot: s.slotName,
|
|
424
|
-
id: s.targetId || null,
|
|
425
|
-
label: s.targetId ? bare(s.targetId) : null,
|
|
426
|
-
guards: (s.guards || []).map(bare),
|
|
427
|
-
guardIds: s.guards || [],
|
|
428
|
-
effects: effectsOf(s.effectSteps)
|
|
429
|
-
})),
|
|
430
|
-
beside: besideOf(i)
|
|
431
|
-
})),
|
|
432
|
-
from: "abstractions.generators[] + abstractions.instantiations[generatorId]"
|
|
433
|
-
};
|
|
434
|
-
};
|
|
435
|
-
const parts = abs.generators.filter((g) => insts.some((i) => i.generatorId === g.id)).map(partOf);
|
|
436
|
-
const wrapperIds = uniq(entries.map((e) => e.wrapper).filter(Boolean)).sort();
|
|
437
|
-
const wrappers = wrapperIds.map((id) => ({
|
|
438
|
-
...parts.find((x) => x.id === id) || partOf(gens.get(id)),
|
|
439
|
-
entries: entries.filter((e) => e.wrapper === id).map((e) => e.key),
|
|
440
|
-
from: "abstractions.generators[] shaping routeShapes[].shapedByGenerator"
|
|
441
|
-
}));
|
|
442
|
-
const handlerToEntry = new Map(entries.map((e) => [e.handlerId, e.key]));
|
|
443
|
-
const passedToEntry = new Map(entries.flatMap((e) => e.passed.filter((p) => p.id).map((p) => [p.id, e.key])));
|
|
444
|
-
const uses = [];
|
|
445
|
-
for (const s of st.supply) {
|
|
446
|
-
const kind = s.via === "record" ? "record" : s.resource;
|
|
447
|
-
if (kind !== "db" && kind !== "record") continue;
|
|
448
|
-
const ids = /* @__PURE__ */ new Set([s.definition]);
|
|
449
|
-
for (const t of s.traces) {
|
|
450
|
-
for (const id of t.through) ids.add(id);
|
|
451
|
-
if (t.end.where) ids.add(t.end.where);
|
|
452
|
-
if (t.end.referrer) ids.add(t.end.referrer);
|
|
453
|
-
}
|
|
454
|
-
let ats;
|
|
455
|
-
if (handlerToEntry.has(s.definition)) ats = [{ node: "entry", entry: handlerToEntry.get(s.definition) }];
|
|
456
|
-
else if (wrapperIds.includes(s.definition)) ats = [{ node: "wrapper", wrapper: s.definition }];
|
|
457
|
-
else if (passedToEntry.has(s.definition)) ats = [{ node: "passed", entry: passedToEntry.get(s.definition), id: s.definition }];
|
|
458
|
-
else {
|
|
459
|
-
const ents = uniq([...ids].map((i) => handlerToEntry.get(i)).filter(Boolean));
|
|
460
|
-
ats = ents.length ? ents.map((entry) => ({ node: "entry", entry, helper: bare(s.definition) })) : [{ node: "definition", id: s.definition }];
|
|
461
|
-
}
|
|
462
|
-
const builtBy = s.traces.map((t) => t.end.kind === "builds" && t.end.by ? bare(t.end.by) : t.end.kind === "reachesFor" ? bare(t.end.definition) : null).find(Boolean) || null;
|
|
463
|
-
const anchor = !s.leaves ? "none" : s.leaves.builtBy.length ? "program" : "platform";
|
|
464
|
-
for (const at of ats) uses.push({
|
|
465
|
-
kind,
|
|
466
|
-
how: s.supply,
|
|
467
|
-
definition: s.definition,
|
|
468
|
-
effect: s.effect || null,
|
|
469
|
-
writes: s.via === "effect" && isWrite(OPS[s.op] || "write"),
|
|
470
|
-
at,
|
|
471
|
-
builtBy,
|
|
472
|
-
untracedSource: s.traces.some((t) => ["asValue", "entry"].includes(t.end.kind)),
|
|
473
|
-
anchor,
|
|
474
|
-
handleBuiltBy: s.leaves ? s.leaves.builtBy : [],
|
|
475
|
-
records: s.records || [],
|
|
476
|
-
ends: s.traces.map((t) => ({ kind: t.end.kind, where: t.end.where || null, referrer: t.end.referrer || null, definition: t.end.definition || null, by: t.end.by || null })),
|
|
477
|
-
from: "structure.supply[]"
|
|
478
|
-
});
|
|
479
|
-
}
|
|
480
|
-
const present = uniq(st.ioKinds.flatMap((b) => b.resources));
|
|
481
|
-
const tables = uniq(entries.flatMap((e) => [...e.reach, ...e.beside ? e.beside.effects : []].map((r) => r.table))).sort();
|
|
482
|
-
const resources = ["db", "model", "net"].filter((k) => present.includes(k)).map((k) => ({ kind: k, ...k === "db" ? { tables } : {}, from: "structure.ioKinds[].resources" }));
|
|
483
|
-
const ghostResources = ["db", "model", "net"].filter((k) => !present.includes(k)).map((k) => ({ kind: k, from: "structure.ioKinds[] checked: no site of this kind" }));
|
|
484
|
-
const transports = uniq(st.entries.map((e) => e.transport));
|
|
485
|
-
const callers = [];
|
|
486
|
-
if (transports.includes("http")) callers.push({ kind: "http", keyKinds: uniq(entries.map(keyKindOf)), from: "structure.entries[transport=http] + authority" });
|
|
487
|
-
if (transports.includes("link")) callers.push({ kind: "link", from: "structure.entries[transport=link]" });
|
|
488
|
-
const ghostCallers = ["http", "link"].filter((k) => !transports.includes(k)).map((k) => ({ kind: k, from: "structure.entries[]: no entry with this transport" }));
|
|
489
|
-
const library = routes.length ? null : {
|
|
490
|
-
packages: layers.packages.map((p) => ({ name: p.name, label: p.name.split("/").pop(), exports: p.definitions.filter((d) => d.exported).map((d) => d.name) })),
|
|
491
|
-
ports: st.ports.map((p) => ({
|
|
492
|
-
id: p.id,
|
|
493
|
-
label: bare(p.id),
|
|
494
|
-
pkg: pkgOf(p.id),
|
|
495
|
-
fields: p.fields,
|
|
496
|
-
heldBy: p.heldBy,
|
|
497
|
-
adapters: p.values.map((v) => ({ id: v.value, label: bare(v.value), usedBy: v.usedBy.map((u) => ({ id: u, label: bare(u), pkg: pkgOf(u) })) })),
|
|
498
|
-
from: "structure.ports[]"
|
|
499
|
-
})),
|
|
500
|
-
chains: st.chains.map((c) => ({
|
|
501
|
-
value: c.value,
|
|
502
|
-
label: bare(c.value),
|
|
503
|
-
pkg: pkgOf(c.value),
|
|
504
|
-
by: bare(c.by),
|
|
505
|
-
start: c.start.map((i) => i.id ? bare(i.id) : i.text),
|
|
506
|
-
steps: c.steps.map((s) => s.map((i) => ({ id: i.id || null, label: i.id ? bare(i.id) : i.text, pkg: i.id ? pkgOf(i.id) : null, applied: i.applied }))),
|
|
507
|
-
from: "structure.chains[]"
|
|
508
|
-
})),
|
|
509
|
-
combinations: st.combinations,
|
|
510
|
-
applied: st.applied.map((a) => ({
|
|
511
|
-
id: a.definition,
|
|
512
|
-
label: bare(a.definition),
|
|
513
|
-
pkg: pkgOf(a.definition),
|
|
514
|
-
fn: a.function,
|
|
515
|
-
insideBranch: a.insideBranch,
|
|
516
|
-
fedBy: a.fedBy,
|
|
517
|
-
from: "structure.applied[]"
|
|
518
|
-
})),
|
|
519
|
-
generic: st.generic.map((g) => ({ id: g.definition, label: bare(g.definition), vars: g.vars, signature: g.signature, from: "structure.generic[]" })),
|
|
520
|
-
exported: st.entries.filter((e) => e.transport === "link").map((e) => e.entry)
|
|
521
|
-
};
|
|
522
|
-
const steps = st.phases.phases.flatMap((ph) => ph.steps.map((s) => ({ pkg: ph.package, type: s.type, label: bare(s.type), by: s.by, from: "structure.phases.phases[].steps" })));
|
|
523
|
-
const keyed = st.keyed.map((k) => ({ id: k.definition, label: bare(k.definition), pkg: pkgOf(k.definition), types: uniq(k.parameters.map((p) => p.type)), from: "structure.keyed[]" }));
|
|
524
|
-
return {
|
|
525
|
-
schema: "system-map-2",
|
|
526
|
-
marks: MARKS_VERSION,
|
|
527
|
-
vocabulary: VOCABULARY,
|
|
528
|
-
program,
|
|
529
|
-
class: report.headline.class,
|
|
530
|
-
kind: routes.length ? "service" : "library",
|
|
531
|
-
callers,
|
|
532
|
-
ghostCallers,
|
|
533
|
-
entries,
|
|
534
|
-
wrappers,
|
|
535
|
-
parts,
|
|
536
|
-
uses,
|
|
537
|
-
resources,
|
|
538
|
-
ghostResources,
|
|
539
|
-
library,
|
|
540
|
-
keyed,
|
|
541
|
-
steps,
|
|
542
|
-
bundles: routes.length > 12 ? bundlesOf(entries, uses, keyed) : null,
|
|
543
|
-
phases: st.phases,
|
|
544
|
-
evidence: {
|
|
545
|
-
tools: ["api_report", "api_organize:abstractions", "api_organize:structure", "api_organize:layers"],
|
|
546
|
-
headline: report.headline,
|
|
547
|
-
derived: ["bundles: entries grouped by wrapper and identical marks"]
|
|
548
|
-
}
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
|
-
var keyKindOf = (e) => e.authority === "publishable" ? "publishable" : e.signedIn ? "secret" : "public";
|
|
552
|
-
function bundlesOf(entries, uses, keyed) {
|
|
553
|
-
const keyedIds = new Set(keyed.map((k) => k.id));
|
|
554
|
-
const sup = (e) => uniq(uses.filter((u) => u.kind === "db" && u.at.entry === e.key).flatMap((u) => [u.how, ...u.untracedSource ? [`?${u.anchor}`] : []])).sort().join(" ");
|
|
555
|
-
const fill = (l) => l.length ? l.some((x) => isWrite(x.op)) ? "W" : "R" : "-";
|
|
556
|
-
const sig = (e) => {
|
|
557
|
-
const p = e.passed[0], b = e.beside;
|
|
558
|
-
return JSON.stringify([
|
|
559
|
-
e.wrapper,
|
|
560
|
-
keyKindOf(e),
|
|
561
|
-
e.roles.length > 0,
|
|
562
|
-
e.writes,
|
|
563
|
-
e.guards.length > 0,
|
|
564
|
-
fill(e.reach.filter((r) => r.where === "direct")),
|
|
565
|
-
fill(e.reach.filter((r) => r.where === "passed")),
|
|
566
|
-
!!(p && p.guards.length),
|
|
567
|
-
e.model,
|
|
568
|
-
e.net,
|
|
569
|
-
sup(e),
|
|
570
|
-
e.limits.length > 0,
|
|
571
|
-
!!(b && b.calls.length),
|
|
572
|
-
!!(b && b.guards.length),
|
|
573
|
-
fill(b ? b.effects : []),
|
|
574
|
-
e.policy.length > 0,
|
|
575
|
-
[e.handlerId, ...e.guardIds, ...p ? [p.id, ...p.guardIds] : []].some((id) => keyedIds.has(id))
|
|
576
|
-
]);
|
|
577
|
-
};
|
|
578
|
-
const groups = /* @__PURE__ */ new Map();
|
|
579
|
-
for (const e of entries) {
|
|
580
|
-
const k = sig(e);
|
|
581
|
-
if (!groups.has(k)) groups.set(k, []);
|
|
582
|
-
groups.get(k).push(e.key);
|
|
583
|
-
}
|
|
584
|
-
const pathOf = new Map(entries.map((e) => [e.key, e.path]));
|
|
585
|
-
return [...groups.values()].map((keys, i) => ({
|
|
586
|
-
id: `bundle:${i + 1}`,
|
|
587
|
-
entries: keys,
|
|
588
|
-
count: keys.length,
|
|
589
|
-
label: pathPattern(keys.map((k) => pathOf.get(k))),
|
|
590
|
-
from: "derived: entries[] grouped by wrapper and identical marks"
|
|
591
|
-
}));
|
|
592
|
-
}
|
|
593
|
-
function pathPattern(paths) {
|
|
594
|
-
if (paths.length === 1) return paths[0];
|
|
595
|
-
const segs = paths.map((p) => p.split("/"));
|
|
596
|
-
const n = Math.min(...segs.map((s) => s.length));
|
|
597
|
-
const out = [];
|
|
598
|
-
for (let i = 0; i < n; i++) {
|
|
599
|
-
const v = uniq(segs.map((s) => s[i]));
|
|
600
|
-
out.push(v.length === 1 ? v[0] : "*");
|
|
601
|
-
}
|
|
602
|
-
if (segs.every((s) => s.length === n)) return out.join("/");
|
|
603
|
-
let k = 0;
|
|
604
|
-
while (k < n && out[k] !== "*") k++;
|
|
605
|
-
return out.slice(0, Math.max(k, 1)).join("/") + "/**";
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
// ../../web/system-map-names.js
|
|
609
|
-
var SKIP = /* @__PURE__ */ new Set(["vocabulary", "evidence", "schema", "marks", "program", "class"]);
|
|
610
|
-
var skipped = (key, v) => SKIP.has(key) || key === "from" && !Array.isArray(v);
|
|
611
|
-
var STRUCTURAL = /* @__PURE__ */ new Set([
|
|
612
|
-
"kind",
|
|
613
|
-
"op",
|
|
614
|
-
"how",
|
|
615
|
-
"transport",
|
|
616
|
-
"authority",
|
|
617
|
-
"where",
|
|
618
|
-
"slotRole",
|
|
619
|
-
"role",
|
|
620
|
-
"passedKind",
|
|
621
|
-
"anchor",
|
|
622
|
-
"node",
|
|
623
|
-
"keyKinds",
|
|
624
|
-
"reachKinds",
|
|
625
|
-
"resources",
|
|
626
|
-
"vars",
|
|
627
|
-
"id"
|
|
628
|
-
]);
|
|
629
|
-
var WHAT = {
|
|
630
|
-
path: "an action the app answers",
|
|
631
|
-
routes: "an action the app answers",
|
|
632
|
-
table: "a kind of record the app keeps",
|
|
633
|
-
tables: "a kind of record the app keeps",
|
|
634
|
-
roles: "a role a person can hold",
|
|
635
|
-
policy: "a setting an action passes to shared code",
|
|
636
|
-
tokens: "a setting an action passes to shared code",
|
|
637
|
-
fields: "an operation a pluggable part offers"
|
|
638
|
-
};
|
|
639
|
-
var PACKAGE = "a section of the program";
|
|
640
|
-
var DEFINITION = "a piece of the program";
|
|
641
|
-
var VALUE = "a kind of value";
|
|
642
|
-
var TYPES = /* @__PURE__ */ new Set(["type", "types", "signature"]);
|
|
643
|
-
var WORD = /[A-Za-z_][\w/]*::\w+|[A-Za-z_]\w*/g;
|
|
644
|
-
var leaves = (record, visit) => {
|
|
645
|
-
const walk = (v, key) => {
|
|
646
|
-
if (typeof v === "string") visit(v, key);
|
|
647
|
-
else if (Array.isArray(v)) v.forEach((x) => walk(x, key));
|
|
648
|
-
else if (v && typeof v === "object") {
|
|
649
|
-
for (const [k, x] of Object.entries(v)) if (!skipped(k, x)) walk(x, k);
|
|
650
|
-
}
|
|
651
|
-
};
|
|
652
|
-
walk(record, null);
|
|
653
|
-
};
|
|
654
|
-
function nameableParts(map) {
|
|
655
|
-
const found = /* @__PURE__ */ new Map();
|
|
656
|
-
const add = (code, what) => {
|
|
657
|
-
if (code && !found.has(code)) found.set(code, what);
|
|
658
|
-
};
|
|
659
|
-
const idParts = (id) => {
|
|
660
|
-
const i = id.lastIndexOf("::");
|
|
661
|
-
add(id.slice(0, i), PACKAGE);
|
|
662
|
-
add(id.slice(i + 2), DEFINITION);
|
|
663
|
-
};
|
|
664
|
-
leaves(map, (s, key) => {
|
|
665
|
-
if (s.startsWith("route:")) return add(s.slice(6), WHAT.path);
|
|
666
|
-
if (TYPES.has(key)) {
|
|
667
|
-
for (const w of s.match(WORD) ?? []) if (w.includes("::")) idParts(w);
|
|
668
|
-
else if (w.length > 1) add(w, VALUE);
|
|
669
|
-
return;
|
|
670
|
-
}
|
|
671
|
-
if (s.includes("::")) {
|
|
672
|
-
for (const w of s.match(WORD)) if (w.includes("::")) idParts(w);
|
|
673
|
-
return;
|
|
674
|
-
}
|
|
675
|
-
if (STRUCTURAL.has(key)) return;
|
|
676
|
-
if (key === "name" || key === "package" || key === "pkg" || key === "instantiatingPackages" || key === "cycles" || key === "to") return add(s, s.includes("/") ? PACKAGE : DEFINITION);
|
|
677
|
-
add(s, WHAT[key] ?? DEFINITION);
|
|
678
|
-
});
|
|
679
|
-
for (const b of map.bundles ?? []) if (b.count > 1) found.delete(b.label);
|
|
680
|
-
return [...found].map(([code, what]) => ({ code, what })).sort((a, b) => a.code.localeCompare(b.code));
|
|
681
|
-
}
|
|
682
|
-
function plainNames(names) {
|
|
683
|
-
const out = /* @__PURE__ */ new Map(), taken = /* @__PURE__ */ new Set();
|
|
684
|
-
for (const [code, name] of Object.entries(names).sort(([a], [b]) => a.localeCompare(b))) {
|
|
685
|
-
const base = name.replace(/::|\//g, " ").replace(/\s+/g, " ").trim();
|
|
686
|
-
if (!base) continue;
|
|
687
|
-
let plain = base;
|
|
688
|
-
for (let n = 2; taken.has(plain); n++) plain = `${base} (${n})`;
|
|
689
|
-
taken.add(plain);
|
|
690
|
-
out.set(code, plain);
|
|
691
|
-
}
|
|
692
|
-
return out;
|
|
693
|
-
}
|
|
694
|
-
function relabelSystemMap(map, names) {
|
|
695
|
-
const plain = plainNames(names);
|
|
696
|
-
const word = (w) => plain.get(w) ?? w;
|
|
697
|
-
const id = (w) => {
|
|
698
|
-
const i = w.lastIndexOf("::");
|
|
699
|
-
return `${word(w.slice(0, i))}::${word(w.slice(i + 2))}`;
|
|
700
|
-
};
|
|
701
|
-
const text3 = (s, key) => {
|
|
702
|
-
if (s.startsWith("route:")) return `route:${word(s.slice(6))}`;
|
|
703
|
-
if (plain.has(s) && !STRUCTURAL.has(key)) return plain.get(s);
|
|
704
|
-
if (s.startsWith("/")) return s;
|
|
705
|
-
return s.replace(WORD, (w) => w.includes("::") ? id(w) : STRUCTURAL.has(key) ? w : word(w));
|
|
706
|
-
};
|
|
707
|
-
const walk = (v, key) => {
|
|
708
|
-
if (typeof v === "string") return text3(v, key);
|
|
709
|
-
if (Array.isArray(v)) return v.map((x) => walk(x, key));
|
|
710
|
-
if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, skipped(k, x) ? x : walk(x, k)]));
|
|
711
|
-
return v;
|
|
712
|
-
};
|
|
713
|
-
const out = walk(map, null);
|
|
714
|
-
const pathOf = new Map(map.entries.map((e) => [e.key, e.path]));
|
|
715
|
-
out.bundles = map.bundles && map.bundles.map((b, i) => {
|
|
716
|
-
const paths = b.entries.map((k) => pathOf.get(k));
|
|
717
|
-
if (!paths.some((p) => plain.has(p))) return out.bundles[i];
|
|
718
|
-
return { ...out.bundles[i], label: b.count === 1 ? word(paths[0]) : `${word(paths[0])} and ${b.count - 1} more` };
|
|
719
|
-
});
|
|
720
|
-
return out;
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
// src/studio/project.ts
|
|
724
|
-
import { createHash } from "crypto";
|
|
725
|
-
import fs from "fs";
|
|
726
|
-
import path from "path";
|
|
727
|
-
var SKIPPED = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "target", "out"]);
|
|
728
|
-
function projectSources(root) {
|
|
729
|
-
const files = [];
|
|
730
|
-
const walk = (dir) => {
|
|
731
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
732
|
-
if (entry.name.startsWith(".") || SKIPPED.has(entry.name)) continue;
|
|
733
|
-
const full = path.join(dir, entry.name);
|
|
734
|
-
if (entry.isDirectory()) walk(full);
|
|
735
|
-
else if (entry.isFile() && entry.name.endsWith(".bosatsu")) {
|
|
736
|
-
files.push({ fileName: path.relative(root, full).split(path.sep).join("/"), source: fs.readFileSync(full, "utf8") });
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
};
|
|
740
|
-
walk(root);
|
|
741
|
-
return files;
|
|
742
|
-
}
|
|
743
|
-
function sourcesHash(files) {
|
|
744
|
-
const hash = createHash("sha256");
|
|
745
|
-
for (const file of files) hash.update(`${file.fileName}\0${file.source}\0`);
|
|
746
|
-
return hash.digest("hex");
|
|
747
|
-
}
|
|
748
|
-
function caseSources(root) {
|
|
749
|
-
const dir = path.join(root, ".yichus", "cases");
|
|
750
|
-
if (!fs.existsSync(dir)) return [];
|
|
751
|
-
return fs.readdirSync(dir).filter((name) => name.endsWith(".bosatsu")).sort().map((name) => ({ fileName: `cases/${name}`, source: fs.readFileSync(path.join(dir, name), "utf8") }));
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
// src/studio/questions.ts
|
|
755
|
-
import { z as z3 } from "zod";
|
|
756
|
-
var Step = z3.looseObject({ op: z3.string(), tables: z3.array(z3.string()).default([]), resource: z3.string() });
|
|
757
|
-
var Route = z3.looseObject({ path: z3.string(), handler: z3.string(), inferredSteps: z3.array(Step).default([]) });
|
|
758
|
-
var Table = z3.looseObject({
|
|
759
|
-
name: z3.string(),
|
|
760
|
-
policy: z3.string().nullable().optional(),
|
|
761
|
-
readers: z3.array(z3.string()).default([]),
|
|
762
|
-
writers: z3.array(z3.string()).default([])
|
|
763
|
-
});
|
|
764
|
-
var Report = z3.looseObject({
|
|
765
|
-
surface: z3.looseObject({ routes: z3.array(Route).default([]) }).default({ routes: [] }),
|
|
766
|
-
dataModel: z3.looseObject({ tables: z3.array(Table).default([]) }).default({ tables: [] })
|
|
767
|
-
});
|
|
768
|
-
var Entry = z3.looseObject({ entry: z3.string(), resources: z3.array(z3.string()).default([]) });
|
|
769
|
-
var Structure = z3.looseObject({ entries: z3.array(Entry).default([]) });
|
|
770
|
-
var ACCESS_POLICY = {
|
|
771
|
-
owner: "OwnerScoped",
|
|
772
|
-
shared: "Guarded",
|
|
773
|
-
"everyone-reads": "PublicReadRoleWrite",
|
|
774
|
-
public: "Public"
|
|
775
|
-
};
|
|
776
|
-
var topology = {
|
|
777
|
-
id: "topology",
|
|
778
|
-
kind: "topology",
|
|
779
|
-
subject: null,
|
|
780
|
-
ask: "When many people use your app at the same time, should it run as one server, or as several copies of the server that share one database?",
|
|
781
|
-
why: "Several copies keep the app up when one fails and when traffic grows, but then two requests really can run at the same moment, so every check below assumes that unless you choose one server.",
|
|
782
|
-
choices: [
|
|
783
|
-
{ id: "many", label: "Several copies", means: "Every check assumes requests can run at the same moment on different copies." },
|
|
784
|
-
{ id: "one", label: "One server", means: "Checks may assume one request at a time. This holds only while exactly one copy runs; the page shows it as an assumption." }
|
|
785
|
-
],
|
|
786
|
-
fact: "The program serves routes."
|
|
787
|
-
};
|
|
788
|
-
var shown = (names, subject) => names[subject] ?? subject;
|
|
789
|
-
function accessQuestion(table, names) {
|
|
790
|
-
return {
|
|
791
|
-
id: `access:${table.name}`,
|
|
792
|
-
kind: "access",
|
|
793
|
-
subject: table.name,
|
|
794
|
-
ask: `Your app saves "${shown(names, table.name)}"${table.name in names ? "" : " records"}. Who should be able to see one, and who should be able to change it?`,
|
|
795
|
-
why: "Without a rule the app has no way to know a record is private. Yichus checks every place the app reads or changes these records against the rule you choose.",
|
|
796
|
-
choices: [
|
|
797
|
-
{ id: "owner", label: "Only the person who created it", means: "Every read and write is tied to the signed-in person, and the check proves no one reaches another person's records." },
|
|
798
|
-
{ id: "shared", label: "The creator and people they share it with", means: "Every read goes through a sharing rule, and the check proves nothing skips it." },
|
|
799
|
-
{ id: "everyone-reads", label: "Everyone can see it; only certain roles can change it", means: "Anyone can read; changes need a role the app gives out." },
|
|
800
|
-
{ id: "public", label: "Anyone, even without signing in", means: "Nothing in these records is private." }
|
|
801
|
-
],
|
|
802
|
-
fact: `The program stores rows in "${table.name}" (policy declared: ${table.policy ?? "none"}).`
|
|
803
|
-
};
|
|
804
|
-
}
|
|
805
|
-
function togetherQuestion(table, handlers, names) {
|
|
806
|
-
return {
|
|
807
|
-
id: `together:${table}`,
|
|
808
|
-
kind: "together",
|
|
809
|
-
subject: table,
|
|
810
|
-
ask: `Two requests change the same record in "${shown(names, table)}" at the same moment (two people, or one person on two devices). What should happen?`,
|
|
811
|
-
why: "When a request reads a record and then writes it back, a second request in between can be silently lost. People rarely notice until data goes missing.",
|
|
812
|
-
choices: [
|
|
813
|
-
{ id: "keep-both", label: "Both changes are kept", means: "Each change happens as one indivisible step, so neither can overwrite the other unseen; the check proves no change is lost." },
|
|
814
|
-
{ id: "refuse-second", label: "The second is refused and they try again", means: "A change made to an out-of-date copy is turned away; the check proves no change is lost." }
|
|
815
|
-
],
|
|
816
|
-
fact: `${handlers.join(", ")} ${handlers.length === 1 ? "reads" : "read"} "${table}" and then ${handlers.length === 1 ? "writes" : "write"} it.`
|
|
817
|
-
};
|
|
818
|
-
}
|
|
819
|
-
function partialQuestion(route, tables, names) {
|
|
820
|
-
return {
|
|
821
|
-
id: `partial:${route.path}`,
|
|
822
|
-
kind: "partial",
|
|
823
|
-
subject: route.path,
|
|
824
|
-
ask: `If the server stops halfway through "${shown(names, route.path)}" (a crash, a database error, a timeout), may part of its changes stay saved?`,
|
|
825
|
-
why: `This action changes ${tables.map((t) => `"${shown(names, t)}"`).join(" and ")} in more than one step. A stop between steps can leave them disagreeing, for example money taken but no receipt.`,
|
|
826
|
-
choices: [
|
|
827
|
-
{ id: "all-or-nothing", label: "All or nothing", means: "Every change this action makes is saved together or not at all; Yichus stops it at each step and checks nothing half-done stays saved." },
|
|
828
|
-
{ id: "partial-ok", label: "Partial is fine", means: "No check is added for this action." }
|
|
829
|
-
],
|
|
830
|
-
fact: `${route.handler} writes ${tables.map((t) => `"${t}"`).join(", ")} in more than one step.`
|
|
831
|
-
};
|
|
832
|
-
}
|
|
833
|
-
function outsideQuestion(route, kinds, names) {
|
|
834
|
-
const service = kinds.includes("model") ? "an AI model" : "another service on the internet";
|
|
835
|
-
return {
|
|
836
|
-
id: `outside:${route.path}`,
|
|
837
|
-
kind: "outside",
|
|
838
|
-
subject: route.path,
|
|
839
|
-
ask: `"${shown(names, route.path)}" calls ${service}. If that service is down or slow, what should the person using your app see?`,
|
|
840
|
-
why: "Outside services fail often. Without a plan, a failure can leave a half-finished record or charge for work that never happened.",
|
|
841
|
-
choices: [
|
|
842
|
-
{ id: "fail-clean", label: "An error, with nothing saved", means: "Yichus makes the service fail and checks that nothing from this action stays saved." },
|
|
843
|
-
{ id: "finish-later", label: "Save the request and finish it later", means: "Yichus makes the service fail and checks the saved request is tried again and finished exactly once." },
|
|
844
|
-
{ id: "no-plan", label: "No preference", means: "No check is added for this action." }
|
|
845
|
-
],
|
|
846
|
-
fact: `${route.handler} reaches ${kinds.join(" and ")}.`
|
|
847
|
-
};
|
|
848
|
-
}
|
|
849
|
-
function questionsFor(report, structure, names = {}) {
|
|
850
|
-
const questions = [];
|
|
851
|
-
if (report.surface.routes.length) questions.push(topology);
|
|
852
|
-
for (const table of report.dataModel.tables) questions.push(accessQuestion(table, names));
|
|
853
|
-
for (const table of report.dataModel.tables) {
|
|
854
|
-
const both = table.readers.filter((h) => table.writers.includes(h));
|
|
855
|
-
if (both.length) questions.push(togetherQuestion(table.name, both, names));
|
|
856
|
-
}
|
|
857
|
-
for (const route of report.surface.routes) {
|
|
858
|
-
const writes = route.inferredSteps.filter((s) => s.resource === "db" && s.op !== "read" && s.op !== "query");
|
|
859
|
-
const tables = [...new Set(writes.flatMap((s) => s.tables))];
|
|
860
|
-
if (writes.length >= 2) questions.push(partialQuestion(route, tables, names));
|
|
861
|
-
}
|
|
862
|
-
for (const route of report.surface.routes) {
|
|
863
|
-
const entry = structure.entries.find((e) => e.entry === `route:${route.path}`);
|
|
864
|
-
const kinds = (entry?.resources ?? []).filter((r) => r === "model" || r === "net");
|
|
865
|
-
if (kinds.length) questions.push(outsideQuestion(route, kinds, names));
|
|
866
|
-
}
|
|
867
|
-
return questions;
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
// src/studio/requirements.ts
|
|
871
|
-
import fs2 from "fs";
|
|
872
|
-
import path2 from "path";
|
|
873
|
-
import { z as z4 } from "zod";
|
|
874
|
-
var Answer = z4.object({
|
|
875
|
-
question: z4.string().min(1),
|
|
876
|
-
choice: z4.string().min(1),
|
|
877
|
-
words: z4.string(),
|
|
878
|
-
answeredAt: z4.string()
|
|
879
|
-
});
|
|
880
|
-
var Scenario = z4.object({
|
|
881
|
-
entry: z4.string().min(1),
|
|
882
|
-
title: z4.string().optional(),
|
|
883
|
-
names: z4.record(z4.string(), z4.string()).optional(),
|
|
884
|
-
expect: z4.array(z4.object({ at: z4.string(), claim: z4.string() }).strict()).optional()
|
|
885
|
-
}).strict();
|
|
886
|
-
var Requirements = z4.object({
|
|
887
|
-
schemaVersion: z4.literal("yichus-requirements-1"),
|
|
888
|
-
description: z4.string().nullable(),
|
|
889
|
-
answers: z4.array(Answer),
|
|
890
|
-
/** Plain names for the program's records and actions, keyed by code name. */
|
|
891
|
-
names: z4.record(z4.string(), z4.string()).optional(),
|
|
892
|
-
scenarios: z4.array(Scenario).optional()
|
|
893
|
-
});
|
|
894
|
-
var studioDir = (root) => path2.join(root, ".yichus");
|
|
895
|
-
var requirementsPath = (root) => path2.join(studioDir(root), "requirements.json");
|
|
896
|
-
function loadRequirements(root) {
|
|
897
|
-
const file = requirementsPath(root);
|
|
898
|
-
if (!fs2.existsSync(file)) return { schemaVersion: "yichus-requirements-1", description: null, answers: [] };
|
|
899
|
-
const parsed = Requirements.safeParse(JSON.parse(fs2.readFileSync(file, "utf8")));
|
|
900
|
-
if (!parsed.success) throw new Error(`${file} is not a yichus-requirements-1 file: ${parsed.error.issues[0]?.message ?? "invalid"}`);
|
|
901
|
-
return parsed.data;
|
|
902
|
-
}
|
|
903
|
-
function saveRequirements(root, requirements) {
|
|
904
|
-
ensureStudioDir(root);
|
|
905
|
-
fs2.writeFileSync(requirementsPath(root), `${JSON.stringify(Requirements.parse(requirements), null, 2)}
|
|
906
|
-
`);
|
|
907
|
-
}
|
|
908
|
-
function withNames(requirements, names) {
|
|
909
|
-
return { ...requirements, names: { ...requirements.names, ...names } };
|
|
910
|
-
}
|
|
911
|
-
function withAnswer(requirements, answer) {
|
|
912
|
-
return { ...requirements, answers: [...requirements.answers.filter((a) => a.question !== answer.question), answer] };
|
|
913
|
-
}
|
|
914
|
-
function ensureStudioDir(root) {
|
|
915
|
-
const dir = studioDir(root);
|
|
916
|
-
fs2.mkdirSync(dir, { recursive: true });
|
|
917
|
-
const ignore = path2.join(dir, ".gitignore");
|
|
918
|
-
if (!fs2.existsSync(ignore)) fs2.writeFileSync(ignore, "state.json\n");
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
// src/studio/director.ts
|
|
922
|
-
var VerifyProperty = z5.looseObject({
|
|
923
|
-
id: z5.string(),
|
|
924
|
-
title: z5.string(),
|
|
925
|
-
status: z5.string(),
|
|
926
|
-
details: z5.array(z5.string()).default([]),
|
|
927
|
-
accepted: z5.unknown().optional()
|
|
928
|
-
});
|
|
929
|
-
var Verify = z5.looseObject({
|
|
930
|
-
topology: z5.string().optional(),
|
|
931
|
-
verdict: z5.looseObject({ proven: z5.boolean(), properties: z5.array(VerifyProperty) })
|
|
932
|
-
});
|
|
933
|
-
var Protocol = z5.looseObject({ protocol: z5.looseObject({ status: z5.string(), name: z5.string().optional() }).optional(), error: z5.string().optional() });
|
|
934
|
-
var caseFile = (root, questionId) => path3.join(studioDir(root), "cases", `${questionId.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "")}.json`);
|
|
935
|
-
var answerOf = (requirements, id) => requirements.answers.find((a) => a.question === id) ?? null;
|
|
936
|
-
function instancesFor(requirements) {
|
|
937
|
-
const choice = answerOf(requirements, "topology")?.choice;
|
|
938
|
-
return choice === "one" ? "1" : choice === "many" ? "many" : void 0;
|
|
939
|
-
}
|
|
940
|
-
async function call(engine, tool, args) {
|
|
941
|
-
const result = await engine.call(tool, args);
|
|
942
|
-
if (result.ok !== true) throw new Error(`${tool} failed: ${typeof result.error === "string" ? result.error : "no reason given"}`);
|
|
943
|
-
return result;
|
|
944
|
-
}
|
|
945
|
-
var isAccepted = (p) => p.status === "warning" && p.accepted !== void 0;
|
|
946
|
-
var worst = (props) => props.find((p) => p.status !== "proven" && !isAccepted(p)) ?? props.find(isAccepted);
|
|
947
|
-
async function judge(root, engine, sources, question, answer, report, verify) {
|
|
948
|
-
const base = { question, answer, evidence: [], check: null };
|
|
949
|
-
if (!answer) return { ...base, status: "unanswered" };
|
|
950
|
-
const byId = (id) => verify.find((p) => p.id === id);
|
|
951
|
-
switch (question.kind) {
|
|
952
|
-
case "topology":
|
|
953
|
-
return {
|
|
954
|
-
...base,
|
|
955
|
-
status: answer.choice === "one" ? "assumed" : "decided",
|
|
956
|
-
evidence: answer.choice === "one" ? ["Every check below assumes exactly one copy of the server runs."] : []
|
|
957
|
-
};
|
|
958
|
-
case "access": {
|
|
959
|
-
const table = report.dataModel.tables.find((t) => t.name === question.subject);
|
|
960
|
-
const want = ACCESS_POLICY[answer.choice];
|
|
961
|
-
const declared = table?.policy ?? null;
|
|
962
|
-
if (!want || !declared || !declared.startsWith(want)) {
|
|
963
|
-
return {
|
|
964
|
-
...base,
|
|
965
|
-
status: "mismatch",
|
|
966
|
-
check: "api_report dataModel.tables[].policy",
|
|
967
|
-
evidence: [`"${question.subject}" is declared ${declared ?? "with no rule"}; the person chose ${want ?? answer.choice}.`]
|
|
968
|
-
};
|
|
969
|
-
}
|
|
970
|
-
const prop = byId(`access:${question.subject}`) ?? byId("access-coverage");
|
|
971
|
-
if (!prop) return { ...base, status: "inconclusive", check: "api_verify", evidence: ["api_verify reported no access property for this table."] };
|
|
972
|
-
return {
|
|
973
|
-
...base,
|
|
974
|
-
check: `api_verify ${prop.id}`,
|
|
975
|
-
evidence: prop.details,
|
|
976
|
-
status: prop.status === "proven" ? "proven" : "broken"
|
|
977
|
-
};
|
|
978
|
-
}
|
|
979
|
-
case "together": {
|
|
980
|
-
const props = verify.filter((p) => p.id === "rmw-transactions" || p.id === "integrity");
|
|
981
|
-
const bad = worst(props);
|
|
982
|
-
const mentions = (p) => p.details.filter((d) => d.includes(`"${question.subject}"`));
|
|
983
|
-
const evidence = props.flatMap((p) => mentions(p).length ? mentions(p) : p.status === "proven" ? [] : p.details);
|
|
984
|
-
const check = `api_verify ${props.map((p) => p.id).join(" + ")}`;
|
|
985
|
-
if (!bad) return { ...base, check, evidence, status: props.length ? "proven" : "inconclusive" };
|
|
986
|
-
return { ...base, check, evidence, status: isAccepted(bad) ? "assumed" : "broken" };
|
|
987
|
-
}
|
|
988
|
-
case "partial":
|
|
989
|
-
case "outside": {
|
|
990
|
-
if (answer.choice === "partial-ok" || answer.choice === "no-plan") return { ...base, status: "no-check" };
|
|
991
|
-
const file = caseFile(root, question.id);
|
|
992
|
-
const rel = path3.relative(root, file).split(path3.sep).join("/");
|
|
993
|
-
if (!fs3.existsSync(file)) return { ...base, casePath: rel, status: "needs-case", check: "api_protocol_check", evidence: [`No protocol case at ${rel} yet.`] };
|
|
994
|
-
let protocolCase;
|
|
995
|
-
try {
|
|
996
|
-
protocolCase = JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
997
|
-
} catch (error) {
|
|
998
|
-
return {
|
|
999
|
-
...base,
|
|
1000
|
-
casePath: rel,
|
|
1001
|
-
check: "api_protocol_check",
|
|
1002
|
-
status: "inconclusive",
|
|
1003
|
-
evidence: [`${rel} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]
|
|
1004
|
-
};
|
|
1005
|
-
}
|
|
1006
|
-
const result = Protocol.parse(await engine.call("api_protocol_check", { sources: [...sources, ...caseSources(root)], case: protocolCase }));
|
|
1007
|
-
const status = result.protocol?.status;
|
|
1008
|
-
const check = `api_protocol_check ${rel}`;
|
|
1009
|
-
if (!status) return { ...base, casePath: rel, check, status: "inconclusive", evidence: [result.error ?? "The protocol check gave no status."] };
|
|
1010
|
-
return {
|
|
1011
|
-
...base,
|
|
1012
|
-
casePath: rel,
|
|
1013
|
-
check,
|
|
1014
|
-
evidence: [`${result.protocol?.name ?? rel}: ${status}`],
|
|
1015
|
-
status: status === "holds" ? "bounded" : status === "violated" ? "broken" : "inconclusive"
|
|
1016
|
-
};
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
var QUESTION_PROPERTIES = (id) => id.startsWith("access:") || id === "access-coverage" || id === "rmw-transactions" || id === "integrity";
|
|
1021
|
-
var GUIDE = {
|
|
1022
|
-
topology: "Multi-instance data integrity",
|
|
1023
|
-
access: "Owner-scoped data",
|
|
1024
|
-
together: "Atomic commands with Yichus/Transaction",
|
|
1025
|
-
partial: "Transaction protocols: finite cases, retries, and receipts",
|
|
1026
|
-
outside: "Transaction protocols: finite cases, retries, and receipts"
|
|
1027
|
-
};
|
|
1028
|
-
function nextStep(state, compileErrors) {
|
|
1029
|
-
if (!state.description) return {
|
|
1030
|
-
stage: "describe",
|
|
1031
|
-
summary: "Waiting for a description of what to build.",
|
|
1032
|
-
instructions: ["Ask the person what they want to build, in their own words. Call yichus_start with their description, unchanged."]
|
|
1033
|
-
};
|
|
1034
|
-
if (!state.files.length) return {
|
|
1035
|
-
stage: "write",
|
|
1036
|
-
summary: "No program yet.",
|
|
1037
|
-
instructions: [
|
|
1038
|
-
'Call api_guide with section "Required workflow", then write the program as .bosatsu files in this project folder.',
|
|
1039
|
-
"For an app that stores records, call api_scaffold first and save its module as a file here. You never need to pass sources: the studio reads every .bosatsu file in the folder.",
|
|
1040
|
-
"Then call yichus_next."
|
|
1041
|
-
]
|
|
1042
|
-
};
|
|
1043
|
-
if (compileErrors) return {
|
|
1044
|
-
stage: "fix-compile",
|
|
1045
|
-
summary: "The program does not compile yet.",
|
|
1046
|
-
instructions: ["Fix these compile errors in the files, then call yichus_next."],
|
|
1047
|
-
evidence: compileErrors
|
|
1048
|
-
};
|
|
1049
|
-
const unnamed = /* @__PURE__ */ new Map();
|
|
1050
|
-
for (const { question } of state.properties) {
|
|
1051
|
-
if (question.subject !== null && !(question.subject in state.names)) unnamed.set(question.subject, [...unnamed.get(question.subject) ?? [], question.fact]);
|
|
1052
|
-
}
|
|
1053
|
-
for (const { code, what } of state.map ? nameableParts(state.map) : []) {
|
|
1054
|
-
if (!(code in state.names) && !unnamed.has(code)) unnamed.set(code, [`${what[0].toUpperCase()}${what.slice(1)}.`]);
|
|
1055
|
-
}
|
|
1056
|
-
if (unnamed.size) return {
|
|
1057
|
-
stage: "name",
|
|
1058
|
-
summary: "Your agent is putting the parts of your app into plain words.",
|
|
1059
|
-
instructions: [
|
|
1060
|
-
`The person sees these parts of the program in questions and in the picture of the program. Give each a short name in the person's own vocabulary, never a code name, path or table name (for example "family lists" or "starting a new list"). Name a kind of value plainly too ("text", "a number"):`,
|
|
1061
|
-
...[...unnamed].map(([subject, facts]) => `${subject}: ${facts.join(" ")}`),
|
|
1062
|
-
"Call yichus_name with all of them at once, then call yichus_next."
|
|
1063
|
-
]
|
|
1064
|
-
};
|
|
1065
|
-
const unanswered = state.properties.filter((p) => p.status === "unanswered");
|
|
1066
|
-
if (unanswered.length) return {
|
|
1067
|
-
stage: "ask",
|
|
1068
|
-
summary: `${unanswered.length} question${unanswered.length === 1 ? "" : "s"} for you about how the app should behave.`,
|
|
1069
|
-
instructions: [
|
|
1070
|
-
"Ask the person each question below, in its words, with its choices. They may also answer on the studio page.",
|
|
1071
|
-
"Speak in product terms: never quote question ids, code names, file names, tool names or the programming language to the person.",
|
|
1072
|
-
'Do not answer for them and do not pick a default: these are product decisions only they can make. If they are unsure, explain the "why" and the choices.',
|
|
1073
|
-
"Record each answer with yichus_answer (the question id, the choice id, and their own words), then call yichus_next."
|
|
1074
|
-
],
|
|
1075
|
-
ask: unanswered.map((p) => ({ id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices }))
|
|
1076
|
-
};
|
|
1077
|
-
const mismatched = state.properties.filter((p) => p.status === "mismatch");
|
|
1078
|
-
if (mismatched.length) return {
|
|
1079
|
-
stage: "declare",
|
|
1080
|
-
summary: "The program's declared rules do not match what you chose yet.",
|
|
1081
|
-
instructions: [
|
|
1082
|
-
...mismatched.map((p) => `Make the AccessSpec rule for "${p.question.subject}" ${ACCESS_POLICY[p.answer.choice]} (api_add_rule gives the snippet; api_guide section "${p.answer.choice === "owner" ? "Owner-scoped data" : p.answer.choice === "shared" ? "Guarded data" : "Public data"}" explains it).`),
|
|
1083
|
-
"Then call yichus_next."
|
|
1084
|
-
],
|
|
1085
|
-
evidence: mismatched.flatMap((p) => p.evidence)
|
|
1086
|
-
};
|
|
1087
|
-
const broken = state.properties.filter((p) => p.status === "broken" || p.status === "inconclusive");
|
|
1088
|
-
if (broken.length || state.other.length) return {
|
|
1089
|
-
stage: "fix",
|
|
1090
|
-
summary: `${broken.length + state.other.length} propert${broken.length + state.other.length === 1 ? "y is" : "ies are"} not holding yet.`,
|
|
1091
|
-
instructions: [
|
|
1092
|
-
"Fix the program so each property below holds. The evidence lines are the engine's own words.",
|
|
1093
|
-
...broken.map((p) => `"${p.question.ask}" The person chose "${p.question.choices.find((c) => c.id === p.answer?.choice)?.label}". Read api_guide section "${GUIDE[p.question.kind]}".`),
|
|
1094
|
-
...state.other.map((o) => `${o.title} (${o.id}) is ${o.status}.`),
|
|
1095
|
-
"Never weaken a rule, delete a check, or declare one server to make a check pass: change the code. Then call yichus_next."
|
|
1096
|
-
],
|
|
1097
|
-
evidence: [...broken.flatMap((p) => p.evidence), ...state.other.flatMap((o) => o.details)]
|
|
1098
|
-
};
|
|
1099
|
-
const cases = state.properties.filter((p) => p.status === "needs-case");
|
|
1100
|
-
if (cases.length) return {
|
|
1101
|
-
stage: "write-case",
|
|
1102
|
-
summary: "Writing the failure scenarios that test your answers.",
|
|
1103
|
-
instructions: [
|
|
1104
|
-
'Call yichus_reference with topic "protocol-case": it returns the case specification and a complete worked case with its program.',
|
|
1105
|
-
"Put any Bosatsu observation predicates the case names in .yichus/cases/*.bosatsu. The studio adds those files to protocol checks only, so they never count as part of the app.",
|
|
1106
|
-
...cases.map((p) => `Write ${p.casePath}: a protocol-case-1.0 for ${p.question.subject} whose invariants state the person's choice ("${p.question.choices.find((c) => c.id === p.answer?.choice)?.label}"), with crashes${p.question.kind === "outside" ? " and failed external results" : ""} at each step.`),
|
|
1107
|
-
"State the person's rule exactly; never weaken it to match the code. Then call yichus_next."
|
|
1108
|
-
]
|
|
1109
|
-
};
|
|
1110
|
-
const assumed = state.properties.filter((p) => p.status === "assumed");
|
|
1111
|
-
return {
|
|
1112
|
-
stage: "done",
|
|
1113
|
-
summary: assumed.length ? "Everything you chose holds, under the assumptions shown." : "Everything you chose holds.",
|
|
1114
|
-
instructions: [
|
|
1115
|
-
"Tell the person every property they chose holds, and point them at the studio page for the evidence.",
|
|
1116
|
-
...assumed.length ? ["Say plainly which results depend on running exactly one server."] : [],
|
|
1117
|
-
"When they describe a new feature, change the code and call yichus_next again: new facts can raise new questions."
|
|
1118
|
-
]
|
|
1119
|
-
};
|
|
1120
|
-
}
|
|
1121
|
-
async function direct({ root, engine, requirements, withMap = true, previous = null }) {
|
|
1122
|
-
const sources = projectSources(root);
|
|
1123
|
-
const hash = sourcesHash(sources);
|
|
1124
|
-
const instances = instancesFor(requirements);
|
|
1125
|
-
const base = {
|
|
1126
|
-
schemaVersion: "yichus-studio-state-1",
|
|
1127
|
-
project: path3.basename(path3.resolve(root)),
|
|
1128
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1129
|
-
sourcesHash: hash,
|
|
1130
|
-
files: sources.map((s) => s.fileName),
|
|
1131
|
-
description: requirements.description,
|
|
1132
|
-
names: requirements.names ?? {},
|
|
1133
|
-
topology: null,
|
|
1134
|
-
proven: null,
|
|
1135
|
-
properties: [],
|
|
1136
|
-
other: [],
|
|
1137
|
-
map: null,
|
|
1138
|
-
mapError: null
|
|
1139
|
-
};
|
|
1140
|
-
let compileErrors = null;
|
|
1141
|
-
if (requirements.description && sources.length) {
|
|
1142
|
-
const verify = Verify.parse(await call(engine, "api_verify", { sources, ...instances ? { instances } : {} }));
|
|
1143
|
-
base.topology = verify.topology ?? null;
|
|
1144
|
-
base.proven = verify.verdict.proven;
|
|
1145
|
-
const compiles = verify.verdict.properties.find((p) => p.id === "compiles");
|
|
1146
|
-
if (compiles && compiles.status !== "proven") compileErrors = compiles.details;
|
|
1147
|
-
else {
|
|
1148
|
-
const report = Report.parse(await call(engine, "api_report", { sources }));
|
|
1149
|
-
const structureRaw = await call(engine, "api_organize", { sources, lens: "structure" });
|
|
1150
|
-
const structure = Structure.parse(structureRaw);
|
|
1151
|
-
for (const question of questionsFor(report, structure, base.names)) {
|
|
1152
|
-
base.properties.push(await judge(root, engine, sources, question, answerOf(requirements, question.id), report, verify.verdict.properties));
|
|
1153
|
-
}
|
|
1154
|
-
base.other = verify.verdict.properties.filter((p) => !QUESTION_PROPERTIES(p.id) && p.status !== "proven" && !isAccepted(p)).map(({ id, title: title2, status, details }) => ({ id, title: title2, status, details }));
|
|
1155
|
-
if (withMap) {
|
|
1156
|
-
if (previous?.sourcesHash === hash && previous.map) base.map = previous.map;
|
|
1157
|
-
else {
|
|
1158
|
-
try {
|
|
1159
|
-
const [abstractions, layers] = [
|
|
1160
|
-
await call(engine, "api_organize", { sources, lens: "abstractions" }),
|
|
1161
|
-
await call(engine, "api_organize", { sources, lens: "layers" })
|
|
1162
|
-
];
|
|
1163
|
-
base.map = buildSystemMap({ report, structure: structureRaw, abstractions, layers }, { program: base.project });
|
|
1164
|
-
} catch (error) {
|
|
1165
|
-
base.mapError = error instanceof Error ? error.message : String(error);
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
const state = { ...base, step: nextStep(base, compileErrors) };
|
|
1172
|
-
writeState(root, state);
|
|
1173
|
-
return state;
|
|
1174
|
-
}
|
|
1175
|
-
function writeState(root, state) {
|
|
1176
|
-
ensureStudioDir(root);
|
|
1177
|
-
fs3.writeFileSync(path3.join(studioDir(root), "state.json"), `${JSON.stringify(state, null, 2)}
|
|
1178
|
-
`);
|
|
1179
|
-
}
|
|
1180
|
-
function readState(root) {
|
|
1181
|
-
const file = path3.join(studioDir(root), "state.json");
|
|
1182
|
-
return fs3.existsSync(file) ? JSON.parse(fs3.readFileSync(file, "utf8")) : null;
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
// src/studio/mcp.ts
|
|
1186
|
-
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
1187
|
-
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
1188
|
-
import { z as z6 } from "zod";
|
|
1189
|
-
|
|
1190
|
-
// src/studio/reference.ts
|
|
1191
|
-
import fs4 from "fs";
|
|
1192
|
-
import path4 from "path";
|
|
1193
|
-
import { fileURLToPath } from "url";
|
|
1194
|
-
|
|
1195
|
-
// src/studio/reference.json
|
|
1196
|
-
var reference_default = {
|
|
1197
|
-
"protocol-case": [
|
|
1198
|
-
{ name: "protocol-specification.txt", from: "docs/protocol-verification.md" },
|
|
1199
|
-
{ name: "withdrawal-case.json", from: "eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/case.json" },
|
|
1200
|
-
{ name: "withdrawal.bosatsu", from: "eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/ledger.bosatsu" }
|
|
1201
|
-
]
|
|
1202
|
-
};
|
|
1203
|
-
|
|
1204
|
-
// src/studio/reference.ts
|
|
1205
|
-
var TOPICS = Object.keys(reference_default);
|
|
1206
|
-
var BUILT_REFERENCE = fileURLToPath(new URL("./studio-reference/", import.meta.url));
|
|
1207
|
-
var REPO_ROOT = fileURLToPath(new URL("../../../../", import.meta.url));
|
|
1208
|
-
var builtCopy = (file) => path4.join(BUILT_REFERENCE, file.name);
|
|
1209
|
-
function readReference(topic, locate) {
|
|
1210
|
-
if (!TOPICS.includes(topic)) return null;
|
|
1211
|
-
return reference_default[topic].map((file) => `===== ${file.name} =====
|
|
1212
|
-
${fs4.readFileSync(locate(file), "utf8")}`).join("\n\n");
|
|
1213
|
-
}
|
|
1214
|
-
|
|
1215
|
-
// src/studio/text.ts
|
|
1216
|
-
var STATUS_WORDS = {
|
|
1217
|
-
unanswered: "not answered yet",
|
|
1218
|
-
decided: "decided",
|
|
1219
|
-
assumed: "holds under an assumption",
|
|
1220
|
-
proven: "proven",
|
|
1221
|
-
bounded: "holds in every scenario checked",
|
|
1222
|
-
broken: "broken",
|
|
1223
|
-
mismatch: "declared differently from the answer",
|
|
1224
|
-
"needs-case": "needs a failure scenario",
|
|
1225
|
-
inconclusive: "not decided by the check",
|
|
1226
|
-
"no-check": "no check needed"
|
|
1227
|
-
};
|
|
1228
|
-
function stepText(state, pageUrl) {
|
|
1229
|
-
const { step } = state;
|
|
1230
|
-
const lines = [`Stage: ${step.stage}. ${step.summary}`, "", "Do this:", ...step.instructions.map((s, i) => `${i + 1}. ${s}`)];
|
|
1231
|
-
for (const q of step.ask ?? []) {
|
|
1232
|
-
lines.push("", `Question ${q.id}: ${q.ask}`, ` Why it matters: ${q.why}`);
|
|
1233
|
-
for (const c of q.choices) lines.push(` - ${c.id}: ${c.label}. ${c.means}`);
|
|
1234
|
-
}
|
|
1235
|
-
if (step.evidence?.length) lines.push("", "Evidence (engine output):", ...step.evidence.map((e) => ` ${e}`));
|
|
1236
|
-
const answered = state.properties.filter((p) => p.status !== "unanswered");
|
|
1237
|
-
if (answered.length) {
|
|
1238
|
-
lines.push("", "Properties:");
|
|
1239
|
-
for (const p of answered) {
|
|
1240
|
-
const choice = p.question.choices.find((c) => c.id === p.answer?.choice)?.label ?? p.answer?.choice;
|
|
1241
|
-
lines.push(` ${p.question.id} (${choice}): ${STATUS_WORDS[p.status]}`);
|
|
1242
|
-
}
|
|
1243
|
-
}
|
|
1244
|
-
if (pageUrl) lines.push("", `Studio page: ${pageUrl}`);
|
|
1245
|
-
return `${lines.join("\n")}
|
|
1246
|
-
`;
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
// src/studio/mcp.ts
|
|
1250
|
-
var INSTRUCTIONS = `Yichus studio: you are building software for a person who will not read the code. Yichus tells you what to do next and proves the properties the person chooses.
|
|
1251
|
-
|
|
1252
|
-
The loop:
|
|
1253
|
-
1. Ask the person what they want built and call yichus_start with their words.
|
|
1254
|
-
2. After every change to the code, call yichus_next and do exactly what it says. It reads the .bosatsu files in the project folder itself; you never paste sources.
|
|
1255
|
-
3. When yichus_next lists questions, put each one to the person with its choices and record their answer with yichus_answer. Never answer for them or pick a default: who may see data, what happens when two people act at once, and what happens when a server or an outside service fails are their product decisions.
|
|
1256
|
-
4. Never weaken a rule, delete a check, or declare a single server to make a check pass. Change the code.
|
|
1257
|
-
5. Give the person the studio page link from yichus_start. It shows the shape of their program and whether each property they chose holds.
|
|
1258
|
-
6. Speak to the person in product terms. They never need the programming language, code names, file names, tool names or question ids; when yichus_next asks you to name parts of the program, use the words they would use.
|
|
1259
|
-
|
|
1260
|
-
Every api_* tool is available too. Leave out sources and the studio supplies the project's files.`;
|
|
1261
|
-
var START = {
|
|
1262
|
-
name: "yichus_start",
|
|
1263
|
-
description: "Record what the person wants built, in their own words, and get the studio page link to give them. Call this first.",
|
|
1264
|
-
inputSchema: { type: "object", properties: { description: { type: "string", description: "The person's description of the software, unchanged." } }, required: ["description"] }
|
|
1265
|
-
};
|
|
1266
|
-
var NEXT = {
|
|
1267
|
-
name: "yichus_next",
|
|
1268
|
-
description: "Read the program from the project folder, run the checks, and return the one next step: questions to ask the person, code to fix, a declaration to add, or done. Call after every change.",
|
|
1269
|
-
inputSchema: { type: "object", properties: {} }
|
|
1270
|
-
};
|
|
1271
|
-
var ANSWER = {
|
|
1272
|
-
name: "yichus_answer",
|
|
1273
|
-
description: "Record the person's answer to a question yichus_next listed: the question id, the id of the choice they picked, and their own words.",
|
|
1274
|
-
inputSchema: { type: "object", properties: {
|
|
1275
|
-
question: { type: "string", description: "The question id from yichus_next." },
|
|
1276
|
-
choice: { type: "string", description: "The id of the choice the person picked." },
|
|
1277
|
-
words: { type: "string", description: "What the person said, in their words." }
|
|
1278
|
-
}, required: ["question", "choice", "words"] }
|
|
1279
|
-
};
|
|
1280
|
-
var NAME = {
|
|
1281
|
-
name: "yichus_name",
|
|
1282
|
-
description: "Give the parts of the program yichus_next listed (kinds of record, actions, pieces of the program) the short plain names the person would use. The person sees these names instead of the code names, in questions and in the picture.",
|
|
1283
|
-
inputSchema: { type: "object", properties: {
|
|
1284
|
-
names: {
|
|
1285
|
-
type: "object",
|
|
1286
|
-
additionalProperties: { type: "string" },
|
|
1287
|
-
description: `Each code name yichus_next listed, such as a table name or a route path, with a few words in the person's vocabulary, such as "family lists" or "starting a new list".`
|
|
1288
|
-
}
|
|
1289
|
-
}, required: ["names"] }
|
|
1290
|
-
};
|
|
1291
|
-
var REFERENCE_TOOL = {
|
|
1292
|
-
name: "yichus_reference",
|
|
1293
|
-
description: "Reference material yichus_next asks for, such as the protocol case specification with a complete worked case.",
|
|
1294
|
-
inputSchema: { type: "object", properties: { topic: { type: "string", enum: TOPICS, description: "The topic yichus_next named." } }, required: ["topic"] }
|
|
1295
|
-
};
|
|
1296
|
-
var StartArgs = z6.object({ description: z6.string().min(1) });
|
|
1297
|
-
var AnswerArgs = z6.object({ question: z6.string().min(1), choice: z6.string().min(1), words: z6.string() });
|
|
1298
|
-
var NameArgs = z6.object({ names: z6.record(z6.string().min(1), z6.string().trim().min(1)).refine((names) => Object.keys(names).length > 0) });
|
|
1299
|
-
var text = (body, structured, isError = false) => ({ content: [{ type: "text", text: body }], ...structured ? { structuredContent: structured } : {}, isError });
|
|
1300
|
-
function studioTool(tool) {
|
|
1301
|
-
const schema = tool.inputSchema;
|
|
1302
|
-
if (!schema.properties || !("sources" in schema.properties)) return tool;
|
|
1303
|
-
return {
|
|
1304
|
-
...tool,
|
|
1305
|
-
description: [tool.description, "In the studio, leave out sources to check every .bosatsu file in the project folder."].filter(Boolean).join(" "),
|
|
1306
|
-
inputSchema: { ...schema, required: (schema.required ?? []).filter((name) => name !== "sources") }
|
|
1307
|
-
};
|
|
1308
|
-
}
|
|
1309
|
-
function recordAnswer(root, args, now) {
|
|
1310
|
-
const parsed = AnswerArgs.safeParse(args);
|
|
1311
|
-
if (!parsed.success) return { ok: false, error: "yichus_answer needs question, choice and words." };
|
|
1312
|
-
const state = readState(root);
|
|
1313
|
-
const property = state?.properties.find((p) => p.question.id === parsed.data.question);
|
|
1314
|
-
if (!property) return { ok: false, error: `No question ${parsed.data.question} in the latest yichus_next; call yichus_next and use its ids.` };
|
|
1315
|
-
if (!property.question.choices.some((c) => c.id === parsed.data.choice)) {
|
|
1316
|
-
return { ok: false, error: `${parsed.data.choice} is not a choice of ${parsed.data.question}; the choices are ${property.question.choices.map((c) => c.id).join(", ")}.` };
|
|
1317
|
-
}
|
|
1318
|
-
saveRequirements(root, withAnswer(loadRequirements(root), { ...parsed.data, answeredAt: now.toISOString() }));
|
|
1319
|
-
return { ok: true };
|
|
1320
|
-
}
|
|
1321
|
-
function recordNames(root, args) {
|
|
1322
|
-
const parsed = NameArgs.safeParse(args);
|
|
1323
|
-
if (!parsed.success) return { ok: false, error: "yichus_name needs names: each code name yichus_next listed, with its plain name." };
|
|
1324
|
-
const state = readState(root);
|
|
1325
|
-
const parts = /* @__PURE__ */ new Set([...state?.properties.flatMap((p) => p.question.subject ?? []) ?? [], ...state?.map ? nameableParts(state.map).map((p) => p.code) : []]);
|
|
1326
|
-
const unknown = Object.keys(parsed.data.names).filter((code) => !parts.has(code));
|
|
1327
|
-
if (unknown.length) {
|
|
1328
|
-
const listed = [...parts].slice(0, 20).join(", ") + (parts.size > 20 ? `, and ${parts.size - 20} more` : "");
|
|
1329
|
-
return { ok: false, error: `No part named ${unknown.join(", ")} in the latest yichus_next; the parts are ${listed || "none yet"}.` };
|
|
1330
|
-
}
|
|
1331
|
-
saveRequirements(root, withNames(loadRequirements(root), parsed.data.names));
|
|
1332
|
-
return { ok: true };
|
|
1333
|
-
}
|
|
1334
|
-
function createStudioMcpServer({ root, engine, catalog, pageUrl, now = () => /* @__PURE__ */ new Date(), locate = builtCopy }) {
|
|
1335
|
-
const server = new Server({ name: "yichus-studio", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
1336
|
-
const active = /* @__PURE__ */ new Set();
|
|
1337
|
-
const track = (task) => {
|
|
1338
|
-
active.add(task);
|
|
1339
|
-
void task.finally(() => active.delete(task)).catch(() => {
|
|
1340
|
-
});
|
|
1341
|
-
return task;
|
|
1342
|
-
};
|
|
1343
|
-
let tools = null;
|
|
1344
|
-
const catalogTools2 = async () => tools ??= (await catalog()).map(studioTool);
|
|
1345
|
-
let last = readState(root);
|
|
1346
|
-
server.setRequestHandler(ListToolsRequestSchema, () => track((async () => ({ tools: [START, NEXT, NAME, ANSWER, REFERENCE_TOOL, ...await catalogTools2()] }))()));
|
|
1347
|
-
server.setRequestHandler(CallToolRequestSchema, (request) => track(callTool(request.params)));
|
|
1348
|
-
async function callTool(params) {
|
|
1349
|
-
const { name, arguments: args = {} } = params;
|
|
1350
|
-
if (name === "yichus_start") {
|
|
1351
|
-
const parsed = StartArgs.safeParse(args);
|
|
1352
|
-
if (!parsed.success) return text("yichus_start needs the person's description.", void 0, true);
|
|
1353
|
-
saveRequirements(root, { ...loadRequirements(root), description: parsed.data.description });
|
|
1354
|
-
const page = pageUrl ? `Give the person this link and ask them to keep it open: ${pageUrl}` : "No studio page is running.";
|
|
1355
|
-
return text(`${page}
|
|
1356
|
-
Next: call yichus_next.`, { pageUrl });
|
|
1357
|
-
}
|
|
1358
|
-
if (name === "yichus_next") {
|
|
1359
|
-
last = await direct({ root, engine, requirements: loadRequirements(root), previous: last });
|
|
1360
|
-
const { map: _map, ...rest } = last;
|
|
1361
|
-
return text(stepText(last, pageUrl), rest);
|
|
1362
|
-
}
|
|
1363
|
-
if (name === "yichus_answer") {
|
|
1364
|
-
const result2 = recordAnswer(root, args, now());
|
|
1365
|
-
return result2.ok ? text("Recorded. Ask any remaining questions, then call yichus_next.") : text(result2.error, void 0, true);
|
|
1366
|
-
}
|
|
1367
|
-
if (name === "yichus_name") {
|
|
1368
|
-
const result2 = recordNames(root, args);
|
|
1369
|
-
return result2.ok ? text("Recorded. Call yichus_next.") : text(result2.error, void 0, true);
|
|
1370
|
-
}
|
|
1371
|
-
if (name === "yichus_reference") {
|
|
1372
|
-
const said = readReference(String(args.topic), locate);
|
|
1373
|
-
return said ? text(said) : text(`No reference topic ${String(args.topic)}; the topics are ${TOPICS.join(", ")}.`, void 0, true);
|
|
1374
|
-
}
|
|
1375
|
-
const tool = (await catalogTools2()).find((t) => t.name === name);
|
|
1376
|
-
if (!tool) return text(`Unknown tool ${name}.`, void 0, true);
|
|
1377
|
-
const filled = { ...args };
|
|
1378
|
-
const props = tool.inputSchema.properties ?? {};
|
|
1379
|
-
if ("sources" in props && filled.sources === void 0) {
|
|
1380
|
-
filled.sources = name === "api_protocol_check" ? [...projectSources(root), ...caseSources(root)] : projectSources(root);
|
|
1381
|
-
}
|
|
1382
|
-
const topology2 = loadRequirements(root).answers.find((a) => a.question === "topology")?.choice;
|
|
1383
|
-
if ("instances" in props && filled.instances === void 0 && topology2) filled.instances = topology2 === "one" ? "1" : "many";
|
|
1384
|
-
const result = await engine.call(name, filled);
|
|
1385
|
-
if (name === "api_guide" && filled.section === void 0 && Array.isArray(result.sections)) {
|
|
1386
|
-
const titles = {
|
|
1387
|
-
ok: true,
|
|
1388
|
-
tool: "api_guide",
|
|
1389
|
-
titles: result.sections.map((s) => s.title),
|
|
1390
|
-
note: "The whole guide is long. Call api_guide with section set to one of these titles, or to part of one."
|
|
1391
|
-
};
|
|
1392
|
-
return text(JSON.stringify(titles), titles);
|
|
1393
|
-
}
|
|
1394
|
-
return text(JSON.stringify(result), result, result.ok !== true);
|
|
1395
|
-
}
|
|
1396
|
-
return {
|
|
1397
|
-
server,
|
|
1398
|
-
async idle() {
|
|
1399
|
-
while (active.size) await Promise.allSettled(active);
|
|
1400
|
-
await new Promise((resolve) => setImmediate(resolve));
|
|
1401
|
-
}
|
|
1402
|
-
};
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
// src/studio/command.ts
|
|
1406
|
-
var STUDIO_COMMANDS = /* @__PURE__ */ new Set(["start", "next", "name", "answer", "reference", "studio"]);
|
|
1407
|
-
var STUDIO_HELP = `
|
|
1408
|
-
Studio (guided building; all take --project DIR, default the current folder):
|
|
1409
|
-
yichus studio [--port N] MCP server on stdio plus the studio page
|
|
1410
|
-
yichus studio --page [--port N] only the studio page, for the commands below
|
|
1411
|
-
yichus start "DESCRIPTION" record what the person wants built
|
|
1412
|
-
yichus next [--json] check the program and print the next step
|
|
1413
|
-
yichus name SUBJECT "NAME" ... plain names the person sees for parts of the program
|
|
1414
|
-
yichus answer QUESTION CHOICE [--words TEXT]
|
|
1415
|
-
yichus reference TOPIC reference material a step asks for
|
|
1416
|
-
`;
|
|
1417
|
-
async function runStudioCommand(argv2, io) {
|
|
1418
|
-
try {
|
|
1419
|
-
const { values, positionals } = parseArgs({ args: argv2, allowPositionals: true, strict: true, options: {
|
|
1420
|
-
project: { type: "string" },
|
|
1421
|
-
json: { type: "boolean" },
|
|
1422
|
-
words: { type: "string" },
|
|
1423
|
-
page: { type: "boolean" },
|
|
1424
|
-
port: { type: "string" }
|
|
1425
|
-
} });
|
|
1426
|
-
const [command, ...rest] = positionals;
|
|
1427
|
-
const root = path5.resolve(values.project ?? ".");
|
|
1428
|
-
const expect = (n, usage) => {
|
|
1429
|
-
if (rest.length !== n) throw new Error(`Usage: ${usage}`);
|
|
1430
|
-
};
|
|
1431
|
-
if (command === "start") {
|
|
1432
|
-
expect(1, 'yichus start "DESCRIPTION"');
|
|
1433
|
-
saveRequirements(root, { ...loadRequirements(root), description: rest[0] });
|
|
1434
|
-
io.stderr("Recorded the description. Next: yichus next\n");
|
|
1435
|
-
return 0;
|
|
1436
|
-
}
|
|
1437
|
-
if (command === "name") {
|
|
1438
|
-
if (!rest.length || rest.length % 2) throw new Error('Usage: yichus name SUBJECT "NAME" [SUBJECT "NAME" ...]');
|
|
1439
|
-
const names = Object.fromEntries(rest.flatMap((s, i) => i % 2 ? [] : [[s, rest[i + 1]]]));
|
|
1440
|
-
const result = recordNames(root, { names });
|
|
1441
|
-
if (!result.ok) throw new Error(result.error);
|
|
1442
|
-
io.stderr(`Named ${Object.entries(names).map(([subject, name]) => `${subject} "${name}"`).join(", ")}. Next: yichus next
|
|
1443
|
-
`);
|
|
1444
|
-
return 0;
|
|
1445
|
-
}
|
|
1446
|
-
if (command === "answer") {
|
|
1447
|
-
expect(2, "yichus answer QUESTION CHOICE [--words TEXT]");
|
|
1448
|
-
const [question, choice] = rest;
|
|
1449
|
-
const result = recordAnswer(root, { question, choice, words: values.words ?? "" }, io.now());
|
|
1450
|
-
if (!result.ok) throw new Error(result.error);
|
|
1451
|
-
io.stderr(`Recorded ${choice} for ${question}. Next: yichus next
|
|
1452
|
-
`);
|
|
1453
|
-
return 0;
|
|
1454
|
-
}
|
|
1455
|
-
if (command === "reference") {
|
|
1456
|
-
expect(1, "yichus reference TOPIC");
|
|
1457
|
-
const said = readReference(rest[0], io.locate);
|
|
1458
|
-
if (!said) throw new Error(`No reference topic ${rest[0]}`);
|
|
1459
|
-
io.stdout(`${said}
|
|
1460
|
-
`);
|
|
1461
|
-
return 0;
|
|
1462
|
-
}
|
|
1463
|
-
if (command === "next") {
|
|
1464
|
-
expect(0, "yichus next [--json]");
|
|
1465
|
-
const state = await direct({ root, engine: await io.engine(), requirements: loadRequirements(root), previous: readState(root) });
|
|
1466
|
-
io.stdout(values.json ? `${JSON.stringify(state, null, 2)}
|
|
1467
|
-
` : stepText(state, null));
|
|
1468
|
-
return 0;
|
|
1469
|
-
}
|
|
1470
|
-
expect(0, "yichus studio [--page] [--port N]");
|
|
1471
|
-
const port = values.port === void 0 ? null : Number(values.port);
|
|
1472
|
-
if (port !== null && (!Number.isInteger(port) || port < 0 || port > 65535)) throw new Error("--port must be a port number");
|
|
1473
|
-
await io.serve({ root, port, pageOnly: values.page ?? false });
|
|
1474
|
-
return 0;
|
|
1475
|
-
} catch (error) {
|
|
1476
|
-
io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}
|
|
1477
|
-
`);
|
|
1478
|
-
return 2;
|
|
1479
|
-
}
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
// src/run.ts
|
|
1483
|
-
var HELP = `yichus \u2014 the Yichus WebMCP analysis engine, locally
|
|
1484
|
-
|
|
1485
|
-
yichus tools
|
|
1486
|
-
yichus call TOOL [--args JSON_FILE|-] [--source FILE ...]
|
|
1487
|
-
yichus verify FILE ... [--instances 1|many] [--block-on-warning ID ...]
|
|
1488
|
-
yichus lean FILE ... --lean-wasm-root DIRECTORY [--timeout-ms N]
|
|
1489
|
-
${STUDIO_HELP}
|
|
1490
|
-
Options:
|
|
1491
|
-
--source FILE Add a Bosatsu source (repeatable; call only). Files
|
|
1492
|
-
sharing a basename are named by their folders.
|
|
1493
|
-
--args FILE|- Tool arguments as a JSON object; - reads stdin.
|
|
1494
|
-
--block-on-warning ID A property id whose warning blocks the verdict, as a
|
|
1495
|
-
violation would (repeatable; all names every property;
|
|
1496
|
-
verify only). An id the verdict lacks exits 2.
|
|
1497
|
-
--output FILE Write the result to this file instead of stdout.
|
|
1498
|
-
--select /POINTER Extract a JSON field; strings are written verbatim.
|
|
1499
|
-
--expect /PTR=JSON Fail unless a result field exactly equals JSON (repeatable).
|
|
1500
|
-
--bundle FILE Explicit Scala.js engine override.
|
|
1501
|
-
--lean-wasm-root DIR Pinned local Lean Wasm installation (lean only).
|
|
1502
|
-
--timeout-ms N Total proof budget, at most 300000 (lean only).
|
|
1503
|
-
--help, -h Show this help without loading the engine.
|
|
1504
|
-
|
|
1505
|
-
tools and call expose Yichus/Mcp::catalog without a second analysis layer.
|
|
1506
|
-
verify runs api_verify and requires verdict.proven to be exactly true.
|
|
1507
|
-
Its JSON opens with proven, the verdict; ok only says the check ran.
|
|
1508
|
-
It always prints a plain summary of the verdict to stderr: each property's
|
|
1509
|
-
status, the first failure's evidence (parse errors carry file:line:col),
|
|
1510
|
-
and where the full JSON verdict went.
|
|
1511
|
-
lean runs the pinned Wasm kernel and requires all discovered obligations to be verified.
|
|
1512
|
-
It prints on stderr whether each law was proven and, if not, why: Lean
|
|
1513
|
-
rejected it (with Lean's words), the law is outside what Lean Wasm admits,
|
|
1514
|
-
the --timeout-ms budget ran out, or no runtime is installed (with the
|
|
1515
|
-
install command).
|
|
1516
|
-
call requires ok:true; use --expect to gate on a check's actual verdict.
|
|
1517
|
-
When the tool fails, stderr gives its error as plain text, what to do
|
|
1518
|
-
instead when the engine names the failure's kind (errorKinds), and where
|
|
1519
|
-
the JSON result went. An unmet --expect is one JSON line on stderr.
|
|
1520
|
-
With --output it says on stderr where the result went; api_abstraction_map
|
|
1521
|
-
also says what it is mapping before it starts, and afterwards its layer,
|
|
1522
|
-
reuse and copy counts in words, each with the JSON field that lists them.
|
|
1523
|
-
No browser is needed. Page editing, visible feedback and app sessions use
|
|
1524
|
-
the separate @yichus/mcp browser relay.
|
|
1525
|
-
|
|
1526
|
-
Exit status: 0 = completed and expectations met; 1 = tool/check rejected;
|
|
1527
|
-
2 = invalid invocation (including a --block-on-warning id the verdict lacks), malformed engine result, or execution/IO failure
|
|
1528
|
-
(for lean: no runtime, the budget ran out, or the runtime failed).
|
|
1529
|
-
JSON diagnostics remain available for rejected checks: the result JSON,
|
|
1530
|
-
or, when --select withheld it, a JSON line on stderr. --select emits no
|
|
1531
|
-
artifact on rejection. A named output is removed before execution so a
|
|
1532
|
-
failed check cannot leave yesterday's artifact behind.
|
|
1533
|
-
`;
|
|
1534
|
-
function pointerParts(pointer) {
|
|
1535
|
-
if (pointer === "") return [];
|
|
1536
|
-
if (!pointer.startsWith("/") || /~(?:[^01]|$)/u.test(pointer)) {
|
|
1537
|
-
throw new Error(`Invalid JSON Pointer: ${pointer}`);
|
|
1538
|
-
}
|
|
1539
|
-
return pointer.slice(1).split("/").map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
1540
|
-
}
|
|
1541
|
-
function readPointer(value, pointer) {
|
|
1542
|
-
for (const part of pointerParts(pointer)) {
|
|
1543
|
-
if (value === null || typeof value !== "object" || !Object.hasOwn(value, part)) return void 0;
|
|
1544
|
-
value = value[part];
|
|
1545
|
-
}
|
|
1546
|
-
return value;
|
|
1547
|
-
}
|
|
1548
|
-
function objectValue(value, label2) {
|
|
1549
|
-
const parsed = z7.record(z7.string(), z7.unknown()).safeParse(value);
|
|
1550
|
-
if (!parsed.success) throw new Error(`${label2} must be a JSON object`);
|
|
1551
|
-
return parsed.data;
|
|
1552
|
-
}
|
|
1553
|
-
var objectJson = (raw, label2) => objectValue(JSON.parse(raw), label2);
|
|
1554
|
-
var FLAGS = {
|
|
1555
|
-
source: { type: "string", multiple: true },
|
|
1556
|
-
args: { type: "string" },
|
|
1557
|
-
instances: { type: "string" },
|
|
1558
|
-
"block-on-warning": { type: "string", multiple: true },
|
|
1559
|
-
output: { type: "string" },
|
|
1560
|
-
bundle: { type: "string" },
|
|
1561
|
-
"lean-wasm-root": { type: "string" },
|
|
1562
|
-
"timeout-ms": { type: "string" },
|
|
1563
|
-
select: { type: "string" },
|
|
1564
|
-
expect: { type: "string", multiple: true }
|
|
1565
|
-
};
|
|
1566
|
-
var TimeoutMs = z7.coerce.number().int().min(1).max(3e5);
|
|
1567
|
-
function parse(argv2) {
|
|
1568
|
-
const { values, positionals, tokens } = parseArgs2({ args: argv2, options: FLAGS, allowPositionals: true, strict: true, tokens: true });
|
|
1569
|
-
const named = tokens.flatMap((token) => token.kind === "option" ? [token.name] : []);
|
|
1570
|
-
const repeated = named.find((name, i) => !("multiple" in FLAGS[name]) && named.indexOf(name) !== i);
|
|
1571
|
-
if (repeated) throw new Error(`Repeated --${repeated}`);
|
|
1572
|
-
const [command, ...rest] = positionals;
|
|
1573
|
-
if (command !== "tools" && command !== "call" && command !== "verify" && command !== "lean") {
|
|
1574
|
-
throw new Error("Expected tools, call TOOL, verify FILE, or lean FILE; use --help for usage.");
|
|
1575
|
-
}
|
|
1576
|
-
const opts = { command, sources: [], expects: [], blockOnWarnings: values["block-on-warning"] ?? [] };
|
|
1577
|
-
if (command === "call") {
|
|
1578
|
-
opts.tool = rest.shift();
|
|
1579
|
-
if (!opts.tool) throw new Error("call requires a tool name");
|
|
1580
|
-
}
|
|
1581
|
-
if ((command === "tools" || command === "call") && rest.length) throw new Error(`Unexpected argument: ${rest[0]}`);
|
|
1582
|
-
opts.sources = [...rest, ...values.source ?? []];
|
|
1583
|
-
opts.args = values.args;
|
|
1584
|
-
opts.instances = values.instances;
|
|
1585
|
-
opts.output = values.output;
|
|
1586
|
-
opts.bundle = values.bundle;
|
|
1587
|
-
opts.leanWasmRoot = values["lean-wasm-root"];
|
|
1588
|
-
if (values["timeout-ms"] !== void 0) {
|
|
1589
|
-
const timeout = TimeoutMs.safeParse(values["timeout-ms"]);
|
|
1590
|
-
if (!timeout.success) throw new Error("--timeout-ms must be an integer from 1 to 300000");
|
|
1591
|
-
opts.timeoutMs = timeout.data;
|
|
1592
|
-
}
|
|
1593
|
-
if (values.select !== void 0) {
|
|
1594
|
-
pointerParts(values.select);
|
|
1595
|
-
opts.select = values.select;
|
|
1596
|
-
}
|
|
1597
|
-
for (const value of values.expect ?? []) {
|
|
1598
|
-
const equal = value.indexOf("=");
|
|
1599
|
-
if (equal < 0) throw new Error("--expect requires /POINTER=JSON");
|
|
1600
|
-
const pointer = value.slice(0, equal);
|
|
1601
|
-
pointerParts(pointer);
|
|
1602
|
-
opts.expects.push({ pointer, value: JSON.parse(value.slice(equal + 1)) });
|
|
1603
|
-
}
|
|
1604
|
-
if (command === "tools" && (opts.sources.length || opts.args || opts.instances)) {
|
|
1605
|
-
throw new Error("tools does not accept sources or tool arguments");
|
|
1606
|
-
}
|
|
1607
|
-
if (command === "verify") {
|
|
1608
|
-
if (!opts.sources.length) throw new Error("verify requires at least one Bosatsu file");
|
|
1609
|
-
if (opts.args) throw new Error("verify accepts --instances; use call for arbitrary arguments");
|
|
1610
|
-
if (values.source !== void 0) throw new Error("verify takes positional files; --source is for call");
|
|
1611
|
-
if (opts.instances && opts.instances !== "1" && opts.instances !== "many") {
|
|
1612
|
-
throw new Error("--instances must be 1 or many");
|
|
1613
|
-
}
|
|
1614
|
-
opts.expects.push({ pointer: "/verdict/proven", value: true });
|
|
1615
|
-
} else if (command === "lean") {
|
|
1616
|
-
if (!opts.sources.length) throw new Error("lean requires at least one Bosatsu file");
|
|
1617
|
-
if (!opts.leanWasmRoot) throw new Error("lean requires --lean-wasm-root");
|
|
1618
|
-
if (opts.args || opts.instances || values.source !== void 0)
|
|
1619
|
-
throw new Error("lean takes positional files and a Wasm root");
|
|
1620
|
-
opts.expects.push({ pointer: "/allVerified", value: true });
|
|
1621
|
-
} else if (opts.instances) {
|
|
1622
|
-
throw new Error("--instances is for verify; pass catalog arguments through --args for call");
|
|
1623
|
-
}
|
|
1624
|
-
if (command !== "verify" && opts.blockOnWarnings.length)
|
|
1625
|
-
throw new Error("--block-on-warning is for verify; pass block_on_warnings through --args for call");
|
|
1626
|
-
if (command !== "lean" && (opts.leanWasmRoot || opts.timeoutMs !== void 0))
|
|
1627
|
-
throw new Error("--lean-wasm-root and --timeout-ms are for lean");
|
|
1628
|
-
return opts;
|
|
1629
|
-
}
|
|
1630
|
-
function closestSibling(file) {
|
|
1631
|
-
const dir = path6.dirname(file);
|
|
1632
|
-
const want = path6.basename(file);
|
|
1633
|
-
let names;
|
|
1634
|
-
try {
|
|
1635
|
-
names = fs5.readdirSync(dir);
|
|
1636
|
-
} catch {
|
|
1637
|
-
return void 0;
|
|
1638
|
-
}
|
|
1639
|
-
const distance = (a, b) => {
|
|
1640
|
-
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
1641
|
-
for (let i = 1; i <= a.length; i++) {
|
|
1642
|
-
let diagonal = row[0];
|
|
1643
|
-
row[0] = i;
|
|
1644
|
-
for (let j = 1; j <= b.length; j++) {
|
|
1645
|
-
const above = row[j];
|
|
1646
|
-
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
1647
|
-
diagonal = above;
|
|
1648
|
-
}
|
|
1649
|
-
}
|
|
1650
|
-
return row[b.length];
|
|
1651
|
-
};
|
|
1652
|
-
const scored = names.map((name) => ({ name, d: distance(want, name) })).filter(({ d }) => d <= 2).sort((x, y) => x.d - y.d);
|
|
1653
|
-
return scored.length ? path6.join(dir, scored[0].name) : void 0;
|
|
1654
|
-
}
|
|
1655
|
-
function readInput(file) {
|
|
1656
|
-
try {
|
|
1657
|
-
return fs5.readFileSync(file, "utf8");
|
|
1658
|
-
} catch (error) {
|
|
1659
|
-
const code = error?.code;
|
|
1660
|
-
if (code === "ENOENT") {
|
|
1661
|
-
const near = closestSibling(file);
|
|
1662
|
-
throw new Error(`File not found: ${file}${near ? `. Did you mean ${near}?` : ""}`);
|
|
1663
|
-
}
|
|
1664
|
-
if (code === "EISDIR") throw new Error(`${file} is a directory; name a file instead.`);
|
|
1665
|
-
if (code === "EACCES" || code === "EPERM") throw new Error(`Permission denied reading ${file}.`);
|
|
1666
|
-
throw error;
|
|
1667
|
-
}
|
|
1668
|
-
}
|
|
1669
|
-
function sourceNames(paths) {
|
|
1670
|
-
const parts = paths.map((p) => path6.resolve(p).split(path6.sep).filter((s) => s !== ""));
|
|
1671
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1672
|
-
parts.forEach((segments, i) => {
|
|
1673
|
-
const full = segments.join("/");
|
|
1674
|
-
if (seen.has(full)) throw new Error(`${paths[i]} names the same file as an earlier --source; name each source once`);
|
|
1675
|
-
seen.add(full);
|
|
1676
|
-
});
|
|
1677
|
-
const tail = (segments, n) => segments.slice(-n).join("/");
|
|
1678
|
-
return parts.map((segments, i) => {
|
|
1679
|
-
let n = 1;
|
|
1680
|
-
while (parts.some((other, j) => j !== i && tail(other, n) === tail(segments, n))) n += 1;
|
|
1681
|
-
return tail(segments, n);
|
|
1682
|
-
});
|
|
1683
|
-
}
|
|
1684
|
-
async function argumentsFor(opts, io) {
|
|
1685
|
-
const args = opts.args ? objectJson(opts.args === "-" ? await io.readStdin() : readInput(opts.args), "Arguments") : {};
|
|
1686
|
-
if (opts.sources.length) {
|
|
1687
|
-
if (Object.hasOwn(args, "sources")) throw new Error("Use either --source files or args.sources, not both");
|
|
1688
|
-
const names = sourceNames(opts.sources);
|
|
1689
|
-
args.sources = opts.sources.map((sourcePath, i) => ({ fileName: names[i], source: readInput(sourcePath) }));
|
|
1690
|
-
}
|
|
1691
|
-
if (opts.instances) args.instances = opts.instances;
|
|
1692
|
-
if (opts.blockOnWarnings.length) args.block_on_warnings = [...new Set(opts.blockOnWarnings)];
|
|
1693
|
-
return args;
|
|
1694
|
-
}
|
|
1695
|
-
function clearOutput(opts) {
|
|
1696
|
-
if (!opts.output) return;
|
|
1697
|
-
const output = path6.resolve(opts.output);
|
|
1698
|
-
const outputStat = fs5.existsSync(output) ? fs5.statSync(output) : void 0;
|
|
1699
|
-
for (const input of [...opts.sources, opts.args, opts.bundle].filter((p) => !!p && p !== "-")) {
|
|
1700
|
-
const inputStat = fs5.existsSync(input) ? fs5.statSync(input) : void 0;
|
|
1701
|
-
if (path6.resolve(input) === output || outputStat && inputStat && inputStat.dev === outputStat.dev && inputStat.ino === outputStat.ino) {
|
|
1702
|
-
throw new Error("--output must not overwrite an input file");
|
|
1703
|
-
}
|
|
1704
|
-
}
|
|
1705
|
-
fs5.rmSync(output, { force: true });
|
|
1706
|
-
}
|
|
1707
|
-
function rejection(result, unmet) {
|
|
1708
|
-
if (result.ok) return `${unmet} --expect ${unmet === 1 ? "expectation was" : "expectations were"} not met`;
|
|
1709
|
-
const said = EngineError.safeParse(result);
|
|
1710
|
-
return said.success ? said.data.error : "The tool failed without saying why; see its result";
|
|
1711
|
-
}
|
|
1712
|
-
async function runCli(argv2, io) {
|
|
1713
|
-
try {
|
|
1714
|
-
if (argv2.length === 0 || argv2.includes("--help") || argv2.includes("-h")) {
|
|
1715
|
-
io.stdout(HELP);
|
|
1716
|
-
return 0;
|
|
1717
|
-
}
|
|
1718
|
-
const opts = parse(argv2);
|
|
1719
|
-
clearOutput(opts);
|
|
1720
|
-
const args = await argumentsFor(opts, io);
|
|
1721
|
-
let result;
|
|
1722
|
-
const timeoutMs = opts.timeoutMs ?? 18e4;
|
|
1723
|
-
if (opts.command === "lean") {
|
|
1724
|
-
if (!io.checkLeanWasm) throw new Error("Lean Wasm backend is unavailable");
|
|
1725
|
-
io.stderr(`Checking the laws in ${opts.sources.join(", ")} with Lean Wasm at ${opts.leanWasmRoot} (budget ${timeoutMs} ms)...
|
|
1726
|
-
`);
|
|
1727
|
-
result = objectValue(await io.checkLeanWasm(
|
|
1728
|
-
opts.bundle,
|
|
1729
|
-
opts.leanWasmRoot,
|
|
1730
|
-
args.sources,
|
|
1731
|
-
timeoutMs
|
|
1732
|
-
), "Lean result");
|
|
1733
|
-
} else {
|
|
1734
|
-
if (opts.command === "call") {
|
|
1735
|
-
const files = Array.isArray(args.sources) ? args.sources.length : void 0;
|
|
1736
|
-
const progress = callProgress(opts.tool, files);
|
|
1737
|
-
if (progress) io.stderr(progress);
|
|
1738
|
-
}
|
|
1739
|
-
const engine = await io.loadEngine(opts.bundle);
|
|
1740
|
-
const raw = opts.command === "tools" ? engine.listTools() : engine.callTool(opts.command === "verify" ? "api_verify" : opts.tool, JSON.stringify(args));
|
|
1741
|
-
result = objectJson(raw, "Engine result");
|
|
1742
|
-
}
|
|
1743
|
-
if (typeof result.ok !== "boolean") throw new Error("Engine result must explicitly contain boolean ok");
|
|
1744
|
-
const unmet = opts.expects.filter(({ pointer, value }) => !isDeepStrictEqual(readPointer(result, pointer), value));
|
|
1745
|
-
const passed = result.ok && unmet.length === 0;
|
|
1746
|
-
if (opts.select === void 0 || passed) {
|
|
1747
|
-
const selected = opts.select === void 0 ? result : readPointer(result, opts.select);
|
|
1748
|
-
if (selected === void 0) throw new Error(`Result field missing: ${opts.select}`);
|
|
1749
|
-
const text3 = opts.select !== void 0 && typeof selected === "string" ? selected : `${JSON.stringify(selected, null, 2)}
|
|
1750
|
-
`;
|
|
1751
|
-
if (opts.output) fs5.writeFileSync(opts.output, text3);
|
|
1752
|
-
else io.stdout(text3);
|
|
1753
|
-
}
|
|
1754
|
-
const artifact = opts.select !== void 0 ? "the unselected result; run without --select to see it" : opts.output ?? "the JSON on standard output";
|
|
1755
|
-
let exit = passed ? 0 : 1;
|
|
1756
|
-
if (opts.command === "verify") {
|
|
1757
|
-
io.stderr(verifySummary(result, passed, artifact));
|
|
1758
|
-
if (!result.ok && result.errorKind === "invalid-arguments") exit = 2;
|
|
1759
|
-
} else if (opts.command === "lean") {
|
|
1760
|
-
const reading = leanSummary(result, artifact, timeoutMs, opts.sources);
|
|
1761
|
-
io.stderr(reading.text);
|
|
1762
|
-
exit = reading.exit;
|
|
1763
|
-
} else if (!result.ok) {
|
|
1764
|
-
io.stderr(callFailure(opts.tool ?? "tools", result, artifact));
|
|
1765
|
-
} else if (passed && opts.select === void 0 && opts.command === "call") {
|
|
1766
|
-
const said = callSummary(opts.tool, result, opts.output);
|
|
1767
|
-
if (said) io.stderr(said);
|
|
1768
|
-
}
|
|
1769
|
-
const generic = opts.command === "call" || opts.command === "tools";
|
|
1770
|
-
if (!passed && (opts.select !== void 0 || generic && result.ok)) {
|
|
1771
|
-
io.stderr(`${JSON.stringify({ ok: false, error: rejection(result, unmet.length), unmet, result: opts.select === void 0 ? void 0 : result })}
|
|
1772
|
-
`);
|
|
1773
|
-
}
|
|
1774
|
-
return exit;
|
|
1775
|
-
} catch (error) {
|
|
1776
|
-
io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}
|
|
1777
|
-
`);
|
|
1778
|
-
return 2;
|
|
1779
|
-
}
|
|
1780
|
-
}
|
|
1781
|
-
|
|
1782
|
-
// src/studio/serve.ts
|
|
1783
|
-
import { once } from "events";
|
|
1784
|
-
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1785
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
1786
|
-
import { EngineWorkerClient, catalogTools } from "@yichus/api-mcp";
|
|
1787
|
-
|
|
1788
|
-
// src/studio/page-server.ts
|
|
1789
|
-
import fs6 from "fs";
|
|
1790
|
-
import http from "http";
|
|
1791
|
-
import path7 from "path";
|
|
1792
|
-
|
|
1793
|
-
// src/studio/page.ts
|
|
1794
|
-
var STUDIO_PAGE = `<!doctype html>
|
|
1795
|
-
<html lang="en">
|
|
1796
|
-
<head>
|
|
1797
|
-
<meta charset="utf-8">
|
|
1798
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1799
|
-
<title>Yichus studio</title>
|
|
1800
|
-
<link rel="stylesheet" href="system-map.css">
|
|
1801
|
-
<style>
|
|
1802
|
-
:root { --ink:#0f172a; --muted:#475569; --faint:#94a3b8; --rule:#e2e8f0; --paper:#ffffff; --page:#f6f8fb;
|
|
1803
|
-
--good:#047857; --goodSoft:#ecfdf5; --bad:#b91c1c; --badSoft:#fef2f2; --warn:#92400e; --warnSoft:#fffbeb; --accent:#22675e; }
|
|
1804
|
-
* { box-sizing:border-box; }
|
|
1805
|
-
body { margin:0; background:var(--page); color:var(--ink); font:16px/1.55 Inter, system-ui, sans-serif; }
|
|
1806
|
-
main { max-width:1100px; margin:0 auto; padding:24px 16px 64px; }
|
|
1807
|
-
header p { margin:4px 0 0; color:var(--muted); }
|
|
1808
|
-
h1 { font-size:1.6rem; margin:0; font-weight:600; }
|
|
1809
|
-
h2 { font-size:1.15rem; margin:32px 0 8px; }
|
|
1810
|
-
section > p.lede { color:var(--muted); margin:0 0 12px; max-width:70ch; }
|
|
1811
|
-
a.guide { color:var(--accent); font-weight:600; }
|
|
1812
|
-
.frame { background:var(--paper); border:1px solid var(--rule); border-radius:10px; padding:16px; position:relative; }
|
|
1813
|
-
.frame > .tag { position:absolute; top:-10px; left:12px; background:var(--page); padding:0 6px; font-size:0.72rem; letter-spacing:0.08em; text-transform:uppercase; color:var(--accent); font-weight:700; }
|
|
1814
|
-
.yours { border-left:3px solid var(--accent); padding:4px 12px; margin:0; font-style:italic; }
|
|
1815
|
-
.label { font-size:0.75rem; color:var(--muted); text-transform:uppercase; letter-spacing:0.06em; margin:0 0 4px; }
|
|
1816
|
-
.now { font-weight:600; }
|
|
1817
|
-
.question { border-top:1px solid var(--rule); padding:14px 0; }
|
|
1818
|
-
.question:first-of-type { border-top:none; padding-top:4px; }
|
|
1819
|
-
.question .ask { font-weight:600; margin:0 0 4px; }
|
|
1820
|
-
.question .why { color:var(--muted); margin:0 0 8px; font-size:0.94rem; }
|
|
1821
|
-
.choice { display:flex; gap:8px; align-items:flex-start; margin:6px 0; }
|
|
1822
|
-
.choice span small { display:block; color:var(--muted); }
|
|
1823
|
-
textarea { width:100%; min-height:3.2em; font:inherit; border:1px solid var(--rule); border-radius:8px; padding:8px; margin:6px 0; }
|
|
1824
|
-
button { font:inherit; font-weight:600; border:none; border-radius:8px; padding:8px 14px; background:var(--accent); color:#fff; cursor:pointer; }
|
|
1825
|
-
button:disabled { opacity:0.5; cursor:default; }
|
|
1826
|
-
.props { list-style:none; margin:0; padding:0; }
|
|
1827
|
-
.props li { border-top:1px solid var(--rule); padding:12px 0; display:grid; grid-template-columns:1fr auto; gap:4px 16px; }
|
|
1828
|
-
.props li:first-child { border-top:none; }
|
|
1829
|
-
.chip { font-size:0.8rem; font-weight:700; border-radius:999px; padding:2px 10px; white-space:nowrap; align-self:start; justify-self:start; }
|
|
1830
|
-
.chip.good { color:var(--good); background:var(--goodSoft); }
|
|
1831
|
-
.chip.bad { color:var(--bad); background:var(--badSoft); }
|
|
1832
|
-
.chip.warn { color:var(--warn); background:var(--warnSoft); }
|
|
1833
|
-
.chip.quiet { color:var(--muted); background:var(--rule); }
|
|
1834
|
-
.props .choice-said { color:var(--muted); font-size:0.94rem; grid-column:1 / -1; }
|
|
1835
|
-
details { grid-column:1 / -1; font-size:0.88rem; }
|
|
1836
|
-
details pre { white-space:pre-wrap; word-break:break-word; background:var(--page); border-radius:8px; padding:8px; margin:6px 0 0; font-size:0.82rem; }
|
|
1837
|
-
.empty { color:var(--muted); }
|
|
1838
|
-
@media (max-width:640px) { .props li { grid-template-columns:1fr; } }
|
|
1839
|
-
</style>
|
|
1840
|
-
</head>
|
|
1841
|
-
<body>
|
|
1842
|
-
<main>
|
|
1843
|
-
<header>
|
|
1844
|
-
<h1>Yichus studio<span id="project"></span></h1>
|
|
1845
|
-
<p id="updated">Waiting for your agent.</p>
|
|
1846
|
-
<p><a class="guide" href="https://yich.us/start/studio.html#page" target="_blank" rel="noopener">How to read this page</a> (opens in a new tab)</p>
|
|
1847
|
-
</header>
|
|
1848
|
-
<section aria-labelledby="h-asked">
|
|
1849
|
-
<h2 id="h-asked">What you asked for</h2>
|
|
1850
|
-
<p class="label">Your words</p>
|
|
1851
|
-
<p class="yours" id="description">Nothing yet. Tell your agent what you want to build.</p>
|
|
1852
|
-
</section>
|
|
1853
|
-
<section aria-labelledby="h-now">
|
|
1854
|
-
<h2 id="h-now">What is happening now</h2>
|
|
1855
|
-
<div class="frame"><span class="tag">Yichus output</span>
|
|
1856
|
-
<p class="now" id="summary">No checks have run yet.</p>
|
|
1857
|
-
</div>
|
|
1858
|
-
</section>
|
|
1859
|
-
<section aria-labelledby="h-questions" id="questions-section" hidden>
|
|
1860
|
-
<h2 id="h-questions">Questions for you</h2>
|
|
1861
|
-
<p class="lede">Your agent will ask you these too. Answer here or in the chat, whichever is easier. <a class="guide" href="https://yich.us/start/studio.html#questions" target="_blank" rel="noopener">About these questions</a></p>
|
|
1862
|
-
<div class="frame"><span class="tag">Yichus output</span><div id="questions"></div></div>
|
|
1863
|
-
</section>
|
|
1864
|
-
<section aria-labelledby="h-props">
|
|
1865
|
-
<h2 id="h-props">What your program must do</h2>
|
|
1866
|
-
<p class="lede"><a class="guide" href="https://yich.us/start/studio.html#statuses" target="_blank" rel="noopener">What each status means</a></p>
|
|
1867
|
-
<div class="frame"><span class="tag">Yichus output</span><ul class="props" id="props"><li class="empty">No properties chosen yet.</li></ul></div>
|
|
1868
|
-
</section>
|
|
1869
|
-
<section aria-labelledby="h-map">
|
|
1870
|
-
<h2 id="h-map">The shape of your program</h2>
|
|
1871
|
-
<p class="lede"><a class="guide" href="https://yich.us/start/studio.html#shape" target="_blank" rel="noopener">How to read the picture</a></p>
|
|
1872
|
-
<div class="frame"><div class="system-map" id="map"><p class="empty">The map appears once the program compiles.</p></div></div>
|
|
1873
|
-
</section>
|
|
1874
|
-
</main>
|
|
1875
|
-
<script type="module">
|
|
1876
|
-
import { mount } from './system-map.js';
|
|
1877
|
-
|
|
1878
|
-
const STATUS = {
|
|
1879
|
-
unanswered: ['waiting for your answer', 'quiet'], decided: ['decided', 'good'], assumed: ['holds, under an assumption', 'warn'],
|
|
1880
|
-
proven: ['proven', 'good'], bounded: ['holds in every scenario checked', 'good'], broken: ['broken', 'bad'],
|
|
1881
|
-
mismatch: ['the code says otherwise', 'bad'], 'needs-case': ['scenario being written', 'quiet'],
|
|
1882
|
-
inconclusive: ['not decided yet', 'warn'], 'no-check': ['no check needed', 'quiet'], pending: ['answered, waiting for your agent to check', 'quiet'],
|
|
1883
|
-
};
|
|
1884
|
-
const el = (tag, props = {}, ...kids) => { const n = Object.assign(document.createElement(tag), props); n.append(...kids); return n; };
|
|
1885
|
-
let mapHash = null;
|
|
1886
|
-
|
|
1887
|
-
function questionCard(q, saved) {
|
|
1888
|
-
const card = el('div', { className: 'question' });
|
|
1889
|
-
card.append(el('p', { className: 'ask', textContent: q.ask }), el('p', { className: 'why', textContent: q.why }));
|
|
1890
|
-
const name = 'q-' + q.id;
|
|
1891
|
-
for (const c of q.choices) {
|
|
1892
|
-
const input = el('input', { type: 'radio', name, value: c.id, checked: saved?.choice === c.id });
|
|
1893
|
-
card.append(el('label', { className: 'choice' }, input, el('span', {}, c.label, el('small', { textContent: c.means }))));
|
|
1894
|
-
}
|
|
1895
|
-
const words = el('textarea', { placeholder: 'In your own words (optional)', value: saved?.words ?? '' });
|
|
1896
|
-
const status = el('span', { className: 'empty', textContent: saved ? ' Saved. Your agent will check it next.' : '' });
|
|
1897
|
-
const save = el('button', { type: 'button', textContent: 'Save answer' });
|
|
1898
|
-
save.addEventListener('click', async () => {
|
|
1899
|
-
const picked = card.querySelector('input[name="' + CSS.escape(name) + '"]:checked');
|
|
1900
|
-
if (!picked) { status.textContent = ' Pick one of the choices first.'; return; }
|
|
1901
|
-
save.disabled = true;
|
|
1902
|
-
const label = q.choices.find(c => c.id === picked.value).label;
|
|
1903
|
-
const response = await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' },
|
|
1904
|
-
body: JSON.stringify({ question: q.id, choice: picked.value, words: words.value.trim() || label }) });
|
|
1905
|
-
const result = await response.json();
|
|
1906
|
-
status.textContent = result.ok ? ' Saved. Your agent will check it next.' : ' ' + result.error;
|
|
1907
|
-
save.disabled = false;
|
|
1908
|
-
});
|
|
1909
|
-
card.append(el('p', { className: 'label', textContent: 'Your words' }), words, save, status);
|
|
1910
|
-
return card;
|
|
1911
|
-
}
|
|
1912
|
-
|
|
1913
|
-
function propertyRow(p, saved) {
|
|
1914
|
-
const stale = saved && (!p.answer || p.answer.answeredAt !== saved.answeredAt);
|
|
1915
|
-
const [words, tone] = STATUS[stale ? 'pending' : p.status];
|
|
1916
|
-
const answer = stale ? saved : p.answer;
|
|
1917
|
-
const label = p.question.choices.find(c => c.id === answer.choice)?.label ?? answer.choice;
|
|
1918
|
-
const li = el('li', {}, el('span', { textContent: p.question.ask }), el('span', { className: 'chip ' + tone, textContent: words }));
|
|
1919
|
-
li.append(el('span', { className: 'choice-said', textContent: 'You chose: ' + label + (answer.words && answer.words !== label ? ' ("' + answer.words + '")' : '') }));
|
|
1920
|
-
return li;
|
|
1921
|
-
}
|
|
1922
|
-
|
|
1923
|
-
async function refresh() {
|
|
1924
|
-
const { state, requirements } = await (await fetch('/state')).json();
|
|
1925
|
-
const savedOf = id => requirements.answers.find(a => a.question === id);
|
|
1926
|
-
if (requirements.description) document.getElementById('description').textContent = requirements.description;
|
|
1927
|
-
if (!state) return;
|
|
1928
|
-
document.getElementById('project').textContent = ': ' + state.project;
|
|
1929
|
-
document.getElementById('updated').textContent = 'Last checked ' + new Date(state.updatedAt).toLocaleTimeString() + '.';
|
|
1930
|
-
document.getElementById('summary').textContent = state.summary;
|
|
1931
|
-
const open = state.properties.filter(p => p.status === 'unanswered' && !savedOf(p.question.id));
|
|
1932
|
-
document.getElementById('questions-section').hidden = !open.length;
|
|
1933
|
-
// Keep a half-written answer: only rebuild cards when the questions change.
|
|
1934
|
-
const qs = document.getElementById('questions');
|
|
1935
|
-
const ids = open.map(p => p.question.id).join(' ');
|
|
1936
|
-
if (qs.dataset.ids !== ids) { qs.dataset.ids = ids; qs.replaceChildren(...open.map(p => questionCard(p.question, savedOf(p.question.id)))); }
|
|
1937
|
-
const chosen = state.properties.filter(p => p.answer || savedOf(p.question.id));
|
|
1938
|
-
document.getElementById('props').replaceChildren(...(chosen.length ? chosen.map(p => propertyRow(p, savedOf(p.question.id)))
|
|
1939
|
-
: [el('li', { className: 'empty', textContent: 'No properties chosen yet.' })]));
|
|
1940
|
-
const map = document.getElementById('map');
|
|
1941
|
-
if (state.map && state.sourcesHash !== mapHash) { mapHash = state.sourcesHash; mount(map, state.map); }
|
|
1942
|
-
else if (!state.map && state.mapError) map.replaceChildren(el('p', { className: 'empty', textContent: 'The map could not be drawn: ' + state.mapError }));
|
|
1943
|
-
}
|
|
1944
|
-
|
|
1945
|
-
new EventSource('/events').addEventListener('change', () => refresh());
|
|
1946
|
-
refresh();
|
|
1947
|
-
</script>
|
|
1948
|
-
</body>
|
|
1949
|
-
</html>
|
|
1950
|
-
`;
|
|
1951
|
-
|
|
1952
|
-
// src/studio/page-server.ts
|
|
1953
|
-
var PAGE_ASSETS = ["system-map.js", "label-fit.js", "system-map-record.js", "system-map.css"];
|
|
1954
|
-
function personView(state, names) {
|
|
1955
|
-
if (!state) return null;
|
|
1956
|
-
return {
|
|
1957
|
-
project: state.project,
|
|
1958
|
-
updatedAt: state.updatedAt,
|
|
1959
|
-
sourcesHash: state.sourcesHash,
|
|
1960
|
-
summary: state.step.summary,
|
|
1961
|
-
properties: state.properties.map((p) => ({
|
|
1962
|
-
question: { id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices },
|
|
1963
|
-
answer: p.answer,
|
|
1964
|
-
status: p.status
|
|
1965
|
-
})),
|
|
1966
|
-
map: state.map ? relabelSystemMap(state.map, names) : null,
|
|
1967
|
-
mapError: state.mapError
|
|
1968
|
-
};
|
|
1969
|
-
}
|
|
1970
|
-
function stateBody(root) {
|
|
1971
|
-
const { description, answers, names } = loadRequirements(root);
|
|
1972
|
-
return { state: personView(readState(root), names ?? {}), requirements: { description, answers } };
|
|
1973
|
-
}
|
|
1974
|
-
var STUDIO_PORTS = [4317, 4318, 4319, 4320, 4321, 0];
|
|
1975
|
-
async function startPageServer(root, assetsDir, port = null, now = () => /* @__PURE__ */ new Date()) {
|
|
1976
|
-
ensureStudioDir(root);
|
|
1977
|
-
const clients = /* @__PURE__ */ new Set();
|
|
1978
|
-
const watched = ["state.json", "requirements.json"].map((name) => path7.join(studioDir(root), name));
|
|
1979
|
-
const changed = (now2, before) => {
|
|
1980
|
-
if (now2.mtimeMs !== before.mtimeMs || now2.size !== before.size) for (const res of clients) res.write("event: change\ndata: {}\n\n");
|
|
1981
|
-
};
|
|
1982
|
-
for (const file of watched) fs6.watchFile(file, { interval: 250 }, changed);
|
|
1983
|
-
const hosts = /* @__PURE__ */ new Set();
|
|
1984
|
-
const server = http.createServer((req, res) => {
|
|
1985
|
-
const send = (status, type, body) => {
|
|
1986
|
-
res.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
1987
|
-
res.end(body);
|
|
1988
|
-
};
|
|
1989
|
-
const host = req.headers.host ?? "";
|
|
1990
|
-
if (!hosts.has(host) || req.headers.origin && req.headers.origin !== `http://${host}`) {
|
|
1991
|
-
send(403, "text/plain", "This studio only answers its own page.");
|
|
1992
|
-
return;
|
|
1993
|
-
}
|
|
1994
|
-
const url = new URL(req.url ?? "/", `http://${host}`);
|
|
1995
|
-
if (req.method === "GET" && url.pathname === "/") return send(200, "text/html; charset=utf-8", STUDIO_PAGE);
|
|
1996
|
-
if (req.method === "GET" && url.pathname === "/state") {
|
|
1997
|
-
return send(200, "application/json", JSON.stringify(stateBody(root)));
|
|
1998
|
-
}
|
|
1999
|
-
if (req.method === "GET" && url.pathname === "/events") {
|
|
2000
|
-
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
|
|
2001
|
-
res.write(": connected\n\n");
|
|
2002
|
-
clients.add(res);
|
|
2003
|
-
req.on("close", () => clients.delete(res));
|
|
2004
|
-
return;
|
|
2005
|
-
}
|
|
2006
|
-
const asset = PAGE_ASSETS.find((a) => url.pathname === `/${a}`);
|
|
2007
|
-
if (req.method === "GET" && asset) {
|
|
2008
|
-
return send(200, asset.endsWith(".css") ? "text/css" : "text/javascript", fs6.readFileSync(path7.join(assetsDir, asset), "utf8"));
|
|
2009
|
-
}
|
|
2010
|
-
if (req.method === "POST" && url.pathname === "/answer") {
|
|
2011
|
-
if (req.headers["content-type"] !== "application/json") return send(415, "text/plain", "Send JSON.");
|
|
2012
|
-
let body = "";
|
|
2013
|
-
req.setEncoding("utf8");
|
|
2014
|
-
req.on("data", (chunk) => {
|
|
2015
|
-
body += chunk;
|
|
2016
|
-
if (body.length > 65536) req.destroy();
|
|
2017
|
-
});
|
|
2018
|
-
req.on("end", () => {
|
|
2019
|
-
let args;
|
|
2020
|
-
try {
|
|
2021
|
-
args = JSON.parse(body);
|
|
2022
|
-
} catch {
|
|
2023
|
-
return send(400, "application/json", JSON.stringify({ ok: false, error: "The answer is not JSON." }));
|
|
2024
|
-
}
|
|
2025
|
-
const result = recordAnswer(root, args, now());
|
|
2026
|
-
send(result.ok ? 200 : 400, "application/json", JSON.stringify(result));
|
|
2027
|
-
});
|
|
2028
|
-
return;
|
|
2029
|
-
}
|
|
2030
|
-
send(404, "text/plain", "Not found.");
|
|
2031
|
-
});
|
|
2032
|
-
for (const candidate of port === null ? STUDIO_PORTS : [port]) {
|
|
2033
|
-
const error = await new Promise((resolve) => {
|
|
2034
|
-
server.once("error", resolve);
|
|
2035
|
-
server.listen(candidate, "127.0.0.1", () => {
|
|
2036
|
-
server.off("error", resolve);
|
|
2037
|
-
resolve(null);
|
|
2038
|
-
});
|
|
2039
|
-
});
|
|
2040
|
-
if (!error) break;
|
|
2041
|
-
if (error.code !== "EADDRINUSE" || candidate === port) throw error;
|
|
2042
|
-
}
|
|
2043
|
-
const bound = server.address().port;
|
|
2044
|
-
hosts.add(`127.0.0.1:${bound}`).add(`localhost:${bound}`);
|
|
2045
|
-
return {
|
|
2046
|
-
url: `http://127.0.0.1:${bound}/`,
|
|
2047
|
-
async close() {
|
|
2048
|
-
for (const file of watched) fs6.unwatchFile(file, changed);
|
|
2049
|
-
const closed = new Promise((resolve) => server.close(() => resolve()));
|
|
2050
|
-
server.closeAllConnections();
|
|
2051
|
-
await closed;
|
|
2052
|
-
}
|
|
2053
|
-
};
|
|
2054
|
-
}
|
|
2055
|
-
|
|
2056
|
-
// src/studio/serve.ts
|
|
2057
|
-
var objectResult = (raw, tool) => {
|
|
2058
|
-
const value = JSON.parse(raw);
|
|
2059
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${tool} returned no JSON object`);
|
|
2060
|
-
return value;
|
|
2061
|
-
};
|
|
2062
|
-
var inProcessEngine = (engine) => ({
|
|
2063
|
-
async call(tool, args) {
|
|
2064
|
-
return objectResult(engine.callTool(tool, JSON.stringify(args)), tool);
|
|
2065
|
-
}
|
|
2066
|
-
});
|
|
2067
|
-
function workerEngine(bundle) {
|
|
2068
|
-
const worker = new EngineWorkerClient(bundle, 9e5);
|
|
2069
|
-
let id = 0;
|
|
2070
|
-
return {
|
|
2071
|
-
async call(tool, args) {
|
|
2072
|
-
return objectResult(await worker.callTool(tool, JSON.stringify(args), `studio-${++id}`), tool);
|
|
2073
|
-
},
|
|
2074
|
-
async catalog() {
|
|
2075
|
-
return catalogTools(await worker.listTools(`studio-${++id}`));
|
|
2076
|
-
},
|
|
2077
|
-
close: () => worker.close()
|
|
2078
|
-
};
|
|
2079
|
-
}
|
|
2080
|
-
var BUILT_ASSETS = fileURLToPath2(new URL("./studio-page/", import.meta.url));
|
|
2081
|
-
async function serveStudio(options) {
|
|
2082
|
-
const page = await startPageServer(options.root, options.assetsDir ?? BUILT_ASSETS, options.port);
|
|
2083
|
-
options.stderr(`Yichus studio page: ${page.url}
|
|
17
|
+
// src/cli.ts
|
|
18
|
+
var problem = nodeVersionProblem(process.versions.node, engines.node);
|
|
19
|
+
if (problem) {
|
|
20
|
+
process.stderr.write(`${problem}
|
|
2084
21
|
`);
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
return;
|
|
2089
|
-
}
|
|
2090
|
-
const engine = workerEngine(options.bundle);
|
|
2091
|
-
const { server, idle } = createStudioMcpServer({ root: options.root, engine, pageUrl: page.url, catalog: engine.catalog });
|
|
2092
|
-
const stdin = options.stdin ?? process.stdin;
|
|
2093
|
-
const closed = once(stdin, "end");
|
|
2094
|
-
try {
|
|
2095
|
-
await server.connect(new StdioServerTransport(stdin, options.stdout ?? process.stdout));
|
|
2096
|
-
await closed;
|
|
2097
|
-
await idle();
|
|
2098
|
-
} finally {
|
|
2099
|
-
await server.close();
|
|
2100
|
-
await engine.close();
|
|
2101
|
-
await page.close();
|
|
2102
|
-
}
|
|
22
|
+
process.exitCode = 1;
|
|
23
|
+
} else {
|
|
24
|
+
await import("./main.js");
|
|
2103
25
|
}
|
|
2104
|
-
|
|
2105
|
-
// src/cli.ts
|
|
2106
|
-
var bundleOrThrow = (bundle) => {
|
|
2107
|
-
const resolved = bundle ?? findApiMcpBundle();
|
|
2108
|
-
if (!resolved) throw new Error("Yichus engine bundle missing. Reinstall @yichus/api-mcp or pass --bundle.");
|
|
2109
|
-
return resolved;
|
|
2110
|
-
};
|
|
2111
|
-
var argv = process.argv.slice(2);
|
|
2112
|
-
process.exitCode = STUDIO_COMMANDS.has(argv[0] ?? "") ? await runStudioCommand(argv, {
|
|
2113
|
-
engine: async () => inProcessEngine(await loadApiEngine(bundleOrThrow())),
|
|
2114
|
-
serve: (options) => serveStudio({ ...options, bundle: bundleOrThrow(), stderr: (text3) => process.stderr.write(text3) }),
|
|
2115
|
-
stdout: (text3) => process.stdout.write(text3),
|
|
2116
|
-
stderr: (text3) => process.stderr.write(text3),
|
|
2117
|
-
now: () => /* @__PURE__ */ new Date(),
|
|
2118
|
-
locate: builtCopy
|
|
2119
|
-
}) : await runCli(argv, {
|
|
2120
|
-
async loadEngine(bundle) {
|
|
2121
|
-
return loadApiEngine(bundleOrThrow(bundle));
|
|
2122
|
-
},
|
|
2123
|
-
async checkLeanWasm(bundle, root, sources, timeoutMs) {
|
|
2124
|
-
return checkLeanWasmSources(bundleOrThrow(bundle), root, sources, timeoutMs);
|
|
2125
|
-
},
|
|
2126
|
-
// A stream, not readFileSync(0): a pipe the parent has not written yet
|
|
2127
|
-
// fails a synchronous read with EAGAIN on macOS.
|
|
2128
|
-
readStdin: () => text2(process.stdin),
|
|
2129
|
-
stdout: (text3) => process.stdout.write(text3),
|
|
2130
|
-
stderr: (text3) => process.stderr.write(text3)
|
|
2131
|
-
});
|
|
2132
26
|
//# sourceMappingURL=cli.js.map
|