yichus 0.3.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 +2 -2
- package/dist/cli.js +17 -3192
- package/dist/cli.js.map +1 -1
- package/dist/main.js +3762 -0
- package/dist/main.js.map +1 -0
- package/dist/studio-page/system-map-record.js +3 -3
- package/dist/studio-page/system-map.js +18 -5
- package/dist/studio-page/what-happens-record.js +11 -4
- package/dist/studio-page/what-happens.js +48 -29
- 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 +6 -6
- package/dist/studio-reference/laws.md +62 -0
- package/dist/studio-reference/porting.md +3 -1
- 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/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 +34 -11
- package/package.json +2 -2
package/dist/main.js
ADDED
|
@@ -0,0 +1,3762 @@
|
|
|
1
|
+
// src/main.ts
|
|
2
|
+
import { text as text2 } from "stream/consumers";
|
|
3
|
+
import { checkLeanWasmSources, findApiMcpBundle, loadApiEngine } from "@yichus/api-mcp";
|
|
4
|
+
|
|
5
|
+
// src/run.ts
|
|
6
|
+
import fs9 from "fs";
|
|
7
|
+
import path9 from "path";
|
|
8
|
+
import { isDeepStrictEqual, parseArgs as parseArgs2 } from "util";
|
|
9
|
+
import { z as z12 } from "zod";
|
|
10
|
+
|
|
11
|
+
// src/engine-results.ts
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
var PropertyStatus = z.enum(["proven", "warning", "violated", "blocked"]);
|
|
14
|
+
var Property = z.looseObject({
|
|
15
|
+
id: z.string(),
|
|
16
|
+
title: z.string().optional(),
|
|
17
|
+
status: PropertyStatus,
|
|
18
|
+
details: z.array(z.string()),
|
|
19
|
+
// The declared assumption an accepted warning rests on, e.g. "instances=1".
|
|
20
|
+
accepted: z.string().optional()
|
|
21
|
+
});
|
|
22
|
+
var VerifyResult = z.looseObject({
|
|
23
|
+
topology: z.string().optional(),
|
|
24
|
+
verdict: z.looseObject({
|
|
25
|
+
properties: z.array(Property),
|
|
26
|
+
errors: z.array(z.string()).default([]),
|
|
27
|
+
// Present only when the caller passed block_on_warnings: the warnings
|
|
28
|
+
// among the listed properties, which made the verdict not proven.
|
|
29
|
+
blockedWarnings: z.array(z.string()).optional()
|
|
30
|
+
})
|
|
31
|
+
});
|
|
32
|
+
var VerdictErrors = z.object({ verdict: z.object({ errors: z.array(z.string()) }) });
|
|
33
|
+
var EngineError = z.object({ error: z.string(), errorKinds: z.array(z.string()).optional() });
|
|
34
|
+
var Count = z.int().nonnegative();
|
|
35
|
+
var AbstractionMap = z.looseObject({
|
|
36
|
+
measures: z.looseObject({
|
|
37
|
+
definitions: Count,
|
|
38
|
+
edges: Count,
|
|
39
|
+
layers: Count,
|
|
40
|
+
layerSkips: Count,
|
|
41
|
+
usedOnce: Count,
|
|
42
|
+
usedMany: Count,
|
|
43
|
+
clonePairs: Count,
|
|
44
|
+
duplicatedMass: Count,
|
|
45
|
+
maxSize: Count,
|
|
46
|
+
largestDefinition: z.string().optional()
|
|
47
|
+
})
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// src/verdict.ts
|
|
51
|
+
var title = (p) => p.title ?? p.id;
|
|
52
|
+
var MEANING = {
|
|
53
|
+
proven: "holds for every input",
|
|
54
|
+
warning: "holds only under the acceptance its details name",
|
|
55
|
+
violated: "is broken; the details are the evidence",
|
|
56
|
+
blocked: "was not checked: the check could not run, could not finish, or could not see its subject"
|
|
57
|
+
};
|
|
58
|
+
var ACCEPTANCE = {
|
|
59
|
+
"instances=1": "Safe while you run one instance (--instances 1). Before running more than one:"
|
|
60
|
+
};
|
|
61
|
+
var acceptance = (a) => ACCEPTANCE[a] ?? `Safe under the declared ${a}. Before dropping it:`;
|
|
62
|
+
var label = (p) => p.status === "warning" && p.accepted !== void 0 ? "accepted" : p.status;
|
|
63
|
+
var indent = (text3, prefix) => text3.split("\n").map((line) => prefix + line).join("\n");
|
|
64
|
+
function count(props) {
|
|
65
|
+
const order = [];
|
|
66
|
+
const counts = /* @__PURE__ */ new Map();
|
|
67
|
+
for (const p of props) {
|
|
68
|
+
const status = label(p);
|
|
69
|
+
if (!counts.has(status)) order.push(status);
|
|
70
|
+
counts.set(status, (counts.get(status) ?? 0) + 1);
|
|
71
|
+
}
|
|
72
|
+
return order.map((status) => `${counts.get(status)} ${status}`).join(", ");
|
|
73
|
+
}
|
|
74
|
+
function verifySummary(result, proven, artifact) {
|
|
75
|
+
const parsed = VerifyResult.safeParse(result);
|
|
76
|
+
if (!parsed.success) {
|
|
77
|
+
const said2 = EngineError.safeParse(result);
|
|
78
|
+
const reason2 = said2.success ? ` The engine said: ${said2.data.error}` : "";
|
|
79
|
+
const errors2 = VerdictErrors.safeParse(result);
|
|
80
|
+
const lines2 = [
|
|
81
|
+
proven ? "Proven, but the verdict has no readable property list." : `Not proven. The engine returned no readable verdict.${reason2}`
|
|
82
|
+
];
|
|
83
|
+
if (errors2.success && errors2.data.verdict.errors.length)
|
|
84
|
+
lines2.push("Errors:", ...errors2.data.verdict.errors.map((e) => indent(e, " ")));
|
|
85
|
+
lines2.push(`The full result is in ${artifact}.`);
|
|
86
|
+
return `${lines2.join("\n")}
|
|
87
|
+
`;
|
|
88
|
+
}
|
|
89
|
+
const checked = parsed.data.verdict.properties;
|
|
90
|
+
const errors = parsed.data.verdict.errors;
|
|
91
|
+
const topology2 = parsed.data.topology !== void 0 ? ` Topology: ${parsed.data.topology}.` : "";
|
|
92
|
+
const lines = [];
|
|
93
|
+
if (proven) {
|
|
94
|
+
lines.push(`Proven: ${checked.length} properties checked (${count(checked)}).${topology2}`);
|
|
95
|
+
} else {
|
|
96
|
+
lines.push(`Not proven: ${checked.length} properties checked (${count(checked)}).${topology2}`);
|
|
97
|
+
const blocking = new Set(parsed.data.verdict.blockedWarnings ?? []);
|
|
98
|
+
const first = checked.find((p) => p.status === "violated") ?? checked.find((p) => p.status !== "proven" && p.status !== "warning") ?? checked.find((p) => blocking.has(p.id));
|
|
99
|
+
if (first) {
|
|
100
|
+
const why = blocking.has(first.id) && first.status === "warning" ? " It blocks because --block-on-warning named it." : "";
|
|
101
|
+
lines.push(`First failure (${first.status}): ${title(first)}. This property ${MEANING[first.status]}.${why}`);
|
|
102
|
+
for (const detail of first.details) lines.push(indent(detail, " "));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
lines.push("Every property:");
|
|
106
|
+
const width = Math.max(...checked.map((p) => label(p).length));
|
|
107
|
+
for (const p of checked) {
|
|
108
|
+
lines.push(` ${label(p).padEnd(width)} ${title(p)}`);
|
|
109
|
+
const pad = ` ${" ".repeat(width)} `;
|
|
110
|
+
if (p.status === "warning" && p.accepted !== void 0) lines.push(pad + acceptance(p.accepted));
|
|
111
|
+
if (p.status === "warning") for (const detail of p.details) lines.push(indent(detail, pad));
|
|
112
|
+
}
|
|
113
|
+
const shown2 = new Set(checked.flatMap((p) => p.details));
|
|
114
|
+
const unshown = errors.filter((e) => !shown2.has(e));
|
|
115
|
+
if (unshown.length) lines.push("Errors:", ...unshown.map((e) => indent(e, " ")));
|
|
116
|
+
lines.push(`The full verdict, with every property's details, is in ${artifact}.`);
|
|
117
|
+
return `${lines.join("\n")}
|
|
118
|
+
`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/lean-verdict.ts
|
|
122
|
+
import { LEAN_WASM_INSTALL_COMMAND, LeanCheckResult } from "@yichus/api-mcp";
|
|
123
|
+
import { z as z2 } from "zod";
|
|
124
|
+
var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
125
|
+
var indent2 = (value, prefix) => value.split("\n").map((line) => prefix + line).join("\n");
|
|
126
|
+
var SIDE = {
|
|
127
|
+
rejected: "checker",
|
|
128
|
+
"axiom-audit": "checker",
|
|
129
|
+
"not-admitted": "checker",
|
|
130
|
+
"runtime-missing": "harness",
|
|
131
|
+
timeout: "harness",
|
|
132
|
+
"runtime-error": "harness"
|
|
133
|
+
};
|
|
134
|
+
var DEFAULT_TIMEOUT_MS = 18e4;
|
|
135
|
+
var MAX_TIMEOUT_MS = 3e5;
|
|
136
|
+
function remedy(cause, timeoutMs, files) {
|
|
137
|
+
const sources = files.map((f) => `--source ${f}`).join(" ");
|
|
138
|
+
switch (cause) {
|
|
139
|
+
case "runtime-missing":
|
|
140
|
+
return [
|
|
141
|
+
"Install the pinned runtime once (about 290 MB to download), then pass that folder as --lean-wasm-root:",
|
|
142
|
+
` ${LEAN_WASM_INSTALL_COMMAND.replace("NEW_DIRECTORY", "/absolute/new/folder")}`
|
|
143
|
+
];
|
|
144
|
+
case "timeout":
|
|
145
|
+
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.`];
|
|
146
|
+
case "runtime-error":
|
|
147
|
+
return [
|
|
148
|
+
"The Lean Wasm runtime could not run. If it was changed or only partly installed, install a fresh copy into a new folder:",
|
|
149
|
+
` ${LEAN_WASM_INSTALL_COMMAND.replace("NEW_DIRECTORY", "/absolute/new/folder")}`
|
|
150
|
+
];
|
|
151
|
+
case "rejected":
|
|
152
|
+
return [
|
|
153
|
+
"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.",
|
|
154
|
+
`To see a failing input, run: yichus call api_law_check ${sources}. Fix the code, not the law.`
|
|
155
|
+
];
|
|
156
|
+
case "axiom-audit":
|
|
157
|
+
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."];
|
|
158
|
+
case "not-admitted":
|
|
159
|
+
return [`Lean Wasm proves Bool and structural List[Bool] laws with one direct witness. Check other laws with: yichus call api_law_check ${sources}`];
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
var unreadable = (artifact, why) => ({
|
|
163
|
+
exit: 2,
|
|
164
|
+
text: `Not checked: the Lean result could not be read (${why}). The full result is in ${artifact}.
|
|
165
|
+
`
|
|
166
|
+
});
|
|
167
|
+
var EngineError2 = z2.object({ ok: z2.literal(false), error: z2.string().min(1), proof: z2.undefined().optional() });
|
|
168
|
+
var issue = (error) => {
|
|
169
|
+
const first = error.issues[0];
|
|
170
|
+
return first.path.length ? `${first.path.join(".")}: ${first.message}` : first.message;
|
|
171
|
+
};
|
|
172
|
+
function leanSummary(raw, artifact, timeoutMs, files) {
|
|
173
|
+
const refused = EngineError2.safeParse(raw);
|
|
174
|
+
if (refused.success) return unreadable(artifact, `the engine said: ${refused.data.error}`);
|
|
175
|
+
const parsed = LeanCheckResult.safeParse(raw);
|
|
176
|
+
if (!parsed.success) return unreadable(artifact, issue(parsed.error));
|
|
177
|
+
const proof = parsed.data.proof;
|
|
178
|
+
const laws = proof.obligations;
|
|
179
|
+
const lines = [];
|
|
180
|
+
if (proof.status === "verified") {
|
|
181
|
+
lines.push(`Proven: ${plural(laws.length, "law")} verified by the pinned Lean Wasm kernel.`);
|
|
182
|
+
for (const row of laws) {
|
|
183
|
+
if (row.status !== "verified") continue;
|
|
184
|
+
const { check, witness, domain } = row.proof.subject;
|
|
185
|
+
lines.push(` ${row.binding}: ${check} holds for ${domain}, and ${witness} holds for at least one.`);
|
|
186
|
+
}
|
|
187
|
+
lines.push(`The proof receipt is in ${artifact}. It is a local Wasm kernel check (independentKernelReplay: false).`);
|
|
188
|
+
return { exit: 0, text: `${lines.join("\n")}
|
|
189
|
+
` };
|
|
190
|
+
}
|
|
191
|
+
if (!laws.length) {
|
|
192
|
+
const cause = proof.cause;
|
|
193
|
+
const checker2 = SIDE[cause] === "checker";
|
|
194
|
+
lines.push(`${checker2 ? "Not proven" : "Not checked"}: ${proof.reason}.`);
|
|
195
|
+
if (cause === "not-admitted") lines.push("Fix the source, or add a Yichus/Law Obligation for lean to prove.");
|
|
196
|
+
else lines.push(...remedy(cause, timeoutMs, files));
|
|
197
|
+
lines.push(`The full result is in ${artifact}.`);
|
|
198
|
+
return { exit: checker2 ? 1 : 2, text: `${lines.join("\n")}
|
|
199
|
+
` };
|
|
200
|
+
}
|
|
201
|
+
const failed = laws.flatMap((row) => row.status === "inconclusive" ? [row] : []);
|
|
202
|
+
const causes = [...new Set(failed.map((row) => row.cause))];
|
|
203
|
+
const checker = causes.some((cause) => SIDE[cause] === "checker");
|
|
204
|
+
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.`);
|
|
205
|
+
for (const row of laws) {
|
|
206
|
+
if (row.status === "verified") {
|
|
207
|
+
lines.push(` verified ${row.binding}`);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
lines.push(` ${row.cause.padEnd(12)} ${row.binding}: ${row.reason}.`);
|
|
211
|
+
if (row.diagnostics?.length) lines.push(" Lean said:", ...row.diagnostics.map((d) => indent2(d, " ")));
|
|
212
|
+
}
|
|
213
|
+
for (const cause of causes) lines.push(...remedy(cause, timeoutMs, files));
|
|
214
|
+
lines.push(`The full result is in ${artifact}.`);
|
|
215
|
+
return { exit: checker ? 1 : 2, text: `${lines.join("\n")}
|
|
216
|
+
` };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/call-summary.ts
|
|
220
|
+
var plural2 = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
221
|
+
function mapSummary(result) {
|
|
222
|
+
const parsed = AbstractionMap.safeParse(result);
|
|
223
|
+
if (!parsed.success) return ["The map has no readable measures block; read the JSON for its contents."];
|
|
224
|
+
const m = parsed.data.measures;
|
|
225
|
+
const lines = [
|
|
226
|
+
`Layers: ${plural2(m.definitions, "definition")} stacked ${plural2(m.layers, "layer")} deep (a definition sits one layer above the highest one it uses).`,
|
|
227
|
+
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.`,
|
|
228
|
+
`Reuse: ${plural2(m.usedMany, "definition is", "definitions are")} used by several others, ${m.usedOnce} by exactly one (each node's "fanIn").`,
|
|
229
|
+
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".`,
|
|
230
|
+
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".`
|
|
231
|
+
];
|
|
232
|
+
if (m.largestDefinition !== void 0)
|
|
233
|
+
lines.push(`Largest definition: ${m.largestDefinition} (${m.maxSize} nodes).`);
|
|
234
|
+
return lines;
|
|
235
|
+
}
|
|
236
|
+
var SUMMARIES = {
|
|
237
|
+
api_abstraction_map: {
|
|
238
|
+
noun: "the abstraction map",
|
|
239
|
+
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...`,
|
|
240
|
+
summary: mapSummary
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
function callProgress(tool, files) {
|
|
244
|
+
const known = SUMMARIES[tool];
|
|
245
|
+
return known ? `${known.progress(files)}
|
|
246
|
+
` : void 0;
|
|
247
|
+
}
|
|
248
|
+
function callSummary(tool, result, output) {
|
|
249
|
+
const known = SUMMARIES[tool];
|
|
250
|
+
const lines = [];
|
|
251
|
+
if (output) lines.push(`Wrote ${known?.noun ?? `the ${tool} result`} to ${output}.`);
|
|
252
|
+
if (known) lines.push(...known.summary(result));
|
|
253
|
+
return lines.length ? `${lines.join("\n")}
|
|
254
|
+
` : void 0;
|
|
255
|
+
}
|
|
256
|
+
var NEXT_STEP = {
|
|
257
|
+
"duplicate-package": "Each package can be declared by only one file. Give each file its own package name, or pass only one of them."
|
|
258
|
+
};
|
|
259
|
+
function callFailure(tool, result, artifact) {
|
|
260
|
+
const said2 = EngineError.safeParse(result);
|
|
261
|
+
const lines = said2.success ? [`${tool} failed:`, said2.data.error] : [`${tool} failed without saying why.`];
|
|
262
|
+
if (said2.success) {
|
|
263
|
+
for (const kind of said2.data.errorKinds ?? []) if (Object.hasOwn(NEXT_STEP, kind)) lines.push(`Next: ${NEXT_STEP[kind]}`);
|
|
264
|
+
}
|
|
265
|
+
lines.push(`The full result is in ${artifact}.`);
|
|
266
|
+
return `${lines.join("\n")}
|
|
267
|
+
`;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// src/studio/command.ts
|
|
271
|
+
import fs8 from "fs";
|
|
272
|
+
import path8 from "path";
|
|
273
|
+
import { parseArgs } from "util";
|
|
274
|
+
|
|
275
|
+
// src/studio/director.ts
|
|
276
|
+
import fs3 from "fs";
|
|
277
|
+
import path3 from "path";
|
|
278
|
+
import { z as z6 } from "zod";
|
|
279
|
+
|
|
280
|
+
// ../../web/system-map-record.js
|
|
281
|
+
var MARKS_VERSION = "yichus-marks-3";
|
|
282
|
+
var VOCABULARY = {
|
|
283
|
+
version: MARKS_VERSION,
|
|
284
|
+
fixedPlaces: {
|
|
285
|
+
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[]",
|
|
286
|
+
openings: "the left wall: one opening per entry <- entries[]",
|
|
287
|
+
hullBand: "the middle band of the wall: wrappers sit here and nowhere else; empty band = no entry goes through a shared wrapper <- wrappers[]",
|
|
288
|
+
afterBand: "between a hull's right wall and the reply bars: work an entry does after its wrapper returns, with its stations and checks; empty = none <- entries[].beside",
|
|
289
|
+
replyBars: "one bar per entry at the same x, past the hull band <- entries[]",
|
|
290
|
+
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]",
|
|
291
|
+
rack: "right of the wall: db, model, net, always in this order; struck = the engine checked and found none <- resources[], ghostResources[]",
|
|
292
|
+
programBand: "the bottom of the wall, under the rail: one container per pure program, its request openings on its right edge, the engine lanes right of it; empty = the engine found no program <- programs[]",
|
|
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 <- entries[].model",
|
|
302
|
+
reachedBy: "under each resource in the rack: how many routes reach it, the resource drawn at that share of the routes (never smaller than its name) <- entries[].db, model, net, beside.resources",
|
|
303
|
+
netRing: "orange ring: the entry reaches the network <- entries[].net",
|
|
304
|
+
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",
|
|
305
|
+
hull: "translucent region in the hull band: paths merge into it, run one shared stretch, and split; everything inside it runs inside the wrapper; its right wall, drawn in the hull ink, is where the wrapper returns <- wrappers[]",
|
|
306
|
+
socket: "broken-rim ring: a function the caller hands in runs here; its centre fills like a station <- entries[].passed[]",
|
|
307
|
+
token: "small grey word under a path: the value the caller fixes for the wrapper <- entries[].policy",
|
|
308
|
+
afterDot: "dot in the after band: a call the entry makes after its wrapper returns <- entries[].beside.calls",
|
|
309
|
+
builder: "plus-disc under a station with the call that builds the handle there <- uses[how=local].builtBy",
|
|
310
|
+
unknown: 'a ? in a circle on the rail, with "partly traced" beside it and a sentence on hover: the engine traced the handle only on some paths <- uses[how=mixed]',
|
|
311
|
+
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[]",
|
|
312
|
+
bundle: 'one cable with how many routes it carries ("4 routes"): entries with the same wrapper and identical marks; its title names every route; opening it draws each one <- bundles[]',
|
|
313
|
+
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",
|
|
314
|
+
step: 'loop arc with a type on the quiet line: functions of the package take that type and return it; gathered, a count in words ("8 steps"), as are choices, db uses and generic parts <- steps[]',
|
|
315
|
+
loop: "loop arc with package names: packages whose types lead back to themselves <- phases.cycles",
|
|
316
|
+
composes: "hull round a chain: a definition takes the type the chain hands in at each step and applies it <- library.applied[].fedBy",
|
|
317
|
+
port: "plug strip on the right: a record of functions; each adapter a plug, hollow when nothing plugs it in <- library.ports[]",
|
|
318
|
+
generic: "the letter \u2200 with its variables over a part that never looks inside what it carries <- library.generic[]",
|
|
319
|
+
program: `large container: a pure program, its step and package named, with its package's own definition count (as the layer stack counts them) and how many more it uses from other packages, the most used named with their counts; routes that act on one step's answer per call are named as its starters ("one step per call of"), and routes that only replay it are named on hover <- programs[], definitions, usesElsewhere, elsewhere[], starters[advances=false], replays[]`,
|
|
320
|
+
decision: "bar and number in the program: its decisions, on one scale shared with its engines' bars <- programs[].decisions",
|
|
321
|
+
struck: 'on a program, a struck "effects": no definition in its package performs an effect <- programs[].beside = []',
|
|
322
|
+
programEffect: "red disc and count on a program: definitions in its own package that perform effects, named in its title <- programs[].beside[]",
|
|
323
|
+
request: "opening on the program's right edge: a request constructor its step can return, with its payload's types <- programs[].requests[]",
|
|
324
|
+
variant: 'short opening under a request: a constructor of a user sum type its payload carries, with what the program calls it ("BriefCase \u2192 Lawyer") where a total match maps each kind to a plain constructor; eight drawn, the rest counted with their names in a title <- programs[].requests[].variants[], namings[]',
|
|
325
|
+
starter: "dashed line from a route's reply bar into the program top: the route calls the step with its values and acts on the answer, found by value flow; a route that runs an engine is named under its loop instead <- programs[].starters[advances=false]",
|
|
326
|
+
gap: "struck opening: a request constructor no engine handles <- programs[].gaps[]",
|
|
327
|
+
wire: "line from an opening to the lane that handles it, ending in the names of the resources the arm reaches, or a dot each where they do not fit <- programs[].requests[].handledBy",
|
|
328
|
+
lane: `thin vertical line on the resource side: an engine that performs the program's requests, its package above it (package.definition where lanes share one) and what it does written from its type (its own parameters \u2192 what its effect yields), its code name and whole type on hover; it ends in the resources its arms reach, then dashed pills under "also" for resources it reaches for no request <- programs[].engines[], pkgLabel, type, resources, also`,
|
|
329
|
+
laneFork: "bar and number on a lane: the engine's decisions, on the program's scale; 0 = a rule-free engine <- programs[].engines[].decisions",
|
|
330
|
+
replyLoop: `one solid arc from a lane's foot back into the program, with one loop node naming what repeats the step within one call, and "each call of \u2026 runs it" naming the routes that run the rounds <- programs[].engines[].replies, loop, starters`,
|
|
331
|
+
replaced: 'a check named "(in place of \u2026)": in the compared base record the same route had that other check at the same place, and it is on that route no longer; says nothing about whether the two do the same <- compare.replaced[]'
|
|
332
|
+
},
|
|
333
|
+
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."
|
|
334
|
+
};
|
|
335
|
+
var bare = (id) => String(id).split("::").pop();
|
|
336
|
+
var pkgOf = (id) => String(id).split("::")[0];
|
|
337
|
+
var uniq = (xs) => [...new Set(xs)];
|
|
338
|
+
var OPS = { read: "read", query: "read", delete: "delete" };
|
|
339
|
+
function effectsOf(steps) {
|
|
340
|
+
return (steps || []).filter((e) => e.resource === "db").flatMap((e) => e.tables.map((table) => ({ op: OPS[e.op] || "write", table })));
|
|
341
|
+
}
|
|
342
|
+
var isWrite = (op) => op !== "read";
|
|
343
|
+
var uniqBy = (xs, key) => {
|
|
344
|
+
const seen = /* @__PURE__ */ new Set();
|
|
345
|
+
return xs.filter((x) => !seen.has(key(x)) && seen.add(key(x)));
|
|
346
|
+
};
|
|
347
|
+
var RUNNER = { CompileProgram: "compile", RunProgram: "run" };
|
|
348
|
+
var effectResource = (e) => e.resource || RUNNER[e.kind] || "io";
|
|
349
|
+
var LANE_RES = ["db", "model", "net", "compile", "run", "io"];
|
|
350
|
+
var resOrder = (rs) => LANE_RES.filter((r) => rs.includes(r));
|
|
351
|
+
function programsOf(st, layers = null) {
|
|
352
|
+
const found = st.programs && st.programs.programs || [];
|
|
353
|
+
const ownCount = (pkg) => {
|
|
354
|
+
const lp = layers && layers.packages.find((x) => x.name === pkg);
|
|
355
|
+
return lp ? lp.definitions.length : null;
|
|
356
|
+
};
|
|
357
|
+
return found.map((p) => {
|
|
358
|
+
const engines = p.engines.map((e) => {
|
|
359
|
+
const resources = resOrder(uniq(e.handles.flatMap((h) => h.effects.map(effectResource))));
|
|
360
|
+
return {
|
|
361
|
+
id: e.id,
|
|
362
|
+
label: bare(e.id),
|
|
363
|
+
pkg: pkgOf(e.id),
|
|
364
|
+
pkgLabel: pkgOf(e.id).split("/").pop(),
|
|
365
|
+
handles: e.handles.map((h) => h.constructor),
|
|
366
|
+
resources,
|
|
367
|
+
// effects the engine performs that are no request's: drawn, not hidden
|
|
368
|
+
also: resOrder(uniq((e.effects || []).map(effectResource))).filter((r) => !resources.includes(r)),
|
|
369
|
+
replies: resOrder(uniq(e.replies.map(effectResource))),
|
|
370
|
+
decisions: +e.decisions,
|
|
371
|
+
entries: e.entries,
|
|
372
|
+
truncated: e.truncated,
|
|
373
|
+
loop: e.loop ? { kind: e.loop.kind, by: e.loop.by, label: e.loop.by ? bare(e.loop.by) : null } : { kind: "sequence", by: null, label: null },
|
|
374
|
+
starters: (p.starters || []).filter((s) => s.advances && s.via.some((v) => v === e.id || e.entries.includes(s.entry))).map((s) => s.entry),
|
|
375
|
+
// what it does, from its type: the program's own and standard parameters, and what its effect yields; the whole type on hover
|
|
376
|
+
type: {
|
|
377
|
+
takes: e.labels.takes,
|
|
378
|
+
returns: e.labels.returns,
|
|
379
|
+
plainTakes: e.labels.plainTakes,
|
|
380
|
+
yields: e.labels.yields,
|
|
381
|
+
from: "structure.programs.programs[].engines[].labels"
|
|
382
|
+
},
|
|
383
|
+
from: "structure.programs.programs[].engines[]"
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
const requests = p.requests.map((q) => ({
|
|
387
|
+
constructor: q.constructor,
|
|
388
|
+
fields: q.fields.map((f) => f.label),
|
|
389
|
+
variants: (q.variants || []).map((v) => ({
|
|
390
|
+
path: v.path,
|
|
391
|
+
type: bare(v.type),
|
|
392
|
+
constructors: v.constructors,
|
|
393
|
+
// what the program calls each kind: total matches onto plain constructors, the type's own package first
|
|
394
|
+
namings: (v.namings || []).slice().sort((a, b) => (pkgOf(b.definition) === pkgOf(v.type)) - (pkgOf(a.definition) === pkgOf(v.type))).map((n) => ({
|
|
395
|
+
definition: n.definition,
|
|
396
|
+
label: bare(n.definition),
|
|
397
|
+
type: bare(n.type),
|
|
398
|
+
names: n.names.map((x) => ({ constructor: x.constructor, name: x.name })),
|
|
399
|
+
from: "structure.programs.programs[].requests[].variants[].namings[]"
|
|
400
|
+
})),
|
|
401
|
+
from: "structure.programs.programs[].requests[].variants[]"
|
|
402
|
+
})),
|
|
403
|
+
handledBy: p.engines.filter((e) => e.handles.some((h) => h.constructor === q.constructor)).map((e) => ({
|
|
404
|
+
engine: e.id,
|
|
405
|
+
resources: resOrder(uniq(e.handles.find((h) => h.constructor === q.constructor).effects.map(effectResource)))
|
|
406
|
+
})),
|
|
407
|
+
gap: p.gaps.some((g) => g.constructor === q.constructor),
|
|
408
|
+
from: "structure.programs.programs[].requests[] + engines[].handles[]"
|
|
409
|
+
}));
|
|
410
|
+
return {
|
|
411
|
+
id: p.step,
|
|
412
|
+
label: bare(p.step),
|
|
413
|
+
pkg: p.package,
|
|
414
|
+
pkgLabel: p.package.split("/").pop(),
|
|
415
|
+
result: bare(p.result),
|
|
416
|
+
requestType: bare(p.requestType),
|
|
417
|
+
carrier: p.carrier,
|
|
418
|
+
decisions: +p.decisions,
|
|
419
|
+
finishes: p.finishes,
|
|
420
|
+
// definitions: the package's own, as the layer stack counts them; reached: everything the program's definitions use
|
|
421
|
+
definitions: ownCount(p.package) ?? +(p.ownDefinitions || 0),
|
|
422
|
+
reached: p.definitions.length,
|
|
423
|
+
// of what it reaches, the definitions that live in other packages
|
|
424
|
+
usesElsewhere: p.definitions.filter((d) => pkgOf(d) !== p.package).length,
|
|
425
|
+
// and which packages those are, the most used first
|
|
426
|
+
elsewhere: Object.entries(p.definitions.filter((d) => pkgOf(d) !== p.package).reduce((m, d) => ({ ...m, [pkgOf(d)]: (m[pkgOf(d)] || 0) + 1 }), {})).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([pkg, n]) => ({ pkg, label: pkg.split("/").pop(), n, from: "structure.programs.programs[].definitions[]" })),
|
|
427
|
+
requests,
|
|
428
|
+
engines,
|
|
429
|
+
starters: (p.starters || []).map((s) => ({
|
|
430
|
+
entry: s.entry,
|
|
431
|
+
path: s.entry.replace(/^route:/, ""),
|
|
432
|
+
advances: s.advances,
|
|
433
|
+
via: s.via,
|
|
434
|
+
from: "structure.programs.programs[].starters[]"
|
|
435
|
+
})),
|
|
436
|
+
// routes that call the step and act on nothing it says: they read where the program is
|
|
437
|
+
replays: (p.replays || []).map((s) => ({ entry: s.entry, path: s.entry.replace(/^route:/, ""), via: s.via, from: "structure.programs.programs[].replays[]" })),
|
|
438
|
+
// what each reaches, as the structure lens's effect sites say (io when none is a resource)
|
|
439
|
+
beside: (p.beside || []).map((b) => ({
|
|
440
|
+
id: b.definition,
|
|
441
|
+
label: bare(b.definition),
|
|
442
|
+
kinds: b.kinds,
|
|
443
|
+
resources: resOrder(uniq((st.ioKinds || []).filter((k) => k.definition === b.definition).flatMap((k) => k.resources))),
|
|
444
|
+
from: "structure.programs.programs[].beside[], structure.ioKinds[].resources"
|
|
445
|
+
})),
|
|
446
|
+
gaps: p.gaps.map((g) => ({ constructor: g.constructor, from: "structure.programs.programs[].gaps[]" })),
|
|
447
|
+
from: "structure.programs.programs[]"
|
|
448
|
+
};
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
var outsideResourcesOf = (steps) => uniq((steps || []).map((e) => e.resource).filter((r) => r === "model" || r === "net"));
|
|
452
|
+
function buildSystemMap(engine, { program }) {
|
|
453
|
+
for (const [k, v] of Object.entries(engine)) if (!v.ok) throw new Error(`${k}: ${v.error}`);
|
|
454
|
+
const report = engine.report, st = engine.structure, abs = engine.abstractions.abstractions, layers = engine.layers.layers;
|
|
455
|
+
const routes = (report.surface.routes || []).slice().sort((a, b) => a.path.localeCompare(b.path));
|
|
456
|
+
const engEntry = new Map(st.entries.map((e) => [e.entry, e]));
|
|
457
|
+
const shapes = new Map(abs.routeShapes.map((r) => [r.path, r]));
|
|
458
|
+
const gens = new Map(abs.generators.map((g) => [g.id, g]));
|
|
459
|
+
const insts = abs.instantiations;
|
|
460
|
+
const besideOf = (inst) => ({
|
|
461
|
+
calls: inst.besideCalls.map(bare),
|
|
462
|
+
callIds: inst.besideCalls,
|
|
463
|
+
guards: inst.besideGuards.map(bare),
|
|
464
|
+
guardIds: inst.besideGuards,
|
|
465
|
+
effects: effectsOf(inst.besideEffectSteps),
|
|
466
|
+
resources: outsideResourcesOf(inst.besideEffectSteps),
|
|
467
|
+
from: "abstractions.instantiations[].beside*"
|
|
468
|
+
});
|
|
469
|
+
const entries = routes.map((r) => {
|
|
470
|
+
const key = `route:${r.path}`;
|
|
471
|
+
const ee = engEntry.get(key);
|
|
472
|
+
const rs = shapes.get(r.path);
|
|
473
|
+
const wrapper = rs.shapedByGenerator;
|
|
474
|
+
const inst = wrapper ? insts.find((i) => i.callerId === rs.handlerId && i.generatorId === wrapper) : null;
|
|
475
|
+
const passed = (inst ? inst.slotBindings : []).filter((sb) => ["function", "effect"].includes(sb.slotRole)).map((sb) => ({
|
|
476
|
+
slot: sb.slotName,
|
|
477
|
+
id: sb.targetId || null,
|
|
478
|
+
label: sb.targetId ? bare(sb.targetId) : null,
|
|
479
|
+
kind: sb.passedKind,
|
|
480
|
+
guards: (sb.guards || []).map(bare),
|
|
481
|
+
guardIds: sb.guards || [],
|
|
482
|
+
effects: effectsOf(sb.effectSteps),
|
|
483
|
+
from: "abstractions.instantiations[].slotBindings[slotRole=function|effect]"
|
|
484
|
+
}));
|
|
485
|
+
const reach = wrapper ? [
|
|
486
|
+
...effectsOf(rs.effectsInGeneratorSteps).map((e) => ({ ...e, where: "wrapper", from: "abstractions.routeShapes[].effectsInGeneratorSteps" })),
|
|
487
|
+
...effectsOf(rs.effectsInPassedFunctionSteps).map((e) => ({ ...e, where: "passed", from: "abstractions.routeShapes[].effectsInPassedFunctionSteps" })),
|
|
488
|
+
...effectsOf(rs.effectsDirectOrBesideSteps).map((e) => ({ ...e, where: "beside", from: "abstractions.routeShapes[].effectsDirectOrBesideSteps" }))
|
|
489
|
+
] : uniqBy([
|
|
490
|
+
...effectsOf(r.inferredSteps).map((e) => ({ ...e, where: "direct", from: "report.surface.routes[].inferredSteps" })),
|
|
491
|
+
...effectsOf(rs.effectsDirectOrBesideSteps).map((e) => ({ ...e, where: "direct", from: "abstractions.routeShapes[].effectsDirectOrBesideSteps" }))
|
|
492
|
+
], (e) => `${e.op} ${e.table}`);
|
|
493
|
+
const limits = ee.limits.written === "literal" ? ee.limits.each.map((l) => ({ requests: +l.requests, seconds: +l.seconds, by: l.by })) : [];
|
|
494
|
+
return {
|
|
495
|
+
key,
|
|
496
|
+
path: r.path,
|
|
497
|
+
handler: r.handler,
|
|
498
|
+
handlerId: rs.handlerId,
|
|
499
|
+
transport: ee.transport,
|
|
500
|
+
authority: ee.authority,
|
|
501
|
+
signedIn: !["public", "anonymous"].includes(ee.authority),
|
|
502
|
+
roles: r.requiredRoles || [],
|
|
503
|
+
limits,
|
|
504
|
+
limitComputed: ee.limits.written === "computed",
|
|
505
|
+
reachKinds: ee.reaches,
|
|
506
|
+
db: ee.resources.includes("db"),
|
|
507
|
+
model: ee.resources.includes("model"),
|
|
508
|
+
net: ee.resources.includes("net"),
|
|
509
|
+
writes: reach.some((e) => isWrite(e.op)),
|
|
510
|
+
guards: rs.handlerGuards.map(bare),
|
|
511
|
+
guardIds: rs.handlerGuards,
|
|
512
|
+
wrapper,
|
|
513
|
+
via: rs.viaSpecialization ? bare(rs.viaSpecialization) : null,
|
|
514
|
+
policy: (inst ? inst.slotBindings : []).filter((s) => s.slotRole === "semantic-object").map((s) => s.value).filter(Boolean),
|
|
515
|
+
passed,
|
|
516
|
+
beside: inst ? besideOf(inst) : null,
|
|
517
|
+
reach,
|
|
518
|
+
from: { entry: "report.surface.routes[]", transport: "structure.entries[]", shape: "abstractions.routeShapes[]", head: "entries[].reach (writes)" }
|
|
519
|
+
};
|
|
520
|
+
});
|
|
521
|
+
const partOf = (g) => {
|
|
522
|
+
const own = insts.filter((i) => i.generatorId === g.id);
|
|
523
|
+
return {
|
|
524
|
+
id: g.id,
|
|
525
|
+
label: g.name || bare(g.id),
|
|
526
|
+
pkg: pkgOf(g.id),
|
|
527
|
+
guards: g.envelope.guards.map(bare),
|
|
528
|
+
guardIds: g.envelope.guards,
|
|
529
|
+
effects: effectsOf(g.envelope.effectSteps),
|
|
530
|
+
groups: (g.parameterGroups || []).map((grp) => grp.map((sl) => ({ name: sl.name, role: sl.role, type: sl.type, guardsFed: (sl.guardsFed || []).map(bare) }))),
|
|
531
|
+
instantiationCount: own.length,
|
|
532
|
+
instantiatingPackages: uniq(own.map((i) => pkgOf(i.callerId))).sort(),
|
|
533
|
+
besideEmpty: own.every((i) => !i.besideCalls.length && !i.besideGuards.length && !i.besideEffects.length),
|
|
534
|
+
callers: own.map((i) => ({
|
|
535
|
+
id: i.callerId,
|
|
536
|
+
label: i.callerName || bare(i.callerId),
|
|
537
|
+
pkg: pkgOf(i.callerId),
|
|
538
|
+
routes: i.routes || [],
|
|
539
|
+
via: i.viaSpecialization ? bare(i.viaSpecialization) : null,
|
|
540
|
+
tokens: i.slotBindings.filter((s) => s.slotRole === "semantic-object").map((s) => s.value).filter(Boolean),
|
|
541
|
+
passed: i.slotBindings.filter((s) => ["function", "effect"].includes(s.slotRole)).map((s) => ({
|
|
542
|
+
slot: s.slotName,
|
|
543
|
+
id: s.targetId || null,
|
|
544
|
+
label: s.targetId ? bare(s.targetId) : null,
|
|
545
|
+
guards: (s.guards || []).map(bare),
|
|
546
|
+
guardIds: s.guards || [],
|
|
547
|
+
effects: effectsOf(s.effectSteps)
|
|
548
|
+
})),
|
|
549
|
+
beside: besideOf(i)
|
|
550
|
+
})),
|
|
551
|
+
from: "abstractions.generators[] + abstractions.instantiations[generatorId]"
|
|
552
|
+
};
|
|
553
|
+
};
|
|
554
|
+
const parts = abs.generators.filter((g) => insts.some((i) => i.generatorId === g.id)).map(partOf);
|
|
555
|
+
const wrapperIds = uniq(entries.map((e) => e.wrapper).filter(Boolean)).sort();
|
|
556
|
+
const wrappers = wrapperIds.map((id) => ({
|
|
557
|
+
...parts.find((x) => x.id === id) || partOf(gens.get(id)),
|
|
558
|
+
entries: entries.filter((e) => e.wrapper === id).map((e) => e.key),
|
|
559
|
+
from: "abstractions.generators[] shaping routeShapes[].shapedByGenerator"
|
|
560
|
+
}));
|
|
561
|
+
const handlerToEntry = new Map(entries.map((e) => [e.handlerId, e.key]));
|
|
562
|
+
const passedToEntry = new Map(entries.flatMap((e) => e.passed.filter((p) => p.id).map((p) => [p.id, e.key])));
|
|
563
|
+
const uses = [];
|
|
564
|
+
for (const s of st.supply) {
|
|
565
|
+
const kind = s.via === "record" ? "record" : s.resource;
|
|
566
|
+
if (kind !== "db" && kind !== "record") continue;
|
|
567
|
+
const ids = /* @__PURE__ */ new Set([s.definition]);
|
|
568
|
+
for (const t of s.traces) {
|
|
569
|
+
for (const id of t.through) ids.add(id);
|
|
570
|
+
if (t.end.where) ids.add(t.end.where);
|
|
571
|
+
if (t.end.referrer) ids.add(t.end.referrer);
|
|
572
|
+
}
|
|
573
|
+
let ats;
|
|
574
|
+
if (handlerToEntry.has(s.definition)) ats = [{ node: "entry", entry: handlerToEntry.get(s.definition) }];
|
|
575
|
+
else if (wrapperIds.includes(s.definition)) ats = [{ node: "wrapper", wrapper: s.definition }];
|
|
576
|
+
else if (passedToEntry.has(s.definition)) ats = [{ node: "passed", entry: passedToEntry.get(s.definition), id: s.definition }];
|
|
577
|
+
else {
|
|
578
|
+
const ents = uniq([...ids].map((i) => handlerToEntry.get(i)).filter(Boolean));
|
|
579
|
+
ats = ents.length ? ents.map((entry) => ({ node: "entry", entry, helper: bare(s.definition) })) : [{ node: "definition", id: s.definition }];
|
|
580
|
+
}
|
|
581
|
+
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;
|
|
582
|
+
const anchor = !s.leaves ? "none" : s.leaves.builtBy.length ? "program" : "platform";
|
|
583
|
+
for (const at of ats) uses.push({
|
|
584
|
+
kind,
|
|
585
|
+
how: s.supply,
|
|
586
|
+
definition: s.definition,
|
|
587
|
+
effect: s.effect || null,
|
|
588
|
+
writes: s.via === "effect" && isWrite(OPS[s.op] || "write"),
|
|
589
|
+
at,
|
|
590
|
+
builtBy,
|
|
591
|
+
untracedSource: s.traces.some((t) => ["asValue", "entry"].includes(t.end.kind)),
|
|
592
|
+
anchor,
|
|
593
|
+
handleBuiltBy: s.leaves ? s.leaves.builtBy : [],
|
|
594
|
+
records: s.records || [],
|
|
595
|
+
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 })),
|
|
596
|
+
from: "structure.supply[]"
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
const present = uniq(st.ioKinds.flatMap((b) => b.resources));
|
|
600
|
+
const tables = uniq(entries.flatMap((e) => [...e.reach, ...e.beside ? e.beside.effects : []].map((r) => r.table))).sort();
|
|
601
|
+
const resources = ["db", "model", "net"].filter((k) => present.includes(k)).map((k) => ({ kind: k, ...k === "db" ? { tables } : {}, from: "structure.ioKinds[].resources" }));
|
|
602
|
+
const ghostResources = ["db", "model", "net"].filter((k) => !present.includes(k)).map((k) => ({ kind: k, from: "structure.ioKinds[] checked: no site of this kind" }));
|
|
603
|
+
const transports = uniq(st.entries.map((e) => e.transport));
|
|
604
|
+
const callers = [];
|
|
605
|
+
if (transports.includes("http")) callers.push({ kind: "http", keyKinds: uniq(entries.map(keyKindOf)), from: "structure.entries[transport=http] + authority" });
|
|
606
|
+
if (transports.includes("link")) callers.push({ kind: "link", from: "structure.entries[transport=link]" });
|
|
607
|
+
const ghostCallers = ["http", "link"].filter((k) => !transports.includes(k)).map((k) => ({ kind: k, from: "structure.entries[]: no entry with this transport" }));
|
|
608
|
+
const library = routes.length ? null : {
|
|
609
|
+
packages: layers.packages.map((p) => ({ name: p.name, label: p.name.split("/").pop(), exports: p.definitions.filter((d) => d.exported).map((d) => d.name) })),
|
|
610
|
+
ports: st.ports.map((p) => ({
|
|
611
|
+
id: p.id,
|
|
612
|
+
label: bare(p.id),
|
|
613
|
+
pkg: pkgOf(p.id),
|
|
614
|
+
fields: p.fields,
|
|
615
|
+
heldBy: p.heldBy,
|
|
616
|
+
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) })) })),
|
|
617
|
+
from: "structure.ports[]"
|
|
618
|
+
})),
|
|
619
|
+
chains: st.chains.map((c) => ({
|
|
620
|
+
value: c.value,
|
|
621
|
+
label: bare(c.value),
|
|
622
|
+
pkg: pkgOf(c.value),
|
|
623
|
+
by: bare(c.by),
|
|
624
|
+
start: c.start.map((i) => i.id ? bare(i.id) : i.text),
|
|
625
|
+
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 }))),
|
|
626
|
+
from: "structure.chains[]"
|
|
627
|
+
})),
|
|
628
|
+
combinations: st.combinations,
|
|
629
|
+
applied: st.applied.map((a) => ({
|
|
630
|
+
id: a.definition,
|
|
631
|
+
label: bare(a.definition),
|
|
632
|
+
pkg: pkgOf(a.definition),
|
|
633
|
+
fn: a.function,
|
|
634
|
+
insideBranch: a.insideBranch,
|
|
635
|
+
fedBy: a.fedBy,
|
|
636
|
+
from: "structure.applied[]"
|
|
637
|
+
})),
|
|
638
|
+
generic: st.generic.map((g) => ({ id: g.definition, label: bare(g.definition), vars: g.vars, signature: g.signature, from: "structure.generic[]" })),
|
|
639
|
+
exported: st.entries.filter((e) => e.transport === "link").map((e) => e.entry)
|
|
640
|
+
};
|
|
641
|
+
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" })));
|
|
642
|
+
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[]" }));
|
|
643
|
+
return {
|
|
644
|
+
schema: "system-map-2",
|
|
645
|
+
marks: MARKS_VERSION,
|
|
646
|
+
vocabulary: VOCABULARY,
|
|
647
|
+
program,
|
|
648
|
+
class: report.headline.class,
|
|
649
|
+
kind: routes.length ? "service" : "library",
|
|
650
|
+
callers,
|
|
651
|
+
ghostCallers,
|
|
652
|
+
entries,
|
|
653
|
+
wrappers,
|
|
654
|
+
parts,
|
|
655
|
+
uses,
|
|
656
|
+
resources,
|
|
657
|
+
ghostResources,
|
|
658
|
+
library,
|
|
659
|
+
keyed,
|
|
660
|
+
steps,
|
|
661
|
+
programs: programsOf(st, layers),
|
|
662
|
+
bundles: routes.length > 12 ? bundlesOf(entries, uses, keyed) : null,
|
|
663
|
+
phases: st.phases,
|
|
664
|
+
evidence: {
|
|
665
|
+
tools: ["api_report", "api_organize:abstractions", "api_organize:structure", "api_organize:layers"],
|
|
666
|
+
headline: report.headline,
|
|
667
|
+
derived: ["bundles: entries grouped by wrapper and identical marks"]
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
var keyKindOf = (e) => e.authority === "publishable" ? "publishable" : e.signedIn ? "secret" : "public";
|
|
672
|
+
function bundlesOf(entries, uses, keyed) {
|
|
673
|
+
const keyedIds = new Set(keyed.map((k) => k.id));
|
|
674
|
+
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(" ");
|
|
675
|
+
const fill = (l) => l.length ? l.some((x) => isWrite(x.op)) ? "W" : "R" : "-";
|
|
676
|
+
const sig = (e) => {
|
|
677
|
+
const p = e.passed[0], b = e.beside;
|
|
678
|
+
return JSON.stringify([
|
|
679
|
+
e.wrapper,
|
|
680
|
+
keyKindOf(e),
|
|
681
|
+
e.roles.length > 0,
|
|
682
|
+
e.writes,
|
|
683
|
+
e.guards.length > 0,
|
|
684
|
+
fill(e.reach.filter((r) => r.where === "direct")),
|
|
685
|
+
fill(e.reach.filter((r) => r.where === "passed")),
|
|
686
|
+
!!(p && p.guards.length),
|
|
687
|
+
e.model,
|
|
688
|
+
e.net,
|
|
689
|
+
sup(e),
|
|
690
|
+
e.limits.length > 0,
|
|
691
|
+
!!(b && b.calls.length),
|
|
692
|
+
!!(b && b.guards.length),
|
|
693
|
+
fill(b ? b.effects : []),
|
|
694
|
+
e.policy.length > 0,
|
|
695
|
+
[e.handlerId, ...e.guardIds, ...p ? [p.id, ...p.guardIds] : []].some((id) => keyedIds.has(id))
|
|
696
|
+
]);
|
|
697
|
+
};
|
|
698
|
+
const groups = /* @__PURE__ */ new Map();
|
|
699
|
+
for (const e of entries) {
|
|
700
|
+
const k = sig(e);
|
|
701
|
+
if (!groups.has(k)) groups.set(k, []);
|
|
702
|
+
groups.get(k).push(e.key);
|
|
703
|
+
}
|
|
704
|
+
const pathOf = new Map(entries.map((e) => [e.key, e.path]));
|
|
705
|
+
return [...groups.values()].map((keys, i) => ({
|
|
706
|
+
id: `bundle:${i + 1}`,
|
|
707
|
+
entries: keys,
|
|
708
|
+
count: keys.length,
|
|
709
|
+
label: pathPattern(keys.map((k) => pathOf.get(k))),
|
|
710
|
+
from: "derived: entries[] grouped by wrapper and identical marks"
|
|
711
|
+
}));
|
|
712
|
+
}
|
|
713
|
+
function pathPattern(paths) {
|
|
714
|
+
if (paths.length === 1) return paths[0];
|
|
715
|
+
const segs = paths.map((p) => p.split("/"));
|
|
716
|
+
const n = Math.min(...segs.map((s) => s.length));
|
|
717
|
+
const out = [];
|
|
718
|
+
for (let i = 0; i < n; i++) {
|
|
719
|
+
const v = uniq(segs.map((s) => s[i]));
|
|
720
|
+
out.push(v.length === 1 ? v[0] : "*");
|
|
721
|
+
}
|
|
722
|
+
if (segs.every((s) => s.length === n)) return out.join("/");
|
|
723
|
+
let k = 0;
|
|
724
|
+
while (k < n && out[k] !== "*") k++;
|
|
725
|
+
return out.slice(0, Math.max(k, 1)).join("/") + "/**";
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// ../../web/system-map-names.js
|
|
729
|
+
var SKIP = /* @__PURE__ */ new Set(["vocabulary", "evidence", "schema", "marks", "program", "class"]);
|
|
730
|
+
var skipped = (key, v) => SKIP.has(key) || key === "from" && !Array.isArray(v);
|
|
731
|
+
var STRUCTURAL = /* @__PURE__ */ new Set([
|
|
732
|
+
"kind",
|
|
733
|
+
"op",
|
|
734
|
+
"how",
|
|
735
|
+
"transport",
|
|
736
|
+
"authority",
|
|
737
|
+
"where",
|
|
738
|
+
"slotRole",
|
|
739
|
+
"role",
|
|
740
|
+
"passedKind",
|
|
741
|
+
"anchor",
|
|
742
|
+
"node",
|
|
743
|
+
"keyKinds",
|
|
744
|
+
"reachKinds",
|
|
745
|
+
"resources",
|
|
746
|
+
"replies",
|
|
747
|
+
"also",
|
|
748
|
+
"kinds",
|
|
749
|
+
"within",
|
|
750
|
+
"vars",
|
|
751
|
+
"id"
|
|
752
|
+
]);
|
|
753
|
+
var WHAT = {
|
|
754
|
+
path: "an action the app answers",
|
|
755
|
+
routes: "an action the app answers",
|
|
756
|
+
table: "a kind of record the app keeps",
|
|
757
|
+
tables: "a kind of record the app keeps",
|
|
758
|
+
roles: "a permission an action requires, held by a person's role or by the app's own server",
|
|
759
|
+
policy: "a setting an action passes to shared code",
|
|
760
|
+
tokens: "a setting an action passes to shared code",
|
|
761
|
+
fields: "an operation a pluggable part offers"
|
|
762
|
+
};
|
|
763
|
+
var PACKAGE = "a section of the program";
|
|
764
|
+
var DEFINITION = "a piece of the program";
|
|
765
|
+
var VALUE = "a kind of value";
|
|
766
|
+
var TYPES = /* @__PURE__ */ new Set(["type", "types", "signature"]);
|
|
767
|
+
var WORD = /[A-Za-z_][\w/]*::\w+|[A-Za-z_]\w*/g;
|
|
768
|
+
var PREDEF_WORDS = {
|
|
769
|
+
String: "text",
|
|
770
|
+
Int: "a number",
|
|
771
|
+
Bool: "yes or no",
|
|
772
|
+
Float64: "a decimal number",
|
|
773
|
+
Char: "a letter",
|
|
774
|
+
Unit: "nothing",
|
|
775
|
+
List: "a list",
|
|
776
|
+
Option: "maybe one",
|
|
777
|
+
Dict: "a lookup table"
|
|
778
|
+
};
|
|
779
|
+
var leaves = (record, visit) => {
|
|
780
|
+
const walk3 = (v, key) => {
|
|
781
|
+
if (typeof v === "string") visit(v, key);
|
|
782
|
+
else if (Array.isArray(v)) v.forEach((x) => walk3(x, key));
|
|
783
|
+
else if (v && typeof v === "object") {
|
|
784
|
+
for (const [k, x] of Object.entries(v)) if (!skipped(k, x)) walk3(x, k);
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
walk3(record, null);
|
|
788
|
+
};
|
|
789
|
+
function nameableParts(map, own) {
|
|
790
|
+
const found = /* @__PURE__ */ new Map();
|
|
791
|
+
const theirs2 = (pkg) => !own || own.has(pkg);
|
|
792
|
+
const add = (code, what) => {
|
|
793
|
+
if (code && !found.has(code) && !(code in PREDEF_WORDS) && (what !== PACKAGE || theirs2(code))) found.set(code, what);
|
|
794
|
+
};
|
|
795
|
+
const idParts = (id) => {
|
|
796
|
+
const i = id.lastIndexOf("::");
|
|
797
|
+
if (!theirs2(id.slice(0, i))) return;
|
|
798
|
+
add(id.slice(0, i), PACKAGE);
|
|
799
|
+
add(id.slice(i + 2), DEFINITION);
|
|
800
|
+
};
|
|
801
|
+
leaves(map, (s, key) => {
|
|
802
|
+
if (s.startsWith("route:")) return add(s.slice(6), WHAT.path);
|
|
803
|
+
if (TYPES.has(key)) {
|
|
804
|
+
for (const w of s.match(WORD) ?? []) if (w.includes("::")) idParts(w);
|
|
805
|
+
else if (w.length > 1) add(w, VALUE);
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
if (s.includes("::")) {
|
|
809
|
+
for (const w of s.match(WORD)) if (w.includes("::")) idParts(w);
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
if (STRUCTURAL.has(key)) return;
|
|
813
|
+
if (key === "name" || key === "package" || key === "pkg" || key === "instantiatingPackages" || key === "cycles" || key === "to") return add(s, s.includes("/") ? PACKAGE : DEFINITION);
|
|
814
|
+
add(s, WHAT[key] ?? DEFINITION);
|
|
815
|
+
});
|
|
816
|
+
for (const b of map.bundles ?? []) if (b.count > 1) found.delete(b.label);
|
|
817
|
+
return [...found].map(([code, what]) => ({ code, what })).sort((a, b) => a.code.localeCompare(b.code));
|
|
818
|
+
}
|
|
819
|
+
function plainNames(names) {
|
|
820
|
+
const out = /* @__PURE__ */ new Map(), taken = /* @__PURE__ */ new Set();
|
|
821
|
+
for (const [code, name] of Object.entries(names).sort(([a], [b]) => a.localeCompare(b))) {
|
|
822
|
+
const base = name.replace(/::|\//g, " ").replace(/\s+/g, " ").trim();
|
|
823
|
+
if (!base) continue;
|
|
824
|
+
let plain = base;
|
|
825
|
+
for (let n = 2; taken.has(plain); n++) plain = `${base} (${n})`;
|
|
826
|
+
taken.add(plain);
|
|
827
|
+
out.set(code, plain);
|
|
828
|
+
}
|
|
829
|
+
return out;
|
|
830
|
+
}
|
|
831
|
+
function relabelSystemMap(map, names) {
|
|
832
|
+
const plain = plainNames({ ...PREDEF_WORDS, ...names });
|
|
833
|
+
const word = (w) => plain.get(w) ?? w;
|
|
834
|
+
const id = (w) => {
|
|
835
|
+
const i = w.lastIndexOf("::");
|
|
836
|
+
return `${word(w.slice(0, i))}::${word(w.slice(i + 2))}`;
|
|
837
|
+
};
|
|
838
|
+
const text3 = (s, key) => {
|
|
839
|
+
if (s.startsWith("route:")) return `route:${word(s.slice(6))}`;
|
|
840
|
+
if (plain.has(s) && !STRUCTURAL.has(key)) return plain.get(s);
|
|
841
|
+
if (s.startsWith("/")) return s;
|
|
842
|
+
return s.replace(WORD, (w) => w.includes("::") ? id(w) : STRUCTURAL.has(key) ? w : word(w));
|
|
843
|
+
};
|
|
844
|
+
const walk3 = (v, key) => {
|
|
845
|
+
if (typeof v === "string") return text3(v, key);
|
|
846
|
+
if (Array.isArray(v)) return v.map((x) => walk3(x, key));
|
|
847
|
+
if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, skipped(k, x) ? x : walk3(x, k)]));
|
|
848
|
+
return v;
|
|
849
|
+
};
|
|
850
|
+
const out = walk3(map, null);
|
|
851
|
+
const pathOf = new Map(map.entries.map((e) => [e.key, e.path]));
|
|
852
|
+
out.bundles = map.bundles && map.bundles.map((b, i) => {
|
|
853
|
+
const paths = b.entries.map((k) => pathOf.get(k));
|
|
854
|
+
if (!paths.some((p) => plain.has(p))) return out.bundles[i];
|
|
855
|
+
return { ...out.bundles[i], label: b.count === 1 ? word(paths[0]) : `${word(paths[0])} and ${b.count - 1} more` };
|
|
856
|
+
});
|
|
857
|
+
return out;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// ../../web/what-happens-record.js
|
|
861
|
+
var SCHEMA = "what-happens-1";
|
|
862
|
+
var VOCABULARY2 = {
|
|
863
|
+
version: MARKS_VERSION,
|
|
864
|
+
added: ["outcome"],
|
|
865
|
+
marks: {
|
|
866
|
+
entryHead: "arrowhead where a request comes in; the rack above the tree has one per described entry, then one dashed line counting the entries no scenario describes, which opens to draw each of them struck <- entries[], ghosts[]",
|
|
867
|
+
guard: "red diamond: the declared sign-in or role check, the first branch of every entry that has one; its failure stem ends in a refusal <- tree node with from.kind=guard",
|
|
868
|
+
fork: "three prongs: a branch the code takes on the request, the caller, a value read from a table, or a call result; the arm each line takes is written where it leaves <- tree nodes",
|
|
869
|
+
station: "ring on a line: an effect on that path, its verb and table beside it; filled = it writes <- arms[].effects, entry.effects",
|
|
870
|
+
modelRing: "violet ring: the path reaches the model <- effects[resource=model]",
|
|
871
|
+
netRing: "orange ring: the path reaches the network <- effects[resource=net]",
|
|
872
|
+
outcome: "the end of a path: a cap with what the request gets back (a constructor, or a refusal with its status and code); red when a claim fails there or a check reports a witness that ends there, green when every obligation that failed there at the base is checked here and holds, hollow and dashed (unchecked) when a claim there is inconclusive or an obligation that failed at the base is no longer checked, grey otherwise <- leaves",
|
|
873
|
+
unchecked: "a hollow dashed cap and a ? tick: the engine cannot say whether the claim holds on this path (a step it could not open, a table it could not name, an answer it could not decide), or what failed here at the base is not checked here; never counted as holding <- claims[verdict=inconclusive], leaves[].gaps, diff.unresolved",
|
|
874
|
+
struck: "a struck ghost: something checked and found absent (an entry nobody described, a write a claim says a path must not make) <- ghosts[], claims holding with not",
|
|
875
|
+
bundle: "a cable with a count: a subtree too large for this view; opening it draws that part with a breadcrumb <- derived from the tree",
|
|
876
|
+
compared: 'a line under the rack, always there: "compared with <base> \xB7 N fixed \xB7 M still failing", or "no base compared" in faint text <- diff',
|
|
877
|
+
hull: `a shaded box on the line: a step that is not the handler's own work, folded (a wrapper's guard or short-circuit, the platform's declared check or the transaction it runs the plan in, work beside the wrapper, a wrapper's work after the handler); it keeps what the step answers instead of running the handler: the effects it makes before its test above the arms, then one row per arm read as a side stub (the arm, the effects that arm makes, its struck writes, what the request gets, ticks), then "continue"; opening it draws the step's own tree; drawn inline, the same hull is a light band behind the step and its exits, with its role and where it comes from above its test, so either way it reads as not the handler's own work <- tree nodes[concern.role], entries[].steps`
|
|
878
|
+
},
|
|
879
|
+
rule: "every entry, branch, arm, effect and outcome the engine computes is drawn, a folded step's inside its box and an undescribed entry behind the rack's one line; the author's words appear only on ids the engine computed, in italic, with the code name beside them.",
|
|
880
|
+
concerns: "where each branch and effect comes from in value flow (concern.layer, effects[].layer): core = the handler's own work, a function it hands its wrapper or its body when it has none; cross = the wrapper its route shape names, shared with other entries; beside = the handler's code outside the wrapper call; platform = the route's declared authority, or the transaction the platform runs a plan in (its arms that give up or cannot confirm skip the handler's work). Roles come from which arms reach the handler, never from names."
|
|
881
|
+
};
|
|
882
|
+
var bare2 = (id) => String(id).split("::").pop();
|
|
883
|
+
var claimKey = (entry, c) => `${entry}\0${c.at}\0${c.parsed}`;
|
|
884
|
+
function walk(tree, f, path11 = []) {
|
|
885
|
+
if (!tree) return;
|
|
886
|
+
f(tree, path11);
|
|
887
|
+
if (tree.kind === "node") for (const arm of tree.arms) {
|
|
888
|
+
f(arm, path11);
|
|
889
|
+
walk(arm.next, f, [...path11, arm]);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
var leavesOf = (tree) => {
|
|
893
|
+
const out = [];
|
|
894
|
+
walk(tree, (t) => {
|
|
895
|
+
if (t.kind === "leaf") out.push(t);
|
|
896
|
+
});
|
|
897
|
+
return out;
|
|
898
|
+
};
|
|
899
|
+
function pathEffects(entry) {
|
|
900
|
+
const out = /* @__PURE__ */ new Map();
|
|
901
|
+
const go = (t, acc) => {
|
|
902
|
+
if (!t) return;
|
|
903
|
+
if (t.kind === "leaf") {
|
|
904
|
+
out.set(t.id, acc);
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
for (const a of t.arms) go(a.next, [...acc, ...a.effects]);
|
|
908
|
+
};
|
|
909
|
+
go(entry.tree, entry.effects || []);
|
|
910
|
+
return out;
|
|
911
|
+
}
|
|
912
|
+
function heldOn(tree, guards) {
|
|
913
|
+
const out = /* @__PURE__ */ new Set();
|
|
914
|
+
const go = (t, held) => {
|
|
915
|
+
if (!t) return;
|
|
916
|
+
if (t.kind === "leaf") {
|
|
917
|
+
if (held) out.add(t.id);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
const isGuard = t.from?.kind === "call" && guards.includes(bare2(t.from.callee));
|
|
921
|
+
for (const a of t.arms) go(a.next, held || isGuard && a.arm === "True");
|
|
922
|
+
};
|
|
923
|
+
go(tree, false);
|
|
924
|
+
return out;
|
|
925
|
+
}
|
|
926
|
+
function witnessesOf(access, entries) {
|
|
927
|
+
if (!access) return [];
|
|
928
|
+
const findings = (access.report?.findings || []).filter((f) => f.status === "violated");
|
|
929
|
+
return findings.map((f, i) => {
|
|
930
|
+
const site = `${f.package}::${f.binding}`;
|
|
931
|
+
const guards = f.pathCondition?.unlessHeld || [];
|
|
932
|
+
const leaves2 = entries.flatMap((e) => {
|
|
933
|
+
const held = heldOn(e.tree, guards);
|
|
934
|
+
return leavesOf(e.tree).filter((l) => !held.has(l.id) && l.effects.some((x) => x.site === site && bare2(x.primitive) === f.operation && x.tables.includes(f.resource)));
|
|
935
|
+
}).map((l) => l.id);
|
|
936
|
+
return {
|
|
937
|
+
id: `witness:${i + 1}`,
|
|
938
|
+
check: "access",
|
|
939
|
+
resource: f.resource,
|
|
940
|
+
site,
|
|
941
|
+
operation: f.operation,
|
|
942
|
+
kind: f.kind,
|
|
943
|
+
detail: f.detail,
|
|
944
|
+
leaves: leaves2,
|
|
945
|
+
...guards.length ? { unlessHeld: guards } : {},
|
|
946
|
+
from: guards.length ? "api_access_check report.findings[status=violated], on paths where pathCondition.unlessHeld did not hold" : "api_access_check report.findings[status=violated]"
|
|
947
|
+
};
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
function buildWhatHappens(engine, { program, base = null, baseLabel = "base" } = {}) {
|
|
951
|
+
for (const [k, v] of Object.entries(engine)) if (v && !v.ok) throw new Error(`${k}: ${v.error}`);
|
|
952
|
+
const st = engine.structure;
|
|
953
|
+
const claims = st.claims || { scenarios: [], undescribed: (st.scenarios || []).map((s) => s.entry) };
|
|
954
|
+
const byEntry = new Map(claims.scenarios.filter((s) => s.status === "matched").map((s) => [s.entry, s]));
|
|
955
|
+
const routes = new Map((st.entries || []).map((e) => [e.entry, e]));
|
|
956
|
+
const entries = st.scenarios.map((s) => {
|
|
957
|
+
const meta = routes.get(s.entry) || {};
|
|
958
|
+
const sc = byEntry.get(s.entry);
|
|
959
|
+
const names = new Map((sc?.names || []).filter((n) => n.status === "named").map((n) => [n.id, n.words]));
|
|
960
|
+
const copy = (t) => {
|
|
961
|
+
if (!t) return null;
|
|
962
|
+
if (t.kind === "leaf") return { ...t, words: names.get(t.id) || null, claims: [], witnesses: [], status: "grey" };
|
|
963
|
+
return { ...t, words: names.get(t.id) || null, arms: t.arms.map((a) => ({ ...a, words: names.get(a.id) || null, next: copy(a.next) })) };
|
|
964
|
+
};
|
|
965
|
+
return {
|
|
966
|
+
entry: s.entry,
|
|
967
|
+
handler: s.handler,
|
|
968
|
+
label: s.entry.replace(/^route:/, ""),
|
|
969
|
+
authority: meta.authority || null,
|
|
970
|
+
transport: meta.transport || null,
|
|
971
|
+
title: sc?.title || null,
|
|
972
|
+
described: !!sc,
|
|
973
|
+
effects: s.effects,
|
|
974
|
+
tree: copy(s.tree),
|
|
975
|
+
leafCount: Number(s.leafCount),
|
|
976
|
+
truncated: s.truncated,
|
|
977
|
+
unsupported: s.unsupported || null,
|
|
978
|
+
wrapper: s.wrapper || null,
|
|
979
|
+
steps: s.steps || [],
|
|
980
|
+
from: "structure.scenarios[]"
|
|
981
|
+
};
|
|
982
|
+
});
|
|
983
|
+
const entryOf = new Map(entries.map((e) => [e.entry, e]));
|
|
984
|
+
const leafById = new Map(entries.flatMap((e) => leavesOf(e.tree).map((l) => [l.id, l])));
|
|
985
|
+
const checked = [], notes = [], refused = [], mismatches = [];
|
|
986
|
+
for (const sc of claims.scenarios) {
|
|
987
|
+
if (sc.status !== "matched") {
|
|
988
|
+
mismatches.push({ entry: sc.entry, title: sc.title || null, reason: sc.reason, from: "structure.claims.scenarios[status=mismatch]" });
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
991
|
+
for (const n of sc.names) if (n.status !== "named") refused.push({ entry: sc.entry, id: n.id, words: n.words, reason: n.reason, from: "structure.claims.scenarios[].names[status=refused]" });
|
|
992
|
+
for (const x of sc.expect) {
|
|
993
|
+
if (x.verdict === "not-a-claim") {
|
|
994
|
+
notes.push({ entry: sc.entry, at: x.at, text: x.claim, from: "structure.claims.scenarios[].expect[verdict=not-a-claim]" });
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
if (x.verdict === "refused") {
|
|
998
|
+
refused.push({ entry: sc.entry, id: x.at, words: x.claim, reason: x.reason, from: "structure.claims.scenarios[].expect[verdict=refused]" });
|
|
999
|
+
continue;
|
|
1000
|
+
}
|
|
1001
|
+
const open = new Map((x.inconclusive || []).map((o) => [o.leaf, o.reasons]));
|
|
1002
|
+
const c = {
|
|
1003
|
+
id: `claim:${checked.length + 1}`,
|
|
1004
|
+
entry: sc.entry,
|
|
1005
|
+
at: x.at,
|
|
1006
|
+
claim: x.claim,
|
|
1007
|
+
parsed: x.parsed,
|
|
1008
|
+
property: x.property,
|
|
1009
|
+
verdict: x.verdict,
|
|
1010
|
+
leaves: x.leaves,
|
|
1011
|
+
failing: x.failing,
|
|
1012
|
+
inconclusive: x.inconclusive || [],
|
|
1013
|
+
from: "structure.claims.scenarios[].expect[]"
|
|
1014
|
+
};
|
|
1015
|
+
checked.push(c);
|
|
1016
|
+
for (const id of x.leaves) {
|
|
1017
|
+
const l = leafById.get(id);
|
|
1018
|
+
if (!l) continue;
|
|
1019
|
+
const verdict = x.failing.includes(id) ? "fails" : open.has(id) ? "inconclusive" : "holds";
|
|
1020
|
+
l.claims.push({ id: c.id, at: x.at, parsed: x.parsed, property: x.property, verdict, ...verdict === "inconclusive" ? { reasons: open.get(id) } : {} });
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
const witnesses = witnessesOf(engine.access, entries);
|
|
1025
|
+
const basePaths = base ? new Map(base.entries.flatMap((e) => [...pathEffects(e)])) : null;
|
|
1026
|
+
for (const w of witnesses) for (const id of w.leaves) leafById.get(id)?.witnesses.push(w.id);
|
|
1027
|
+
for (const l of leafById.values()) {
|
|
1028
|
+
if (l.claims.some((c) => c.verdict === "fails") || l.witnesses.length) l.status = "red";
|
|
1029
|
+
else if (l.claims.some((c) => c.verdict === "inconclusive")) l.status = "unchecked";
|
|
1030
|
+
}
|
|
1031
|
+
let diff = null;
|
|
1032
|
+
if (base) {
|
|
1033
|
+
const baseRed = new Map(base.entries.flatMap((e) => leavesOf(e.tree).filter((l) => l.status === "red").map((l) => [l.id, { entry: e.entry, leaf: l }])));
|
|
1034
|
+
const baseWitness = new Map((base.witnesses || []).map((w) => [w.id, w]));
|
|
1035
|
+
const fixed = [], still = [], gone = [], unresolved = [];
|
|
1036
|
+
for (const [id, { entry, leaf: bl }] of baseRed) {
|
|
1037
|
+
const here = leafById.get(id);
|
|
1038
|
+
if (!here) {
|
|
1039
|
+
gone.push(id);
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
if (here.status === "red") {
|
|
1043
|
+
still.push(id);
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
const reasons = [
|
|
1047
|
+
...bl.claims.filter((c) => c.verdict === "fails").flatMap((c) => {
|
|
1048
|
+
const now = here.claims.find((h) => claimKey(entry, h) === claimKey(entry, c));
|
|
1049
|
+
if (!now) return [`the claim ${c.parsed} at ${c.at} failed here at the base and is not checked here`];
|
|
1050
|
+
return now.verdict === "holds" ? [] : [`the claim ${c.parsed} at ${c.at} failed here at the base and is inconclusive here`];
|
|
1051
|
+
}),
|
|
1052
|
+
...bl.witnesses.length && !engine.access ? [`the access check reported a witness here at the base and did not run here`] : []
|
|
1053
|
+
];
|
|
1054
|
+
const baseClaims = bl.claims, baseWitnesses = bl.witnesses.map((w) => baseWitness.get(w)).filter(Boolean);
|
|
1055
|
+
here.base = { outcome: bl.outcome, effects: bl.effects || basePaths.get(id) || [], claims: baseClaims, witnesses: baseWitnesses };
|
|
1056
|
+
if (reasons.length) {
|
|
1057
|
+
here.status = "unchecked";
|
|
1058
|
+
unresolved.push({ id, reasons });
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
here.status = "green";
|
|
1062
|
+
fixed.push(id);
|
|
1063
|
+
}
|
|
1064
|
+
diff = {
|
|
1065
|
+
base: baseLabel,
|
|
1066
|
+
fixed,
|
|
1067
|
+
stillRed: still,
|
|
1068
|
+
goneAtHead: gone,
|
|
1069
|
+
unresolved,
|
|
1070
|
+
from: "derived: base leaves[status=red] matched by id; each failed claim matched by entry, at and parsed claim; a witness is gone when the access check ran here and reports none on the leaf"
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
const ghosts = entries.filter((e) => !e.described).map((e) => ({ entry: e.entry, from: "structure.claims.undescribed[]" }));
|
|
1074
|
+
for (const l of leafById.values()) delete l.effects;
|
|
1075
|
+
return {
|
|
1076
|
+
schema: SCHEMA,
|
|
1077
|
+
marks: MARKS_VERSION,
|
|
1078
|
+
vocabulary: VOCABULARY2,
|
|
1079
|
+
program,
|
|
1080
|
+
entries,
|
|
1081
|
+
ghosts,
|
|
1082
|
+
claims: checked,
|
|
1083
|
+
witnesses,
|
|
1084
|
+
notes,
|
|
1085
|
+
refused,
|
|
1086
|
+
mismatches,
|
|
1087
|
+
diff,
|
|
1088
|
+
counts: {
|
|
1089
|
+
entries: entries.length,
|
|
1090
|
+
described: entries.length - ghosts.length,
|
|
1091
|
+
leaves: leafById.size,
|
|
1092
|
+
steps: entries.reduce((n, e) => n + e.steps.length, 0),
|
|
1093
|
+
wrapped: entries.filter((e) => e.wrapper && e.wrapper.wraps).length,
|
|
1094
|
+
red: [...leafById.values()].filter((l) => l.status === "red").length,
|
|
1095
|
+
green: [...leafById.values()].filter((l) => l.status === "green").length,
|
|
1096
|
+
unchecked: [...leafById.values()].filter((l) => l.status === "unchecked").length
|
|
1097
|
+
},
|
|
1098
|
+
evidence: { tools: ["api_organize:structure", ...engine.access ? ["api_access_check"] : []], derived: ["diff: base red leaves matched by id, their failed obligations by identity"] }
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
function stationLabel(e) {
|
|
1102
|
+
const verb = e.op === "mint id" ? "mint" : e.op;
|
|
1103
|
+
if (e.tables.length) return `${verb} \xB7 ${e.tables.join(", ")}`;
|
|
1104
|
+
if (e.resource === "model" || e.resource === "net") return verb;
|
|
1105
|
+
return `${verb} \xB7 ${bare2(e.primitive)}`;
|
|
1106
|
+
}
|
|
1107
|
+
var said = (f) => {
|
|
1108
|
+
if (f.kind !== "read") return null;
|
|
1109
|
+
const gives = `what ${f.op} \xB7 ${f.table || bare2(f.primitive)} gives back`;
|
|
1110
|
+
return f.path && f.path.length ? `the ${f.path.join(".")} of ${gives}` : gives;
|
|
1111
|
+
};
|
|
1112
|
+
function outcomeLabel(o) {
|
|
1113
|
+
if (o.status && !o.constructors.length) return o.shown;
|
|
1114
|
+
const head = o.constructors.length ? o.constructors.join(" | ") : o.from && said(o.from) || (o.value ? `the ${o.value}` : o.shown);
|
|
1115
|
+
return head;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
// src/studio/project.ts
|
|
1119
|
+
import { createHash } from "crypto";
|
|
1120
|
+
import fs from "fs";
|
|
1121
|
+
import path from "path";
|
|
1122
|
+
var SKIPPED = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "target", "out"]);
|
|
1123
|
+
function projectSources(root) {
|
|
1124
|
+
const files = [];
|
|
1125
|
+
const walk3 = (dir) => {
|
|
1126
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1127
|
+
if (entry.name.startsWith(".") || SKIPPED.has(entry.name)) continue;
|
|
1128
|
+
const full = path.join(dir, entry.name);
|
|
1129
|
+
if (entry.isDirectory()) walk3(full);
|
|
1130
|
+
else if (entry.isFile() && entry.name.endsWith(".bosatsu")) {
|
|
1131
|
+
files.push({ fileName: path.relative(root, full).split(path.sep).join("/"), source: fs.readFileSync(full, "utf8") });
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
walk3(root);
|
|
1136
|
+
return files;
|
|
1137
|
+
}
|
|
1138
|
+
function sourcesHash(files) {
|
|
1139
|
+
const hash = createHash("sha256");
|
|
1140
|
+
for (const file of files) hash.update(`${file.fileName}\0${file.source}\0`);
|
|
1141
|
+
return hash.digest("hex");
|
|
1142
|
+
}
|
|
1143
|
+
function caseSources(root) {
|
|
1144
|
+
const dir = path.join(root, ".yichus", "cases");
|
|
1145
|
+
if (!fs.existsSync(dir)) return [];
|
|
1146
|
+
return fs.readdirSync(dir).filter((name) => name.endsWith(".bosatsu")).sort().map((name) => ({ fileName: `cases/${name}`, source: fs.readFileSync(path.join(dir, name), "utf8") }));
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
// src/studio/questions.ts
|
|
1150
|
+
import { z as z3 } from "zod";
|
|
1151
|
+
var Step = z3.looseObject({ op: z3.string(), tables: z3.array(z3.string()).default([]), resource: z3.string() });
|
|
1152
|
+
var Route = z3.looseObject({
|
|
1153
|
+
path: z3.string(),
|
|
1154
|
+
handler: z3.string(),
|
|
1155
|
+
authority: z3.string().optional(),
|
|
1156
|
+
tables: z3.array(z3.string()).default([]),
|
|
1157
|
+
inferredSteps: z3.array(Step).default([])
|
|
1158
|
+
});
|
|
1159
|
+
var Access = z3.looseObject({
|
|
1160
|
+
kind: z3.string(),
|
|
1161
|
+
guards: z3.array(z3.string()).default([]),
|
|
1162
|
+
roles: z3.array(z3.string()).default([])
|
|
1163
|
+
});
|
|
1164
|
+
var Table = z3.looseObject({
|
|
1165
|
+
name: z3.string(),
|
|
1166
|
+
policy: z3.string().nullable().optional(),
|
|
1167
|
+
access: Access.nullable().optional(),
|
|
1168
|
+
readers: z3.array(z3.string()).default([]),
|
|
1169
|
+
writers: z3.array(z3.string()).default([])
|
|
1170
|
+
});
|
|
1171
|
+
var Report = z3.looseObject({
|
|
1172
|
+
surface: z3.looseObject({ routes: z3.array(Route).default([]) }).default({ routes: [] }),
|
|
1173
|
+
dataModel: z3.looseObject({ tables: z3.array(Table).default([]) }).default({ tables: [] })
|
|
1174
|
+
});
|
|
1175
|
+
var Entry = z3.looseObject({ entry: z3.string(), resources: z3.array(z3.string()).default([]) });
|
|
1176
|
+
var Structure = z3.looseObject({ entries: z3.array(Entry).default([]) });
|
|
1177
|
+
var ACCESS_RULES = {
|
|
1178
|
+
owner: { declared: (a) => a.kind === "OwnerScoped", write: "OwnerScoped", guide: "Owner-scoped data" },
|
|
1179
|
+
// A guard every person passes through; a role may pass it only where every route that reaches it requires the role.
|
|
1180
|
+
shared: {
|
|
1181
|
+
declared: (a) => (a.kind === "Guarded" || a.kind === "GuardedOrRoles") && a.guards.length > 0,
|
|
1182
|
+
write: "Guarded([the guard that says who may see a record]), or GuardedOrRoles([the guard], [the roles that may pass it])",
|
|
1183
|
+
guide: "Guarded data"
|
|
1184
|
+
},
|
|
1185
|
+
"server-only": { declared: (a) => a.kind === "GuardedOrRoles" && !a.guards.length, write: "GuardedOrRoles([], [the grants of the worker routes that use it])", guide: "Principal is a trust boundary" },
|
|
1186
|
+
"everyone-reads": { declared: (a) => a.kind === "PublicReadRoleWrite", write: "PublicReadRoleWrite([the roles that may change it])", guide: "Public data" },
|
|
1187
|
+
public: { declared: (a) => a.kind === "Public", write: "Public", guide: "Public data" }
|
|
1188
|
+
};
|
|
1189
|
+
var platform = {
|
|
1190
|
+
id: "platform",
|
|
1191
|
+
kind: "platform",
|
|
1192
|
+
subject: null,
|
|
1193
|
+
ask: "Where do you want your app to run once it is ready?",
|
|
1194
|
+
why: "Each place runs apps differently: some keep a server running, some only run the page people open. Knowing it now means your agent builds the pieces that place can run, instead of rebuilding them later.",
|
|
1195
|
+
choices: [
|
|
1196
|
+
{ id: "render", label: "Render", means: "The server, its database, the page and background jobs all run on Render." },
|
|
1197
|
+
{ id: "vercel", label: "Vercel", means: "The page people open runs on Vercel; the server and its database run on a second service, because Vercel does not keep a server running." },
|
|
1198
|
+
{ id: "netlify", label: "Netlify", means: "The page people open runs on Netlify; the server and its database run on a second service, because Netlify does not keep a server running." },
|
|
1199
|
+
{ id: "aws", label: "Amazon Web Services", means: "The server runs on App Runner or ECS with an RDS database." },
|
|
1200
|
+
{ id: "gcp", label: "Google Cloud", means: "The server runs on Cloud Run with a Cloud SQL database." },
|
|
1201
|
+
{ id: "azure", label: "Microsoft Azure", means: "The server runs on Container Apps or App Service with an Azure PostgreSQL database." },
|
|
1202
|
+
{ id: "undecided", label: "Not sure yet", means: "Your agent builds for Render, which holds everything in one place; moving later changes configuration, not the app." }
|
|
1203
|
+
],
|
|
1204
|
+
fact: "Every app runs somewhere."
|
|
1205
|
+
};
|
|
1206
|
+
var PLATFORM_SECTION = {
|
|
1207
|
+
render: "Render",
|
|
1208
|
+
vercel: "Vercel",
|
|
1209
|
+
netlify: "Netlify",
|
|
1210
|
+
aws: "AWS",
|
|
1211
|
+
gcp: "Google Cloud",
|
|
1212
|
+
azure: "Microsoft Azure",
|
|
1213
|
+
undecided: "Not decided yet"
|
|
1214
|
+
};
|
|
1215
|
+
var PAGE_ONLY = /* @__PURE__ */ new Set(["vercel", "netlify"]);
|
|
1216
|
+
var HOST_SECTION = { render: "Render", gcp: "Google Cloud", aws: "AWS", azure: "Microsoft Azure", undecided: "Render" };
|
|
1217
|
+
function hostQuestion(platformLabel) {
|
|
1218
|
+
return {
|
|
1219
|
+
id: "host",
|
|
1220
|
+
kind: "host",
|
|
1221
|
+
subject: null,
|
|
1222
|
+
ask: `${platformLabel} runs the page people open, but it does not keep a server running. Where should your app's server and its database run?`,
|
|
1223
|
+
why: "This is a second service with its own account and its own monthly bill, next to the one you already have. Your agent sets it up there and connects your pages to it.",
|
|
1224
|
+
choices: [
|
|
1225
|
+
{ id: "render", label: "Render", means: "The server and its database run on Render, set up from one file in your project." },
|
|
1226
|
+
{ id: "gcp", label: "Google Cloud", means: "The server runs on Cloud Run with a Cloud SQL database." },
|
|
1227
|
+
{ id: "aws", label: "Amazon Web Services", means: "The server runs on App Runner with an RDS database." },
|
|
1228
|
+
{ id: "azure", label: "Microsoft Azure", means: "The server runs on Container Apps with an Azure PostgreSQL database." },
|
|
1229
|
+
{ id: "undecided", label: "Not sure yet", means: "Your agent builds for Render; moving later changes configuration, not the app." }
|
|
1230
|
+
],
|
|
1231
|
+
fact: `${platformLabel} does not keep a server running.`
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
var topology = {
|
|
1235
|
+
id: "topology",
|
|
1236
|
+
kind: "topology",
|
|
1237
|
+
subject: null,
|
|
1238
|
+
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?",
|
|
1239
|
+
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.",
|
|
1240
|
+
choices: [
|
|
1241
|
+
{ id: "many", label: "Several copies", means: "Every check assumes requests can run at the same moment on different copies." },
|
|
1242
|
+
{ 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." }
|
|
1243
|
+
],
|
|
1244
|
+
fact: "The program serves routes."
|
|
1245
|
+
};
|
|
1246
|
+
var shown = (names, subject) => names[subject] ?? subject;
|
|
1247
|
+
function accessQuestion(table, names) {
|
|
1248
|
+
return {
|
|
1249
|
+
id: `access:${table.name}`,
|
|
1250
|
+
kind: "access",
|
|
1251
|
+
subject: table.name,
|
|
1252
|
+
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?`,
|
|
1253
|
+
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.",
|
|
1254
|
+
choices: [
|
|
1255
|
+
{ 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. No one else, not even a manager, sees or changes them, so anything someone else decides about them, such as an approval, belongs in records only the person who decides it may change." },
|
|
1256
|
+
{ id: "shared", label: "Only the people a rule lets in", means: "For example the members of a team, or the people a record was shared with. Every read and change goes through that rule, except work done under a role you name, such as an administrator or the app's own server, and the check proves nothing else skips it." },
|
|
1257
|
+
{ id: "server-only", label: "No person, only the app's own server", means: "Records the app keeps for itself, such as which number belongs to whom or which messages it has already seen. Only work the app's own server starts may read or change them, and the check proves nothing a person calls reaches them." },
|
|
1258
|
+
{ 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." },
|
|
1259
|
+
{ id: "public", label: "Anyone, even without signing in", means: "Nothing in these records is private." }
|
|
1260
|
+
],
|
|
1261
|
+
fact: `The program stores rows in "${table.name}" (policy declared: ${table.policy ?? "none"}).`
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
function togetherQuestion(table, handlers, names) {
|
|
1265
|
+
const who = table.access?.kind === "OwnerScoped" ? "the person it belongs to, on two devices or in two tabs" : "two people, or one person on two devices";
|
|
1266
|
+
return {
|
|
1267
|
+
id: `together:${table.name}`,
|
|
1268
|
+
kind: "together",
|
|
1269
|
+
subject: table.name,
|
|
1270
|
+
ask: `Two requests change the same record in "${shown(names, table.name)}" at the same moment (${who}). What should happen?`,
|
|
1271
|
+
why: "When a request reads a record and then writes it back, a second request in between can be silently lost, or both can pass a limit only one should, such as two people taking the last spot. People rarely notice until data goes missing.",
|
|
1272
|
+
choices: [
|
|
1273
|
+
{ id: "keep-both", label: "Both changes are kept", means: "Each change happens as one indivisible step that sees the one before it, so neither can overwrite the other unseen and a limit the app checks is never passed twice; the check proves no change is lost." },
|
|
1274
|
+
{ 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." }
|
|
1275
|
+
],
|
|
1276
|
+
fact: `${handlers.join(", ")} ${handlers.length === 1 ? "reads" : "read"} "${table.name}" and then ${handlers.length === 1 ? "writes" : "write"} it.`
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
function partialQuestion(route, tables, names) {
|
|
1280
|
+
return {
|
|
1281
|
+
id: `partial:${route.path}`,
|
|
1282
|
+
kind: "partial",
|
|
1283
|
+
subject: route.path,
|
|
1284
|
+
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?`,
|
|
1285
|
+
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.`,
|
|
1286
|
+
choices: [
|
|
1287
|
+
{ 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." },
|
|
1288
|
+
{ id: "partial-ok", label: "Partial is fine", means: "No check is added for this action." }
|
|
1289
|
+
],
|
|
1290
|
+
fact: `${route.handler} writes ${tables.map((t) => `"${t}"`).join(", ")} in more than one step.`
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
function outsideQuestion(route, kinds, names) {
|
|
1294
|
+
const service = kinds.includes("model") ? "an AI model" : "another service on the internet";
|
|
1295
|
+
return {
|
|
1296
|
+
id: `outside:${route.path}`,
|
|
1297
|
+
kind: "outside",
|
|
1298
|
+
subject: route.path,
|
|
1299
|
+
ask: `"${shown(names, route.path)}" calls ${service}. If that service is down or slow, what should the person using your app see?`,
|
|
1300
|
+
why: "Outside services fail often. Without a plan, a failure can leave a half-finished record or charge for work that never happened.",
|
|
1301
|
+
choices: [
|
|
1302
|
+
{ id: "fail-clean", label: "An error, with nothing saved", means: "Yichus makes the service fail and checks that nothing from this action stays saved." },
|
|
1303
|
+
{ 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." },
|
|
1304
|
+
{ id: "no-plan", label: "No preference", means: "No check is added for this action." }
|
|
1305
|
+
],
|
|
1306
|
+
fact: `${route.handler} reaches ${kinds.join(" and ")}.`
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
var PERSON_SIGNS_IN = /* @__PURE__ */ new Set(["authenticated", "publishable", "requires-roles"]);
|
|
1310
|
+
var signIn = {
|
|
1311
|
+
id: "sign-in",
|
|
1312
|
+
kind: "sign-in",
|
|
1313
|
+
subject: null,
|
|
1314
|
+
ask: "How do people sign in to your app?",
|
|
1315
|
+
why: "The server checks who is asking before it shows or changes anything private, so it has to trust the same sign-in your pages use.",
|
|
1316
|
+
choices: [
|
|
1317
|
+
{ id: "new", label: "They don't yet", means: "Your agent adds sign-in with a provider that runs it for you, such as Clerk." },
|
|
1318
|
+
{ id: "clerk", label: "Clerk", means: "The server checks each person's Clerk session." },
|
|
1319
|
+
{ id: "supabase", label: "Supabase", means: "The server checks each person's Supabase session. Your agent checks how your Supabase project signs sessions, because the server has to be set up to match." },
|
|
1320
|
+
{ id: "other", label: "Another sign-in provider", means: "Auth0, Google, Firebase, Cognito, Microsoft Entra or another provider that publishes its signing keys." },
|
|
1321
|
+
{ id: "keys", label: "Only programs call it, with keys", means: "No person signs in: scripts and other servers call the app with API keys." }
|
|
1322
|
+
],
|
|
1323
|
+
fact: "Some actions are for signed-in people only."
|
|
1324
|
+
};
|
|
1325
|
+
var existingData = {
|
|
1326
|
+
id: "data",
|
|
1327
|
+
kind: "data",
|
|
1328
|
+
subject: null,
|
|
1329
|
+
ask: "Are there records somewhere today, such as in an app you already run, that this app must start with?",
|
|
1330
|
+
why: "Moving records is a step of its own: they have to be copied in, matched to the people they belong to, and checked. Anything the old place keeps that this app does not would be lost, so your agent lists those first.",
|
|
1331
|
+
choices: [
|
|
1332
|
+
{ id: "new", label: "No, it starts empty", means: "Nothing is moved." },
|
|
1333
|
+
{ id: "move", label: "Yes, copy them in", means: "Your agent writes a one-time import into this app's database. Before anything moves, it lists every kind of record the old place keeps that this app would not, and you decide about each." },
|
|
1334
|
+
{ id: "same-database", label: "Yes, and keep the database they are in", means: "This app keeps its records in the PostgreSQL database you already have, beside the old tables, and the old records are copied in once. Your agent lists anything this app would not keep, and you decide about each." }
|
|
1335
|
+
],
|
|
1336
|
+
fact: "The program keeps records."
|
|
1337
|
+
};
|
|
1338
|
+
function questionsFor(report, structure, names = {}) {
|
|
1339
|
+
const questions = [];
|
|
1340
|
+
if (report.surface.routes.length) questions.push(topology);
|
|
1341
|
+
for (const table of report.dataModel.tables) questions.push(accessQuestion(table, names));
|
|
1342
|
+
for (const table of report.dataModel.tables) {
|
|
1343
|
+
const both = table.readers.filter((h) => table.writers.includes(h));
|
|
1344
|
+
if (both.length) questions.push(togetherQuestion(table, both, names));
|
|
1345
|
+
}
|
|
1346
|
+
for (const route of report.surface.routes) {
|
|
1347
|
+
const writes = route.inferredSteps.filter((s) => s.resource === "db" && s.op !== "read" && s.op !== "query");
|
|
1348
|
+
const tables = [...new Set(writes.flatMap((s) => s.tables))];
|
|
1349
|
+
if (writes.length >= 2) questions.push(partialQuestion(route, tables, names));
|
|
1350
|
+
}
|
|
1351
|
+
for (const route of report.surface.routes) {
|
|
1352
|
+
const entry = structure.entries.find((e) => e.entry === `route:${route.path}`);
|
|
1353
|
+
const kinds = (entry?.resources ?? []).filter((r) => r === "model" || r === "net");
|
|
1354
|
+
if (kinds.length) questions.push(outsideQuestion(route, kinds, names));
|
|
1355
|
+
}
|
|
1356
|
+
if (report.surface.routes.some((r) => r.authority !== void 0 && PERSON_SIGNS_IN.has(r.authority))) questions.push(signIn);
|
|
1357
|
+
if (report.dataModel.tables.length) questions.push(existingData);
|
|
1358
|
+
return questions;
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// src/studio/requirements.ts
|
|
1362
|
+
import fs2 from "fs";
|
|
1363
|
+
import path2 from "path";
|
|
1364
|
+
import { z as z4 } from "zod";
|
|
1365
|
+
var Answer = z4.object({
|
|
1366
|
+
question: z4.string().min(1),
|
|
1367
|
+
choice: z4.string().min(1),
|
|
1368
|
+
words: z4.string(),
|
|
1369
|
+
answeredAt: z4.string()
|
|
1370
|
+
});
|
|
1371
|
+
var Scenario = z4.object({
|
|
1372
|
+
entry: z4.string().min(1),
|
|
1373
|
+
title: z4.string().optional(),
|
|
1374
|
+
names: z4.record(z4.string(), z4.string()).optional(),
|
|
1375
|
+
expect: z4.array(z4.object({ at: z4.string(), claim: z4.string() }).strict()).optional()
|
|
1376
|
+
}).strict();
|
|
1377
|
+
var RuleRecord = z4.object({ rule: z4.string().trim().min(1), laws: z4.array(z4.string().min(1)).min(1) }).strict();
|
|
1378
|
+
var Requirements = z4.object({
|
|
1379
|
+
schemaVersion: z4.literal("yichus-requirements-1"),
|
|
1380
|
+
description: z4.string().nullable(),
|
|
1381
|
+
answers: z4.array(Answer),
|
|
1382
|
+
/** Plain names for the program's records and actions, keyed by code name. */
|
|
1383
|
+
names: z4.record(z4.string(), z4.string()).optional(),
|
|
1384
|
+
scenarios: z4.array(Scenario).optional(),
|
|
1385
|
+
/** The rules the agent listed; absent until it has looked, empty when the
|
|
1386
|
+
* person stated none. */
|
|
1387
|
+
rules: z4.array(RuleRecord).optional()
|
|
1388
|
+
});
|
|
1389
|
+
var studioDir = (root) => path2.join(root, ".yichus");
|
|
1390
|
+
var requirementsPath = (root) => path2.join(studioDir(root), "requirements.json");
|
|
1391
|
+
function loadRequirements(root) {
|
|
1392
|
+
const file = requirementsPath(root);
|
|
1393
|
+
if (!fs2.existsSync(file)) return { schemaVersion: "yichus-requirements-1", description: null, answers: [] };
|
|
1394
|
+
const parsed = Requirements.safeParse(JSON.parse(fs2.readFileSync(file, "utf8")));
|
|
1395
|
+
if (!parsed.success) throw new Error(`${file} is not a yichus-requirements-1 file: ${parsed.error.issues[0]?.message ?? "invalid"}`);
|
|
1396
|
+
return parsed.data;
|
|
1397
|
+
}
|
|
1398
|
+
function saveRequirements(root, requirements) {
|
|
1399
|
+
ensureStudioDir(root);
|
|
1400
|
+
fs2.writeFileSync(requirementsPath(root), `${JSON.stringify(Requirements.parse(requirements), null, 2)}
|
|
1401
|
+
`);
|
|
1402
|
+
}
|
|
1403
|
+
function withNames(requirements, names) {
|
|
1404
|
+
return { ...requirements, names: { ...requirements.names, ...names } };
|
|
1405
|
+
}
|
|
1406
|
+
function withScenarios(requirements, scenarios, drop = []) {
|
|
1407
|
+
const replaced = /* @__PURE__ */ new Set([...scenarios.map((s) => s.entry), ...drop]);
|
|
1408
|
+
return { ...requirements, scenarios: [...(requirements.scenarios ?? []).filter((s) => !replaced.has(s.entry)), ...scenarios] };
|
|
1409
|
+
}
|
|
1410
|
+
function withAnswer(requirements, answer) {
|
|
1411
|
+
return { ...requirements, answers: [...requirements.answers.filter((a) => a.question !== answer.question), answer] };
|
|
1412
|
+
}
|
|
1413
|
+
function ensureStudioDir(root) {
|
|
1414
|
+
const dir = studioDir(root);
|
|
1415
|
+
fs2.mkdirSync(dir, { recursive: true });
|
|
1416
|
+
const ignore = path2.join(dir, ".gitignore");
|
|
1417
|
+
const before = fs2.existsSync(ignore) ? fs2.readFileSync(ignore, "utf8") : "";
|
|
1418
|
+
const kept = new Set(before.split("\n").map((line) => line.trim()));
|
|
1419
|
+
const missing = ["state.json", "marks.json", "viewing.json", "pages/"].filter((name) => !kept.has(name));
|
|
1420
|
+
if (missing.length) fs2.appendFileSync(ignore, `${before && !before.endsWith("\n") ? "\n" : ""}${missing.map((line) => `${line}
|
|
1421
|
+
`).join("")}`);
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// src/studio/scenarios.ts
|
|
1425
|
+
import { z as z5 } from "zod";
|
|
1426
|
+
var Effect = z5.looseObject({ op: z5.string(), tables: z5.array(z5.string()).default([]) });
|
|
1427
|
+
var Claim = z5.looseObject({
|
|
1428
|
+
verdict: z5.string(),
|
|
1429
|
+
parsed: z5.string(),
|
|
1430
|
+
at: z5.string(),
|
|
1431
|
+
property: z5.looseObject({ is: z5.string(), subject: z5.string().optional() }).optional()
|
|
1432
|
+
});
|
|
1433
|
+
var Leaf = z5.looseObject({ kind: z5.literal("leaf"), id: z5.string(), words: z5.string().nullable(), outcome: z5.unknown(), claims: z5.array(Claim).default([]) });
|
|
1434
|
+
var Tree = z5.lazy(() => z5.union([Leaf, z5.looseObject({
|
|
1435
|
+
kind: z5.literal("node"),
|
|
1436
|
+
id: z5.string(),
|
|
1437
|
+
test: z5.string(),
|
|
1438
|
+
words: z5.string().nullable(),
|
|
1439
|
+
arms: z5.array(z5.looseObject({ id: z5.string(), pattern: z5.string(), words: z5.string().nullable(), effects: z5.array(Effect).default([]), next: Tree }))
|
|
1440
|
+
})]));
|
|
1441
|
+
var Entry2 = z5.looseObject({
|
|
1442
|
+
entry: z5.string(),
|
|
1443
|
+
title: z5.string().nullable(),
|
|
1444
|
+
described: z5.boolean(),
|
|
1445
|
+
effects: z5.array(Effect).default([]),
|
|
1446
|
+
tree: Tree.nullable(),
|
|
1447
|
+
unsupported: z5.string().nullable()
|
|
1448
|
+
});
|
|
1449
|
+
var Checked = z5.looseObject({ entry: z5.string(), at: z5.string(), claim: z5.string(), parsed: z5.string(), verdict: z5.string() });
|
|
1450
|
+
var Refused = z5.looseObject({ entry: z5.string(), id: z5.string(), words: z5.string(), reason: z5.string() });
|
|
1451
|
+
var WhatHappens = z5.looseObject({
|
|
1452
|
+
entries: z5.array(Entry2),
|
|
1453
|
+
claims: z5.array(Checked),
|
|
1454
|
+
refused: z5.array(Refused),
|
|
1455
|
+
/** Expectations that are not claims in the grammar, so nothing checks them. */
|
|
1456
|
+
notes: z5.array(z5.looseObject({ entry: z5.string(), at: z5.string(), text: z5.string() })),
|
|
1457
|
+
mismatches: z5.array(z5.looseObject({ entry: z5.string(), reason: z5.string() }))
|
|
1458
|
+
});
|
|
1459
|
+
var effectsText = (effects) => effects.length ? `; effects: ${effects.map(stationLabel).join(", ")}` : "";
|
|
1460
|
+
function walk2(tree, visit) {
|
|
1461
|
+
if (!tree) return;
|
|
1462
|
+
if (tree.kind === "leaf") {
|
|
1463
|
+
visit(tree.id, `outcome: ${outcomeLabel(tree.outcome)}`, tree.words, true, tree.claims.length);
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
visit(tree.id, `the program checks ${tree.test}`, tree.words, false, 0);
|
|
1467
|
+
for (const arm of tree.arms) {
|
|
1468
|
+
if (arm.next.id !== arm.id) visit(arm.id, `when ${arm.pattern}${effectsText(arm.effects)}`, arm.words, false, 0);
|
|
1469
|
+
else if (arm.next.kind === "leaf") {
|
|
1470
|
+
const leaf = arm.next;
|
|
1471
|
+
visit(leaf.id, `when ${arm.pattern}${effectsText(arm.effects)}, outcome: ${outcomeLabel(leaf.outcome)}`, leaf.words ?? arm.words, true, leaf.claims.length);
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
1474
|
+
walk2(arm.next, visit);
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
function owed(record) {
|
|
1478
|
+
return record.entries.map((e) => {
|
|
1479
|
+
const unnamed = [], uncovered = [];
|
|
1480
|
+
walk2(e.tree, (id, what, words, leaf, claims) => {
|
|
1481
|
+
if (!words) unnamed.push({ id, what });
|
|
1482
|
+
if (leaf && !claims) uncovered.push(id);
|
|
1483
|
+
});
|
|
1484
|
+
return { entry: e.entry, undescribed: !e.described, unnamed, uncovered };
|
|
1485
|
+
}).filter((o) => o.undescribed || o.unnamed.length || o.uncovered.length);
|
|
1486
|
+
}
|
|
1487
|
+
function replies(record) {
|
|
1488
|
+
const found = /* @__PURE__ */ new Set();
|
|
1489
|
+
const visit = (tree) => {
|
|
1490
|
+
if (!tree) return;
|
|
1491
|
+
if (tree.kind === "leaf") {
|
|
1492
|
+
for (const c of tree.claims) if (c.property?.is === "returns" && c.property.subject) found.add(c.property.subject);
|
|
1493
|
+
return;
|
|
1494
|
+
}
|
|
1495
|
+
for (const arm of tree.arms) visit(arm.next);
|
|
1496
|
+
};
|
|
1497
|
+
for (const e of record.entries) visit(e.tree);
|
|
1498
|
+
return [...found].sort();
|
|
1499
|
+
}
|
|
1500
|
+
function unfollowed(record) {
|
|
1501
|
+
return record.entries.filter((e) => !e.tree).map((e) => ({
|
|
1502
|
+
entry: e.entry,
|
|
1503
|
+
why: e.unsupported ?? "the engine gave no reason"
|
|
1504
|
+
}));
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
// src/studio/surface.ts
|
|
1508
|
+
var MCP = {
|
|
1509
|
+
surface: "mcp",
|
|
1510
|
+
name: (tool) => tool,
|
|
1511
|
+
use: (tool) => `call ${tool}`,
|
|
1512
|
+
useWith: (tool, input) => `call ${tool} with ${input}`,
|
|
1513
|
+
reference: (topic) => `call yichus_reference with topic "${topic}"`,
|
|
1514
|
+
api: (tool, args) => {
|
|
1515
|
+
const given = Object.entries(args ?? {}).map(([key, value]) => `${key} ${JSON.stringify(value)}`);
|
|
1516
|
+
return `call ${tool}${given.length ? ` with ${given.join(" and ")}` : ""}`;
|
|
1517
|
+
}
|
|
1518
|
+
};
|
|
1519
|
+
var COMMAND = {
|
|
1520
|
+
yichus_start: 'yichus start "DESCRIPTION"',
|
|
1521
|
+
yichus_next: "yichus next",
|
|
1522
|
+
yichus_name: 'yichus name CODE "NAME" [CODE "NAME" ...]',
|
|
1523
|
+
yichus_answer: 'yichus answer QUESTION CHOICE --words "THEIR WORDS"',
|
|
1524
|
+
yichus_rules: "yichus rules FILE.json",
|
|
1525
|
+
yichus_scenario: "yichus scenario FILE.json",
|
|
1526
|
+
yichus_point: "yichus point FILE.json",
|
|
1527
|
+
yichus_page: "yichus page"
|
|
1528
|
+
};
|
|
1529
|
+
var CLI = {
|
|
1530
|
+
surface: "cli",
|
|
1531
|
+
name: (tool) => `\`${COMMAND[tool].split(" ").slice(0, 2).join(" ")}\``,
|
|
1532
|
+
use: (tool) => `run \`${COMMAND[tool]}\``,
|
|
1533
|
+
// A command that takes input reads it from the FILE.json it names.
|
|
1534
|
+
useWith: (tool, input) => `run \`${COMMAND[tool]}\` with FILE.json holding ${input}`,
|
|
1535
|
+
reference: (topic) => `run \`yichus reference ${topic}\``,
|
|
1536
|
+
api: (tool, args) => {
|
|
1537
|
+
const select = tool === "api_guide" && args?.section !== void 0 ? " --select /sections/0/body" : "";
|
|
1538
|
+
if (!args || !Object.keys(args).length) return `run \`yichus call ${tool}${select}\``;
|
|
1539
|
+
return `run \`yichus call ${tool} --args ARGS.json${select}\` with ARGS.json holding ${JSON.stringify(args)}`;
|
|
1540
|
+
}
|
|
1541
|
+
};
|
|
1542
|
+
var CLI_LEGEND = [
|
|
1543
|
+
"On the command line, the tools this document names are commands:",
|
|
1544
|
+
...Object.entries(COMMAND).map(([tool, command]) => ` ${tool}: ${command}`),
|
|
1545
|
+
" yichus_reference: yichus reference TOPIC",
|
|
1546
|
+
" api_* (an engine tool): yichus call TOOL [--args ARGS.json]; a tool that requires sources reads every .bosatsu file in the project folder (--project DIR, default the current folder), so you never pass them"
|
|
1547
|
+
].join("\n");
|
|
1548
|
+
|
|
1549
|
+
// src/studio/director.ts
|
|
1550
|
+
var VerifyProperty = z6.looseObject({
|
|
1551
|
+
id: z6.string(),
|
|
1552
|
+
title: z6.string(),
|
|
1553
|
+
status: z6.string(),
|
|
1554
|
+
details: z6.array(z6.string()).default([]),
|
|
1555
|
+
accepted: z6.unknown().optional()
|
|
1556
|
+
});
|
|
1557
|
+
var Verify = z6.looseObject({
|
|
1558
|
+
topology: z6.string().optional(),
|
|
1559
|
+
verdict: z6.looseObject({ proven: z6.boolean(), properties: z6.array(VerifyProperty) })
|
|
1560
|
+
});
|
|
1561
|
+
var Protocol = z6.looseObject({ protocol: z6.looseObject({ status: z6.string(), name: z6.string().optional() }).optional(), error: z6.string().optional() });
|
|
1562
|
+
var LawRow = z6.looseObject({
|
|
1563
|
+
binding: z6.string(),
|
|
1564
|
+
law: z6.string().nullable().optional(),
|
|
1565
|
+
verdict: z6.string(),
|
|
1566
|
+
complete: z6.boolean().optional(),
|
|
1567
|
+
scope: z6.looseObject({ kind: z6.string() }).optional(),
|
|
1568
|
+
detail: z6.string().optional(),
|
|
1569
|
+
reason: z6.string().optional(),
|
|
1570
|
+
counterexample: z6.string().optional()
|
|
1571
|
+
});
|
|
1572
|
+
var LawCheck = z6.looseObject({
|
|
1573
|
+
laws: z6.looseObject({ obligations: z6.array(LawRow) }).optional(),
|
|
1574
|
+
notSampled: z6.array(z6.looseObject({ binding: z6.string() })).optional(),
|
|
1575
|
+
reach: z6.array(z6.looseObject({ binding: z6.string(), usedBy: z6.array(z6.string()) })).optional()
|
|
1576
|
+
});
|
|
1577
|
+
var caseFile = (root, questionId) => path3.join(studioDir(root), "cases", `${questionId.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "")}.json`);
|
|
1578
|
+
var answerOf = (requirements, id) => requirements.answers.find((a) => a.question === id) ?? null;
|
|
1579
|
+
function instancesFor(requirements) {
|
|
1580
|
+
const choice = answerOf(requirements, "topology")?.choice;
|
|
1581
|
+
return choice === "one" ? "1" : choice === "many" ? "many" : void 0;
|
|
1582
|
+
}
|
|
1583
|
+
async function call(engine, tool, args) {
|
|
1584
|
+
const result = await engine.call(tool, args);
|
|
1585
|
+
if (result.ok !== true) throw new Error(`${tool} failed: ${typeof result.error === "string" ? result.error : "no reason given"}`);
|
|
1586
|
+
return result;
|
|
1587
|
+
}
|
|
1588
|
+
var isAccepted = (p) => p.status === "warning" && p.accepted !== void 0;
|
|
1589
|
+
var raceCell = (detail) => /^race-free:([^:\s]+):/.exec(detail)?.[1] ?? null;
|
|
1590
|
+
var worst = (props) => props.find((p) => p.status !== "proven" && !isAccepted(p)) ?? props.find(isAccepted);
|
|
1591
|
+
async function judge(root, engine, sources, question, saved, report, verify, together = /* @__PURE__ */ new Set()) {
|
|
1592
|
+
const answer = saved && question.choices.some((c) => c.id === saved.choice) ? saved : null;
|
|
1593
|
+
const base = { question, answer, evidence: [], check: null };
|
|
1594
|
+
if (!answer) return { ...base, status: "unanswered" };
|
|
1595
|
+
const byId = (id) => verify.find((p) => p.id === id);
|
|
1596
|
+
switch (question.kind) {
|
|
1597
|
+
case "platform":
|
|
1598
|
+
case "host":
|
|
1599
|
+
case "sign-in":
|
|
1600
|
+
case "data":
|
|
1601
|
+
return { ...base, status: "decided" };
|
|
1602
|
+
case "topology":
|
|
1603
|
+
return {
|
|
1604
|
+
...base,
|
|
1605
|
+
status: answer.choice === "one" ? "assumed" : "decided",
|
|
1606
|
+
evidence: answer.choice === "one" ? ["Every check below assumes exactly one copy of the server runs."] : []
|
|
1607
|
+
};
|
|
1608
|
+
case "access": {
|
|
1609
|
+
const table = report.dataModel.tables.find((t) => t.name === question.subject);
|
|
1610
|
+
const rule = ACCESS_RULES[answer.choice];
|
|
1611
|
+
const access = table?.access ?? null;
|
|
1612
|
+
const check = "api_report dataModel.tables[].access";
|
|
1613
|
+
if (!access || !rule.declared(access)) {
|
|
1614
|
+
return {
|
|
1615
|
+
...base,
|
|
1616
|
+
status: "mismatch",
|
|
1617
|
+
check,
|
|
1618
|
+
evidence: [`"${question.subject}" is declared ${table?.policy ?? "with no rule"}; the person chose ${rule.write}.`]
|
|
1619
|
+
};
|
|
1620
|
+
}
|
|
1621
|
+
const personal = answer.choice === "server-only" ? report.surface.routes.filter((r) => r.tables.includes(question.subject) && r.authority !== "requires-worker") : [];
|
|
1622
|
+
if (personal.length) {
|
|
1623
|
+
return {
|
|
1624
|
+
...base,
|
|
1625
|
+
status: "mismatch",
|
|
1626
|
+
check: "api_report surface.routes[].authority",
|
|
1627
|
+
evidence: personal.map((r) => `${r.path} reaches "${question.subject}" and is called ${r.authority === "requires-roles" ? "by a person with a role" : "by a person"}, not by the app's own server.`)
|
|
1628
|
+
};
|
|
1629
|
+
}
|
|
1630
|
+
const prop = byId(`access:${question.subject}`) ?? byId("access-coverage");
|
|
1631
|
+
if (!prop) return { ...base, status: "inconclusive", check: "api_verify", evidence: ["api_verify reported no access property for this table."] };
|
|
1632
|
+
return {
|
|
1633
|
+
...base,
|
|
1634
|
+
check: `api_verify ${prop.id}`,
|
|
1635
|
+
evidence: prop.details,
|
|
1636
|
+
status: prop.status === "proven" ? "proven" : "broken"
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
case "together": {
|
|
1640
|
+
const elsewhere = (p) => p.details.length > 0 && p.details.every((d) => {
|
|
1641
|
+
const cell = raceCell(d);
|
|
1642
|
+
return cell !== null && cell !== question.subject && together.has(cell);
|
|
1643
|
+
});
|
|
1644
|
+
const props = verify.filter((p) => (p.id === "rmw-transactions" || p.id === "integrity") && !elsewhere(p));
|
|
1645
|
+
const bad = worst(props);
|
|
1646
|
+
const mentions = (p) => p.details.filter((d) => d.includes(`"${question.subject}"`) || raceCell(d) === question.subject);
|
|
1647
|
+
const evidence = props.flatMap((p) => mentions(p).length ? mentions(p) : p.status === "proven" ? [] : p.details);
|
|
1648
|
+
const check = `api_verify ${props.map((p) => p.id).join(" + ")}`;
|
|
1649
|
+
if (!bad) return { ...base, check, evidence, status: props.length ? "proven" : "inconclusive" };
|
|
1650
|
+
return { ...base, check, evidence, status: isAccepted(bad) ? "assumed" : "broken" };
|
|
1651
|
+
}
|
|
1652
|
+
case "partial":
|
|
1653
|
+
case "outside": {
|
|
1654
|
+
if (answer.choice === "partial-ok" || answer.choice === "no-plan") return { ...base, status: "no-check" };
|
|
1655
|
+
const file = caseFile(root, question.id);
|
|
1656
|
+
const rel = path3.relative(root, file).split(path3.sep).join("/");
|
|
1657
|
+
if (!fs3.existsSync(file)) return { ...base, casePath: rel, status: "needs-case", check: "api_protocol_check", evidence: [`No protocol case at ${rel} yet.`] };
|
|
1658
|
+
let protocolCase;
|
|
1659
|
+
try {
|
|
1660
|
+
protocolCase = JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
1661
|
+
} catch (error) {
|
|
1662
|
+
return {
|
|
1663
|
+
...base,
|
|
1664
|
+
casePath: rel,
|
|
1665
|
+
check: "api_protocol_check",
|
|
1666
|
+
status: "inconclusive",
|
|
1667
|
+
evidence: [`${rel} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]
|
|
1668
|
+
};
|
|
1669
|
+
}
|
|
1670
|
+
const result = Protocol.parse(await engine.call("api_protocol_check", { sources: [...sources, ...caseSources(root)], case: protocolCase }));
|
|
1671
|
+
const status = result.protocol?.status;
|
|
1672
|
+
const check = `api_protocol_check ${rel}`;
|
|
1673
|
+
if (!status) return { ...base, casePath: rel, check, status: "inconclusive", evidence: [result.error ?? "The protocol check gave no status."] };
|
|
1674
|
+
return {
|
|
1675
|
+
...base,
|
|
1676
|
+
casePath: rel,
|
|
1677
|
+
check,
|
|
1678
|
+
evidence: [`${result.protocol?.name ?? rel}: ${status}`],
|
|
1679
|
+
status: status === "holds" ? "bounded" : status === "violated" ? "broken" : "inconclusive"
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
var reason = (result) => typeof result.error === "string" ? result.error : "no reason given";
|
|
1685
|
+
async function checkLaws(engine, sources) {
|
|
1686
|
+
const answer = async (mode) => {
|
|
1687
|
+
const result = await engine.call("api_law_check", { sources, ...mode === "exhaustive" ? { mode } : {} });
|
|
1688
|
+
if (result.ok !== true) return { answer: { kind: "refused", reason: reason(result) }, finite: [] };
|
|
1689
|
+
const parsed = LawCheck.parse(result);
|
|
1690
|
+
const reach2 = parsed.reach ? new Map(parsed.reach.map((r) => [r.binding, r.usedBy])) : null;
|
|
1691
|
+
return { answer: { kind: "rows", rows: parsed.laws?.obligations ?? [], reach: reach2 }, finite: (parsed.notSampled ?? []).map((n) => n.binding) };
|
|
1692
|
+
};
|
|
1693
|
+
const sampled = await answer("sampled");
|
|
1694
|
+
if (sampled.answer.kind === "rows" && !sampled.answer.rows.length && !sampled.finite.length) return { laws: [], error: null };
|
|
1695
|
+
const { answer: exhaustive } = await answer("exhaustive");
|
|
1696
|
+
if (sampled.answer.kind === "refused" && exhaustive.kind === "refused")
|
|
1697
|
+
return { laws: [], error: `api_law_check failed: ${sampled.answer.reason}; exhaustive: ${exhaustive.reason}` };
|
|
1698
|
+
const rowsOf = (a) => a.kind === "rows" ? a.rows : [];
|
|
1699
|
+
const reach = [sampled.answer, exhaustive].flatMap((a) => a.kind === "rows" && a.reach ? [a.reach] : [])[0] ?? null;
|
|
1700
|
+
const bindings = [.../* @__PURE__ */ new Set([...rowsOf(sampled.answer).map((r) => r.binding), ...sampled.finite, ...rowsOf(exhaustive).map((r) => r.binding)])];
|
|
1701
|
+
return { error: null, laws: bindings.map((binding) => {
|
|
1702
|
+
const s = rowsOf(sampled.answer).find((r) => r.binding === binding);
|
|
1703
|
+
const e = rowsOf(exhaustive).find((r) => r.binding === binding);
|
|
1704
|
+
const listed = e?.scope !== void 0 && e.scope.kind !== "type-wide";
|
|
1705
|
+
const said2 = (mode, r) => `${mode}: ${r.verdict}${r.detail ? `; ${r.detail}` : ""}${r.reason ? `; ${r.reason}` : ""}${r.counterexample ? `; counterexample ${r.counterexample}` : ""}`;
|
|
1706
|
+
const evidence = [
|
|
1707
|
+
...s ? [said2("sampled", s)] : [],
|
|
1708
|
+
...!s && sampled.answer.kind === "refused" ? [`sampled: refused; ${sampled.answer.reason}`] : [],
|
|
1709
|
+
...!s && sampled.finite.includes(binding) ? ["sampled: left to the check over its listed inputs"] : [],
|
|
1710
|
+
...!e && exhaustive.kind === "refused" ? [`every input: refused; ${exhaustive.reason}`] : [],
|
|
1711
|
+
...e ? [said2(listed ? "only the listed inputs" : "every input", e)] : []
|
|
1712
|
+
];
|
|
1713
|
+
const name = s?.law ?? e?.law ?? null;
|
|
1714
|
+
const usedBy = reach?.get(binding) ?? null;
|
|
1715
|
+
if (usedBy && !usedBy.length) evidence.push("used by: no action of the app reaches what its check calls");
|
|
1716
|
+
const status = s?.verdict === "violated" || e?.verdict === "violated" ? "broken" : e?.verdict === "holds-exhaustive" ? e.complete && e.scope?.kind === "type-wide" ? "proven" : "bounded" : s?.verdict === "holds" ? "bounded" : "inconclusive";
|
|
1717
|
+
return { binding, name, status, usedBy, evidence };
|
|
1718
|
+
}) };
|
|
1719
|
+
}
|
|
1720
|
+
var lawNamed = (laws, ref) => laws.find((l) => l.binding === ref || l.binding.endsWith(`::${ref}`) || l.name === ref);
|
|
1721
|
+
var unused = (law) => law.usedBy !== null && !law.usedBy.length;
|
|
1722
|
+
function judgeRule(rule, laws) {
|
|
1723
|
+
const found = rule.laws.map((ref) => [ref, lawNamed(laws, ref)]);
|
|
1724
|
+
const missing = found.filter(([, law]) => !law).map(([ref]) => ref);
|
|
1725
|
+
const checked = found.flatMap(([, law]) => law ? [law] : []);
|
|
1726
|
+
const evidence = [...missing.map((ref) => `No law named ${ref} in the program.`), ...checked.flatMap((l) => l.evidence.map((e) => `${l.name ?? l.binding}: ${e}`))];
|
|
1727
|
+
const status = missing.length || !checked.length ? "needs-law" : checked.some((l) => l.status === "broken") ? "broken" : checked.some((l) => l.status === "inconclusive") ? "inconclusive" : checked.some(unused) ? "unused" : checked.every((l) => l.status === "proven") ? "proven" : "bounded";
|
|
1728
|
+
return { ...rule, status, evidence };
|
|
1729
|
+
}
|
|
1730
|
+
var USE_THE_LAW = "If the function the law checks is in the program, make the action the rule is about decide with it. If it is defined next to the law, move it into the program, have the law check it there, and make the action decide with it. Never weaken what the law says.";
|
|
1731
|
+
var QUESTION_PROPERTIES = (id) => id.startsWith("access:") || id === "access-coverage" || id === "rmw-transactions" || id === "integrity";
|
|
1732
|
+
var GUIDE = {
|
|
1733
|
+
access: "Owner-scoped data",
|
|
1734
|
+
together: "Atomic commands with Yichus/Transaction",
|
|
1735
|
+
partial: "Transaction protocols: finite cases, retries, and receipts",
|
|
1736
|
+
outside: "Transaction protocols: finite cases, retries, and receipts"
|
|
1737
|
+
};
|
|
1738
|
+
var SCAFFOLD_ARGS = {
|
|
1739
|
+
package_name: "My/App/Api",
|
|
1740
|
+
service_name: "my_app",
|
|
1741
|
+
resources: [{ name: "record", fields: [{ name: "title", type: "String" }], policy: "owner" }]
|
|
1742
|
+
};
|
|
1743
|
+
var plural3 = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
1744
|
+
var capital = (s) => `${s[0].toUpperCase()}${s.slice(1)}`;
|
|
1745
|
+
var askStep = (open, say2) => ({
|
|
1746
|
+
stage: "ask",
|
|
1747
|
+
summary: `${plural3(open.length, "question", "questions")} for you about how the app should behave.`,
|
|
1748
|
+
instructions: [
|
|
1749
|
+
"Ask the person each question below, in its words, with its choices. They may also answer on the studio page.",
|
|
1750
|
+
"Speak in product terms: never quote question ids, code names, file names, tool names or the programming language to the person.",
|
|
1751
|
+
'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.',
|
|
1752
|
+
`Record each answer: ${say2.use("yichus_answer")} with the question id, the choice id, and their own words. Then ${say2.use("yichus_next")}.`
|
|
1753
|
+
],
|
|
1754
|
+
ask: open.map((p) => ({ id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices }))
|
|
1755
|
+
});
|
|
1756
|
+
function deploySections(state) {
|
|
1757
|
+
const choice = (kind) => state.properties.find((p) => p.question.kind === kind)?.answer?.choice;
|
|
1758
|
+
const where = choice("platform");
|
|
1759
|
+
if (!where) return [];
|
|
1760
|
+
const host = choice("host");
|
|
1761
|
+
return host ? [PLATFORM_SECTION[where], HOST_SECTION[host]] : [PLATFORM_SECTION[where]];
|
|
1762
|
+
}
|
|
1763
|
+
var sectionsText = (sections) => sections.map((s) => `"${s}"`).join(" and ");
|
|
1764
|
+
function nextStep(state, compileErrors, say2 = MCP) {
|
|
1765
|
+
const next = `Then ${say2.use("yichus_next")}.`;
|
|
1766
|
+
if (!state.description) return {
|
|
1767
|
+
stage: "describe",
|
|
1768
|
+
summary: "Waiting for a description of what to build.",
|
|
1769
|
+
instructions: [`Ask the person what they want to build, in their own words. ${capital(say2.use("yichus_start"))} with their description, unchanged.`]
|
|
1770
|
+
};
|
|
1771
|
+
const sections = deploySections(state);
|
|
1772
|
+
if (!state.files.length) return {
|
|
1773
|
+
stage: "write",
|
|
1774
|
+
summary: "No program yet.",
|
|
1775
|
+
instructions: [
|
|
1776
|
+
`If this replaces an app the person already has, ${say2.reference("porting")} first: reading the old app is yours, and the studio sees only the new one. Keep the new program in this folder, apart from the old app's code.`,
|
|
1777
|
+
"Build only what the person asked for. A calculation that keeps no records needs no server, database or sign-in: write it as pure functions, with a law for each rule about its numbers.",
|
|
1778
|
+
`An app that keeps records runs as a server. The program is the same wherever it runs, so build it first; the studio asks the person where it runs once the program has records or actions, and ${say2.reference("deploy")} then says how to put it online.`,
|
|
1779
|
+
`${capital(say2.api("api_guide", { section: "Required workflow" }))}, then write the program as .bosatsu files in this project folder.`,
|
|
1780
|
+
`For an app that stores records, ${say2.api("api_scaffold", SCAFFOLD_ARGS)} first and save its module as a file here. Each resource's policy is owner or public. You never need to pass sources: the studio reads every .bosatsu file in the folder.`,
|
|
1781
|
+
`Shape the records to the people in the description before you show anything. The scaffold's owner and public records are only a start.`,
|
|
1782
|
+
"Its creator decides everything in a record they own. So a decision someone else makes about it (a manager approving a claim, a coordinator confirming a sign-up) goes in records of its own that only that role may change. Otherwise the creator can make the decision themselves.",
|
|
1783
|
+
`Records other people must see (a coordinator who sees every sign-up) need a rule that lets them in, not owner-only. ${capital(say2.api("api_guide", { section: "Guarded data" }))} for how to write one with roles.`,
|
|
1784
|
+
`A limit across many people's records ("each shift has 10 spots") needs one record that holds the count. Change it in the same transaction as the sign-up. Then the studio asks what happens when two people take the last spot.`,
|
|
1785
|
+
`Put every decision the app makes in pure functions, and keep the code that reads, writes and calls out free of business rules. When work takes several steps or waits on an outside service (a model, a web page, a payment), write it as one pure step program that a rule-free engine drives: ${say2.reference("portable-programs")} before writing it.`,
|
|
1786
|
+
`Write each rule the person states about what the app must always or never do as a law: ${say2.reference("laws")} for the syntax, the standard functions and a worked example.`,
|
|
1787
|
+
"A law checks the pure function it calls. So the action the rule is about must decide by calling that same function. A law over a helper no action uses passes while the app ignores the rule.",
|
|
1788
|
+
next
|
|
1789
|
+
]
|
|
1790
|
+
};
|
|
1791
|
+
if (compileErrors) return {
|
|
1792
|
+
stage: "fix-compile",
|
|
1793
|
+
summary: "The program does not compile yet.",
|
|
1794
|
+
instructions: [`Fix these compile errors in the files. ${next}`, `For the standard functions the language has, ${say2.reference("laws")}.`],
|
|
1795
|
+
evidence: compileErrors
|
|
1796
|
+
};
|
|
1797
|
+
if (!state.rulesListed) return {
|
|
1798
|
+
stage: "rules",
|
|
1799
|
+
summary: "Your agent is writing down the rules you gave for your app, so each one is checked.",
|
|
1800
|
+
instructions: [
|
|
1801
|
+
`Read the person's description and answers again. List every rule they stated about what the app must always or never do, in their words (for example "a fan who opts out stays opted out").`,
|
|
1802
|
+
`Write a law for each rule in a .bosatsu file of the app (${say2.reference("laws")} for the syntax, the standard functions and a worked example). A law states the rule, never what the code happens to do.`,
|
|
1803
|
+
`${capital(say2.use("yichus_next"))} so the studio finds the laws you wrote, then record the rules with the laws that check each: ${say2.useWith("yichus_rules", '{"rules": [{"rule": their words, "laws": [law names]}]}')}. If they stated no rule, record an empty list.`,
|
|
1804
|
+
"A rule no law can state (for example one about what a page shows) is not checked: tell the person so, and leave it out.",
|
|
1805
|
+
next
|
|
1806
|
+
],
|
|
1807
|
+
...state.laws.length ? { items: { heading: "Laws the program has", lines: state.laws.map((l) => `${l.binding}${l.name ? ` ("${l.name}")` : ""}: ${l.status}`) } } : {}
|
|
1808
|
+
};
|
|
1809
|
+
const unnamed = /* @__PURE__ */ new Map();
|
|
1810
|
+
for (const { question } of state.properties) {
|
|
1811
|
+
if (question.subject !== null && !(question.subject in state.names)) unnamed.set(question.subject, [...unnamed.get(question.subject) ?? [], question.fact]);
|
|
1812
|
+
}
|
|
1813
|
+
for (const { code, what } of drawnParts(state)) {
|
|
1814
|
+
if (!(code in state.names) && !unnamed.has(code)) unnamed.set(code, [`${capital(what)}.`]);
|
|
1815
|
+
}
|
|
1816
|
+
if (unnamed.size) return {
|
|
1817
|
+
stage: "name",
|
|
1818
|
+
summary: "Your agent is putting the parts of your app into plain words.",
|
|
1819
|
+
instructions: [
|
|
1820
|
+
`The person sees the parts of the program below in questions and in the pictures 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").`,
|
|
1821
|
+
`${capital(say2.use("yichus_name"))} with all of them at once. ${next}`
|
|
1822
|
+
],
|
|
1823
|
+
items: { heading: "Parts to name", lines: [...unnamed].map(([subject, facts]) => `${subject}: ${facts.join(" ")}`) }
|
|
1824
|
+
};
|
|
1825
|
+
const unanswered = state.properties.filter((p) => p.status === "unanswered");
|
|
1826
|
+
if (unanswered.length) return askStep(unanswered, say2);
|
|
1827
|
+
const mismatched = state.properties.filter((p) => p.status === "mismatch");
|
|
1828
|
+
if (mismatched.length) return {
|
|
1829
|
+
stage: "declare",
|
|
1830
|
+
summary: "The program's declared rules do not match what you chose yet.",
|
|
1831
|
+
instructions: [
|
|
1832
|
+
...mismatched.map((p) => {
|
|
1833
|
+
const rule = ACCESS_RULES[p.answer.choice];
|
|
1834
|
+
return `Make the AccessSpec rule for "${p.question.subject}" ${rule.write}${p.answer.choice === "server-only" ? ", and reach it only from worker routes" : ""} (${say2.api("api_add_rule")} for the snippet; ${say2.api("api_guide", { section: rule.guide })} for what it means).`;
|
|
1835
|
+
}),
|
|
1836
|
+
next
|
|
1837
|
+
],
|
|
1838
|
+
evidence: mismatched.flatMap((p) => p.evidence)
|
|
1839
|
+
};
|
|
1840
|
+
const broken = state.properties.filter((p) => p.status === "broken" || p.status === "inconclusive");
|
|
1841
|
+
const failing = state.other.filter((o) => o.status !== "warning");
|
|
1842
|
+
const warnings = state.other.filter((o) => o.status === "warning");
|
|
1843
|
+
const brokenRules = state.rules.filter((r) => r.status !== "proven" && r.status !== "bounded");
|
|
1844
|
+
const ruled = new Set(state.rules.flatMap((r) => r.laws.flatMap((ref) => lawNamed(state.laws, ref)?.binding ?? [])));
|
|
1845
|
+
const brokenLaws = state.laws.filter((l) => !ruled.has(l.binding) && (l.status === "broken" || l.status === "inconclusive" || unused(l)));
|
|
1846
|
+
const notHolding = broken.length + failing.length + brokenRules.length + brokenLaws.length + (state.lawsError ? 1 : 0);
|
|
1847
|
+
if (notHolding || warnings.length) return {
|
|
1848
|
+
stage: "fix",
|
|
1849
|
+
summary: [
|
|
1850
|
+
notHolding ? `${notHolding === 1 ? "1 property is" : `${notHolding} properties are`} not holding yet.` : "",
|
|
1851
|
+
warnings.length ? `${plural3(warnings.length, "warning needs", "warnings need")} a look.` : ""
|
|
1852
|
+
].filter(Boolean).join(" "),
|
|
1853
|
+
instructions: [
|
|
1854
|
+
"Fix the program so each property below holds. The evidence lines are the engine's own words.",
|
|
1855
|
+
...broken.map((p) => `"${p.question.ask}" The person chose "${p.question.choices.find((c) => c.id === p.answer?.choice)?.label}".${GUIDE[p.question.kind] ? ` ${capital(say2.api("api_guide", { section: GUIDE[p.question.kind] }))} for how.` : ""}`),
|
|
1856
|
+
...failing.map((o) => `${o.title} (${o.id}) is ${o.status}.`),
|
|
1857
|
+
...warnings.map((o) => `${o.title} (${o.id}) is a warning, not a failure: read its evidence. Change the code if it shows something the person did not choose, such as a stored field an action gives away; otherwise tell the person what it means.`),
|
|
1858
|
+
...brokenRules.map((r) => r.status === "needs-law" ? `The person's rule "${r.rule}" has no law in the program that checks it. Write one (${say2.reference("laws")} for how), then record the rules again with ${say2.name("yichus_rules")}.` : r.status === "unused" ? `The person's rule "${r.rule}" is checked by a law whose check calls nothing any action of the app reaches, so the law says nothing about what the app's actions do. ${USE_THE_LAW}` : `The person's rule "${r.rule}" is ${r.status === "broken" ? "broken: a law that states it fails" : "not decided by its laws"}. Change the code, never the law.`),
|
|
1859
|
+
...brokenLaws.map((l) => `The law ${l.name ? `"${l.name}" (${l.binding})` : l.binding} ${l.status === "broken" ? "is broken. Change the code, never the law." : l.status === "inconclusive" ? "is not decided. Change the code, never the law." : `checks code no action of the app reaches. ${USE_THE_LAW}`}`),
|
|
1860
|
+
...state.lawsError ? ["The engine could not check the program's laws, so no rule the person stated is checked. If the error below points at the program, fix the program; otherwise tell the person their rules are not checked yet."] : [],
|
|
1861
|
+
`Never weaken a rule, delete a check, a law or a claim, or declare one server to make a check pass: change the code. ${next}`
|
|
1862
|
+
],
|
|
1863
|
+
evidence: [
|
|
1864
|
+
...broken.flatMap((p) => p.evidence),
|
|
1865
|
+
...state.other.flatMap((o) => o.details),
|
|
1866
|
+
...brokenRules.flatMap((r) => r.evidence),
|
|
1867
|
+
...brokenLaws.flatMap((l) => l.evidence),
|
|
1868
|
+
...state.lawsError ? [state.lawsError] : []
|
|
1869
|
+
]
|
|
1870
|
+
};
|
|
1871
|
+
const scenarios = state.whatHappens;
|
|
1872
|
+
const owes = scenarios ? owed(scenarios) : [];
|
|
1873
|
+
if (scenarios && (owes.length || scenarios.refused.length || scenarios.notes.length || scenarios.mismatches.length)) return {
|
|
1874
|
+
stage: "scenarios",
|
|
1875
|
+
summary: "Your agent is writing down, in your words, what should happen in each thing your app does.",
|
|
1876
|
+
instructions: [
|
|
1877
|
+
`Write down what should happen in each action listed below, as the person would say it, and ${say2.use("yichus_scenario")} with all of them at once. For each action give:`,
|
|
1878
|
+
'title: what the person does ("You add a note").',
|
|
1879
|
+
'names: for every id listed under the action, a few words the person would use: the question the app asks itself ("are you signed in?"), each answer, and each outcome ("your note is saved").',
|
|
1880
|
+
'expect: for every outcome, what must and must not happen there, each {"at": an id, "claim": a claim}. A claim is [not] reads TABLE, writes TABLE, refused, returns CONSTRUCTOR, reaches model or reaches net; a claim at an id covers every outcome under it.',
|
|
1881
|
+
"State what the person wants, from their description and answers, never what the code happens to do. Where you cannot tell, ask the person in product terms.",
|
|
1882
|
+
...scenarios.notes.length ? ["Some expectations are not claims, so nothing checks them (the evidence lists them). Write each as a claim in the grammar above. If what the person expects cannot be said that way, tell them it will not be checked and leave it out."] : [],
|
|
1883
|
+
...scenarios.mismatches.length ? ["Some scenarios are for actions the app no longer has (the evidence lists them). If the person dropped the action, pass it in drop. If it was renamed or moved, describe the new action and drop the old one in the same call."] : [],
|
|
1884
|
+
next
|
|
1885
|
+
],
|
|
1886
|
+
...owes.length ? { items: { heading: "Actions to describe", lines: owes.flatMap((o) => [
|
|
1887
|
+
`${o.entry}${o.undescribed ? " (not described yet)" : ""}:`,
|
|
1888
|
+
...o.unnamed.map((u) => ` ${u.id}: ${u.what}`),
|
|
1889
|
+
...o.uncovered.length ? [` outcomes no claim covers: ${o.uncovered.join(", ")}`] : []
|
|
1890
|
+
]) } } : {},
|
|
1891
|
+
evidence: [
|
|
1892
|
+
...scenarios.refused.map((r) => `${r.entry}: "${r.words}" at ${r.id} was refused: ${r.reason}`),
|
|
1893
|
+
...scenarios.notes.map((n) => `${n.entry}: "${n.text}" at ${n.at} is not a claim`),
|
|
1894
|
+
...scenarios.mismatches.map((m) => `${m.entry}: ${m.reason}`)
|
|
1895
|
+
]
|
|
1896
|
+
};
|
|
1897
|
+
const claims = (scenarios?.claims ?? []).filter((c) => c.verdict !== "holds");
|
|
1898
|
+
const unfollowedEntries = scenarios ? unfollowed(scenarios) : [];
|
|
1899
|
+
const open = claims.length + (state.whatHappensError ? 1 : 0) + unfollowedEntries.length;
|
|
1900
|
+
if (open) return {
|
|
1901
|
+
stage: "fix",
|
|
1902
|
+
summary: `${open === 1 ? "1 property is" : `${open} properties are`} not holding yet.`,
|
|
1903
|
+
instructions: [
|
|
1904
|
+
"Fix the program so each property below holds. The evidence lines are the engine's own words.",
|
|
1905
|
+
...claims.map((c) => `${c.entry}: the person expects "${c.claim}" at ${c.at}, and the engine finds it ${c.verdict === "fails" ? "fails" : "cannot be decided"} there.`),
|
|
1906
|
+
...state.whatHappensError ? ["The engine could not follow each action through, so no scenario is checked. If the error below points at the program, fix the program. Otherwise tell the person their scenarios cannot be checked yet, and never tell them their choices hold."] : [],
|
|
1907
|
+
...unfollowedEntries.length ? ["The engine could not follow some actions through (the evidence says which and why), so nothing the person expects of them is checked. If the reason points at the program, such as an action with too many ways through, change the program so it can be followed. Otherwise tell the person those actions are not checked, and never tell them their choices hold."] : [],
|
|
1908
|
+
`Never weaken a rule, delete a check or a claim, or declare one server to make a check pass: change the code. If a claim misread what the person wants, ask them and correct the scenario. ${next}`
|
|
1909
|
+
],
|
|
1910
|
+
evidence: [
|
|
1911
|
+
...claims.map((c) => `${c.entry} at ${c.at}: ${c.parsed}: ${c.verdict}`),
|
|
1912
|
+
...state.whatHappensError ? [state.whatHappensError] : [],
|
|
1913
|
+
...unfollowedEntries.map((u) => `${u.entry} could not be followed: ${u.why}`)
|
|
1914
|
+
]
|
|
1915
|
+
};
|
|
1916
|
+
const cases = state.properties.filter((p) => p.status === "needs-case");
|
|
1917
|
+
if (cases.length) return {
|
|
1918
|
+
stage: "write-case",
|
|
1919
|
+
summary: "Writing the failure scenarios that test your answers.",
|
|
1920
|
+
instructions: [
|
|
1921
|
+
`${capital(say2.reference("protocol-case"))}: it gives the case specification and a complete worked case with its program.`,
|
|
1922
|
+
"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.",
|
|
1923
|
+
...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.`),
|
|
1924
|
+
`State the person's rule exactly; never weaken it to match the code. ${next}`
|
|
1925
|
+
]
|
|
1926
|
+
};
|
|
1927
|
+
const assumed = state.properties.filter((p) => p.status === "assumed");
|
|
1928
|
+
const data = state.properties.find((p) => p.question.kind === "data")?.answer?.choice;
|
|
1929
|
+
return {
|
|
1930
|
+
stage: "done",
|
|
1931
|
+
summary: assumed.length ? "Everything you chose holds, under the assumptions shown." : "Everything you chose holds.",
|
|
1932
|
+
instructions: [
|
|
1933
|
+
"Tell the person every property they chose holds, and point them at the studio page for the evidence.",
|
|
1934
|
+
...assumed.length ? ["Say plainly which results depend on running exactly one server."] : [],
|
|
1935
|
+
...data === "move" || data === "same-database" ? [`Before any record moves, list for the person every kind of record the old place keeps that this app does not (for example timestamps or a message log), and ask about each: add it to the app, or agree to leave it behind. ${capital(say2.reference("porting"))} says how to bring the data over.`] : [],
|
|
1936
|
+
`When they describe a new feature, change the code and ${say2.use("yichus_next")} again: new facts can raise new questions.`,
|
|
1937
|
+
sections.length ? `When they want the app online, follow the ${sectionsText(sections)} section${sections.length === 1 ? "" : "s"} of the deploy reference (${say2.reference("deploy")}), and ${say2.api("api_deploy")} to generate the server.` : `The program keeps no records and has no actions people call, so it needs no server. When they want it on a page, ${say2.reference("calculator")}.`
|
|
1938
|
+
]
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
function drawnParts(state) {
|
|
1942
|
+
return [
|
|
1943
|
+
...state.map ? nameableParts(state.map, ownPackages(state.layers)) : [],
|
|
1944
|
+
...(state.whatHappens ? replies(state.whatHappens) : []).map((code) => ({ code, what: "an answer the app gives" }))
|
|
1945
|
+
];
|
|
1946
|
+
}
|
|
1947
|
+
function ownPackages(layers) {
|
|
1948
|
+
const parsed = z6.looseObject({ layers: z6.looseObject({ packages: z6.array(z6.looseObject({ name: z6.string() })) }) }).safeParse(layers);
|
|
1949
|
+
return parsed.success ? new Set(parsed.data.layers.packages.map((p) => p.name)) : void 0;
|
|
1950
|
+
}
|
|
1951
|
+
var serves = (report) => report.surface.routes.length > 0 || report.dataModel.tables.length > 0;
|
|
1952
|
+
async function direct({ root, engine, requirements, withMap = true, previous = null, say: say2 = MCP }) {
|
|
1953
|
+
const sources = projectSources(root);
|
|
1954
|
+
const hash = sourcesHash(sources);
|
|
1955
|
+
const instances = instancesFor(requirements);
|
|
1956
|
+
const base = {
|
|
1957
|
+
schemaVersion: "yichus-studio-state-1",
|
|
1958
|
+
project: path3.basename(path3.resolve(root)),
|
|
1959
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1960
|
+
sourcesHash: hash,
|
|
1961
|
+
files: sources.map((s) => s.fileName),
|
|
1962
|
+
description: requirements.description,
|
|
1963
|
+
names: requirements.names ?? {},
|
|
1964
|
+
topology: null,
|
|
1965
|
+
proven: null,
|
|
1966
|
+
properties: [],
|
|
1967
|
+
other: [],
|
|
1968
|
+
laws: [],
|
|
1969
|
+
lawsError: null,
|
|
1970
|
+
rulesListed: requirements.rules !== void 0,
|
|
1971
|
+
rules: [],
|
|
1972
|
+
map: null,
|
|
1973
|
+
mapError: null,
|
|
1974
|
+
layers: null,
|
|
1975
|
+
hasActions: null,
|
|
1976
|
+
whatHappens: null,
|
|
1977
|
+
whatHappensError: null
|
|
1978
|
+
};
|
|
1979
|
+
let compileErrors = null;
|
|
1980
|
+
if (requirements.description && sources.length) {
|
|
1981
|
+
const verify = Verify.parse(await call(engine, "api_verify", { sources, ...instances ? { instances } : {} }));
|
|
1982
|
+
base.topology = verify.topology ?? null;
|
|
1983
|
+
base.proven = verify.verdict.proven;
|
|
1984
|
+
const compiles = verify.verdict.properties.find((p) => p.id === "compiles");
|
|
1985
|
+
if (compiles && compiles.status !== "proven") compileErrors = compiles.details;
|
|
1986
|
+
else {
|
|
1987
|
+
const report = Report.parse(await call(engine, "api_report", { sources }));
|
|
1988
|
+
const structureRaw = await call(engine, "api_organize", { sources, lens: "structure", requirements });
|
|
1989
|
+
const structure = Structure.parse(structureRaw);
|
|
1990
|
+
const questions = questionsFor(report, structure, base.names);
|
|
1991
|
+
if (serves(report)) {
|
|
1992
|
+
questions.push(platform);
|
|
1993
|
+
const where = answerOf(requirements, platform.id)?.choice;
|
|
1994
|
+
if (where && PAGE_ONLY.has(where)) questions.push(hostQuestion(platform.choices.find((c) => c.id === where).label));
|
|
1995
|
+
}
|
|
1996
|
+
const together = new Set(questions.filter((q) => q.kind === "together").map((q) => q.subject));
|
|
1997
|
+
for (const question of questions) {
|
|
1998
|
+
base.properties.push(await judge(root, engine, sources, question, answerOf(requirements, question.id), report, verify.verdict.properties, together));
|
|
1999
|
+
}
|
|
2000
|
+
const routeless = (p) => !serves(report) && p.status === "warning" && p.id.startsWith("route-");
|
|
2001
|
+
base.other = verify.verdict.properties.filter((p) => !QUESTION_PROPERTIES(p.id) && p.status !== "proven" && !isAccepted(p) && !routeless(p)).map(({ id, title: title2, status, details }) => ({ id, title: title2, status, details }));
|
|
2002
|
+
const checked = await checkLaws(engine, sources);
|
|
2003
|
+
base.laws = checked.laws;
|
|
2004
|
+
base.lawsError = checked.error;
|
|
2005
|
+
base.rules = (requirements.rules ?? []).map((r) => judgeRule(r, base.laws));
|
|
2006
|
+
base.hasActions = report.surface.routes.length > 0;
|
|
2007
|
+
if (base.hasActions || requirements.scenarios?.length) {
|
|
2008
|
+
try {
|
|
2009
|
+
const access = await call(engine, "api_access_check", { sources });
|
|
2010
|
+
const record = WhatHappens.parse(buildWhatHappens({ structure: structureRaw, access }, { program: base.project }));
|
|
2011
|
+
base.whatHappens = base.hasActions ? record : { ...record, entries: [], ghosts: [], claims: [], witnesses: [], refused: [], notes: [] };
|
|
2012
|
+
} catch (error) {
|
|
2013
|
+
base.whatHappensError = error instanceof Error ? error.message : String(error);
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
if (withMap) {
|
|
2017
|
+
if (previous?.sourcesHash === hash && previous.map) {
|
|
2018
|
+
base.map = previous.map;
|
|
2019
|
+
base.layers = previous.layers ?? null;
|
|
2020
|
+
} else {
|
|
2021
|
+
try {
|
|
2022
|
+
const [abstractions, layers] = [
|
|
2023
|
+
await call(engine, "api_organize", { sources, lens: "abstractions" }),
|
|
2024
|
+
await call(engine, "api_organize", { sources, lens: "layers" })
|
|
2025
|
+
];
|
|
2026
|
+
base.map = buildSystemMap({ report, structure: structureRaw, abstractions, layers }, { program: base.project });
|
|
2027
|
+
base.layers = layers;
|
|
2028
|
+
} catch (error) {
|
|
2029
|
+
base.mapError = error instanceof Error ? error.message : String(error);
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
const state = { ...base, step: nextStep(base, compileErrors, say2) };
|
|
2036
|
+
writeState(root, state);
|
|
2037
|
+
return state;
|
|
2038
|
+
}
|
|
2039
|
+
function writeState(root, state) {
|
|
2040
|
+
ensureStudioDir(root);
|
|
2041
|
+
fs3.writeFileSync(path3.join(studioDir(root), "state.json"), `${JSON.stringify(state, null, 2)}
|
|
2042
|
+
`);
|
|
2043
|
+
}
|
|
2044
|
+
function readState(root) {
|
|
2045
|
+
const file = path3.join(studioDir(root), "state.json");
|
|
2046
|
+
return fs3.existsSync(file) ? JSON.parse(fs3.readFileSync(file, "utf8")) : null;
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
// src/studio/mcp.ts
|
|
2050
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2051
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2052
|
+
import { z as z10 } from "zod";
|
|
2053
|
+
|
|
2054
|
+
// src/studio/marks.ts
|
|
2055
|
+
import fs4 from "fs";
|
|
2056
|
+
import path4 from "path";
|
|
2057
|
+
import { z as z8 } from "zod";
|
|
2058
|
+
|
|
2059
|
+
// src/studio/person.ts
|
|
2060
|
+
import { createHash as createHash2 } from "crypto";
|
|
2061
|
+
import { z as z7 } from "zod";
|
|
2062
|
+
|
|
2063
|
+
// ../../web/layer-groups.js
|
|
2064
|
+
var dimensions = Object.freeze({
|
|
2065
|
+
connections: "packages they connect to",
|
|
2066
|
+
types: "types they share",
|
|
2067
|
+
tables: "tables they touch",
|
|
2068
|
+
none: "no grouping"
|
|
2069
|
+
});
|
|
2070
|
+
function usesElsewhere(data, nodeOf = new Map(data.packages.map((p) => [p.name, p.name]))) {
|
|
2071
|
+
const pkg = (id) => id.slice(0, id.indexOf("::"));
|
|
2072
|
+
const uses = new Map([...new Set(nodeOf.values())].map((n) => [n, 0]));
|
|
2073
|
+
const add = (from, to, n) => {
|
|
2074
|
+
if (nodeOf.get(from) !== nodeOf.get(to)) uses.set(nodeOf.get(to), uses.get(nodeOf.get(to)) + n);
|
|
2075
|
+
};
|
|
2076
|
+
for (const e of data.crossEdges) add(pkg(e.from), pkg(e.to), 1);
|
|
2077
|
+
for (const e of data.packageEdges) add(e.from, e.to, e.typeNames.length);
|
|
2078
|
+
return uses;
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// src/studio/person.ts
|
|
2082
|
+
var named = (names, code) => names[code] ?? null;
|
|
2083
|
+
var theirs = (words, missing) => words === null ? missing : { theirs: words };
|
|
2084
|
+
var Package = z7.looseObject({
|
|
2085
|
+
name: z7.string(),
|
|
2086
|
+
level: z7.number(),
|
|
2087
|
+
reads: z7.array(z7.string()),
|
|
2088
|
+
writes: z7.array(z7.string()),
|
|
2089
|
+
handedIn: z7.array(z7.string())
|
|
2090
|
+
});
|
|
2091
|
+
var Layers = z7.looseObject({
|
|
2092
|
+
layers: z7.looseObject({ packages: z7.array(Package), packageEdges: z7.array(z7.looseObject({})), crossEdges: z7.array(z7.looseObject({})) })
|
|
2093
|
+
});
|
|
2094
|
+
function personSections(layers, names, anchors = /* @__PURE__ */ new Map()) {
|
|
2095
|
+
const parsed = Layers.safeParse(layers);
|
|
2096
|
+
if (!parsed.success) return null;
|
|
2097
|
+
const data = parsed.data.layers;
|
|
2098
|
+
const uses = usesElsewhere(data);
|
|
2099
|
+
const levels = [...new Set(data.packages.map((p) => p.level))].sort((a, b) => b - a);
|
|
2100
|
+
return levels.map((level, i) => data.packages.filter((p) => p.level === level).map((p) => {
|
|
2101
|
+
const own = (tables) => [...new Set(tables.filter((t) => !p.handedIn.includes(t)).map((t) => named(names, t)))];
|
|
2102
|
+
const changes = own(p.writes);
|
|
2103
|
+
return { code: p.name, name: named(names, p.name), changes, looks: own(p.reads).filter((t) => !changes.includes(t)), uses: uses.get(p.name) };
|
|
2104
|
+
}).sort((a, b) => b.uses - a.uses).map(({ code, ...section }, k) => {
|
|
2105
|
+
const anchor = `section-${i}-${k}`;
|
|
2106
|
+
anchors.set(code, anchor);
|
|
2107
|
+
return { anchor, ...section };
|
|
2108
|
+
}));
|
|
2109
|
+
}
|
|
2110
|
+
var Property2 = z7.object({ negated: z7.boolean(), is: z7.enum(["reads", "writes", "refused", "returns", "reaches"]), subject: z7.string().optional() });
|
|
2111
|
+
var Claim2 = z7.looseObject({ property: Property2, verdict: z7.enum(["holds", "fails", "inconclusive"]) });
|
|
2112
|
+
var Leaf2 = z7.looseObject({
|
|
2113
|
+
kind: z7.literal("leaf"),
|
|
2114
|
+
id: z7.string(),
|
|
2115
|
+
words: z7.string().nullable(),
|
|
2116
|
+
status: z7.enum(["grey", "red", "green", "unchecked"]),
|
|
2117
|
+
outcome: z7.looseObject({ kind: z7.string() }),
|
|
2118
|
+
claims: z7.array(Claim2),
|
|
2119
|
+
witnesses: z7.array(z7.string())
|
|
2120
|
+
});
|
|
2121
|
+
var Tree2 = z7.lazy(() => z7.union([Leaf2, z7.looseObject({
|
|
2122
|
+
kind: z7.literal("node"),
|
|
2123
|
+
id: z7.string(),
|
|
2124
|
+
words: z7.string().nullable(),
|
|
2125
|
+
arms: z7.array(z7.looseObject({ id: z7.string(), words: z7.string().nullable(), next: Tree2 }))
|
|
2126
|
+
})]));
|
|
2127
|
+
var Happens = z7.looseObject({
|
|
2128
|
+
entries: z7.array(z7.looseObject({ entry: z7.string(), title: z7.string().nullable(), described: z7.boolean(), tree: Tree2.nullable() })),
|
|
2129
|
+
witnesses: z7.array(z7.looseObject({ id: z7.string(), resource: z7.string() }))
|
|
2130
|
+
});
|
|
2131
|
+
function sayClaim({ negated, is, subject }, names) {
|
|
2132
|
+
const thing = theirs(subject === void 0 ? null : named(names, subject), "something not named yet");
|
|
2133
|
+
const said2 = is === "refused" ? ["turned away"] : is === "reaches" ? [subject === "model" ? "asks the AI model" : "reaches the internet"] : [is === "reads" ? "looks at " : is === "writes" ? "changes " : "answers ", thing];
|
|
2134
|
+
return !negated ? said2 : is === "refused" ? ["not turned away"] : ["never ", ...said2];
|
|
2135
|
+
}
|
|
2136
|
+
function personWhatHappens(record, names, anchors = /* @__PURE__ */ new Map()) {
|
|
2137
|
+
const parsed = Happens.safeParse(record);
|
|
2138
|
+
if (!parsed.success) return null;
|
|
2139
|
+
const reach = new Map(parsed.data.witnesses.map((w) => [w.id, named(names, w.resource)]));
|
|
2140
|
+
const VERDICT = { holds: "holds", fails: "fails", inconclusive: "cannot say" };
|
|
2141
|
+
const at = (id, anchor) => {
|
|
2142
|
+
anchors.set(id, anchor);
|
|
2143
|
+
return anchor;
|
|
2144
|
+
};
|
|
2145
|
+
const step = (t, said2, place) => {
|
|
2146
|
+
if (t.kind === "leaf") return {
|
|
2147
|
+
kind: "outcome",
|
|
2148
|
+
anchor: at(t.id, place),
|
|
2149
|
+
words: t.words === said2 ? null : t.words,
|
|
2150
|
+
refused: t.outcome.kind === "refused",
|
|
2151
|
+
status: t.status,
|
|
2152
|
+
checks: [
|
|
2153
|
+
...t.claims.map((c) => ({ says: sayClaim(c.property, names), verdict: VERDICT[c.verdict] })),
|
|
2154
|
+
...t.witnesses.map((w) => ({ says: ["someone else's ", theirs(reach.get(w) ?? null, "records"), " can be reached here"], verdict: "fails" }))
|
|
2155
|
+
]
|
|
2156
|
+
};
|
|
2157
|
+
return { kind: "choice", anchor: at(t.id, place), words: t.words, ways: t.arms.map((a, k) => {
|
|
2158
|
+
const then = step(a.next, a.next.id === a.id ? a.words : null, `${place}-${k}`);
|
|
2159
|
+
return { anchor: a.next.id === a.id ? then.anchor : at(a.id, `${place}-${k}-way`), words: a.words, then };
|
|
2160
|
+
}) };
|
|
2161
|
+
};
|
|
2162
|
+
const described = parsed.data.entries.filter((e) => e.described);
|
|
2163
|
+
return {
|
|
2164
|
+
actions: described.map((e, i) => ({ anchor: at(e.entry, `action-${i}`), title: e.title, first: e.tree && step(e.tree, null, `action-${i}-step`) })),
|
|
2165
|
+
waiting: parsed.data.entries.length - described.length
|
|
2166
|
+
};
|
|
2167
|
+
}
|
|
2168
|
+
function personDiagrams(state, names) {
|
|
2169
|
+
const anchors = /* @__PURE__ */ new Map();
|
|
2170
|
+
const sections = personSections(state.layers, names, anchors);
|
|
2171
|
+
const whatHappens = state.whatHappens ? personWhatHappens(state.whatHappens, names, anchors) : null;
|
|
2172
|
+
const drawing = createHash2("sha256").update(JSON.stringify([...anchors])).digest("hex").slice(0, 16);
|
|
2173
|
+
return { sections, whatHappens, anchors, drawing };
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
// src/studio/marks.ts
|
|
2177
|
+
var Mark = z8.object({ at: z8.string().min(1), note: z8.string().trim().min(1).max(280) }).strict();
|
|
2178
|
+
var Marks = z8.object({ schemaVersion: z8.literal("yichus-marks-1"), said: z8.string(), marks: z8.array(Mark) });
|
|
2179
|
+
var PointArgs = z8.object({ marks: z8.array(Mark) }).strict();
|
|
2180
|
+
var marksPath = (root) => path4.join(studioDir(root), "marks.json");
|
|
2181
|
+
function loadMarks(root) {
|
|
2182
|
+
const file = marksPath(root);
|
|
2183
|
+
if (!fs4.existsSync(file)) return null;
|
|
2184
|
+
const parsed = Marks.safeParse(JSON.parse(fs4.readFileSync(file, "utf8")));
|
|
2185
|
+
if (!parsed.success) throw new Error(`${file} is not a yichus-marks-1 file: ${z8.prettifyError(parsed.error)}`);
|
|
2186
|
+
return parsed.data;
|
|
2187
|
+
}
|
|
2188
|
+
function pointable(root) {
|
|
2189
|
+
const state = readState(root);
|
|
2190
|
+
return new Set(state ? personDiagrams(state, loadRequirements(root).names ?? {}).anchors.keys() : []);
|
|
2191
|
+
}
|
|
2192
|
+
function recordMarks(root, args, now) {
|
|
2193
|
+
const parsed = PointArgs.safeParse(args);
|
|
2194
|
+
if (!parsed.success) return { ok: false, error: `yichus_point needs marks, each with at and a note of at most 280 characters. ${z8.prettifyError(parsed.error)}` };
|
|
2195
|
+
const known = pointable(root);
|
|
2196
|
+
const unknown = parsed.data.marks.map((m) => m.at).filter((at) => !known.has(at));
|
|
2197
|
+
if (unknown.length) return { ok: false, error: `The page draws nothing at ${unknown.join(", ")}. Point at a section (a part's code name as yichus_name took it), an action once yichus_scenario described it, or an id yichus_next listed under a described action; call yichus_next for the latest ids.` };
|
|
2198
|
+
ensureStudioDir(root);
|
|
2199
|
+
fs4.writeFileSync(marksPath(root), `${JSON.stringify(Marks.parse({ schemaVersion: "yichus-marks-1", said: now.toISOString(), marks: parsed.data.marks }), null, 2)}
|
|
2200
|
+
`);
|
|
2201
|
+
return { ok: true };
|
|
2202
|
+
}
|
|
2203
|
+
|
|
2204
|
+
// src/studio/page.ts
|
|
2205
|
+
var PAGE_STATUS = {
|
|
2206
|
+
unanswered: ["waiting for your answer", "quiet"],
|
|
2207
|
+
decided: ["decided", "good"],
|
|
2208
|
+
assumed: ["holds, under an assumption", "warn"],
|
|
2209
|
+
proven: ["proven", "good"],
|
|
2210
|
+
bounded: ["holds in every scenario checked", "good"],
|
|
2211
|
+
broken: ["broken", "bad"],
|
|
2212
|
+
mismatch: ["the code says otherwise", "bad"],
|
|
2213
|
+
"needs-case": ["scenario being written", "quiet"],
|
|
2214
|
+
"needs-law": ["check being written", "quiet"],
|
|
2215
|
+
unused: ["checked, but your app does not use it yet", "bad"],
|
|
2216
|
+
inconclusive: ["not decided yet", "warn"],
|
|
2217
|
+
"no-check": ["no check needed", "quiet"],
|
|
2218
|
+
pending: ["answered, waiting for your agent to check", "quiet"]
|
|
2219
|
+
};
|
|
2220
|
+
var PAGE_HEADINGS = {
|
|
2221
|
+
asked: "What you asked for",
|
|
2222
|
+
now: "What is happening now",
|
|
2223
|
+
questions: "Questions for you",
|
|
2224
|
+
props: "What your program must do",
|
|
2225
|
+
happens: "What happens when",
|
|
2226
|
+
sections: "How your app is built",
|
|
2227
|
+
map: "The shape of your program"
|
|
2228
|
+
};
|
|
2229
|
+
var NO_ACTIONS = "Nothing to follow here: your program works out answers from what is entered, and has no actions people take, such as saving or sending something.";
|
|
2230
|
+
var STUDIO_PAGE = `<!doctype html>
|
|
2231
|
+
<html lang="en">
|
|
2232
|
+
<head>
|
|
2233
|
+
<meta charset="utf-8">
|
|
2234
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
2235
|
+
<title>Yichus studio</title>
|
|
2236
|
+
<link rel="stylesheet" href="system-map.css">
|
|
2237
|
+
<style>
|
|
2238
|
+
:root { --ink:#0f172a; --muted:#475569; --faint:#94a3b8; --rule:#e2e8f0; --paper:#ffffff; --page:#f6f8fb;
|
|
2239
|
+
--good:#047857; --goodSoft:#ecfdf5; --bad:#b91c1c; --badSoft:#fef2f2; --warn:#92400e; --warnSoft:#fffbeb; --accent:#22675e;
|
|
2240
|
+
--agent:#4f46e5; --agentSoft:rgba(79,70,229,0.16); }
|
|
2241
|
+
* { box-sizing:border-box; }
|
|
2242
|
+
body { margin:0; background:var(--page); color:var(--ink); font:16px/1.55 Inter, system-ui, sans-serif; }
|
|
2243
|
+
main { max-width:1100px; margin:0 auto; padding:24px 16px 64px; }
|
|
2244
|
+
header p { margin:4px 0 0; color:var(--muted); }
|
|
2245
|
+
h1 { font-size:1.6rem; margin:0; font-weight:600; }
|
|
2246
|
+
h2 { font-size:1.15rem; margin:32px 0 8px; }
|
|
2247
|
+
section > p.lede { color:var(--muted); margin:0 0 12px; max-width:70ch; }
|
|
2248
|
+
.frame { background:var(--paper); border:1px solid var(--rule); border-radius:10px; padding:16px; position:relative; }
|
|
2249
|
+
.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; }
|
|
2250
|
+
.yours { border-left:3px solid var(--accent); padding:4px 12px; margin:0; font-style:italic; }
|
|
2251
|
+
.label { font-size:0.75rem; color:var(--muted); text-transform:uppercase; letter-spacing:0.06em; margin:0 0 4px; }
|
|
2252
|
+
.now { font-weight:600; }
|
|
2253
|
+
.question { border-top:1px solid var(--rule); padding:14px 0; }
|
|
2254
|
+
.question:first-of-type { border-top:none; padding-top:4px; }
|
|
2255
|
+
.question .ask { font-weight:600; margin:0 0 4px; }
|
|
2256
|
+
.question .why { color:var(--muted); margin:0 0 8px; font-size:0.94rem; }
|
|
2257
|
+
.choice { display:flex; gap:8px; align-items:flex-start; margin:6px 0; }
|
|
2258
|
+
.choice span small { display:block; color:var(--muted); }
|
|
2259
|
+
textarea { width:100%; min-height:3.2em; font:inherit; border:1px solid var(--rule); border-radius:8px; padding:8px; margin:6px 0; }
|
|
2260
|
+
button { font:inherit; font-weight:600; border:none; border-radius:8px; padding:8px 14px; background:var(--accent); color:#fff; cursor:pointer; }
|
|
2261
|
+
button:disabled { opacity:0.5; cursor:default; }
|
|
2262
|
+
.props { list-style:none; margin:0; padding:0; }
|
|
2263
|
+
.props li { border-top:1px solid var(--rule); padding:12px 0; display:grid; grid-template-columns:1fr auto; gap:4px 16px; }
|
|
2264
|
+
.props li:first-child { border-top:none; }
|
|
2265
|
+
.chip { font-size:0.8rem; font-weight:700; border-radius:999px; padding:2px 10px; white-space:nowrap; align-self:start; justify-self:start; }
|
|
2266
|
+
.chip.good { color:var(--good); background:var(--goodSoft); }
|
|
2267
|
+
.chip.bad { color:var(--bad); background:var(--badSoft); }
|
|
2268
|
+
.chip.warn { color:var(--warn); background:var(--warnSoft); }
|
|
2269
|
+
.chip.quiet { color:var(--muted); background:var(--rule); }
|
|
2270
|
+
.props .choice-said { color:var(--muted); font-size:0.94rem; grid-column:1 / -1; }
|
|
2271
|
+
details { grid-column:1 / -1; font-size:0.88rem; }
|
|
2272
|
+
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; }
|
|
2273
|
+
.empty { color:var(--muted); }
|
|
2274
|
+
.studio-action { border-top:1px solid var(--rule); padding:12px 0; }
|
|
2275
|
+
.studio-action:first-child { border-top:none; padding-top:0; }
|
|
2276
|
+
.studio-action h3 { font-size:1rem; margin:0 0 8px; font-weight:600; }
|
|
2277
|
+
.studio-ask, .studio-way { margin:0; }
|
|
2278
|
+
.studio-ways { list-style:none; margin:4px 0 0 9px; padding:0 0 0 14px; border-left:2px solid var(--rule); }
|
|
2279
|
+
.studio-ways > li { position:relative; padding:4px 0; }
|
|
2280
|
+
.studio-ways > li::before { content:''; position:absolute; left:-14px; top:15px; width:10px; border-top:2px solid var(--rule); }
|
|
2281
|
+
.studio-way, .studio-on { color:var(--muted); }
|
|
2282
|
+
.studio-on { margin:4px 0 0; }
|
|
2283
|
+
.studio-fold summary { cursor:pointer; color:var(--muted); }
|
|
2284
|
+
.studio-folded { margin:4px 0 0; padding-left:10px; border-left:2px dashed var(--rule); }
|
|
2285
|
+
.studio-outcome { display:grid; grid-template-columns:20px minmax(0, 1fr); align-items:center; gap:2px 8px; margin:2px 0 0; }
|
|
2286
|
+
.studio-said, .studio-ask, .studio-way, .studio-checks li { overflow-wrap:anywhere; }
|
|
2287
|
+
.studio-end { font-weight:600; }
|
|
2288
|
+
.studio-outcome[data-status="red"] .studio-end { color:var(--bad); }
|
|
2289
|
+
.studio-outcome[data-status="green"] .studio-end { color:var(--good); }
|
|
2290
|
+
.studio-checks { list-style:none; margin:0; padding:0; grid-column:2; display:flex; flex-wrap:wrap; gap:2px 12px; font-size:0.9rem; color:var(--muted); }
|
|
2291
|
+
.studio-checks li { min-width:0; }
|
|
2292
|
+
.studio-checks [data-verdict="fails"] { color:var(--bad); font-weight:600; }
|
|
2293
|
+
.studio-checks [data-verdict="cannot say"] { color:var(--warn); }
|
|
2294
|
+
.studio-unnamed, .studio-waiting { color:var(--faint); }
|
|
2295
|
+
.studio-stack { display:block; max-width:100%; height:auto; }
|
|
2296
|
+
.studio-band { fill:var(--page); }
|
|
2297
|
+
.studio-band[data-shade="1"] { fill:#eef2f7; }
|
|
2298
|
+
.studio-section rect { fill:var(--paper); stroke:var(--faint); }
|
|
2299
|
+
.studio-canvas { fill:var(--paper); }
|
|
2300
|
+
.studio-section-name { fill:var(--ink); }
|
|
2301
|
+
.studio-section[data-named="false"] .studio-section-name { fill:var(--faint); }
|
|
2302
|
+
.studio-section-does { fill:var(--muted); }
|
|
2303
|
+
.agent-layer { position:absolute; left:0; top:0; width:0; height:0; z-index:20; pointer-events:none; }
|
|
2304
|
+
.agent-ring { position:absolute; border-radius:10px; box-shadow:0 0 0 2px var(--agent), 0 0 0 8px var(--agentSoft); }
|
|
2305
|
+
.agent-bubble { position:absolute; pointer-events:auto; background:var(--paper); border:1px solid var(--agent); border-radius:4px 14px 14px 14px;
|
|
2306
|
+
padding:8px 30px 10px 12px; box-shadow:0 10px 28px rgba(15,23,42,0.18); font-size:0.94rem; }
|
|
2307
|
+
.agent-tail { position:absolute; top:-7px; width:12px; height:12px; background:var(--paper); border-left:1px solid var(--agent); border-top:1px solid var(--agent); transform:rotate(45deg); }
|
|
2308
|
+
.agent-bubble[data-side="right"] { border-radius:14px 14px 14px 14px; }
|
|
2309
|
+
.agent-bubble[data-side="right"] .agent-tail { transform:rotate(-45deg); }
|
|
2310
|
+
.agent-who { margin:0 0 2px; font-size:0.72rem; font-weight:700; letter-spacing:0.06em; text-transform:uppercase; color:var(--agent); }
|
|
2311
|
+
.agent-who span { color:var(--muted); font-weight:600; }
|
|
2312
|
+
.agent-says { margin:0; overflow-wrap:anywhere; }
|
|
2313
|
+
.agent-close { position:absolute; top:4px; right:4px; background:none; color:var(--muted); padding:2px 8px; font-size:1rem; line-height:1; }
|
|
2314
|
+
.agent-in { animation:agent-in 280ms ease-out both; }
|
|
2315
|
+
@keyframes agent-in { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }
|
|
2316
|
+
@media (prefers-reduced-motion: reduce) { .agent-in { animation:none; } }
|
|
2317
|
+
@media (max-width:640px) { .props li { grid-template-columns:1fr; } }
|
|
2318
|
+
</style>
|
|
2319
|
+
</head>
|
|
2320
|
+
<body>
|
|
2321
|
+
<main>
|
|
2322
|
+
<header>
|
|
2323
|
+
<h1>Yichus studio<span id="project"></span></h1>
|
|
2324
|
+
<p id="updated">Waiting for your agent.</p>
|
|
2325
|
+
<p>Ask your agent what anything here means.</p>
|
|
2326
|
+
</header>
|
|
2327
|
+
<section aria-labelledby="h-asked" data-section="asked">
|
|
2328
|
+
<h2 id="h-asked">${PAGE_HEADINGS.asked}</h2>
|
|
2329
|
+
<p class="label">Your words</p>
|
|
2330
|
+
<p class="yours" id="description">Nothing yet. Tell your agent what you want to build.</p>
|
|
2331
|
+
</section>
|
|
2332
|
+
<section aria-labelledby="h-now" data-section="now">
|
|
2333
|
+
<h2 id="h-now">${PAGE_HEADINGS.now}</h2>
|
|
2334
|
+
<div class="frame"><span class="tag">Yichus output</span>
|
|
2335
|
+
<p class="now" id="summary">No checks have run yet.</p>
|
|
2336
|
+
</div>
|
|
2337
|
+
</section>
|
|
2338
|
+
<section aria-labelledby="h-questions" id="questions-section" data-section="questions" hidden>
|
|
2339
|
+
<h2 id="h-questions">${PAGE_HEADINGS.questions}</h2>
|
|
2340
|
+
<p class="lede">Your agent will ask you these too. Answer here or in the chat, whichever is easier.</p>
|
|
2341
|
+
<div class="frame"><span class="tag">Yichus output</span><div id="questions"></div></div>
|
|
2342
|
+
</section>
|
|
2343
|
+
<section aria-labelledby="h-props" data-section="props">
|
|
2344
|
+
<h2 id="h-props">${PAGE_HEADINGS.props}</h2>
|
|
2345
|
+
<div class="frame"><span class="tag">Yichus output</span><ul class="props" id="props"><li class="empty">No properties chosen yet.</li></ul></div>
|
|
2346
|
+
</section>
|
|
2347
|
+
<section aria-labelledby="h-happens" data-section="happens">
|
|
2348
|
+
<h2 id="h-happens">${PAGE_HEADINGS.happens}</h2>
|
|
2349
|
+
<p class="lede">Each thing your app does, every way it can go, and what you get at the end, in the words you and your agent chose.</p>
|
|
2350
|
+
<p class="label">Drawn by Yichus. Words in italics are your agent's, not checked</p>
|
|
2351
|
+
<div class="frame"><div id="happens"><p class="empty">This appears once the program compiles.</p></div></div>
|
|
2352
|
+
</section>
|
|
2353
|
+
<section aria-labelledby="h-sections" data-section="sections">
|
|
2354
|
+
<h2 id="h-sections">${PAGE_HEADINGS.sections}</h2>
|
|
2355
|
+
<p class="lede">The parts of your app, stacked: each layer is built only from the layers below it.</p>
|
|
2356
|
+
<p class="label">Drawn by Yichus. Words in italics are your agent's, not checked</p>
|
|
2357
|
+
<div class="frame"><div id="sections"><p class="empty">This appears once the program compiles.</p></div></div>
|
|
2358
|
+
</section>
|
|
2359
|
+
<section aria-labelledby="h-map" data-section="map">
|
|
2360
|
+
<h2 id="h-map">${PAGE_HEADINGS.map}</h2>
|
|
2361
|
+
<div class="frame"><div class="system-map" id="map"><p class="empty">The map appears once the program compiles.</p></div></div>
|
|
2362
|
+
</section>
|
|
2363
|
+
</main>
|
|
2364
|
+
<script type="module">
|
|
2365
|
+
import { mount } from './system-map.js';
|
|
2366
|
+
import { mountSections, mountWhatHappens, reportViewing, showMarks } from './studio-views.js';
|
|
2367
|
+
|
|
2368
|
+
const STATUS = ${JSON.stringify(PAGE_STATUS)};
|
|
2369
|
+
const NO_ACTIONS = ${JSON.stringify(NO_ACTIONS)};
|
|
2370
|
+
const el = (tag, props = {}, ...kids) => { const n = Object.assign(document.createElement(tag), props); n.append(...kids); return n; };
|
|
2371
|
+
let mapHash = null, drawn = '';
|
|
2372
|
+
|
|
2373
|
+
function questionCard(q, saved) {
|
|
2374
|
+
const card = el('div', { className: 'question' });
|
|
2375
|
+
card.dataset.question = q.id;
|
|
2376
|
+
card.append(el('p', { className: 'ask', textContent: q.ask }), el('p', { className: 'why', textContent: q.why }));
|
|
2377
|
+
const name = 'q-' + q.id;
|
|
2378
|
+
for (const c of q.choices) {
|
|
2379
|
+
const input = el('input', { type: 'radio', name, value: c.id, checked: saved?.choice === c.id });
|
|
2380
|
+
card.append(el('label', { className: 'choice' }, input, el('span', {}, c.label, el('small', { textContent: c.means }))));
|
|
2381
|
+
}
|
|
2382
|
+
const words = el('textarea', { placeholder: 'In your own words (optional)', value: saved?.words ?? '' });
|
|
2383
|
+
const status = el('span', { className: 'empty', textContent: saved ? ' Saved. Your agent will check it next.' : '' });
|
|
2384
|
+
const save = el('button', { type: 'button', textContent: 'Save answer' });
|
|
2385
|
+
save.addEventListener('click', async () => {
|
|
2386
|
+
const picked = card.querySelector('input[name="' + CSS.escape(name) + '"]:checked');
|
|
2387
|
+
if (!picked) { status.textContent = ' Pick one of the choices first.'; return; }
|
|
2388
|
+
save.disabled = true;
|
|
2389
|
+
const label = q.choices.find(c => c.id === picked.value).label;
|
|
2390
|
+
const response = await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' },
|
|
2391
|
+
body: JSON.stringify({ question: q.id, choice: picked.value, words: words.value.trim() || label }) });
|
|
2392
|
+
const result = await response.json();
|
|
2393
|
+
status.textContent = result.ok ? ' Saved. Your agent will check it next.' : ' ' + result.error;
|
|
2394
|
+
save.disabled = false;
|
|
2395
|
+
});
|
|
2396
|
+
card.append(el('p', { className: 'label', textContent: 'Your words' }), words, save, status);
|
|
2397
|
+
return card;
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
function ruleRow(r) {
|
|
2401
|
+
const [words, tone] = STATUS[r.status];
|
|
2402
|
+
const li = el('li', {}, el('span', { textContent: 'A rule you gave: ' }, el('em', { textContent: r.rule })), el('span', { className: 'chip ' + tone, textContent: words }));
|
|
2403
|
+
li.append(el('span', { className: 'choice-said', textContent: 'Checked with ' + (r.laws === 1 ? '1 law' : r.laws + ' laws') + ' your agent wrote.' }));
|
|
2404
|
+
return li;
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
function propertyRow(p, saved) {
|
|
2408
|
+
const stale = saved && (!p.answer || p.answer.answeredAt !== saved.answeredAt);
|
|
2409
|
+
const [words, tone] = STATUS[stale ? 'pending' : p.status];
|
|
2410
|
+
const answer = stale ? saved : p.answer;
|
|
2411
|
+
const label = p.question.choices.find(c => c.id === answer.choice)?.label ?? answer.choice;
|
|
2412
|
+
const li = el('li', {}, el('span', { textContent: p.question.ask }), el('span', { className: 'chip ' + tone, textContent: words }));
|
|
2413
|
+
li.dataset.property = p.question.id;
|
|
2414
|
+
li.append(el('span', { className: 'choice-said', textContent: 'You chose: ' + label + (answer.words && answer.words !== label ? ' ("' + answer.words + '")' : '') }));
|
|
2415
|
+
return li;
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
async function refresh() {
|
|
2419
|
+
const { state, requirements } = await (await fetch('/state')).json();
|
|
2420
|
+
const savedOf = id => requirements.answers.find(a => a.question === id);
|
|
2421
|
+
if (requirements.description) document.getElementById('description').textContent = requirements.description;
|
|
2422
|
+
if (!state) return;
|
|
2423
|
+
document.getElementById('project').textContent = ': ' + state.project;
|
|
2424
|
+
document.getElementById('updated').textContent = 'Last checked ' + new Date(state.updatedAt).toLocaleTimeString() + '.';
|
|
2425
|
+
document.getElementById('summary').textContent = state.summary;
|
|
2426
|
+
const open = state.properties.filter(p => p.status === 'unanswered' && !savedOf(p.question.id));
|
|
2427
|
+
document.getElementById('questions-section').hidden = !open.length;
|
|
2428
|
+
// Keep a half-written answer: only rebuild cards when the questions change.
|
|
2429
|
+
const qs = document.getElementById('questions');
|
|
2430
|
+
const ids = open.map(p => p.question.id).join(' ');
|
|
2431
|
+
if (qs.dataset.ids !== ids) { qs.dataset.ids = ids; qs.replaceChildren(...open.map(p => questionCard(p.question, savedOf(p.question.id)))); }
|
|
2432
|
+
const chosen = state.properties.filter(p => p.answer || savedOf(p.question.id));
|
|
2433
|
+
const rows = [...state.rules.map(ruleRow), ...chosen.map(p => propertyRow(p, savedOf(p.question.id)))];
|
|
2434
|
+
document.getElementById('props').replaceChildren(...(rows.length ? rows : [el('li', { className: 'empty', textContent: 'No properties chosen yet.' })]));
|
|
2435
|
+
// Redrawn only when the words or the program change.
|
|
2436
|
+
const views = JSON.stringify([state.hasActions, state.whatHappens, state.sections]);
|
|
2437
|
+
if (views !== drawn) {
|
|
2438
|
+
drawn = views;
|
|
2439
|
+
const happens = document.getElementById('happens');
|
|
2440
|
+
if (state.hasActions === false) happens.replaceChildren(el('p', { className: 'empty', textContent: NO_ACTIONS }));
|
|
2441
|
+
else if (state.whatHappens) mountWhatHappens(happens, state.whatHappens);
|
|
2442
|
+
else happens.replaceChildren(el('p', { className: 'empty', textContent: 'This appears once the program compiles.' }));
|
|
2443
|
+
if (state.sections) mountSections(document.getElementById('sections'), state.sections);
|
|
2444
|
+
}
|
|
2445
|
+
const map = document.getElementById('map');
|
|
2446
|
+
if (state.map && state.sourcesHash !== mapHash) { mapHash = state.sourcesHash; mount(map, state.map); }
|
|
2447
|
+
else if (!state.map && state.mapError) map.replaceChildren(el('p', { className: 'empty', textContent: 'The map could not be drawn: ' + state.mapError }));
|
|
2448
|
+
// Last, so each note is placed over the pictures as they are now drawn.
|
|
2449
|
+
showMarks(state.marks);
|
|
2450
|
+
viewing(state.drawing);
|
|
2451
|
+
}
|
|
2452
|
+
|
|
2453
|
+
// What the person has in view goes to the studio, so their agent can follow
|
|
2454
|
+
// along when they say "this one".
|
|
2455
|
+
const viewing = reportViewing(body => fetch('/viewing', { method: 'POST', headers: { 'content-type': 'application/json' }, body }));
|
|
2456
|
+
|
|
2457
|
+
new EventSource('/events').addEventListener('change', () => refresh());
|
|
2458
|
+
refresh();
|
|
2459
|
+
</script>
|
|
2460
|
+
</body>
|
|
2461
|
+
</html>
|
|
2462
|
+
`;
|
|
2463
|
+
|
|
2464
|
+
// src/studio/viewing.ts
|
|
2465
|
+
import fs5 from "fs";
|
|
2466
|
+
import path5 from "path";
|
|
2467
|
+
import { z as z9 } from "zod";
|
|
2468
|
+
var PAGE_SECTIONS = ["asked", "now", "questions", "props", "happens", "sections", "map"];
|
|
2469
|
+
var Id = z9.string().min(1).max(200);
|
|
2470
|
+
var Ids = z9.array(Id).max(1e3);
|
|
2471
|
+
var Section = z9.enum(PAGE_SECTIONS);
|
|
2472
|
+
var Touched = z9.discriminatedUnion("kind", [
|
|
2473
|
+
z9.object({ kind: z9.literal("section"), id: Section }).strict(),
|
|
2474
|
+
z9.object({ kind: z9.enum(["part", "question", "property"]), id: Id }).strict()
|
|
2475
|
+
]);
|
|
2476
|
+
var Report2 = z9.object({
|
|
2477
|
+
/** The page's tab is the one in front. */
|
|
2478
|
+
shown: z9.boolean(),
|
|
2479
|
+
sections: z9.array(Section).max(PAGE_SECTIONS.length),
|
|
2480
|
+
/** Anchors of the drawn parts on screen (person.ts). */
|
|
2481
|
+
parts: Ids,
|
|
2482
|
+
questions: Ids,
|
|
2483
|
+
/** Question ids of the properties shown. */
|
|
2484
|
+
properties: Ids,
|
|
2485
|
+
/** Anchors of the folds the person opened. */
|
|
2486
|
+
open: Ids,
|
|
2487
|
+
touched: Touched.nullable(),
|
|
2488
|
+
/** The drawing the anchors belong to (person.ts), or null before one is drawn. */
|
|
2489
|
+
drawing: z9.string().max(64).nullable()
|
|
2490
|
+
}).strict();
|
|
2491
|
+
var Viewing = Report2.extend({ schemaVersion: z9.literal("yichus-viewing-1"), at: z9.string() }).strict();
|
|
2492
|
+
var viewingPath = (root) => path5.join(studioDir(root), "viewing.json");
|
|
2493
|
+
function loadViewing(root) {
|
|
2494
|
+
const file = viewingPath(root);
|
|
2495
|
+
if (!fs5.existsSync(file)) return null;
|
|
2496
|
+
const parsed = Viewing.safeParse(JSON.parse(fs5.readFileSync(file, "utf8")));
|
|
2497
|
+
if (!parsed.success) throw new Error(`${file} is not a yichus-viewing-1 file: ${z9.prettifyError(parsed.error)}`);
|
|
2498
|
+
return parsed.data;
|
|
2499
|
+
}
|
|
2500
|
+
function recordViewing(root, report, now) {
|
|
2501
|
+
const parsed = Report2.safeParse(report);
|
|
2502
|
+
if (!parsed.success) return { ok: false, error: `The page's report is not one this studio reads. ${z9.prettifyError(parsed.error)}` };
|
|
2503
|
+
ensureStudioDir(root);
|
|
2504
|
+
const file = viewingPath(root), written = `${file}.${process.pid}.tmp`;
|
|
2505
|
+
fs5.writeFileSync(written, `${JSON.stringify(Viewing.parse({ schemaVersion: "yichus-viewing-1", at: now.toISOString(), ...parsed.data }), null, 2)}
|
|
2506
|
+
`);
|
|
2507
|
+
fs5.renameSync(written, file);
|
|
2508
|
+
return { ok: true };
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
// src/studio/page-view.ts
|
|
2512
|
+
var quoted = (words, missing) => words === null ? missing : `"${words}"`;
|
|
2513
|
+
var say = (phrase) => phrase.map((p) => typeof p === "string" ? p : `"${p.theirs}"`).join("");
|
|
2514
|
+
var TICK = { holds: "\u2713", fails: "\u2717", "cannot say": "?" };
|
|
2515
|
+
var ENDING = {
|
|
2516
|
+
grey: "no expectation is false here",
|
|
2517
|
+
red: "something expected is false here",
|
|
2518
|
+
green: "an ending that was broken is fixed",
|
|
2519
|
+
unchecked: "the check cannot say"
|
|
2520
|
+
};
|
|
2521
|
+
function ago(from, now) {
|
|
2522
|
+
const seconds = Math.max(0, Math.round((now.getTime() - Date.parse(from)) / 1e3));
|
|
2523
|
+
const [n, unit] = seconds < 120 ? [seconds, "second"] : seconds < 7200 ? [Math.round(seconds / 60), "minute"] : [Math.round(seconds / 3600), "hour"];
|
|
2524
|
+
return `${n} ${unit}${n === 1 ? "" : "s"} ago`;
|
|
2525
|
+
}
|
|
2526
|
+
function pageText(root, pageUrl, now, surface) {
|
|
2527
|
+
const state = readState(root);
|
|
2528
|
+
const { description, answers, names = {} } = loadRequirements(root);
|
|
2529
|
+
const marks = loadMarks(root);
|
|
2530
|
+
const { sections, whatHappens, anchors, drawing } = state ? personDiagrams(state, names) : { sections: null, whatHappens: null, anchors: /* @__PURE__ */ new Map(), drawing: null };
|
|
2531
|
+
const codeAt = new Map([...anchors].map(([code, anchor]) => [anchor, code]));
|
|
2532
|
+
const said2 = /* @__PURE__ */ new Map();
|
|
2533
|
+
const part = (anchor, words) => {
|
|
2534
|
+
said2.set(codeAt.get(anchor), words);
|
|
2535
|
+
return `[${codeAt.get(anchor)}]`;
|
|
2536
|
+
};
|
|
2537
|
+
const out = [`The studio page${pageUrl ? ` (${pageUrl})` : ""}, as the person sees it now. Words in quotes are yours or the person's; the rest is computed. [ids] are what ${surface.name("yichus_point")} takes.`];
|
|
2538
|
+
const heading = (key) => out.push("", `## ${PAGE_HEADINGS[key]}`);
|
|
2539
|
+
out.push("", "## What the person has in view");
|
|
2540
|
+
const inView = out.length;
|
|
2541
|
+
heading("asked");
|
|
2542
|
+
out.push(description ? `"${description}"` : "Nothing yet.");
|
|
2543
|
+
heading("now");
|
|
2544
|
+
out.push(state ? state.step.summary : "No checks have run yet.");
|
|
2545
|
+
const savedOf = (id) => answers.find((a) => a.question === id);
|
|
2546
|
+
const open = (state?.properties ?? []).filter((p) => p.status === "unanswered" && !savedOf(p.question.id));
|
|
2547
|
+
if (open.length) {
|
|
2548
|
+
heading("questions");
|
|
2549
|
+
for (const { question: q } of open) out.push(`question ${q.id}: ${q.ask}`, ...q.choices.map((c) => ` - ${c.label}: ${c.means}`));
|
|
2550
|
+
}
|
|
2551
|
+
heading("props");
|
|
2552
|
+
const chosen = (state?.properties ?? []).filter((p) => p.answer || savedOf(p.question.id));
|
|
2553
|
+
const rules = state?.rules ?? [];
|
|
2554
|
+
if (!chosen.length && !rules.length) out.push("No properties chosen yet.");
|
|
2555
|
+
for (const r of rules) out.push(`A rule the person gave: "${r.rule}" Status: ${PAGE_STATUS[r.status][0]}. Checked with ${r.laws.length === 1 ? "1 law" : `${r.laws.length} laws`} you wrote.`);
|
|
2556
|
+
for (const p of chosen) {
|
|
2557
|
+
const saved = savedOf(p.question.id);
|
|
2558
|
+
const stale = saved && (!p.answer || p.answer.answeredAt !== saved.answeredAt);
|
|
2559
|
+
const answer = stale ? saved : p.answer;
|
|
2560
|
+
const label2 = p.question.choices.find((c) => c.id === answer.choice)?.label ?? answer.choice;
|
|
2561
|
+
out.push(`question ${p.question.id}: ${p.question.ask} Status: ${PAGE_STATUS[stale ? "pending" : p.status][0]}. They chose ${label2}${answer.words && answer.words !== label2 ? ` ("${answer.words}")` : ""}.`);
|
|
2562
|
+
}
|
|
2563
|
+
heading("happens");
|
|
2564
|
+
const step = (s, pad) => {
|
|
2565
|
+
if (s.kind === "outcome") {
|
|
2566
|
+
const end = `${s.refused ? "turned away" : "answered"}${s.words ? ` "${s.words}"` : ""}`;
|
|
2567
|
+
return [`${pad}${part(s.anchor, end)} ${end}: ${ENDING[s.status]}`, ...s.checks.map((c) => `${pad} ${TICK[c.verdict]} ${say(c.says)}`)];
|
|
2568
|
+
}
|
|
2569
|
+
const asks = quoted(s.words, "a check not described yet");
|
|
2570
|
+
return [`${pad}${part(s.anchor, asks)} checks ${asks}`, ...s.ways.flatMap((w) => {
|
|
2571
|
+
const words = quoted(w.words, "a way not described yet");
|
|
2572
|
+
return [`${pad} way ${words}${w.anchor === w.then.anchor ? "" : ` ${part(w.anchor, words)}`}:`, ...step(w.then, `${pad} `)];
|
|
2573
|
+
})];
|
|
2574
|
+
};
|
|
2575
|
+
if (state?.hasActions === false) out.push(NO_ACTIONS);
|
|
2576
|
+
else if (!whatHappens) out.push(state?.whatHappensError ? `It could not be drawn: ${state.whatHappensError}` : "This appears once the program compiles.");
|
|
2577
|
+
else {
|
|
2578
|
+
if (!whatHappens.actions.length && !whatHappens.waiting) out.push("The app has no actions yet.");
|
|
2579
|
+
for (const a of whatHappens.actions) {
|
|
2580
|
+
const title2 = quoted(a.title, "an action not described yet");
|
|
2581
|
+
out.push(`${part(a.anchor, title2)} ${title2}`, ...a.first ? step(a.first, " ") : [" This action could not be followed."]);
|
|
2582
|
+
}
|
|
2583
|
+
if (whatHappens.waiting) out.push(`${whatHappens.waiting} more ${whatHappens.waiting === 1 ? "action is" : "actions are"} not described yet.`);
|
|
2584
|
+
}
|
|
2585
|
+
heading("sections");
|
|
2586
|
+
const records = (verb, names2) => names2.length ? [`${verb} ${names2.map((n) => quoted(n, "a kind of record not named yet")).join(", ")}`] : [];
|
|
2587
|
+
const does = (s) => [...records("changes", s.changes), ...records("looks at", s.looks)].join(" \xB7 ") || "keeps no records itself";
|
|
2588
|
+
if (!sections) out.push("This appears once the program compiles.");
|
|
2589
|
+
else sections.forEach((layer, i) => {
|
|
2590
|
+
out.push(`layer ${i + 1} of ${sections.length}${i === 0 ? ", the top" : ""}:`);
|
|
2591
|
+
for (const s of layer) {
|
|
2592
|
+
const name = quoted(s.name, "a part not named yet");
|
|
2593
|
+
out.push(` ${part(s.anchor, name)} ${name}: ${does(s)}`);
|
|
2594
|
+
}
|
|
2595
|
+
});
|
|
2596
|
+
heading("map");
|
|
2597
|
+
if (state?.map) {
|
|
2598
|
+
const parts = nameableParts(state.map, ownPackages(state.layers));
|
|
2599
|
+
const unnamed = parts.filter((p) => !(p.code in names)).length;
|
|
2600
|
+
out.push(`The system map of the program, drawn with the person's names for ${parts.length - unnamed} of its ${parts.length} parts${unnamed === 1 ? "; the other one shows its code name" : unnamed ? `; the other ${unnamed} show their code names` : ""}. api_abstraction_map gives the map itself.`);
|
|
2601
|
+
} else out.push(state?.mapError ? `The map could not be drawn: ${state.mapError}` : "The map appears once the program compiles.");
|
|
2602
|
+
out.push("", "## Your notes on the page");
|
|
2603
|
+
const report = loadViewing(root);
|
|
2604
|
+
const viewing = report && { ...report, current: report.drawing === drawing };
|
|
2605
|
+
const visible = new Set(!viewing?.current ? [] : viewing.parts.flatMap((a) => codeAt.has(a) ? [codeAt.get(a)] : []));
|
|
2606
|
+
const notes = marks?.marks.filter((m) => anchors.has(m.at)) ?? [];
|
|
2607
|
+
if (!notes.length) out.push(`None. ${surface.name("yichus_point")} puts a note over a part of the page.`);
|
|
2608
|
+
else out.push(`Said ${ago(marks.said, now)}:`, ...notes.map((m) => ` [${m.at}] "${m.note}"${visible.has(m.at) ? " (on screen)" : ""}`));
|
|
2609
|
+
out.splice(inView, 0, ...inViewLines(viewing, codeAt, said2, now, pageUrl));
|
|
2610
|
+
return `${out.join("\n")}
|
|
2611
|
+
`;
|
|
2612
|
+
}
|
|
2613
|
+
function inViewLines(viewing, codeAt, said2, now, pageUrl) {
|
|
2614
|
+
if (!viewing) return [`The page has not said what is on screen: it may not be open. ${pageUrl ? `Give the person its link: ${pageUrl}` : "The page is not running: start `yichus studio --page` in the background in this folder, then run this again for its link."}`];
|
|
2615
|
+
const parts = (anchors) => !viewing.current ? [] : anchors.flatMap((a) => codeAt.has(a) ? [`[${codeAt.get(a)}] ${said2.get(codeAt.get(a))}`] : []);
|
|
2616
|
+
const list = (what, items) => items.length ? [`${what}:`, ...items.map((i) => ` ${i}`)] : [];
|
|
2617
|
+
const { touched } = viewing;
|
|
2618
|
+
const clicked = !touched ? [] : touched.kind === "section" ? [`Last clicked: in ${PAGE_HEADINGS[touched.id]}.`] : touched.kind === "question" ? [`Last clicked: question ${touched.id}.`] : touched.kind === "property" ? [`Last clicked: the property of question ${touched.id}.`] : parts([touched.id]).map((p) => `Last clicked: ${p}`);
|
|
2619
|
+
return [
|
|
2620
|
+
`The page said this ${ago(viewing.at, now)}. ${viewing.shown ? "Its tab is in front." : "Its tab is behind another one."}`,
|
|
2621
|
+
`On screen: ${viewing.sections.map((s) => PAGE_HEADINGS[s]).join(", ") || "nothing of the page"}.`,
|
|
2622
|
+
...viewing.current ? [] : ["The pictures have changed since, so which of their parts are in view is not known until the page redraws and says again."],
|
|
2623
|
+
...list("Parts on screen", parts(viewing.parts)),
|
|
2624
|
+
...list("Questions on screen", viewing.questions.map((q) => `question ${q}`)),
|
|
2625
|
+
...list("Properties on screen", viewing.properties.map((q) => `question ${q}`)),
|
|
2626
|
+
...list("Folds the person opened", parts(viewing.open)),
|
|
2627
|
+
...clicked
|
|
2628
|
+
];
|
|
2629
|
+
}
|
|
2630
|
+
|
|
2631
|
+
// src/studio/reference.ts
|
|
2632
|
+
import fs6 from "fs";
|
|
2633
|
+
import path6 from "path";
|
|
2634
|
+
import { fileURLToPath } from "url";
|
|
2635
|
+
|
|
2636
|
+
// src/studio/reference.json
|
|
2637
|
+
var reference_default = {
|
|
2638
|
+
guiding: {
|
|
2639
|
+
about: "How to guide the person through the studio page: what each part shows and when to bring it up.",
|
|
2640
|
+
files: [
|
|
2641
|
+
{ name: "the-page.md", from: "docs/studio/the-page.md" }
|
|
2642
|
+
]
|
|
2643
|
+
},
|
|
2644
|
+
porting: {
|
|
2645
|
+
about: "Replacing an app the person already has: reading the old app, where its entry points go, worker routes for webhooks and forms, and bringing its data over.",
|
|
2646
|
+
files: [
|
|
2647
|
+
{ name: "porting.md", from: "docs/studio/porting.md" },
|
|
2648
|
+
{ name: "worker-authority.md", from: "docs/runtime/worker-authority.md", sections: ["Worker authority in generated APIs", "Secret bootstrap"] }
|
|
2649
|
+
]
|
|
2650
|
+
},
|
|
2651
|
+
deploy: {
|
|
2652
|
+
about: "What to build for each place the app can run, with a working server, store and Render Blueprint to start from.",
|
|
2653
|
+
files: [
|
|
2654
|
+
{ name: "deploy-platforms.md", from: "docs/studio/deploy-platforms.md" },
|
|
2655
|
+
{ name: "server.mjs", from: "docs/studio/deploy-example/server.mjs" },
|
|
2656
|
+
{ name: "store.mjs", from: "docs/studio/deploy-example/store.mjs" },
|
|
2657
|
+
{ name: "render.yaml", from: "docs/studio/deploy-example/render.yaml" }
|
|
2658
|
+
]
|
|
2659
|
+
},
|
|
2660
|
+
laws: {
|
|
2661
|
+
about: "Writing a rule the person stated as a law the studio checks, and the standard functions the language has.",
|
|
2662
|
+
files: [
|
|
2663
|
+
{ name: "laws.md", from: "docs/studio/laws.md" },
|
|
2664
|
+
{ name: "consent.bosatsu", from: "docs/studio/laws-example/consent.bosatsu" },
|
|
2665
|
+
{ name: "consent-laws.bosatsu", from: "docs/studio/laws-example/consent-laws.bosatsu" },
|
|
2666
|
+
{ name: "balance.bosatsu", from: "docs/studio/laws-example/limits/balance.bosatsu" },
|
|
2667
|
+
{ name: "balance-listed-laws.bosatsu", from: "docs/studio/laws-example/limits/balance-listed-laws.bosatsu" }
|
|
2668
|
+
]
|
|
2669
|
+
},
|
|
2670
|
+
"portable-programs": {
|
|
2671
|
+
about: "Work that takes several steps or waits on an outside service, written as one pure step program a rule-free engine drives.",
|
|
2672
|
+
files: [
|
|
2673
|
+
{ name: "portable-programs.md", from: "docs/studio/portable-programs.md" },
|
|
2674
|
+
{ name: "refund-policy.bosatsu", from: "demos/portable/refund-policy.bosatsu" },
|
|
2675
|
+
{ name: "refund-desk.bosatsu", from: "demos/portable/refund-desk.bosatsu" },
|
|
2676
|
+
{ name: "refund-test.bosatsu", from: "demos/portable/refund-test.bosatsu" },
|
|
2677
|
+
{ name: "refund-desk-one-round.bosatsu", from: "demos/portable/limits/refund-desk-one-round.bosatsu" }
|
|
2678
|
+
]
|
|
2679
|
+
},
|
|
2680
|
+
"protocol-case": {
|
|
2681
|
+
about: "The failure scenarios the studio checks for an action that must be all or nothing, or must survive an outside service failing: the case format and a complete worked case.",
|
|
2682
|
+
files: [
|
|
2683
|
+
{ name: "protocol-cases.md", from: "docs/studio/protocol-cases.md" },
|
|
2684
|
+
{ name: "protocol-specification.md", from: "docs/protocol-verification.md", sections: ["Case format: protocol-case-1.0", "Observation predicates", "Trace assertions", "Reachability witnesses", "Interpretation and limits"] },
|
|
2685
|
+
{ name: "withdrawal-case.json", from: "eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/case.json" },
|
|
2686
|
+
{ name: "withdrawal.bosatsu", from: "eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/ledger.bosatsu" }
|
|
2687
|
+
]
|
|
2688
|
+
},
|
|
2689
|
+
calculator: {
|
|
2690
|
+
about: "A calculation that keeps no records (a calculator, a quote): what the studio checks for it, and putting it on a page with Why on every number.",
|
|
2691
|
+
files: [
|
|
2692
|
+
{ name: "calculator.md", from: "docs/studio/calculator.md" }
|
|
2693
|
+
]
|
|
2694
|
+
}
|
|
2695
|
+
};
|
|
2696
|
+
|
|
2697
|
+
// src/studio/reference.ts
|
|
2698
|
+
var TOPICS = Object.keys(reference_default);
|
|
2699
|
+
var BUILT_REFERENCE = fileURLToPath(new URL("./studio-reference/", import.meta.url));
|
|
2700
|
+
var REPO_ROOT = fileURLToPath(new URL("../../../../", import.meta.url));
|
|
2701
|
+
var builtCopy = (file) => path6.join(BUILT_REFERENCE, file.name);
|
|
2702
|
+
function sectionsOf(text3, titles) {
|
|
2703
|
+
const lines = text3.split("\n");
|
|
2704
|
+
let fenced = false;
|
|
2705
|
+
const headings = lines.map((line) => {
|
|
2706
|
+
if (line.startsWith("```")) fenced = !fenced;
|
|
2707
|
+
const match = fenced ? null : /^(#+) (.*)$/.exec(line);
|
|
2708
|
+
return match ? { level: match[1].length, title: match[2] } : null;
|
|
2709
|
+
});
|
|
2710
|
+
const parts = titles.map((title2) => {
|
|
2711
|
+
const start = headings.findIndex((h) => h?.title === title2);
|
|
2712
|
+
if (start < 0) throw new Error(`No section "${title2}" in the reference file`);
|
|
2713
|
+
const level = Math.max(headings[start].level, 2);
|
|
2714
|
+
const end = headings.findIndex((h, i) => i > start && h !== null && h.level <= level);
|
|
2715
|
+
return lines.slice(start, end < 0 ? void 0 : end).join("\n").trim();
|
|
2716
|
+
});
|
|
2717
|
+
return `${parts.join("\n\n")}
|
|
2718
|
+
`;
|
|
2719
|
+
}
|
|
2720
|
+
var topicList = (ask) => ["Reference topics:", ...TOPICS.map((topic) => ` ${topic}: ${reference_default[topic].about} (${ask(topic)})`)].join("\n");
|
|
2721
|
+
function readReference(topic, locate) {
|
|
2722
|
+
if (!TOPICS.includes(topic)) return null;
|
|
2723
|
+
return reference_default[topic].files.map((file) => {
|
|
2724
|
+
const text3 = fs6.readFileSync(locate(file), "utf8");
|
|
2725
|
+
return `===== ${file.name} =====
|
|
2726
|
+
${file.sections ? sectionsOf(text3, file.sections) : text3}`;
|
|
2727
|
+
}).join("\n\n");
|
|
2728
|
+
}
|
|
2729
|
+
|
|
2730
|
+
// src/studio/text.ts
|
|
2731
|
+
var STATUS_WORDS = {
|
|
2732
|
+
unanswered: "not answered yet",
|
|
2733
|
+
decided: "decided",
|
|
2734
|
+
assumed: "holds under an assumption",
|
|
2735
|
+
proven: "proven",
|
|
2736
|
+
bounded: "holds in every scenario checked",
|
|
2737
|
+
broken: "broken",
|
|
2738
|
+
mismatch: "declared differently from the answer",
|
|
2739
|
+
"needs-case": "needs a failure scenario",
|
|
2740
|
+
"needs-law": "needs a law that checks it",
|
|
2741
|
+
unused: "checked, but no action of the app uses what the law checks",
|
|
2742
|
+
inconclusive: "not decided by the check",
|
|
2743
|
+
"no-check": "no check needed"
|
|
2744
|
+
};
|
|
2745
|
+
function stepText(state, pageUrl) {
|
|
2746
|
+
const { step } = state;
|
|
2747
|
+
const lines = [`Stage: ${step.stage}. ${step.summary}`, "", "Do this:", ...step.instructions.map((s, i) => `${i + 1}. ${s}`)];
|
|
2748
|
+
if (step.items) lines.push("", `${step.items.heading}:`, ...step.items.lines.map((l) => ` ${l}`));
|
|
2749
|
+
for (const q of step.ask ?? []) {
|
|
2750
|
+
lines.push("", `Question ${q.id}: ${q.ask}`, ` Why it matters: ${q.why}`);
|
|
2751
|
+
for (const c of q.choices) lines.push(` - ${c.id}: ${c.label}. ${c.means}`);
|
|
2752
|
+
}
|
|
2753
|
+
if (step.evidence?.length) lines.push("", "Evidence (engine output):", ...step.evidence.map((e) => ` ${e}`));
|
|
2754
|
+
const answered = state.properties.filter((p) => p.status !== "unanswered");
|
|
2755
|
+
if (answered.length) {
|
|
2756
|
+
lines.push("", "Properties:");
|
|
2757
|
+
for (const p of answered) {
|
|
2758
|
+
const choice = p.question.choices.find((c) => c.id === p.answer?.choice)?.label ?? p.answer?.choice;
|
|
2759
|
+
lines.push(` ${p.question.id} (${choice}): ${STATUS_WORDS[p.status]}`);
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
if (state.rules.length) {
|
|
2763
|
+
lines.push("", "Rules the person stated:");
|
|
2764
|
+
for (const r of state.rules) lines.push(` "${r.rule}" (${r.laws.join(", ")}): ${STATUS_WORDS[r.status]}`);
|
|
2765
|
+
}
|
|
2766
|
+
if (pageUrl) lines.push("", `Studio page: ${pageUrl}`);
|
|
2767
|
+
return `${lines.join("\n")}
|
|
2768
|
+
`;
|
|
2769
|
+
}
|
|
2770
|
+
|
|
2771
|
+
// src/studio/mcp.ts
|
|
2772
|
+
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 checks the properties the person's answers set, and the rules they state become laws it checks.
|
|
2773
|
+
|
|
2774
|
+
Why this is worth it to them: they cannot read your code or your tests, so the studio's checks, run again after every change, are their evidence instead of your word. The cost is a less common language that you maintain, on Yichus's MIT-licensed engine and a host they pick; porting in or out is cheap with you doing it. When they ask whether it is worth it, or the app keeps no records (a calculator), answer from yichus_reference topic "guiding", "Is this worth it?".
|
|
2775
|
+
|
|
2776
|
+
The loop:
|
|
2777
|
+
1. Ask the person what they want built and call yichus_start with their words. If it replaces an app they already have, read yichus_reference topic "porting" first: reading the old app is yours, and the studio sees only the new one.
|
|
2778
|
+
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.
|
|
2779
|
+
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.
|
|
2780
|
+
4. Never weaken a rule, delete a check or a law, or declare a single server to make a check pass. Change the code. Each rule the person states about what the app must always or never do becomes a law the studio runs; yichus_next asks you to record them with yichus_rules.
|
|
2781
|
+
5. Give the person the studio page link from yichus_start, if their browser can reach it (it says when it cannot). It shows the shape of their program, what happens in each thing it does, and whether each property they chose holds. The person reads no documentation: everything they need to know about the steps, the questions, the statuses and the pictures comes from you, a little at a time as it becomes relevant. Read yichus_reference topic "guiding" before you give them the link.
|
|
2782
|
+
6. Speak to the person in product terms. They never need code names, file names, tool names or question ids. Name the language only if they ask, but tell them the trade-off of a less common language. When yichus_next asks you to name parts of the program or describe what happens, use the words they would use.
|
|
2783
|
+
7. Build only what the person asked for. A calculation that keeps no records needs no server, database or sign-in (yichus_reference topic "calculator"). An app that keeps records runs as a server, and is the same program wherever it runs. The studio asks where once the program has records or actions, and yichus_reference topic "deploy" says how to put it online there. Keep every business decision in pure code: work that takes several steps or waits on outside services is one pure step program that a rule-free engine drives (yichus_reference topic "portable-programs").
|
|
2784
|
+
8. While you talk with the person, point at what you mean on the studio page with yichus_point: a section of their app, an action, or a step in one, with a sentence or two as you would say it in the chat. The page shows each note over the pictures as yours, not checked, so never use a note to say something holds; the checks say that. Point again as the conversation moves on, and clear the marks when they no longer help.
|
|
2785
|
+
9. You drive the conversation, and the person reads the studio page while you talk. Call yichus_page to see what the page shows them, in words: what they asked for, the questions, each property with its status, what happens in each action, the sections of their app, your notes, and what they have on screen and last clicked. Call it whenever they refer to something on the page ("this one", "the red one", "what does that mean"), and after they answer on the page.
|
|
2786
|
+
|
|
2787
|
+
Every api_* tool is available too. Leave out sources and the studio supplies the project's files. Pages on yich.us, such as calculators and the playground, come through a separate connection (@yichus/mcp); building needs only this one.`;
|
|
2788
|
+
var START = {
|
|
2789
|
+
name: "yichus_start",
|
|
2790
|
+
description: "Record what the person wants built, in their own words, and get the studio page link to give them. Call this first.",
|
|
2791
|
+
inputSchema: { type: "object", properties: { description: { type: "string", description: "The person's description of the software, unchanged." } }, required: ["description"] }
|
|
2792
|
+
};
|
|
2793
|
+
var NEXT = {
|
|
2794
|
+
name: "yichus_next",
|
|
2795
|
+
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.",
|
|
2796
|
+
inputSchema: { type: "object", properties: {} }
|
|
2797
|
+
};
|
|
2798
|
+
var ANSWER = {
|
|
2799
|
+
name: "yichus_answer",
|
|
2800
|
+
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.",
|
|
2801
|
+
inputSchema: { type: "object", properties: {
|
|
2802
|
+
question: { type: "string", description: "The question id from yichus_next." },
|
|
2803
|
+
choice: { type: "string", description: "The id of the choice the person picked." },
|
|
2804
|
+
words: { type: "string", description: "What the person said, in their words." }
|
|
2805
|
+
}, required: ["question", "choice", "words"] }
|
|
2806
|
+
};
|
|
2807
|
+
var NAME = {
|
|
2808
|
+
name: "yichus_name",
|
|
2809
|
+
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.",
|
|
2810
|
+
inputSchema: { type: "object", properties: {
|
|
2811
|
+
names: {
|
|
2812
|
+
type: "object",
|
|
2813
|
+
additionalProperties: { type: "string" },
|
|
2814
|
+
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".`
|
|
2815
|
+
}
|
|
2816
|
+
}, required: ["names"] }
|
|
2817
|
+
};
|
|
2818
|
+
var SCENARIO = {
|
|
2819
|
+
name: "yichus_scenario",
|
|
2820
|
+
description: "Record what should happen in actions yichus_next listed, in the person's words: a title, names for the ids the engine computed, and claims the engine checks on each outcome. A scenario replaces any earlier one for the same action. drop removes the scenario of an action the app no longer has.",
|
|
2821
|
+
inputSchema: { type: "object", properties: {
|
|
2822
|
+
scenarios: { type: "array", items: { type: "object", properties: {
|
|
2823
|
+
entry: { type: "string", description: "The action, as yichus_next listed it (route:/path)." },
|
|
2824
|
+
title: { type: "string", description: "What the person does, in their words." },
|
|
2825
|
+
names: { type: "object", additionalProperties: { type: "string" }, description: "Each id yichus_next listed under the action, with the person's words for it." },
|
|
2826
|
+
expect: {
|
|
2827
|
+
type: "array",
|
|
2828
|
+
items: { type: "object", properties: { at: { type: "string" }, claim: { type: "string" } }, required: ["at", "claim"] },
|
|
2829
|
+
description: "What must and must not happen: [not] reads TABLE, writes TABLE, refused, returns CONSTRUCTOR, reaches model or reaches net, at an id."
|
|
2830
|
+
}
|
|
2831
|
+
}, required: ["entry", "title", "names", "expect"] } },
|
|
2832
|
+
drop: { type: "array", items: { type: "string" }, description: "Actions yichus_next reports the app no longer has, whose scenarios to remove." }
|
|
2833
|
+
} }
|
|
2834
|
+
};
|
|
2835
|
+
var RULES = {
|
|
2836
|
+
name: "yichus_rules",
|
|
2837
|
+
description: "Record the rules the person stated about what the app must always or never do, in their words, each with the laws (Yichus/Law) in the program that check it. A call replaces the whole list; an empty list says they stated none.",
|
|
2838
|
+
inputSchema: { type: "object", properties: {
|
|
2839
|
+
rules: { type: "array", items: { type: "object", properties: {
|
|
2840
|
+
rule: { type: "string", description: "The rule, in the person's words." },
|
|
2841
|
+
laws: { type: "array", items: { type: "string" }, description: "The laws that check it: each a law binding's name, or the name the Law gives itself." }
|
|
2842
|
+
}, required: ["rule", "laws"] } }
|
|
2843
|
+
}, required: ["rules"] }
|
|
2844
|
+
};
|
|
2845
|
+
var POINT = {
|
|
2846
|
+
name: "yichus_point",
|
|
2847
|
+
description: "Point at parts of the studio page while you talk with the person: each mark puts your short note over the picture, next to a section of their app, an action, or a step in one, marked as your words and not checked. A call replaces the marks before it; an empty list clears them.",
|
|
2848
|
+
inputSchema: { type: "object", properties: {
|
|
2849
|
+
marks: { type: "array", items: { type: "object", properties: {
|
|
2850
|
+
at: { type: "string", description: "What to point at: a section by its code name as yichus_name took it, an action yichus_scenario described (route:/path), or an id yichus_next listed under a described action." },
|
|
2851
|
+
note: { type: "string", description: "What you are saying about it, in the person's words, at most 280 characters." }
|
|
2852
|
+
}, required: ["at", "note"] } }
|
|
2853
|
+
}, required: ["marks"] }
|
|
2854
|
+
};
|
|
2855
|
+
var PAGE = {
|
|
2856
|
+
name: "yichus_page",
|
|
2857
|
+
description: "See the studio page as the person sees it now, in words, with the id yichus_point takes for each part: the questions, each property and its status, what happens in each action, the sections of their app and your notes. Also what the person has on screen, the folds they opened and what they last clicked. Call it when the person refers to something on the page.",
|
|
2858
|
+
inputSchema: { type: "object", properties: {} }
|
|
2859
|
+
};
|
|
2860
|
+
var REFERENCE_TOOL = {
|
|
2861
|
+
name: "yichus_reference",
|
|
2862
|
+
description: `Reference material yichus_next asks for. ${TOPICS.map((t) => `${t}: ${reference_default[t].about}`).join(" ")}`,
|
|
2863
|
+
inputSchema: { type: "object", properties: { topic: { type: "string", enum: TOPICS, description: "The topic yichus_next named." } }, required: ["topic"] }
|
|
2864
|
+
};
|
|
2865
|
+
var StartArgs = z10.object({ description: z10.string().min(1) }).strict();
|
|
2866
|
+
var AnswerArgs = z10.object({ question: z10.string().min(1), choice: z10.string().min(1), words: z10.string() }).strict();
|
|
2867
|
+
var ScenarioInput = z10.object({
|
|
2868
|
+
entry: z10.string().min(1),
|
|
2869
|
+
title: z10.string().trim().min(1),
|
|
2870
|
+
names: z10.record(z10.string().min(1), z10.string().trim().min(1)),
|
|
2871
|
+
expect: z10.array(z10.object({ at: z10.string().min(1), claim: z10.string().trim().min(1) }).strict())
|
|
2872
|
+
}).strict();
|
|
2873
|
+
var ScenarioArgs = z10.object({ scenarios: z10.array(ScenarioInput).default([]), drop: z10.array(z10.string().min(1)).default([]) }).refine((a) => a.scenarios.length + a.drop.length > 0, "give at least one scenario or one action to drop");
|
|
2874
|
+
var RulesArgs = z10.object({ rules: z10.array(RuleRecord) }).strict();
|
|
2875
|
+
var NameArgs = z10.object({ names: z10.record(z10.string().min(1), z10.string().trim().min(1)).refine((names) => Object.keys(names).length > 0) });
|
|
2876
|
+
var text = (body, structured, isError = false) => ({ content: [{ type: "text", text: body }], ...structured ? { structuredContent: structured } : {}, isError });
|
|
2877
|
+
function studioTool(tool) {
|
|
2878
|
+
const schema = tool.inputSchema;
|
|
2879
|
+
if (!schema.properties || !("sources" in schema.properties)) return tool;
|
|
2880
|
+
return {
|
|
2881
|
+
...tool,
|
|
2882
|
+
description: [tool.description, "In the studio, leave out sources to check every .bosatsu file in the project folder."].filter(Boolean).join(" "),
|
|
2883
|
+
inputSchema: { ...schema, required: (schema.required ?? []).filter((name) => name !== "sources") }
|
|
2884
|
+
};
|
|
2885
|
+
}
|
|
2886
|
+
function recordStart(root, args, say2 = MCP) {
|
|
2887
|
+
const parsed = StartArgs.safeParse(args);
|
|
2888
|
+
if (!parsed.success) return { ok: false, error: `${say2.name("yichus_start")} needs the person's description, and nothing else. ${z10.prettifyError(parsed.error)}` };
|
|
2889
|
+
saveRequirements(root, { ...loadRequirements(root), description: parsed.data.description });
|
|
2890
|
+
return { ok: true };
|
|
2891
|
+
}
|
|
2892
|
+
function recordAnswer(root, args, now, say2 = MCP) {
|
|
2893
|
+
const parsed = AnswerArgs.safeParse(args);
|
|
2894
|
+
if (!parsed.success) return { ok: false, error: `${say2.name("yichus_answer")} needs question, choice and words, and nothing else. ${z10.prettifyError(parsed.error)}` };
|
|
2895
|
+
const state = readState(root);
|
|
2896
|
+
const property = state?.properties.find((p) => p.question.id === parsed.data.question);
|
|
2897
|
+
if (!property) return { ok: false, error: `No question ${parsed.data.question} in the latest ${say2.name("yichus_next")}; ${say2.use("yichus_next")} and use its ids.` };
|
|
2898
|
+
if (!property.question.choices.some((c) => c.id === parsed.data.choice)) {
|
|
2899
|
+
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(", ")}.` };
|
|
2900
|
+
}
|
|
2901
|
+
saveRequirements(root, withAnswer(loadRequirements(root), { ...parsed.data, answeredAt: now.toISOString() }));
|
|
2902
|
+
return { ok: true };
|
|
2903
|
+
}
|
|
2904
|
+
function recordNames(root, args, say2 = MCP) {
|
|
2905
|
+
const parsed = NameArgs.safeParse(args);
|
|
2906
|
+
if (!parsed.success) return { ok: false, error: `${say2.name("yichus_name")} needs names: each code name ${say2.name("yichus_next")} listed, with its plain name.` };
|
|
2907
|
+
const state = readState(root);
|
|
2908
|
+
const parts = /* @__PURE__ */ new Set([...state?.properties.flatMap((p) => p.question.subject ?? []) ?? [], ...state ? drawnParts(state).map((p) => p.code) : []]);
|
|
2909
|
+
const unknown = Object.keys(parsed.data.names).filter((code) => !parts.has(code));
|
|
2910
|
+
if (unknown.length) {
|
|
2911
|
+
const listed = [...parts].slice(0, 20).join(", ") + (parts.size > 20 ? `, and ${parts.size - 20} more` : "");
|
|
2912
|
+
const changed = state && state.sourcesHash !== sourcesHash(projectSources(root)) ? ` The program changed since then: ${say2.use("yichus_next")} first.` : "";
|
|
2913
|
+
return { ok: false, error: `No part named ${unknown.join(", ")} in the latest ${say2.name("yichus_next")}; the parts are ${listed || "none yet"}.${changed}` };
|
|
2914
|
+
}
|
|
2915
|
+
saveRequirements(root, withNames(loadRequirements(root), parsed.data.names));
|
|
2916
|
+
return { ok: true };
|
|
2917
|
+
}
|
|
2918
|
+
function recordScenarios(root, args, say2 = MCP) {
|
|
2919
|
+
const parsed = ScenarioArgs.safeParse(args);
|
|
2920
|
+
if (!parsed.success) return { ok: false, error: `${say2.name("yichus_scenario")} needs scenarios, each with entry, title, names and expect, or drop. ${z10.prettifyError(parsed.error)}` };
|
|
2921
|
+
const happens = readState(root)?.whatHappens;
|
|
2922
|
+
const entries = new Set(happens?.entries.map((e) => e.entry) ?? []);
|
|
2923
|
+
const unknown = parsed.data.scenarios.map((s) => s.entry).filter((e) => !entries.has(e));
|
|
2924
|
+
if (unknown.length) return { ok: false, error: `No action ${unknown.join(", ")} in the latest ${say2.name("yichus_next")}; the actions are ${[...entries].join(", ") || "none yet"}.` };
|
|
2925
|
+
const gone = new Set(happens?.mismatches.map((m) => m.entry));
|
|
2926
|
+
const kept = parsed.data.drop.filter((e) => !gone.has(e));
|
|
2927
|
+
if (kept.length) return { ok: false, error: `The latest ${say2.name("yichus_next")} does not report ${kept.join(", ")} as gone, so its scenario stays. Only an action the app no longer has can be dropped; replace the scenario of one it still has.` };
|
|
2928
|
+
saveRequirements(root, withScenarios(loadRequirements(root), parsed.data.scenarios, parsed.data.drop));
|
|
2929
|
+
return { ok: true };
|
|
2930
|
+
}
|
|
2931
|
+
function recordRules(root, args, say2 = MCP) {
|
|
2932
|
+
const parsed = RulesArgs.safeParse(args);
|
|
2933
|
+
if (!parsed.success) return { ok: false, error: `${say2.name("yichus_rules")} needs rules: a list of {"rule": the person's words, "laws": [law names]}, empty if they stated none. ${z10.prettifyError(parsed.error)}` };
|
|
2934
|
+
const laws = readState(root)?.laws ?? [];
|
|
2935
|
+
const known = (ref) => laws.some((l) => l.binding === ref || l.binding.endsWith(`::${ref}`) || l.name === ref);
|
|
2936
|
+
const unknown = [...new Set(parsed.data.rules.flatMap((r) => r.laws).filter((ref) => !known(ref)))];
|
|
2937
|
+
if (unknown.length) {
|
|
2938
|
+
const listed = laws.map((l) => l.binding.slice(l.binding.lastIndexOf("::") + 2)).join(", ");
|
|
2939
|
+
return { ok: false, error: `No law named ${unknown.join(", ")} in the latest ${say2.name("yichus_next")}; the laws are ${listed || "none yet"}. Write the law, ${say2.use("yichus_next")}, then record the rules.` };
|
|
2940
|
+
}
|
|
2941
|
+
saveRequirements(root, { ...loadRequirements(root), rules: parsed.data.rules });
|
|
2942
|
+
return { ok: true };
|
|
2943
|
+
}
|
|
2944
|
+
function pageNote(pageUrl, say2) {
|
|
2945
|
+
const elsewhere = `If the person's browser is elsewhere (you run in a cloud container or on another computer), tell them the page is not reachable from there, and describe it to them with ${say2.name("yichus_page")}.`;
|
|
2946
|
+
if (!pageUrl) return [
|
|
2947
|
+
`The studio page is not running yet. Start it in the background in this folder with \`yichus studio --page\` and leave it running; ${say2.name("yichus_start")}, ${say2.name("yichus_next")} and ${say2.name("yichus_page")} then give its link. It opens only in a browser on the computer it runs on.`,
|
|
2948
|
+
`${elsewhere} Before you give them the link, ${say2.reference("guiding")}.`
|
|
2949
|
+
].join("\n");
|
|
2950
|
+
return [
|
|
2951
|
+
`Read the "guiding" reference (${say2.reference("guiding")}), then give the person this link and ask them to keep it open: ${pageUrl}`,
|
|
2952
|
+
`It opens only in a browser on the computer the studio runs on. ${elsewhere}`
|
|
2953
|
+
].join("\n");
|
|
2954
|
+
}
|
|
2955
|
+
function createStudioMcpServer({ root, engine, catalog, pageUrl, now = () => /* @__PURE__ */ new Date(), locate = builtCopy }) {
|
|
2956
|
+
const server = new Server({ name: "yichus-studio", version: "0.3.1" }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
2957
|
+
const active = /* @__PURE__ */ new Set();
|
|
2958
|
+
const track = (task) => {
|
|
2959
|
+
active.add(task);
|
|
2960
|
+
void task.finally(() => active.delete(task)).catch(() => {
|
|
2961
|
+
});
|
|
2962
|
+
return task;
|
|
2963
|
+
};
|
|
2964
|
+
let tools = null;
|
|
2965
|
+
const catalogTools2 = async () => tools ??= (await catalog()).map(studioTool);
|
|
2966
|
+
let last = readState(root);
|
|
2967
|
+
server.setRequestHandler(ListToolsRequestSchema, () => track((async () => ({ tools: [START, NEXT, NAME, ANSWER, RULES, SCENARIO, POINT, PAGE, REFERENCE_TOOL, ...await catalogTools2()] }))()));
|
|
2968
|
+
server.setRequestHandler(CallToolRequestSchema, (request) => track(callTool(request.params)));
|
|
2969
|
+
async function callTool(params) {
|
|
2970
|
+
const { name, arguments: args = {} } = params;
|
|
2971
|
+
if (name === "yichus_start") {
|
|
2972
|
+
const result2 = recordStart(root, args);
|
|
2973
|
+
if (!result2.ok) return text(result2.error, void 0, true);
|
|
2974
|
+
return text(`${pageNote(pageUrl, MCP)}
|
|
2975
|
+
If this replaces an app the person already has, read yichus_reference topic "porting" first.
|
|
2976
|
+
Next: call yichus_next.`, { pageUrl });
|
|
2977
|
+
}
|
|
2978
|
+
if (name === "yichus_next") {
|
|
2979
|
+
last = await direct({ root, engine, requirements: loadRequirements(root), previous: last });
|
|
2980
|
+
const { map: _map, layers: _layers, whatHappens: _whatHappens, ...rest } = last;
|
|
2981
|
+
return text(stepText(last, pageUrl), rest);
|
|
2982
|
+
}
|
|
2983
|
+
if (name === "yichus_answer") {
|
|
2984
|
+
const result2 = recordAnswer(root, args, now());
|
|
2985
|
+
return result2.ok ? text("Recorded. Ask any remaining questions, then call yichus_next.") : text(result2.error, void 0, true);
|
|
2986
|
+
}
|
|
2987
|
+
if (name === "yichus_name") {
|
|
2988
|
+
const result2 = recordNames(root, args);
|
|
2989
|
+
return result2.ok ? text("Recorded. Call yichus_next.") : text(result2.error, void 0, true);
|
|
2990
|
+
}
|
|
2991
|
+
if (name === "yichus_rules") {
|
|
2992
|
+
const result2 = recordRules(root, args);
|
|
2993
|
+
return result2.ok ? text("Recorded. Call yichus_next: it runs every law and says how each rule stands.") : text(result2.error, void 0, true);
|
|
2994
|
+
}
|
|
2995
|
+
if (name === "yichus_scenario") {
|
|
2996
|
+
const result2 = recordScenarios(root, args);
|
|
2997
|
+
return result2.ok ? text("Recorded. Call yichus_next: the engine checks every name and claim.") : text(result2.error, void 0, true);
|
|
2998
|
+
}
|
|
2999
|
+
if (name === "yichus_point") {
|
|
3000
|
+
const result2 = recordMarks(root, args, now());
|
|
3001
|
+
return result2.ok ? text("The page shows your notes now. Go on talking with the person.") : text(result2.error, void 0, true);
|
|
3002
|
+
}
|
|
3003
|
+
if (name === "yichus_page") {
|
|
3004
|
+
if (Object.keys(args).length) return text("yichus_page takes no arguments.", void 0, true);
|
|
3005
|
+
return text(pageText(root, pageUrl, now(), MCP));
|
|
3006
|
+
}
|
|
3007
|
+
if (name === "yichus_reference") {
|
|
3008
|
+
const said2 = readReference(String(args.topic), locate);
|
|
3009
|
+
return said2 ? text(said2) : text(`No reference topic ${String(args.topic)}.
|
|
3010
|
+
${topicList((topic) => `topic "${topic}"`)}`, void 0, true);
|
|
3011
|
+
}
|
|
3012
|
+
const tool = (await catalogTools2()).find((t) => t.name === name);
|
|
3013
|
+
if (!tool) return text(`Unknown tool ${name}.`, void 0, true);
|
|
3014
|
+
const filled = { ...args };
|
|
3015
|
+
const props = tool.inputSchema.properties ?? {};
|
|
3016
|
+
if ("sources" in props && filled.sources === void 0) {
|
|
3017
|
+
filled.sources = name === "api_protocol_check" ? [...projectSources(root), ...caseSources(root)] : projectSources(root);
|
|
3018
|
+
}
|
|
3019
|
+
const topology2 = loadRequirements(root).answers.find((a) => a.question === "topology")?.choice;
|
|
3020
|
+
if ("instances" in props && filled.instances === void 0 && topology2) filled.instances = topology2 === "one" ? "1" : "many";
|
|
3021
|
+
const result = await engine.call(name, filled);
|
|
3022
|
+
if (name === "api_guide" && filled.section === void 0 && Array.isArray(result.sections)) {
|
|
3023
|
+
const titles = {
|
|
3024
|
+
ok: true,
|
|
3025
|
+
tool: "api_guide",
|
|
3026
|
+
titles: result.sections.map((s) => s.title),
|
|
3027
|
+
note: "The whole guide is long. Call api_guide with section set to one of these titles, or to part of one."
|
|
3028
|
+
};
|
|
3029
|
+
return text(JSON.stringify(titles), titles);
|
|
3030
|
+
}
|
|
3031
|
+
return text(JSON.stringify(result), result, result.ok !== true);
|
|
3032
|
+
}
|
|
3033
|
+
return {
|
|
3034
|
+
server,
|
|
3035
|
+
async idle() {
|
|
3036
|
+
while (active.size) await Promise.allSettled(active);
|
|
3037
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
3038
|
+
}
|
|
3039
|
+
};
|
|
3040
|
+
}
|
|
3041
|
+
|
|
3042
|
+
// src/studio/page-link.ts
|
|
3043
|
+
import fs7 from "fs";
|
|
3044
|
+
import path7 from "path";
|
|
3045
|
+
import { z as z11 } from "zod";
|
|
3046
|
+
var PageLink = z11.object({
|
|
3047
|
+
schemaVersion: z11.literal("yichus-page-2"),
|
|
3048
|
+
url: z11.string().url(),
|
|
3049
|
+
pid: z11.number().int().positive(),
|
|
3050
|
+
startedAt: z11.number().int().nonnegative()
|
|
3051
|
+
}).strict();
|
|
3052
|
+
var pagesDir = (root) => path7.join(studioDir(root), "pages");
|
|
3053
|
+
var linkPath = (root, url, pid) => path7.join(pagesDir(root), `${pid}-${new URL(url).port}.json`);
|
|
3054
|
+
function writePageLink(root, url, pid = process.pid, startedAt = Date.now()) {
|
|
3055
|
+
ensureStudioDir(root);
|
|
3056
|
+
fs7.mkdirSync(pagesDir(root), { recursive: true });
|
|
3057
|
+
fs7.rmSync(path7.join(studioDir(root), "page.json"), { force: true });
|
|
3058
|
+
const port = new URL(url).port;
|
|
3059
|
+
for (const { file: file2, link } of liveLinks(root)) if (new URL(link.url).port === port) fs7.rmSync(file2, { force: true });
|
|
3060
|
+
const file = linkPath(root, url, pid), written = `${file}.tmp`;
|
|
3061
|
+
fs7.writeFileSync(written, `${JSON.stringify(PageLink.parse({ schemaVersion: "yichus-page-2", url, pid, startedAt }), null, 2)}
|
|
3062
|
+
`);
|
|
3063
|
+
fs7.renameSync(written, file);
|
|
3064
|
+
}
|
|
3065
|
+
function clearPageLink(root, url, pid = process.pid) {
|
|
3066
|
+
fs7.rmSync(linkPath(root, url, pid), { force: true });
|
|
3067
|
+
}
|
|
3068
|
+
var running = (pid) => {
|
|
3069
|
+
try {
|
|
3070
|
+
process.kill(pid, 0);
|
|
3071
|
+
return true;
|
|
3072
|
+
} catch (error) {
|
|
3073
|
+
return error.code === "EPERM";
|
|
3074
|
+
}
|
|
3075
|
+
};
|
|
3076
|
+
function liveLinks(root) {
|
|
3077
|
+
const dir = pagesDir(root);
|
|
3078
|
+
if (!fs7.existsSync(dir)) return [];
|
|
3079
|
+
return fs7.readdirSync(dir).filter((name) => name.endsWith(".json")).flatMap((name) => {
|
|
3080
|
+
const file = path7.join(dir, name);
|
|
3081
|
+
let raw;
|
|
3082
|
+
try {
|
|
3083
|
+
raw = JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
3084
|
+
} catch {
|
|
3085
|
+
raw = null;
|
|
3086
|
+
}
|
|
3087
|
+
const parsed = PageLink.safeParse(raw);
|
|
3088
|
+
if (parsed.success && running(parsed.data.pid)) return [{ file, link: parsed.data }];
|
|
3089
|
+
fs7.rmSync(file, { force: true });
|
|
3090
|
+
return [];
|
|
3091
|
+
});
|
|
3092
|
+
}
|
|
3093
|
+
function runningPageUrl(root) {
|
|
3094
|
+
const live = liveLinks(root).map(({ link }) => link);
|
|
3095
|
+
return live.length ? live.reduce((a, b) => b.startedAt > a.startedAt ? b : a).url : null;
|
|
3096
|
+
}
|
|
3097
|
+
|
|
3098
|
+
// src/studio/command.ts
|
|
3099
|
+
var STUDIO_COMMANDS = /* @__PURE__ */ new Set(["start", "next", "name", "answer", "rules", "scenario", "point", "page", "reference", "studio"]);
|
|
3100
|
+
var STUDIO_HELP = `
|
|
3101
|
+
Studio (guided building; all take --project DIR, default the current folder).
|
|
3102
|
+
Keep the project in a folder of its own, apart from any old app it replaces:
|
|
3103
|
+
the studio reads every .bosatsu file in it.
|
|
3104
|
+
yichus studio [--port N] MCP server on stdio plus the studio page
|
|
3105
|
+
yichus studio --page [--port N] only the studio page, for the commands below
|
|
3106
|
+
yichus start "DESCRIPTION" record what the person wants built
|
|
3107
|
+
yichus next [--json] check the program and print the next step
|
|
3108
|
+
yichus name SUBJECT "NAME" ... plain names the person sees for parts of the program
|
|
3109
|
+
yichus answer QUESTION CHOICE [--words TEXT]
|
|
3110
|
+
yichus rules FILE.json the rules the person stated: {"rules": [{"rule": ..., "laws": [...]}]}
|
|
3111
|
+
yichus scenario FILE.json what should happen in actions: {"scenarios": [...], "drop": [...]}
|
|
3112
|
+
yichus point FILE.json point at parts of the page: {"marks": [{"at": ..., "note": ...}]}
|
|
3113
|
+
yichus page the page as the person sees it now, in words
|
|
3114
|
+
yichus reference [TOPIC] reference material a step asks for; no topic lists them
|
|
3115
|
+
`;
|
|
3116
|
+
async function runStudioCommand(argv2, io) {
|
|
3117
|
+
try {
|
|
3118
|
+
const { values, positionals } = parseArgs({ args: argv2, allowPositionals: true, strict: true, options: {
|
|
3119
|
+
project: { type: "string" },
|
|
3120
|
+
json: { type: "boolean" },
|
|
3121
|
+
words: { type: "string" },
|
|
3122
|
+
page: { type: "boolean" },
|
|
3123
|
+
port: { type: "string" }
|
|
3124
|
+
} });
|
|
3125
|
+
const [command, ...rest] = positionals;
|
|
3126
|
+
const root = path8.resolve(values.project ?? ".");
|
|
3127
|
+
const expect = (n, usage) => {
|
|
3128
|
+
if (rest.length !== n) throw new Error(`Usage: ${usage}`);
|
|
3129
|
+
};
|
|
3130
|
+
if (command === "start") {
|
|
3131
|
+
expect(1, 'yichus start "DESCRIPTION"');
|
|
3132
|
+
const result = recordStart(root, { description: rest[0] }, CLI);
|
|
3133
|
+
if (!result.ok) throw new Error(result.error);
|
|
3134
|
+
io.stdout(`Recorded the description.
|
|
3135
|
+
${pageNote(runningPageUrl(root), CLI)}
|
|
3136
|
+
If this replaces an app the person already has, run \`yichus reference porting\` first.
|
|
3137
|
+
Next: yichus next
|
|
3138
|
+
`);
|
|
3139
|
+
return 0;
|
|
3140
|
+
}
|
|
3141
|
+
if (command === "name") {
|
|
3142
|
+
if (!rest.length || rest.length % 2) throw new Error('Usage: yichus name SUBJECT "NAME" [SUBJECT "NAME" ...]');
|
|
3143
|
+
const names = Object.fromEntries(rest.flatMap((s, i) => i % 2 ? [] : [[s, rest[i + 1]]]));
|
|
3144
|
+
const result = recordNames(root, { names }, CLI);
|
|
3145
|
+
if (!result.ok) throw new Error(result.error);
|
|
3146
|
+
io.stderr(`Named ${Object.entries(names).map(([subject, name]) => `${subject} "${name}"`).join(", ")}. Next: yichus next
|
|
3147
|
+
`);
|
|
3148
|
+
return 0;
|
|
3149
|
+
}
|
|
3150
|
+
if (command === "answer") {
|
|
3151
|
+
expect(2, "yichus answer QUESTION CHOICE [--words TEXT]");
|
|
3152
|
+
const [question, choice] = rest;
|
|
3153
|
+
const result = recordAnswer(root, { question, choice, words: values.words ?? "" }, io.now(), CLI);
|
|
3154
|
+
if (!result.ok) throw new Error(result.error);
|
|
3155
|
+
io.stderr(`Recorded ${choice} for ${question}. Next: yichus next
|
|
3156
|
+
`);
|
|
3157
|
+
return 0;
|
|
3158
|
+
}
|
|
3159
|
+
if (command === "rules") {
|
|
3160
|
+
expect(1, "yichus rules FILE.json");
|
|
3161
|
+
const result = recordRules(root, JSON.parse(fs8.readFileSync(path8.resolve(rest[0]), "utf8")), CLI);
|
|
3162
|
+
if (!result.ok) throw new Error(result.error);
|
|
3163
|
+
io.stderr("Recorded the rules. Next: yichus next\n");
|
|
3164
|
+
return 0;
|
|
3165
|
+
}
|
|
3166
|
+
if (command === "scenario") {
|
|
3167
|
+
expect(1, "yichus scenario FILE.json");
|
|
3168
|
+
const result = recordScenarios(root, JSON.parse(fs8.readFileSync(path8.resolve(rest[0]), "utf8")), CLI);
|
|
3169
|
+
if (!result.ok) throw new Error(result.error);
|
|
3170
|
+
io.stderr("Recorded the scenarios. Next: yichus next\n");
|
|
3171
|
+
return 0;
|
|
3172
|
+
}
|
|
3173
|
+
if (command === "point") {
|
|
3174
|
+
expect(1, "yichus point FILE.json");
|
|
3175
|
+
const result = recordMarks(root, JSON.parse(fs8.readFileSync(path8.resolve(rest[0]), "utf8")), io.now());
|
|
3176
|
+
if (!result.ok) throw new Error(result.error);
|
|
3177
|
+
io.stderr("The page shows the notes now.\n");
|
|
3178
|
+
return 0;
|
|
3179
|
+
}
|
|
3180
|
+
if (command === "page") {
|
|
3181
|
+
expect(0, "yichus page");
|
|
3182
|
+
io.stdout(pageText(root, runningPageUrl(root), io.now(), CLI));
|
|
3183
|
+
return 0;
|
|
3184
|
+
}
|
|
3185
|
+
if (command === "reference") {
|
|
3186
|
+
if (rest.length > 1) throw new Error("Usage: yichus reference [TOPIC]");
|
|
3187
|
+
const list = topicList((topic) => `yichus reference ${topic}`);
|
|
3188
|
+
if (!rest.length) {
|
|
3189
|
+
io.stdout(`${list}
|
|
3190
|
+
`);
|
|
3191
|
+
return 0;
|
|
3192
|
+
}
|
|
3193
|
+
const said2 = readReference(rest[0], io.locate);
|
|
3194
|
+
if (!said2) throw new Error(`No reference topic ${rest[0]}.
|
|
3195
|
+
${list}`);
|
|
3196
|
+
io.stdout(`${CLI_LEGEND}
|
|
3197
|
+
|
|
3198
|
+
${said2}
|
|
3199
|
+
`);
|
|
3200
|
+
return 0;
|
|
3201
|
+
}
|
|
3202
|
+
if (command === "next") {
|
|
3203
|
+
expect(0, "yichus next [--json]");
|
|
3204
|
+
const state = await direct({ root, engine: await io.engine(), requirements: loadRequirements(root), previous: readState(root), say: CLI });
|
|
3205
|
+
io.stdout(values.json ? `${JSON.stringify(state, null, 2)}
|
|
3206
|
+
` : stepText(state, runningPageUrl(root)));
|
|
3207
|
+
return 0;
|
|
3208
|
+
}
|
|
3209
|
+
expect(0, "yichus studio [--page] [--port N]");
|
|
3210
|
+
const port = values.port === void 0 ? null : Number(values.port);
|
|
3211
|
+
if (port !== null && (!Number.isInteger(port) || port < 0 || port > 65535)) throw new Error("--port must be a port number");
|
|
3212
|
+
await io.serve({ root, port, pageOnly: values.page ?? false });
|
|
3213
|
+
return 0;
|
|
3214
|
+
} catch (error) {
|
|
3215
|
+
io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}
|
|
3216
|
+
`);
|
|
3217
|
+
return 2;
|
|
3218
|
+
}
|
|
3219
|
+
}
|
|
3220
|
+
|
|
3221
|
+
// src/run.ts
|
|
3222
|
+
var HELP = `yichus \u2014 the Yichus WebMCP analysis engine, locally
|
|
3223
|
+
|
|
3224
|
+
yichus tools
|
|
3225
|
+
yichus call TOOL [--args JSON_FILE|-] [--source FILE ... | --project DIR]
|
|
3226
|
+
yichus verify FILE ... [--instances 1|many] [--block-on-warning ID ...]
|
|
3227
|
+
yichus lean FILE ... --lean-wasm-root DIRECTORY [--timeout-ms N]
|
|
3228
|
+
${STUDIO_HELP}
|
|
3229
|
+
Options:
|
|
3230
|
+
--source FILE Add a Bosatsu source (repeatable; call only). Files
|
|
3231
|
+
sharing a basename are named by their folders.
|
|
3232
|
+
--project DIR For a tool that requires sources, given no --source
|
|
3233
|
+
and no args.sources: every .bosatsu file under DIR
|
|
3234
|
+
(default the current folder), as the studio reads
|
|
3235
|
+
it (call only).
|
|
3236
|
+
--args FILE|- Tool arguments as a JSON object; - reads stdin.
|
|
3237
|
+
--block-on-warning ID A property id whose warning blocks the verdict, as a
|
|
3238
|
+
violation would (repeatable; all names every property;
|
|
3239
|
+
verify only). An id the verdict lacks exits 2.
|
|
3240
|
+
--output FILE Write the result to this file instead of stdout.
|
|
3241
|
+
--select /POINTER Extract a JSON field; strings are written verbatim.
|
|
3242
|
+
--expect /PTR=JSON Fail unless a result field exactly equals JSON (repeatable).
|
|
3243
|
+
--bundle FILE Explicit Scala.js engine override.
|
|
3244
|
+
--lean-wasm-root DIR Pinned local Lean Wasm installation (lean only).
|
|
3245
|
+
--timeout-ms N Total proof budget, at most 300000 (lean only).
|
|
3246
|
+
--help, -h Show this help without loading the engine.
|
|
3247
|
+
|
|
3248
|
+
tools and call expose Yichus/Mcp::catalog without a second analysis layer.
|
|
3249
|
+
verify runs api_verify and requires verdict.proven to be exactly true.
|
|
3250
|
+
Its JSON opens with proven, the verdict; ok only says the check ran.
|
|
3251
|
+
It always prints a plain summary of the verdict to stderr: each property's
|
|
3252
|
+
status, the first failure's evidence (parse errors carry file:line:col),
|
|
3253
|
+
and where the full JSON verdict went.
|
|
3254
|
+
lean runs the pinned Wasm kernel and requires all discovered obligations to be verified.
|
|
3255
|
+
It prints on stderr whether each law was proven and, if not, why: Lean
|
|
3256
|
+
rejected it (with Lean's words), the law is outside what Lean Wasm admits,
|
|
3257
|
+
the --timeout-ms budget ran out, or no runtime is installed (with the
|
|
3258
|
+
install command).
|
|
3259
|
+
call requires ok:true; use --expect to gate on a check's actual verdict.
|
|
3260
|
+
When the tool fails, stderr gives its error as plain text, what to do
|
|
3261
|
+
instead when the engine names the failure's kind (errorKinds), and where
|
|
3262
|
+
the JSON result went. An unmet --expect is one JSON line on stderr.
|
|
3263
|
+
With --output it says on stderr where the result went; api_abstraction_map
|
|
3264
|
+
also says what it is mapping before it starts, and afterwards its layer,
|
|
3265
|
+
reuse and copy counts in words, each with the JSON field that lists them.
|
|
3266
|
+
No browser is needed. Page editing, visible feedback and app sessions use
|
|
3267
|
+
the separate @yichus/mcp browser relay.
|
|
3268
|
+
|
|
3269
|
+
Exit status: 0 = completed and expectations met; 1 = tool/check rejected;
|
|
3270
|
+
2 = invalid invocation (including a --block-on-warning id the verdict lacks), malformed engine result, or execution/IO failure
|
|
3271
|
+
(for lean: no runtime, the budget ran out, or the runtime failed).
|
|
3272
|
+
JSON diagnostics remain available for rejected checks: the result JSON,
|
|
3273
|
+
or, when --select withheld it, a JSON line on stderr. --select emits no
|
|
3274
|
+
artifact on rejection. A named output is removed before execution so a
|
|
3275
|
+
failed check cannot leave yesterday's artifact behind.
|
|
3276
|
+
`;
|
|
3277
|
+
function pointerParts(pointer) {
|
|
3278
|
+
if (pointer === "") return [];
|
|
3279
|
+
if (!pointer.startsWith("/") || /~(?:[^01]|$)/u.test(pointer)) {
|
|
3280
|
+
throw new Error(`Invalid JSON Pointer: ${pointer}`);
|
|
3281
|
+
}
|
|
3282
|
+
return pointer.slice(1).split("/").map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
3283
|
+
}
|
|
3284
|
+
function readPointer(value, pointer) {
|
|
3285
|
+
for (const part of pointerParts(pointer)) {
|
|
3286
|
+
if (value === null || typeof value !== "object" || !Object.hasOwn(value, part)) return void 0;
|
|
3287
|
+
value = value[part];
|
|
3288
|
+
}
|
|
3289
|
+
return value;
|
|
3290
|
+
}
|
|
3291
|
+
function objectValue(value, label2) {
|
|
3292
|
+
const parsed = z12.record(z12.string(), z12.unknown()).safeParse(value);
|
|
3293
|
+
if (!parsed.success) throw new Error(`${label2} must be a JSON object`);
|
|
3294
|
+
return parsed.data;
|
|
3295
|
+
}
|
|
3296
|
+
var objectJson = (raw, label2) => objectValue(JSON.parse(raw), label2);
|
|
3297
|
+
var FLAGS = {
|
|
3298
|
+
source: { type: "string", multiple: true },
|
|
3299
|
+
args: { type: "string" },
|
|
3300
|
+
project: { type: "string" },
|
|
3301
|
+
instances: { type: "string" },
|
|
3302
|
+
"block-on-warning": { type: "string", multiple: true },
|
|
3303
|
+
output: { type: "string" },
|
|
3304
|
+
bundle: { type: "string" },
|
|
3305
|
+
"lean-wasm-root": { type: "string" },
|
|
3306
|
+
"timeout-ms": { type: "string" },
|
|
3307
|
+
select: { type: "string" },
|
|
3308
|
+
expect: { type: "string", multiple: true }
|
|
3309
|
+
};
|
|
3310
|
+
var TimeoutMs = z12.coerce.number().int().min(1).max(3e5);
|
|
3311
|
+
function parse(argv2) {
|
|
3312
|
+
const { values, positionals, tokens } = parseArgs2({ args: argv2, options: FLAGS, allowPositionals: true, strict: true, tokens: true });
|
|
3313
|
+
const named2 = tokens.flatMap((token) => token.kind === "option" ? [token.name] : []);
|
|
3314
|
+
const repeated = named2.find((name, i) => !("multiple" in FLAGS[name]) && named2.indexOf(name) !== i);
|
|
3315
|
+
if (repeated) throw new Error(`Repeated --${repeated}`);
|
|
3316
|
+
const [command, ...rest] = positionals;
|
|
3317
|
+
if (command !== "tools" && command !== "call" && command !== "verify" && command !== "lean") {
|
|
3318
|
+
throw new Error("Expected tools, call TOOL, verify FILE, or lean FILE; use --help for usage.");
|
|
3319
|
+
}
|
|
3320
|
+
const opts = { command, sources: [], expects: [], blockOnWarnings: values["block-on-warning"] ?? [] };
|
|
3321
|
+
if (command === "call") {
|
|
3322
|
+
opts.tool = rest.shift();
|
|
3323
|
+
if (!opts.tool) throw new Error("call requires a tool name");
|
|
3324
|
+
}
|
|
3325
|
+
if ((command === "tools" || command === "call") && rest.length) throw new Error(`Unexpected argument: ${rest[0]}`);
|
|
3326
|
+
opts.sources = [...rest, ...values.source ?? []];
|
|
3327
|
+
opts.args = values.args;
|
|
3328
|
+
opts.project = values.project;
|
|
3329
|
+
if (opts.project !== void 0 && command !== "call") throw new Error("--project is for call");
|
|
3330
|
+
if (opts.project !== void 0 && opts.sources.length) throw new Error("Use either --source files or --project, not both");
|
|
3331
|
+
opts.instances = values.instances;
|
|
3332
|
+
opts.output = values.output;
|
|
3333
|
+
opts.bundle = values.bundle;
|
|
3334
|
+
opts.leanWasmRoot = values["lean-wasm-root"];
|
|
3335
|
+
if (values["timeout-ms"] !== void 0) {
|
|
3336
|
+
const timeout = TimeoutMs.safeParse(values["timeout-ms"]);
|
|
3337
|
+
if (!timeout.success) throw new Error("--timeout-ms must be an integer from 1 to 300000");
|
|
3338
|
+
opts.timeoutMs = timeout.data;
|
|
3339
|
+
}
|
|
3340
|
+
if (values.select !== void 0) {
|
|
3341
|
+
pointerParts(values.select);
|
|
3342
|
+
opts.select = values.select;
|
|
3343
|
+
}
|
|
3344
|
+
for (const value of values.expect ?? []) {
|
|
3345
|
+
const equal = value.indexOf("=");
|
|
3346
|
+
if (equal < 0) throw new Error("--expect requires /POINTER=JSON");
|
|
3347
|
+
const pointer = value.slice(0, equal);
|
|
3348
|
+
pointerParts(pointer);
|
|
3349
|
+
opts.expects.push({ pointer, value: JSON.parse(value.slice(equal + 1)) });
|
|
3350
|
+
}
|
|
3351
|
+
if (command === "tools" && (opts.sources.length || opts.args || opts.instances)) {
|
|
3352
|
+
throw new Error("tools does not accept sources or tool arguments");
|
|
3353
|
+
}
|
|
3354
|
+
if (command === "verify") {
|
|
3355
|
+
if (!opts.sources.length) throw new Error("verify requires at least one Bosatsu file");
|
|
3356
|
+
if (opts.args) throw new Error("verify accepts --instances; use call for arbitrary arguments");
|
|
3357
|
+
if (values.source !== void 0) throw new Error("verify takes positional files; --source is for call");
|
|
3358
|
+
if (opts.instances && opts.instances !== "1" && opts.instances !== "many") {
|
|
3359
|
+
throw new Error("--instances must be 1 or many");
|
|
3360
|
+
}
|
|
3361
|
+
opts.expects.push({ pointer: "/verdict/proven", value: true });
|
|
3362
|
+
} else if (command === "lean") {
|
|
3363
|
+
if (!opts.sources.length) throw new Error("lean requires at least one Bosatsu file");
|
|
3364
|
+
if (!opts.leanWasmRoot) throw new Error("lean requires --lean-wasm-root");
|
|
3365
|
+
if (opts.args || opts.instances || values.source !== void 0)
|
|
3366
|
+
throw new Error("lean takes positional files and a Wasm root");
|
|
3367
|
+
opts.expects.push({ pointer: "/allVerified", value: true });
|
|
3368
|
+
} else if (opts.instances) {
|
|
3369
|
+
throw new Error("--instances is for verify; pass catalog arguments through --args for call");
|
|
3370
|
+
}
|
|
3371
|
+
if (command !== "verify" && opts.blockOnWarnings.length)
|
|
3372
|
+
throw new Error("--block-on-warning is for verify; pass block_on_warnings through --args for call");
|
|
3373
|
+
if (command !== "lean" && (opts.leanWasmRoot || opts.timeoutMs !== void 0))
|
|
3374
|
+
throw new Error("--lean-wasm-root and --timeout-ms are for lean");
|
|
3375
|
+
return opts;
|
|
3376
|
+
}
|
|
3377
|
+
function closestSibling(file) {
|
|
3378
|
+
const dir = path9.dirname(file);
|
|
3379
|
+
const want = path9.basename(file);
|
|
3380
|
+
let names;
|
|
3381
|
+
try {
|
|
3382
|
+
names = fs9.readdirSync(dir);
|
|
3383
|
+
} catch {
|
|
3384
|
+
return void 0;
|
|
3385
|
+
}
|
|
3386
|
+
const distance = (a, b) => {
|
|
3387
|
+
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
3388
|
+
for (let i = 1; i <= a.length; i++) {
|
|
3389
|
+
let diagonal = row[0];
|
|
3390
|
+
row[0] = i;
|
|
3391
|
+
for (let j = 1; j <= b.length; j++) {
|
|
3392
|
+
const above = row[j];
|
|
3393
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
3394
|
+
diagonal = above;
|
|
3395
|
+
}
|
|
3396
|
+
}
|
|
3397
|
+
return row[b.length];
|
|
3398
|
+
};
|
|
3399
|
+
const scored = names.map((name) => ({ name, d: distance(want, name) })).filter(({ d }) => d <= 2).sort((x, y) => x.d - y.d);
|
|
3400
|
+
return scored.length ? path9.join(dir, scored[0].name) : void 0;
|
|
3401
|
+
}
|
|
3402
|
+
function readInput(file) {
|
|
3403
|
+
try {
|
|
3404
|
+
return fs9.readFileSync(file, "utf8");
|
|
3405
|
+
} catch (error) {
|
|
3406
|
+
const code = error?.code;
|
|
3407
|
+
if (code === "ENOENT") {
|
|
3408
|
+
const near = closestSibling(file);
|
|
3409
|
+
throw new Error(`File not found: ${file}${near ? `. Did you mean ${near}?` : ""}`);
|
|
3410
|
+
}
|
|
3411
|
+
if (code === "EISDIR") throw new Error(`${file} is a directory; name a file instead.`);
|
|
3412
|
+
if (code === "EACCES" || code === "EPERM") throw new Error(`Permission denied reading ${file}.`);
|
|
3413
|
+
throw error;
|
|
3414
|
+
}
|
|
3415
|
+
}
|
|
3416
|
+
function sourceNames(paths) {
|
|
3417
|
+
const parts = paths.map((p) => path9.resolve(p).split(path9.sep).filter((s) => s !== ""));
|
|
3418
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3419
|
+
parts.forEach((segments, i) => {
|
|
3420
|
+
const full = segments.join("/");
|
|
3421
|
+
if (seen.has(full)) throw new Error(`${paths[i]} names the same file as an earlier --source; name each source once`);
|
|
3422
|
+
seen.add(full);
|
|
3423
|
+
});
|
|
3424
|
+
const tail = (segments, n) => segments.slice(-n).join("/");
|
|
3425
|
+
return parts.map((segments, i) => {
|
|
3426
|
+
let n = 1;
|
|
3427
|
+
while (parts.some((other, j) => j !== i && tail(other, n) === tail(segments, n))) n += 1;
|
|
3428
|
+
return tail(segments, n);
|
|
3429
|
+
});
|
|
3430
|
+
}
|
|
3431
|
+
async function argumentsFor(opts, io) {
|
|
3432
|
+
const args = opts.args ? objectJson(opts.args === "-" ? await io.readStdin() : readInput(opts.args), "Arguments") : {};
|
|
3433
|
+
if (opts.sources.length) {
|
|
3434
|
+
if (Object.hasOwn(args, "sources")) throw new Error("Use either --source files or args.sources, not both");
|
|
3435
|
+
const names = sourceNames(opts.sources);
|
|
3436
|
+
args.sources = opts.sources.map((sourcePath, i) => ({ fileName: names[i], source: readInput(sourcePath) }));
|
|
3437
|
+
}
|
|
3438
|
+
if (opts.instances) args.instances = opts.instances;
|
|
3439
|
+
if (opts.blockOnWarnings.length) args.block_on_warnings = [...new Set(opts.blockOnWarnings)];
|
|
3440
|
+
return args;
|
|
3441
|
+
}
|
|
3442
|
+
var Catalog = z12.looseObject({ tools: z12.array(z12.looseObject({
|
|
3443
|
+
name: z12.string(),
|
|
3444
|
+
inputSchema: z12.looseObject({ required: z12.array(z12.string()).default([]) }).optional()
|
|
3445
|
+
})).default([]) });
|
|
3446
|
+
function readsProgram(engine, tool) {
|
|
3447
|
+
const catalog = Catalog.safeParse(JSON.parse(engine.listTools()));
|
|
3448
|
+
return catalog.success && (catalog.data.tools.find((t) => t.name === tool)?.inputSchema?.required.includes("sources") ?? false);
|
|
3449
|
+
}
|
|
3450
|
+
function folderSources(tool, project) {
|
|
3451
|
+
const root = path9.resolve(project ?? ".");
|
|
3452
|
+
const files = projectSources(root);
|
|
3453
|
+
if (!files.length) throw new Error(`${tool} reads the program, and there is no .bosatsu file under ${root}. Pass --project with the project folder, or --source for each file.`);
|
|
3454
|
+
return files;
|
|
3455
|
+
}
|
|
3456
|
+
function clearOutput(opts) {
|
|
3457
|
+
if (!opts.output) return;
|
|
3458
|
+
const output = path9.resolve(opts.output);
|
|
3459
|
+
const outputStat = fs9.existsSync(output) ? fs9.statSync(output) : void 0;
|
|
3460
|
+
for (const input of [...opts.sources, opts.args, opts.bundle].filter((p) => !!p && p !== "-")) {
|
|
3461
|
+
const inputStat = fs9.existsSync(input) ? fs9.statSync(input) : void 0;
|
|
3462
|
+
if (path9.resolve(input) === output || outputStat && inputStat && inputStat.dev === outputStat.dev && inputStat.ino === outputStat.ino) {
|
|
3463
|
+
throw new Error("--output must not overwrite an input file");
|
|
3464
|
+
}
|
|
3465
|
+
}
|
|
3466
|
+
fs9.rmSync(output, { force: true });
|
|
3467
|
+
}
|
|
3468
|
+
function rejection(result, unmet) {
|
|
3469
|
+
if (result.ok) return `${unmet} --expect ${unmet === 1 ? "expectation was" : "expectations were"} not met`;
|
|
3470
|
+
const said2 = EngineError.safeParse(result);
|
|
3471
|
+
return said2.success ? said2.data.error : "The tool failed without saying why; see its result";
|
|
3472
|
+
}
|
|
3473
|
+
async function runCli(argv2, io) {
|
|
3474
|
+
try {
|
|
3475
|
+
if (argv2.length === 0 || argv2.includes("--help") || argv2.includes("-h")) {
|
|
3476
|
+
io.stdout(HELP);
|
|
3477
|
+
return 0;
|
|
3478
|
+
}
|
|
3479
|
+
const opts = parse(argv2);
|
|
3480
|
+
clearOutput(opts);
|
|
3481
|
+
const args = await argumentsFor(opts, io);
|
|
3482
|
+
let result;
|
|
3483
|
+
const timeoutMs = opts.timeoutMs ?? 18e4;
|
|
3484
|
+
if (opts.command === "lean") {
|
|
3485
|
+
if (!io.checkLeanWasm) throw new Error("Lean Wasm backend is unavailable");
|
|
3486
|
+
io.stderr(`Checking the laws in ${opts.sources.join(", ")} with Lean Wasm at ${opts.leanWasmRoot} (budget ${timeoutMs} ms)...
|
|
3487
|
+
`);
|
|
3488
|
+
result = objectValue(await io.checkLeanWasm(
|
|
3489
|
+
opts.bundle,
|
|
3490
|
+
opts.leanWasmRoot,
|
|
3491
|
+
args.sources,
|
|
3492
|
+
timeoutMs
|
|
3493
|
+
), "Lean result");
|
|
3494
|
+
} else {
|
|
3495
|
+
if (opts.command === "call") {
|
|
3496
|
+
const files = Array.isArray(args.sources) ? args.sources.length : void 0;
|
|
3497
|
+
const progress = callProgress(opts.tool, files);
|
|
3498
|
+
if (progress) io.stderr(progress);
|
|
3499
|
+
}
|
|
3500
|
+
const engine = await io.loadEngine(opts.bundle);
|
|
3501
|
+
if (opts.command === "call" && !Object.hasOwn(args, "sources") && readsProgram(engine, opts.tool)) {
|
|
3502
|
+
args.sources = folderSources(opts.tool, opts.project);
|
|
3503
|
+
}
|
|
3504
|
+
const raw = opts.command === "tools" ? engine.listTools() : engine.callTool(opts.command === "verify" ? "api_verify" : opts.tool, JSON.stringify(args));
|
|
3505
|
+
result = objectJson(raw, "Engine result");
|
|
3506
|
+
}
|
|
3507
|
+
if (typeof result.ok !== "boolean") throw new Error("Engine result must explicitly contain boolean ok");
|
|
3508
|
+
const unmet = opts.expects.filter(({ pointer, value }) => !isDeepStrictEqual(readPointer(result, pointer), value));
|
|
3509
|
+
const passed = result.ok && unmet.length === 0;
|
|
3510
|
+
if (opts.select === void 0 || passed) {
|
|
3511
|
+
const selected = opts.select === void 0 ? result : readPointer(result, opts.select);
|
|
3512
|
+
if (selected === void 0) throw new Error(`Result field missing: ${opts.select}`);
|
|
3513
|
+
const text3 = opts.select !== void 0 && typeof selected === "string" ? selected : `${JSON.stringify(selected, null, 2)}
|
|
3514
|
+
`;
|
|
3515
|
+
if (opts.output) fs9.writeFileSync(opts.output, text3);
|
|
3516
|
+
else io.stdout(text3);
|
|
3517
|
+
}
|
|
3518
|
+
const artifact = opts.select !== void 0 ? "the unselected result; run without --select to see it" : opts.output ?? "the JSON on standard output";
|
|
3519
|
+
let exit = passed ? 0 : 1;
|
|
3520
|
+
if (opts.command === "verify") {
|
|
3521
|
+
io.stderr(verifySummary(result, passed, artifact));
|
|
3522
|
+
if (!result.ok && result.errorKind === "invalid-arguments") exit = 2;
|
|
3523
|
+
} else if (opts.command === "lean") {
|
|
3524
|
+
const reading = leanSummary(result, artifact, timeoutMs, opts.sources);
|
|
3525
|
+
io.stderr(reading.text);
|
|
3526
|
+
exit = reading.exit;
|
|
3527
|
+
} else if (!result.ok) {
|
|
3528
|
+
io.stderr(callFailure(opts.tool ?? "tools", result, artifact));
|
|
3529
|
+
} else if (passed && opts.select === void 0 && opts.command === "call") {
|
|
3530
|
+
const said2 = callSummary(opts.tool, result, opts.output);
|
|
3531
|
+
if (said2) io.stderr(said2);
|
|
3532
|
+
}
|
|
3533
|
+
const generic = opts.command === "call" || opts.command === "tools";
|
|
3534
|
+
if (!passed && (opts.select !== void 0 || generic && result.ok)) {
|
|
3535
|
+
io.stderr(`${JSON.stringify({ ok: false, error: rejection(result, unmet.length), unmet, result: opts.select === void 0 ? void 0 : result })}
|
|
3536
|
+
`);
|
|
3537
|
+
}
|
|
3538
|
+
return exit;
|
|
3539
|
+
} catch (error) {
|
|
3540
|
+
io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}
|
|
3541
|
+
`);
|
|
3542
|
+
return 2;
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3545
|
+
|
|
3546
|
+
// src/studio/serve.ts
|
|
3547
|
+
import { once } from "events";
|
|
3548
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
3549
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3550
|
+
import { EngineWorkerClient, catalogTools } from "@yichus/api-mcp";
|
|
3551
|
+
|
|
3552
|
+
// src/studio/page-server.ts
|
|
3553
|
+
import fs10 from "fs";
|
|
3554
|
+
import http from "http";
|
|
3555
|
+
import path10 from "path";
|
|
3556
|
+
|
|
3557
|
+
// src/studio/page-assets.json
|
|
3558
|
+
var page_assets_default = ["system-map.js", "label-fit.js", "system-map-record.js", "system-map.css", "dom.js", "layer-groups.js", "layer-diagram.js", "source-link.js", "what-happens.js", "what-happens-record.js", "studio-views.js"];
|
|
3559
|
+
|
|
3560
|
+
// src/studio/page-server.ts
|
|
3561
|
+
var PAGE_ASSETS = page_assets_default;
|
|
3562
|
+
function personView(state, names, marks = null) {
|
|
3563
|
+
if (!state) return null;
|
|
3564
|
+
const { sections, whatHappens, anchors, drawing } = personDiagrams(state, names);
|
|
3565
|
+
return {
|
|
3566
|
+
project: state.project,
|
|
3567
|
+
updatedAt: state.updatedAt,
|
|
3568
|
+
sourcesHash: state.sourcesHash,
|
|
3569
|
+
summary: state.step.summary,
|
|
3570
|
+
properties: state.properties.map((p) => ({
|
|
3571
|
+
question: { id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices },
|
|
3572
|
+
answer: p.answer,
|
|
3573
|
+
status: p.status
|
|
3574
|
+
})),
|
|
3575
|
+
// A state written before rules were kept has none.
|
|
3576
|
+
rules: (state.rules ?? []).map((r) => ({ rule: r.rule, status: r.status, laws: r.laws.length })),
|
|
3577
|
+
map: state.map ? relabelSystemMap(state.map, names) : null,
|
|
3578
|
+
mapError: state.mapError,
|
|
3579
|
+
sections,
|
|
3580
|
+
// A state written before this field says nothing either way.
|
|
3581
|
+
hasActions: state.hasActions ?? null,
|
|
3582
|
+
whatHappens,
|
|
3583
|
+
// Sent back with what the person has in view, so a report about an
|
|
3584
|
+
// older drawing is not read against this one.
|
|
3585
|
+
drawing,
|
|
3586
|
+
// A mark on a part the page no longer draws is left out.
|
|
3587
|
+
marks: marks && { said: marks.said, marks: marks.marks.flatMap((m) => anchors.has(m.at) ? [{ anchor: anchors.get(m.at), note: m.note }] : []) }
|
|
3588
|
+
};
|
|
3589
|
+
}
|
|
3590
|
+
function stateBody(root) {
|
|
3591
|
+
const { description, answers, names } = loadRequirements(root);
|
|
3592
|
+
return { state: personView(readState(root), names ?? {}, loadMarks(root)), requirements: { description, answers } };
|
|
3593
|
+
}
|
|
3594
|
+
var STUDIO_PORTS = [4317, 4318, 4319, 4320, 4321, 0];
|
|
3595
|
+
async function startPageServer(root, assetsDir, port = null, now = () => /* @__PURE__ */ new Date()) {
|
|
3596
|
+
ensureStudioDir(root);
|
|
3597
|
+
const clients = /* @__PURE__ */ new Set();
|
|
3598
|
+
const watched = ["state.json", "requirements.json", "marks.json"].map((name) => path10.join(studioDir(root), name));
|
|
3599
|
+
const changed = (now2, before) => {
|
|
3600
|
+
if (now2.mtimeMs !== before.mtimeMs || now2.size !== before.size) for (const res of clients) res.write("event: change\ndata: {}\n\n");
|
|
3601
|
+
};
|
|
3602
|
+
for (const file of watched) fs10.watchFile(file, { interval: 250 }, changed);
|
|
3603
|
+
const hosts = /* @__PURE__ */ new Set();
|
|
3604
|
+
const takes = /* @__PURE__ */ new Map([
|
|
3605
|
+
["/answer", (args) => recordAnswer(root, args, now())],
|
|
3606
|
+
["/viewing", (args) => recordViewing(root, args, now())]
|
|
3607
|
+
]);
|
|
3608
|
+
const server = http.createServer((req, res) => {
|
|
3609
|
+
const send = (status, type, body) => {
|
|
3610
|
+
res.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
3611
|
+
res.end(body);
|
|
3612
|
+
};
|
|
3613
|
+
const host = req.headers.host ?? "";
|
|
3614
|
+
if (!hosts.has(host) || req.headers.origin && req.headers.origin !== `http://${host}`) {
|
|
3615
|
+
send(403, "text/plain", "This studio only answers its own page.");
|
|
3616
|
+
return;
|
|
3617
|
+
}
|
|
3618
|
+
const url = new URL(req.url ?? "/", `http://${host}`);
|
|
3619
|
+
if (req.method === "GET" && url.pathname === "/") return send(200, "text/html; charset=utf-8", STUDIO_PAGE);
|
|
3620
|
+
if (req.method === "GET" && url.pathname === "/state") {
|
|
3621
|
+
return send(200, "application/json", JSON.stringify(stateBody(root)));
|
|
3622
|
+
}
|
|
3623
|
+
if (req.method === "GET" && url.pathname === "/events") {
|
|
3624
|
+
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
|
|
3625
|
+
res.write(": connected\n\n");
|
|
3626
|
+
clients.add(res);
|
|
3627
|
+
req.on("close", () => clients.delete(res));
|
|
3628
|
+
return;
|
|
3629
|
+
}
|
|
3630
|
+
const asset = PAGE_ASSETS.find((a) => url.pathname === `/${a}`);
|
|
3631
|
+
if (req.method === "GET" && asset) {
|
|
3632
|
+
return send(200, asset.endsWith(".css") ? "text/css" : "text/javascript", fs10.readFileSync(path10.join(assetsDir, asset), "utf8"));
|
|
3633
|
+
}
|
|
3634
|
+
const take = req.method === "POST" ? takes.get(url.pathname) : void 0;
|
|
3635
|
+
if (take) {
|
|
3636
|
+
if (req.headers["content-type"] !== "application/json") return send(415, "text/plain", "Send JSON.");
|
|
3637
|
+
let body = "";
|
|
3638
|
+
req.setEncoding("utf8");
|
|
3639
|
+
req.on("data", (chunk) => {
|
|
3640
|
+
body += chunk;
|
|
3641
|
+
if (body.length > 65536) req.destroy();
|
|
3642
|
+
});
|
|
3643
|
+
req.on("end", () => {
|
|
3644
|
+
let args;
|
|
3645
|
+
try {
|
|
3646
|
+
args = JSON.parse(body);
|
|
3647
|
+
} catch {
|
|
3648
|
+
return send(400, "application/json", JSON.stringify({ ok: false, error: "The request is not JSON." }));
|
|
3649
|
+
}
|
|
3650
|
+
const result = take(args);
|
|
3651
|
+
send(result.ok ? 200 : 400, "application/json", JSON.stringify(result));
|
|
3652
|
+
});
|
|
3653
|
+
return;
|
|
3654
|
+
}
|
|
3655
|
+
send(404, "text/plain", "Not found.");
|
|
3656
|
+
});
|
|
3657
|
+
for (const candidate of port === null ? STUDIO_PORTS : [port]) {
|
|
3658
|
+
const error = await new Promise((resolve) => {
|
|
3659
|
+
server.once("error", resolve);
|
|
3660
|
+
server.listen(candidate, "127.0.0.1", () => {
|
|
3661
|
+
server.off("error", resolve);
|
|
3662
|
+
resolve(null);
|
|
3663
|
+
});
|
|
3664
|
+
});
|
|
3665
|
+
if (!error) break;
|
|
3666
|
+
if (error.code !== "EADDRINUSE" || candidate === port) throw error;
|
|
3667
|
+
}
|
|
3668
|
+
const bound = server.address().port;
|
|
3669
|
+
hosts.add(`127.0.0.1:${bound}`).add(`localhost:${bound}`);
|
|
3670
|
+
return {
|
|
3671
|
+
url: `http://127.0.0.1:${bound}/`,
|
|
3672
|
+
async close() {
|
|
3673
|
+
for (const file of watched) fs10.unwatchFile(file, changed);
|
|
3674
|
+
const closed = new Promise((resolve) => server.close(() => resolve()));
|
|
3675
|
+
server.closeAllConnections();
|
|
3676
|
+
await closed;
|
|
3677
|
+
}
|
|
3678
|
+
};
|
|
3679
|
+
}
|
|
3680
|
+
|
|
3681
|
+
// src/studio/serve.ts
|
|
3682
|
+
var objectResult = (raw, tool) => {
|
|
3683
|
+
const value = JSON.parse(raw);
|
|
3684
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${tool} returned no JSON object`);
|
|
3685
|
+
return value;
|
|
3686
|
+
};
|
|
3687
|
+
var inProcessEngine = (engine) => ({
|
|
3688
|
+
async call(tool, args) {
|
|
3689
|
+
return objectResult(engine.callTool(tool, JSON.stringify(args)), tool);
|
|
3690
|
+
}
|
|
3691
|
+
});
|
|
3692
|
+
function workerEngine(bundle) {
|
|
3693
|
+
const worker = new EngineWorkerClient(bundle, 9e5);
|
|
3694
|
+
let id = 0;
|
|
3695
|
+
return {
|
|
3696
|
+
async call(tool, args) {
|
|
3697
|
+
return objectResult(await worker.callTool(tool, JSON.stringify(args), `studio-${++id}`), tool);
|
|
3698
|
+
},
|
|
3699
|
+
async catalog() {
|
|
3700
|
+
return catalogTools(await worker.listTools(`studio-${++id}`));
|
|
3701
|
+
},
|
|
3702
|
+
close: () => worker.close()
|
|
3703
|
+
};
|
|
3704
|
+
}
|
|
3705
|
+
var BUILT_ASSETS = fileURLToPath2(new URL("./studio-page/", import.meta.url));
|
|
3706
|
+
async function serveStudio(options) {
|
|
3707
|
+
const started = await startPageServer(options.root, options.assetsDir ?? BUILT_ASSETS, options.port);
|
|
3708
|
+
writePageLink(options.root, started.url);
|
|
3709
|
+
const page = { url: started.url, async close() {
|
|
3710
|
+
clearPageLink(options.root, started.url);
|
|
3711
|
+
await started.close();
|
|
3712
|
+
} };
|
|
3713
|
+
options.stderr(`Yichus studio page: ${page.url}
|
|
3714
|
+
`);
|
|
3715
|
+
if (options.pageOnly) {
|
|
3716
|
+
await (options.stopped ?? Promise.race([once(process, "SIGINT"), once(process, "SIGTERM")]));
|
|
3717
|
+
await page.close();
|
|
3718
|
+
return;
|
|
3719
|
+
}
|
|
3720
|
+
const engine = workerEngine(options.bundle);
|
|
3721
|
+
const { server, idle } = createStudioMcpServer({ root: options.root, engine, pageUrl: page.url, catalog: engine.catalog });
|
|
3722
|
+
const stdin = options.stdin ?? process.stdin;
|
|
3723
|
+
const closed = once(stdin, "end");
|
|
3724
|
+
try {
|
|
3725
|
+
await server.connect(new StdioServerTransport(stdin, options.stdout ?? process.stdout));
|
|
3726
|
+
await closed;
|
|
3727
|
+
await idle();
|
|
3728
|
+
} finally {
|
|
3729
|
+
await server.close();
|
|
3730
|
+
await engine.close();
|
|
3731
|
+
await page.close();
|
|
3732
|
+
}
|
|
3733
|
+
}
|
|
3734
|
+
|
|
3735
|
+
// src/main.ts
|
|
3736
|
+
var bundleOrThrow = (bundle) => {
|
|
3737
|
+
const resolved = bundle ?? findApiMcpBundle();
|
|
3738
|
+
if (!resolved) throw new Error("Yichus engine bundle missing. Reinstall @yichus/api-mcp or pass --bundle.");
|
|
3739
|
+
return resolved;
|
|
3740
|
+
};
|
|
3741
|
+
var argv = process.argv.slice(2);
|
|
3742
|
+
process.exitCode = STUDIO_COMMANDS.has(argv[0] ?? "") ? await runStudioCommand(argv, {
|
|
3743
|
+
engine: async () => inProcessEngine(await loadApiEngine(bundleOrThrow())),
|
|
3744
|
+
serve: (options) => serveStudio({ ...options, bundle: bundleOrThrow(), stderr: (text3) => process.stderr.write(text3) }),
|
|
3745
|
+
stdout: (text3) => process.stdout.write(text3),
|
|
3746
|
+
stderr: (text3) => process.stderr.write(text3),
|
|
3747
|
+
now: () => /* @__PURE__ */ new Date(),
|
|
3748
|
+
locate: builtCopy
|
|
3749
|
+
}) : await runCli(argv, {
|
|
3750
|
+
async loadEngine(bundle) {
|
|
3751
|
+
return loadApiEngine(bundleOrThrow(bundle));
|
|
3752
|
+
},
|
|
3753
|
+
async checkLeanWasm(bundle, root, sources, timeoutMs) {
|
|
3754
|
+
return checkLeanWasmSources(bundleOrThrow(bundle), root, sources, timeoutMs);
|
|
3755
|
+
},
|
|
3756
|
+
// A stream, not readFileSync(0): a pipe the parent has not written yet
|
|
3757
|
+
// fails a synchronous read with EAGAIN on macOS.
|
|
3758
|
+
readStdin: () => text2(process.stdin),
|
|
3759
|
+
stdout: (text3) => process.stdout.write(text3),
|
|
3760
|
+
stderr: (text3) => process.stderr.write(text3)
|
|
3761
|
+
});
|
|
3762
|
+
//# sourceMappingURL=main.js.map
|