yichus 0.3.1 → 0.3.3

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/dist/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/main.ts","../src/run.ts","../src/engine-results.ts","../src/verdict.ts","../src/lean-verdict.ts","../src/call-summary.ts","../src/studio/command.ts","../src/studio/director.ts","../../../web/system-map-record.js","../../../web/system-map-names.js","../../../web/what-happens-record.js","../src/studio/project.ts","../src/studio/questions.ts","../src/studio/requirements.ts","../src/studio/scenarios.ts","../src/studio/surface.ts","../src/studio/mcp.ts","../src/studio/marks.ts","../src/studio/person.ts","../../../web/layer-groups.js","../src/studio/page.ts","../src/studio/viewing.ts","../src/studio/page-view.ts","../src/studio/reference.ts","../src/studio/reference.json","../src/studio/text.ts","../src/studio/page-link.ts","../src/studio/serve.ts","../src/studio/page-server.ts","../src/studio/page-assets.json"],"sourcesContent":["import { text } from 'node:stream/consumers';\nimport { checkLeanWasmSources, findApiMcpBundle, loadApiEngine } from '@yichus/api-mcp';\nimport { runCli } from './run.js';\nimport { STUDIO_COMMANDS, runStudioCommand } from './studio/command.js';\nimport { builtCopy } from './studio/reference.js';\nimport { inProcessEngine, serveStudio } from './studio/serve.js';\n\nconst bundleOrThrow = (bundle?: string): string => {\n const resolved = bundle ?? findApiMcpBundle();\n if (!resolved) throw new Error('Yichus engine bundle missing. Reinstall @yichus/api-mcp or pass --bundle.');\n return resolved;\n};\n\nconst argv = process.argv.slice(2);\nprocess.exitCode = STUDIO_COMMANDS.has(argv[0] ?? '')\n ? await runStudioCommand(argv, {\n engine: async () => inProcessEngine(await loadApiEngine(bundleOrThrow())),\n serve: options => serveStudio({ ...options, bundle: bundleOrThrow(), stderr: (text) => process.stderr.write(text) }),\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n now: () => new Date(),\n locate: builtCopy,\n })\n : await runCli(argv, {\n async loadEngine(bundle) {\n return loadApiEngine(bundleOrThrow(bundle));\n },\n async checkLeanWasm(bundle, root, sources, timeoutMs) {\n return checkLeanWasmSources(bundleOrThrow(bundle), root, sources, timeoutMs);\n },\n // A stream, not readFileSync(0): a pipe the parent has not written yet\n // fails a synchronous read with EAGAIN on macOS.\n readStdin: () => text(process.stdin),\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n });\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { isDeepStrictEqual, parseArgs } from 'node:util';\nimport type { ApiEngine } from '@yichus/api-mcp';\nimport { z } from 'zod';\nimport { verifySummary } from './verdict.js';\nimport { leanSummary } from './lean-verdict.js';\nimport { callFailure, callProgress, callSummary } from './call-summary.js';\nimport { EngineError } from './engine-results.js';\nimport { STUDIO_HELP } from './studio/command.js';\nimport { projectSources } from './studio/project.js';\n\nexport interface CliIo {\n loadEngine(bundle?: string): Promise<ApiEngine>;\n checkLeanWasm?(bundle: string | undefined, root: string,\n sources: Array<{ fileName: string; source: string }>, timeoutMs: number): Promise<unknown>;\n readStdin(): Promise<string>;\n stdout(text: string): void;\n stderr(text: string): void;\n}\n\nconst HELP = `yichus — the Yichus WebMCP analysis engine, locally\n\n yichus tools\n yichus call TOOL [--args JSON_FILE|-] [--source FILE ... | --project DIR]\n yichus verify FILE ... [--instances 1|many] [--block-on-warning ID ...]\n yichus lean FILE ... --lean-wasm-root DIRECTORY [--timeout-ms N]\n${STUDIO_HELP}\nOptions:\n --source FILE Add a Bosatsu source (repeatable; call only). Files\n sharing a basename are named by their folders.\n --project DIR For a tool that requires sources, given no --source\n and no args.sources: every .bosatsu file under DIR\n (default the current folder), as the studio reads\n it (call only).\n --args FILE|- Tool arguments as a JSON object; - reads stdin.\n --block-on-warning ID A property id whose warning blocks the verdict, as a\n violation would (repeatable; all names every property;\n verify only). An id the verdict lacks exits 2.\n --output FILE Write the result to this file instead of stdout.\n --select /POINTER Extract a JSON field; strings are written verbatim.\n --expect /PTR=JSON Fail unless a result field exactly equals JSON (repeatable).\n --bundle FILE Explicit Scala.js engine override.\n --lean-wasm-root DIR Pinned local Lean Wasm installation (lean only).\n --timeout-ms N Total proof budget, at most 300000 (lean only).\n --help, -h Show this help without loading the engine.\n\ntools and call expose Yichus/Mcp::catalog without a second analysis layer.\nverify runs api_verify and requires verdict.proven to be exactly true.\nIts JSON opens with proven, the verdict; ok only says the check ran.\nIt always prints a plain summary of the verdict to stderr: each property's\nstatus, the first failure's evidence (parse errors carry file:line:col),\nand where the full JSON verdict went.\nlean runs the pinned Wasm kernel and requires all discovered obligations to be verified.\nIt prints on stderr whether each law was proven and, if not, why: Lean\nrejected it (with Lean's words), the law is outside what Lean Wasm admits,\nthe --timeout-ms budget ran out, or no runtime is installed (with the\ninstall command).\ncall requires ok:true; use --expect to gate on a check's actual verdict.\nWhen the tool fails, stderr gives its error as plain text, what to do\ninstead when the engine names the failure's kind (errorKinds), and where\nthe JSON result went. An unmet --expect is one JSON line on stderr.\nWith --output it says on stderr where the result went; api_abstraction_map\nalso says what it is mapping before it starts, and afterwards its layer,\nreuse and copy counts in words, each with the JSON field that lists them.\nNo browser is needed. Page editing, visible feedback and app sessions use\nthe separate @yichus/mcp browser relay.\n\nExit status: 0 = completed and expectations met; 1 = tool/check rejected;\n2 = invalid invocation (including a --block-on-warning id the verdict lacks), malformed engine result, or execution/IO failure\n(for lean: no runtime, the budget ran out, or the runtime failed).\nJSON diagnostics remain available for rejected checks: the result JSON,\nor, when --select withheld it, a JSON line on stderr. --select emits no\nartifact on rejection. A named output is removed before execution so a\nfailed check cannot leave yesterday's artifact behind.\n`;\n\ninterface Options {\n command: 'tools' | 'call' | 'verify' | 'lean';\n tool?: string;\n args?: string;\n sources: string[];\n project?: string;\n instances?: string;\n blockOnWarnings: string[];\n output?: string;\n select?: string;\n expects: Array<{ pointer: string; value: unknown }>;\n bundle?: string;\n leanWasmRoot?: string;\n timeoutMs?: number;\n}\n\nfunction pointerParts(pointer: string): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/') || /~(?:[^01]|$)/u.test(pointer)) {\n throw new Error(`Invalid JSON Pointer: ${pointer}`);\n }\n return pointer.slice(1).split('/').map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\nfunction readPointer(value: unknown, pointer: string): unknown {\n for (const part of pointerParts(pointer)) {\n if (value === null || typeof value !== 'object' || !Object.hasOwn(value, part)) return undefined;\n value = (value as Record<string, unknown>)[part];\n }\n return value;\n}\n\nfunction objectValue(value: unknown, label: string): Record<string, unknown> {\n const parsed = z.record(z.string(), z.unknown()).safeParse(value);\n if (!parsed.success) throw new Error(`${label} must be a JSON object`);\n return parsed.data;\n}\n\nconst objectJson = (raw: string, label: string): Record<string, unknown> => objectValue(JSON.parse(raw), label);\n\nconst FLAGS = {\n source: { type: 'string', multiple: true },\n args: { type: 'string' },\n project: { type: 'string' },\n instances: { type: 'string' },\n 'block-on-warning': { type: 'string', multiple: true },\n output: { type: 'string' },\n bundle: { type: 'string' },\n 'lean-wasm-root': { type: 'string' },\n 'timeout-ms': { type: 'string' },\n select: { type: 'string' },\n expect: { type: 'string', multiple: true },\n} as const;\n\nconst TimeoutMs = z.coerce.number().int().min(1).max(300_000);\n\nfunction parse(argv: string[]): Options {\n const { values, positionals, tokens } = parseArgs({ args: argv, options: FLAGS, allowPositionals: true, strict: true, tokens: true });\n // parseArgs keeps the last of a repeated single-valued flag; a repeat is a mistake here.\n const named = tokens.flatMap((token) => token.kind === 'option' ? [token.name as keyof typeof FLAGS] : []);\n const repeated = named.find((name, i) => !('multiple' in FLAGS[name]) && named.indexOf(name) !== i);\n if (repeated) throw new Error(`Repeated --${repeated}`);\n const [command, ...rest] = positionals;\n if (command !== 'tools' && command !== 'call' && command !== 'verify' && command !== 'lean') {\n throw new Error('Expected tools, call TOOL, verify FILE, or lean FILE; use --help for usage.');\n }\n const opts: Options = { command, sources: [], expects: [], blockOnWarnings: values['block-on-warning'] ?? [] };\n if (command === 'call') {\n opts.tool = rest.shift();\n if (!opts.tool) throw new Error('call requires a tool name');\n }\n if ((command === 'tools' || command === 'call') && rest.length) throw new Error(`Unexpected argument: ${rest[0]}`);\n opts.sources = [...rest, ...(values.source ?? [])];\n opts.args = values.args;\n opts.project = values.project;\n if (opts.project !== undefined && command !== 'call') throw new Error('--project is for call');\n if (opts.project !== undefined && opts.sources.length) throw new Error('Use either --source files or --project, not both');\n opts.instances = values.instances;\n opts.output = values.output;\n opts.bundle = values.bundle;\n opts.leanWasmRoot = values['lean-wasm-root'];\n if (values['timeout-ms'] !== undefined) {\n const timeout = TimeoutMs.safeParse(values['timeout-ms']);\n if (!timeout.success) throw new Error('--timeout-ms must be an integer from 1 to 300000');\n opts.timeoutMs = timeout.data;\n }\n if (values.select !== undefined) {\n pointerParts(values.select);\n opts.select = values.select;\n }\n for (const value of values.expect ?? []) {\n const equal = value.indexOf('=');\n if (equal < 0) throw new Error('--expect requires /POINTER=JSON');\n const pointer = value.slice(0, equal);\n pointerParts(pointer);\n opts.expects.push({ pointer, value: JSON.parse(value.slice(equal + 1)) });\n }\n if (command === 'tools' && (opts.sources.length || opts.args || opts.instances)) {\n throw new Error('tools does not accept sources or tool arguments');\n }\n if (command === 'verify') {\n if (!opts.sources.length) throw new Error('verify requires at least one Bosatsu file');\n if (opts.args) throw new Error('verify accepts --instances; use call for arbitrary arguments');\n if (values.source !== undefined) throw new Error('verify takes positional files; --source is for call');\n if (opts.instances && opts.instances !== '1' && opts.instances !== 'many') {\n throw new Error('--instances must be 1 or many');\n }\n opts.expects.push({ pointer: '/verdict/proven', value: true });\n } else if (command === 'lean') {\n if (!opts.sources.length) throw new Error('lean requires at least one Bosatsu file');\n if (!opts.leanWasmRoot) throw new Error('lean requires --lean-wasm-root');\n if (opts.args || opts.instances || values.source !== undefined)\n throw new Error('lean takes positional files and a Wasm root');\n opts.expects.push({ pointer: '/allVerified', value: true });\n } else if (opts.instances) {\n throw new Error('--instances is for verify; pass catalog arguments through --args for call');\n }\n if (command !== 'verify' && opts.blockOnWarnings.length)\n throw new Error('--block-on-warning is for verify; pass block_on_warnings through --args for call');\n if (command !== 'lean' && (opts.leanWasmRoot || opts.timeoutMs !== undefined))\n throw new Error('--lean-wasm-root and --timeout-ms are for lean');\n return opts;\n}\n\n// The closest name in the same directory, for a mistyped input path.\nfunction closestSibling(file: string): string | undefined {\n const dir = path.dirname(file);\n const want = path.basename(file);\n let names: string[];\n try { names = fs.readdirSync(dir); } catch { return undefined; }\n const distance = (a: string, b: string): number => {\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let diagonal = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const above = row[j]!;\n row[j] = Math.min(row[j]! + 1, row[j - 1]! + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));\n diagonal = above;\n }\n }\n return row[b.length]!;\n };\n const scored = names.map((name) => ({ name, d: distance(want, name) })).filter(({ d }) => d <= 2).sort((x, y) => x.d - y.d);\n return scored.length ? path.join(dir, scored[0]!.name) : undefined;\n}\n\n// An input file the user named, read or explained in words: the error's\n// own code and path say what went wrong, never its message text.\nfunction readInput(file: string): string {\n try {\n return fs.readFileSync(file, 'utf8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code;\n if (code === 'ENOENT') {\n const near = closestSibling(file);\n throw new Error(`File not found: ${file}${near ? `. Did you mean ${near}?` : ''}`);\n }\n if (code === 'EISDIR') throw new Error(`${file} is a directory; name a file instead.`);\n if (code === 'EACCES' || code === 'EPERM') throw new Error(`Permission denied reading ${file}.`);\n throw error;\n }\n}\n\n// The one place a --source path becomes the name the engine knows the file\n// by: its basename, or, where two files share a basename, the fewest\n// trailing folders of each path that tell them apart\n// (\"billing/api.bosatsu\" and \"notes/api.bosatsu\"). The same file named\n// twice is refused, since it would compile twice.\nfunction sourceNames(paths: string[]): string[] {\n const parts = paths.map((p) => path.resolve(p).split(path.sep).filter((s) => s !== ''));\n const seen = new Set<string>();\n parts.forEach((segments, i) => {\n const full = segments.join('/');\n if (seen.has(full)) throw new Error(`${paths[i]} names the same file as an earlier --source; name each source once`);\n seen.add(full);\n });\n const tail = (segments: string[], n: number) => segments.slice(-n).join('/');\n return parts.map((segments, i) => {\n let n = 1;\n while (parts.some((other, j) => j !== i && tail(other, n) === tail(segments, n))) n += 1;\n return tail(segments, n);\n });\n}\n\nasync function argumentsFor(opts: Options, io: CliIo): Promise<Record<string, unknown>> {\n const args = opts.args\n ? objectJson(opts.args === '-' ? await io.readStdin() : readInput(opts.args), 'Arguments')\n : {};\n if (opts.sources.length) {\n if (Object.hasOwn(args, 'sources')) throw new Error('Use either --source files or args.sources, not both');\n const names = sourceNames(opts.sources);\n args.sources = opts.sources.map((sourcePath, i) => ({ fileName: names[i]!, source: readInput(sourcePath) }));\n }\n if (opts.instances) args.instances = opts.instances;\n if (opts.blockOnWarnings.length) args.block_on_warnings = [...new Set(opts.blockOnWarnings)];\n return args;\n}\n\n// A tool that requires sources reads the program; given none, it reads the\n// program in the project folder, the same files the studio checks. A tool\n// whose sources are optional means something else without them (a generic\n// template, a cached receipt), so it is left as called.\nconst Catalog = z.looseObject({ tools: z.array(z.looseObject({ name: z.string(),\n inputSchema: z.looseObject({ required: z.array(z.string()).default([]) }).optional() })).default([]) });\n\nfunction readsProgram(engine: ApiEngine, tool: string): boolean {\n const catalog = Catalog.safeParse(JSON.parse(engine.listTools()));\n return catalog.success && (catalog.data.tools.find(t => t.name === tool)?.inputSchema?.required.includes('sources') ?? false);\n}\n\nfunction folderSources(tool: string, project: string | undefined): Array<{ fileName: string; source: string }> {\n const root = path.resolve(project ?? '.');\n const files = projectSources(root);\n 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.`);\n return files;\n}\n\nfunction clearOutput(opts: Options): void {\n if (!opts.output) return;\n const output = path.resolve(opts.output);\n // Protect named inputs even through symlinks and hard links. Only the\n // output path itself is removed; never follow it to remove a target.\n const outputStat = fs.existsSync(output) ? fs.statSync(output) : undefined;\n for (const input of [...opts.sources, opts.args, opts.bundle].filter((p): p is string => !!p && p !== '-')) {\n const inputStat = fs.existsSync(input) ? fs.statSync(input) : undefined;\n if (path.resolve(input) === output || (outputStat && inputStat && inputStat.dev === outputStat.dev && inputStat.ino === outputStat.ino)) {\n throw new Error('--output must not overwrite an input file');\n }\n }\n fs.rmSync(output, { force: true });\n}\n\n// Why a completed run did not pass. A tool that failed (ok: false) is\n// reported in its own words; expectations are blamed only when the tool\n// succeeded and an --expect did not match.\nfunction rejection(result: Record<string, unknown>, unmet: number): string {\n if (result.ok) return `${unmet} --expect ${unmet === 1 ? 'expectation was' : 'expectations were'} not met`;\n const said = EngineError.safeParse(result);\n return said.success ? said.data.error : 'The tool failed without saying why; see its result';\n}\n\nexport async function runCli(argv: string[], io: CliIo): Promise<number> {\n try {\n if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {\n io.stdout(HELP);\n return 0;\n }\n const opts = parse(argv);\n // Protect inputs before removing stale output, but remove output before\n // reading arguments or loading the engine: either can fail this run.\n clearOutput(opts);\n const args = await argumentsFor(opts, io);\n let result: Record<string, unknown>;\n const timeoutMs = opts.timeoutMs ?? 180_000;\n if (opts.command === 'lean') {\n if (!io.checkLeanWasm) throw new Error('Lean Wasm backend is unavailable');\n io.stderr(`Checking the laws in ${opts.sources.join(', ')} with Lean Wasm at ${opts.leanWasmRoot!} `\n + `(budget ${timeoutMs} ms)...\\n`);\n result = objectValue(await io.checkLeanWasm(opts.bundle, opts.leanWasmRoot!,\n args.sources as Array<{ fileName: string; source: string }>, timeoutMs), 'Lean result');\n } else {\n if (opts.command === 'call') {\n const files = Array.isArray(args.sources) ? args.sources.length : undefined;\n const progress = callProgress(opts.tool!, files);\n if (progress) io.stderr(progress);\n }\n const engine = await io.loadEngine(opts.bundle);\n if (opts.command === 'call' && !Object.hasOwn(args, 'sources') && readsProgram(engine, opts.tool!)) {\n args.sources = folderSources(opts.tool!, opts.project);\n }\n const raw = opts.command === 'tools'\n ? engine.listTools()\n : engine.callTool(opts.command === 'verify' ? 'api_verify' : opts.tool!, JSON.stringify(args));\n result = objectJson(raw, 'Engine result');\n }\n if (typeof result.ok !== 'boolean') throw new Error('Engine result must explicitly contain boolean ok');\n const unmet = opts.expects.filter(({ pointer, value }) => !isDeepStrictEqual(readPointer(result, pointer), value));\n const passed = result.ok && unmet.length === 0;\n if (opts.select === undefined || passed) {\n const selected = opts.select === undefined ? result : readPointer(result, opts.select);\n if (selected === undefined) throw new Error(`Result field missing: ${opts.select}`);\n const text = opts.select !== undefined && typeof selected === 'string'\n ? selected : `${JSON.stringify(selected, null, 2)}\\n`;\n if (opts.output) fs.writeFileSync(opts.output, text);\n else io.stdout(text);\n }\n // verify and lean always read their verdict aloud on stderr; the JSON\n // artifact (stdout or --output) is unchanged. The generic envelope\n // below is only repeated when --select withheld the verdict JSON.\n const artifact = opts.select !== undefined ? 'the unselected result; run without --select to see it'\n : opts.output ?? 'the JSON on standard output';\n let exit: number = passed ? 0 : 1;\n if (opts.command === 'verify') {\n io.stderr(verifySummary(result, passed, artifact));\n // An id the verdict does not have is the caller's mistake, not a\n // rejected check: the engine says so by errorKind.\n if (!result.ok && result.errorKind === 'invalid-arguments') exit = 2;\n } else if (opts.command === 'lean') {\n const reading = leanSummary(result, artifact, timeoutMs, opts.sources);\n io.stderr(reading.text);\n exit = reading.exit;\n } else if (!result.ok) {\n // A failed tool is read aloud in its own words, with the next step\n // when the engine names the failure's kind; its JSON is the artifact.\n io.stderr(callFailure(opts.tool ?? 'tools', result, artifact));\n } else if (passed && opts.select === undefined && opts.command === 'call') {\n const said = callSummary(opts.tool!, result, opts.output);\n if (said) io.stderr(said);\n }\n // The JSON line is the machine-readable diagnostic wherever no JSON\n // artifact carries the failure: an unmet --expect on a completed tool,\n // and any rejection whose result --select withheld.\n const generic = opts.command === 'call' || opts.command === 'tools';\n if (!passed && (opts.select !== undefined || (generic && result.ok))) {\n io.stderr(`${JSON.stringify({ ok: false, error: rejection(result, unmet.length), unmet, result: opts.select === undefined ? undefined : result })}\\n`);\n }\n return exit;\n } catch (error) {\n // A run that could not start (bad arguments, an unreadable file, an\n // engine that would not load) is reported as a sentence; the JSON\n // envelopes above are for results the engine actually produced.\n io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}\\n`);\n return 2;\n }\n}\n","import { z } from 'zod';\n\n// The engine results this CLI reads aloud, as the engine writes them.\n\n/** ApiSafety.PropertyStatus.render: every status an api_verify property can have. */\nexport const PropertyStatus = z.enum(['proven', 'warning', 'violated', 'blocked']);\nexport type PropertyStatus = z.infer<typeof PropertyStatus>;\n\nconst Property = z.looseObject({\n id: z.string(),\n title: z.string().optional(),\n status: PropertyStatus,\n details: z.array(z.string()),\n // The declared assumption an accepted warning rests on, e.g. \"instances=1\".\n accepted: z.string().optional(),\n});\nexport type Property = z.infer<typeof Property>;\n\nexport const VerifyResult = z.looseObject({\n topology: z.string().optional(),\n verdict: z.looseObject({\n properties: z.array(Property),\n errors: z.array(z.string()).default([]),\n // Present only when the caller passed block_on_warnings: the warnings\n // among the listed properties, which made the verdict not proven.\n blockedWarnings: z.array(z.string()).optional(),\n }),\n});\n\n/** What is left to say when the verdict cannot be read: its errors, if those can. */\nexport const VerdictErrors = z.object({ verdict: z.object({ errors: z.array(z.string()) }) });\n/** ApiChecks.fail / compileFailure: a tool's error, and the kinds of compile\n * failure it names (CompileKernel.CompileErrorKind codes) when it names any. */\nexport const EngineError = z.object({ error: z.string(), errorKinds: z.array(z.string()).optional() });\n\nconst Count = z.int().nonnegative();\nexport const AbstractionMap = z.looseObject({\n measures: z.looseObject({\n definitions: Count, edges: Count, layers: Count, layerSkips: Count, usedOnce: Count, usedMany: Count,\n clonePairs: Count, duplicatedMass: Count, maxSize: Count,\n largestDefinition: z.string().optional(),\n }),\n});\n","// The human reading of an api_verify result. It is rendered from the\n// api-safety verdict's own fields (verdict.proven, verdict.properties[]\n// with id/title/status/details, verdict.errors[]) and never from the\n// narrative text or any string matching. The headline comes from the\n// same `proven === true` test that decides the exit status, so the words\n// and the exit code cannot disagree. A result whose shape cannot be read\n// says so instead of inheriting a label.\n\nimport { EngineError, VerdictErrors, VerifyResult, type Property, type PropertyStatus } from './engine-results.js';\n\nconst title = (p: Property) => p.title ?? p.id;\n\n// What each status word means, in the engine's own terms\n// (VerdictNarrative.propertyStatus).\nconst MEANING: Record<PropertyStatus, string> = {\n proven: 'holds for every input',\n warning: 'holds only under the acceptance its details name',\n violated: 'is broken; the details are the evidence',\n blocked: 'was not checked: the check could not run, could not finish, or could not see its subject',\n};\n\n// An accepted warning is safe as deployed; say so, and say what the\n// details ask for before the assumption is dropped. An acceptance this\n// CLI does not know is named verbatim.\nconst ACCEPTANCE: Record<string, string> = {\n 'instances=1': 'Safe while you run one instance (--instances 1). Before running more than one:',\n};\nconst acceptance = (a: string) => ACCEPTANCE[a] ?? `Safe under the declared ${a}. Before dropping it:`;\n\n// The word in the status column: an accepted warning reads \"accepted\".\nconst label = (p: Property) => p.status === 'warning' && p.accepted !== undefined ? 'accepted' : p.status;\n\nconst indent = (text: string, prefix: string) => text.split('\\n').map((line) => prefix + line).join('\\n');\n\nfunction count(props: Property[]): string {\n const order: string[] = [];\n const counts = new Map<string, number>();\n for (const p of props) {\n const status = label(p);\n if (!counts.has(status)) order.push(status);\n counts.set(status, (counts.get(status) ?? 0) + 1);\n }\n return order.map((status) => `${counts.get(status)} ${status}`).join(', ');\n}\n\n/** Plain-language summary of an api_verify result, ending in a newline. */\nexport function verifySummary(result: Record<string, unknown>, proven: boolean, artifact: string): string {\n const parsed = VerifyResult.safeParse(result);\n if (!parsed.success) {\n const said = EngineError.safeParse(result);\n const reason = said.success ? ` The engine said: ${said.data.error}` : '';\n const errors = VerdictErrors.safeParse(result);\n const lines = [\n proven\n ? 'Proven, but the verdict has no readable property list.'\n : `Not proven. The engine returned no readable verdict.${reason}`,\n ];\n if (errors.success && errors.data.verdict.errors.length)\n lines.push('Errors:', ...errors.data.verdict.errors.map((e) => indent(e, ' ')));\n lines.push(`The full result is in ${artifact}.`);\n return `${lines.join('\\n')}\\n`;\n }\n const checked = parsed.data.verdict.properties;\n const errors = parsed.data.verdict.errors;\n const topology = parsed.data.topology !== undefined ? ` Topology: ${parsed.data.topology}.` : '';\n const lines: string[] = [];\n if (proven) {\n lines.push(`Proven: ${checked.length} properties checked (${count(checked)}).${topology}`);\n } else {\n lines.push(`Not proven: ${checked.length} properties checked (${count(checked)}).${topology}`);\n // The first failure a reader should fix: the first violated property,\n // otherwise the first one that is neither proven nor accepted,\n // otherwise a warning the caller chose to block on.\n const blocking = new Set(parsed.data.verdict.blockedWarnings ?? []);\n const first = checked.find((p) => p.status === 'violated')\n ?? checked.find((p) => p.status !== 'proven' && p.status !== 'warning')\n ?? checked.find((p) => blocking.has(p.id));\n if (first) {\n const why = blocking.has(first.id) && first.status === 'warning'\n ? ' It blocks because --block-on-warning named it.' : '';\n lines.push(`First failure (${first.status}): ${title(first)}. This property ${MEANING[first.status]}.${why}`);\n for (const detail of first.details) lines.push(indent(detail, ' '));\n }\n }\n lines.push('Every property:');\n const width = Math.max(...checked.map((p) => label(p).length));\n for (const p of checked) {\n lines.push(` ${label(p).padEnd(width)} ${title(p)}`);\n // Warnings name the acceptance they rest on; show it beside the property.\n const pad = ` ${' '.repeat(width)} `;\n if (p.status === 'warning' && p.accepted !== undefined) lines.push(pad + acceptance(p.accepted));\n if (p.status === 'warning') for (const detail of p.details) lines.push(indent(detail, pad));\n }\n const shown = new Set(checked.flatMap((p) => p.details));\n const unshown = errors.filter((e) => !shown.has(e));\n if (unshown.length) lines.push('Errors:', ...unshown.map((e) => indent(e, ' ')));\n lines.push(`The full verdict, with every property's details, is in ${artifact}.`);\n return `${lines.join('\\n')}\\n`;\n}\n","// The human reading of a `yichus lean` result. It is rendered from the\n// Lean Wasm run's own typed fields (allVerified, proof.status,\n// proof.obligations[] with binding/status/cause/reason/diagnostics, and\n// proof.cause for a run with no rows) and never from message text. The\n// same reading decides the exit status, so the words and the exit code\n// cannot disagree:\n// 0 every discovered law was verified;\n// 1 the checker answered and something did not verify (Lean rejected a\n// theorem or its axiom audit, or a law is outside what it admits);\n// 2 the check could not finish (no runtime, the budget ran out, the\n// runtime failed) or the result could not be read.\n// A cause this CLI does not know is never mapped onto one it does.\nimport { LEAN_WASM_INSTALL_COMMAND, LeanCheckResult } from '@yichus/api-mcp';\nimport { z } from 'zod';\n\nexport interface LeanReading { text: string; exit: 0 | 1 | 2 }\n\ntype Run = LeanCheckResult['proof'];\ntype Cause = NonNullable<Run['cause']> | Extract<Run['obligations'][number], { status: 'inconclusive' }>['cause'];\n\nconst plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;\nconst indent = (value: string, prefix: string) => value.split('\\n').map((line) => prefix + line).join('\\n');\n\n// Which side of the boundary each cause is on: the checker answered, or\n// the check could not finish.\nconst SIDE: Record<Cause, 'checker' | 'harness'> = {\n rejected: 'checker', 'axiom-audit': 'checker', 'not-admitted': 'checker',\n 'runtime-missing': 'harness', timeout: 'harness', 'runtime-error': 'harness',\n};\n\nconst DEFAULT_TIMEOUT_MS = 180_000;\nconst MAX_TIMEOUT_MS = 300_000;\n\n// What to do about each cause, said once per run.\nfunction remedy(cause: Cause, timeoutMs: number, files: string[]): string[] {\n const sources = files.map((f) => `--source ${f}`).join(' ');\n switch (cause) {\n case 'runtime-missing':\n return ['Install the pinned runtime once (about 290 MB to download), then pass that folder as --lean-wasm-root:',\n ` ${LEAN_WASM_INSTALL_COMMAND.replace('NEW_DIRECTORY', '/absolute/new/folder')}`];\n case 'timeout':\n return [timeoutMs < MAX_TIMEOUT_MS\n ? `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}).`\n : `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.`];\n case 'runtime-error':\n return ['The Lean Wasm runtime could not run. If it was changed or only partly installed, install a fresh copy into a new folder:',\n ` ${LEAN_WASM_INSTALL_COMMAND.replace('NEW_DIRECTORY', '/absolute/new/folder')}`];\n case 'rejected':\n return ['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.',\n `To see a failing input, run: yichus call api_law_check ${sources}. Fix the code, not the law.`];\n case 'axiom-audit':\n 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.'];\n case 'not-admitted':\n return ['Lean Wasm proves Bool and structural List[Bool] laws with one direct witness. Check other laws with: '\n + `yichus call api_law_check ${sources}`];\n }\n}\n\nconst unreadable = (artifact: string, why: string): LeanReading => ({\n exit: 2,\n text: `Not checked: the Lean result could not be read (${why}). The full result is in ${artifact}.\\n`,\n});\n\nconst EngineError = z.object({ ok: z.literal(false), error: z.string().min(1), proof: z.undefined().optional() });\n\nconst issue = (error: z.ZodError): string => {\n const first = error.issues[0]!;\n return first.path.length ? `${first.path.join('.')}: ${first.message}` : first.message;\n};\n\n/** Plain-language reading of a `yichus lean` result, ending in a newline. */\nexport function leanSummary(raw: unknown, artifact: string, timeoutMs: number, files: string[]): LeanReading {\n const refused = EngineError.safeParse(raw);\n if (refused.success) return unreadable(artifact, `the engine said: ${refused.data.error}`);\n const parsed = LeanCheckResult.safeParse(raw);\n if (!parsed.success) return unreadable(artifact, issue(parsed.error));\n const proof = parsed.data.proof;\n const laws = proof.obligations;\n const lines: string[] = [];\n\n if (proof.status === 'verified') {\n lines.push(`Proven: ${plural(laws.length, 'law')} verified by the pinned Lean Wasm kernel.`);\n for (const row of laws) {\n if (row.status !== 'verified') continue;\n const { check, witness, domain } = row.proof.subject;\n lines.push(` ${row.binding}: ${check} holds for ${domain}, and ${witness} holds for at least one.`);\n }\n lines.push(`The proof receipt is in ${artifact}. It is a local Wasm kernel check (independentKernelReplay: false).`);\n return { exit: 0, text: `${lines.join('\\n')}\\n` };\n }\n\n // Nothing to report per law: the run itself names why.\n if (!laws.length) {\n const cause = proof.cause!;\n const checker = SIDE[cause] === 'checker';\n lines.push(`${checker ? 'Not proven' : 'Not checked'}: ${proof.reason!}.`);\n if (cause === 'not-admitted') lines.push('Fix the source, or add a Yichus/Law Obligation for lean to prove.');\n else lines.push(...remedy(cause, timeoutMs, files));\n lines.push(`The full result is in ${artifact}.`);\n return { exit: checker ? 1 : 2, text: `${lines.join('\\n')}\\n` };\n }\n\n const failed = laws.flatMap((row) => row.status === 'inconclusive' ? [row] : []);\n const causes = [...new Set(failed.map((row) => row.cause))];\n const checker = causes.some((cause) => SIDE[cause] === 'checker');\n lines.push(checker\n ? `Not proven: ${failed.length} of ${plural(laws.length, 'law')} did not verify.`\n : `Not checked: ${failed.length} of ${plural(laws.length, 'law')} could not be checked.`);\n for (const row of laws) {\n if (row.status === 'verified') { lines.push(` verified ${row.binding}`); continue; }\n lines.push(` ${row.cause.padEnd(12)} ${row.binding}: ${row.reason}.`);\n if (row.diagnostics?.length) lines.push(' Lean said:', ...row.diagnostics.map((d) => indent(d, ' ')));\n }\n for (const cause of causes) lines.push(...remedy(cause, timeoutMs, files));\n lines.push(`The full result is in ${artifact}.`);\n return { exit: checker ? 1 : 2, text: `${lines.join('\\n')}\\n` };\n}\n","// What `yichus call` says on stderr around its result. The JSON artifact\n// (stdout or --output) is unchanged; these lines only say what a slow tool\n// is doing before it starts, where the result went, and, for tools with a\n// summary block, read that block's own fields aloud in words, each with\n// the JSON field to read next. When a tool fails, it gives the tool's error\n// in plain text and, from the engine's errorKinds, what to do instead.\n// Nothing here is parsed from text.\n\nimport { AbstractionMap, EngineError } from './engine-results.js';\n\nconst plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;\n\n// api_abstraction_map's `measures` block: layers, reuse and copies.\nfunction mapSummary(result: Record<string, unknown>): string[] {\n const parsed = AbstractionMap.safeParse(result);\n if (!parsed.success) return ['The map has no readable measures block; read the JSON for its contents.'];\n const m = parsed.data.measures;\n const lines = [\n `Layers: ${plural(m.definitions, 'definition')} stacked ${plural(m.layers, 'layer')} deep `\n + '(a definition sits one layer above the highest one it uses).',\n m.layerSkips === 0\n ? `Layer skips: none of the ${plural(m.edges, 'dependency edge')} reaches past the layer just below.`\n : `Layer skips: ${m.layerSkips} of ${plural(m.edges, 'dependency edge')} reach past the layer just below, `\n + 'using a definition two or more layers down; they are the \"edges\" with \"span\" above 1.',\n `Reuse: ${plural(m.usedMany, 'definition is', 'definitions are')} used by several others, `\n + `${m.usedOnce} by exactly one (each node's \"fanIn\").`,\n m.clonePairs === 0\n ? 'Copies: no two definitions have the same compiled body.'\n : `Copies: ${plural(m.clonePairs, 'pair')} of definitions have the same compiled body; see \"clonePairs\".`,\n m.duplicatedMass === 0\n ? 'Repeats: no block of code repeats inside a definition.'\n : `Repeats: blocks repeated inside one definition add ${plural(m.duplicatedMass, 'node')}; `\n + 'nodes with \"repeatedBlockMass\" above 0 list each block\\'s places in \"repeatedBlocks\".',\n ];\n if (m.largestDefinition !== undefined)\n lines.push(`Largest definition: ${m.largestDefinition} (${m.maxSize} nodes).`);\n return lines;\n}\n\ninterface Known {\n noun: string;\n // Said before the tool runs, so a long run is not silence.\n progress: (files: number | undefined) => string;\n summary: (r: Record<string, unknown>) => string[];\n}\n\nconst SUMMARIES: Record<string, Known> = {\n api_abstraction_map: {\n noun: 'the abstraction map',\n progress: (files) => `Mapping ${files === undefined ? 'the program' : plural(files, 'Bosatsu file')}: `\n + 'compiling it and measuring every definition, which can take half a minute or more for a large program...',\n summary: mapSummary,\n },\n};\n\n/** A line for stderr before a slow tool runs, or undefined for any other tool. */\nexport function callProgress(tool: string, files: number | undefined): string | undefined {\n const known = SUMMARIES[tool];\n return known ? `${known.progress(files)}\\n` : undefined;\n}\n\n/** Lines for stderr after a successful call, or undefined when there is nothing to say. */\nexport function callSummary(tool: string, result: Record<string, unknown>, output: string | undefined): string | undefined {\n const known = SUMMARIES[tool];\n const lines: string[] = [];\n if (output) lines.push(`Wrote ${known?.noun ?? `the ${tool} result`} to ${output}.`);\n if (known) lines.push(...known.summary(result));\n return lines.length ? `${lines.join('\\n')}\\n` : undefined;\n}\n\n// What to do instead, for each compile-failure kind the engine names\n// (CompileKernel.CompileErrorKind codes). A kind not listed here gets no\n// advice line; the error's own words still say what went wrong.\nconst NEXT_STEP: Record<string, string> = {\n 'duplicate-package': 'Each package can be declared by only one file. '\n + 'Give each file its own package name, or pass only one of them.',\n};\n\n/**\n * Lines for stderr when a tool returned ok:false: the tool's error as plain\n * text, what to do instead when the engine names the failure's kind, and\n * where the full JSON result is.\n */\nexport function callFailure(tool: string, result: Record<string, unknown>, artifact: string): string {\n const said = EngineError.safeParse(result);\n const lines = said.success\n ? [`${tool} failed:`, said.data.error]\n : [`${tool} failed without saying why.`];\n if (said.success)\n for (const kind of said.data.errorKinds ?? []) if (Object.hasOwn(NEXT_STEP, kind)) lines.push(`Next: ${NEXT_STEP[kind]}`);\n lines.push(`The full result is in ${artifact}.`);\n return `${lines.join('\\n')}\\n`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { type StudioEngine, direct, readState } from './director.js';\nimport { pageNote, recordAnswer, recordNames, recordRules, recordScenarios, recordStart } from './mcp.js';\nimport { type Locate, readReference, topicList } from './reference.js';\nimport { recordMarks } from './marks.js';\nimport { runningPageUrl } from './page-link.js';\nimport { pageText } from './page-view.js';\nimport { loadRequirements } from './requirements.js';\nimport { CLI, CLI_LEGEND } from './surface.js';\nimport { stepText } from './text.js';\n\n// The studio from a terminal: the same director as the MCP tools, for an\n// agent that runs shell commands, or a person who wants to look.\n//\n// yichus start \"what to build\" record the description\n// yichus next [--json] run the checks and print the next step\n// yichus name SUBJECT \"NAME\" ... plain names for parts of the program\n// yichus answer QUESTION CHOICE [--words TEXT]\n// yichus rules FILE.json the rules the person stated, with the laws that check each\n// yichus scenario FILE.json what should happen in actions, in the person's words\n// yichus point FILE.json point at parts of the page, with notes\n// yichus page the page as the person sees it, in words\n// yichus reference [TOPIC] reference material a step asks for; no topic lists them\n// yichus studio [--page] [--port N] the MCP server and page (--page: page only)\n\nexport const STUDIO_COMMANDS = new Set(['start', 'next', 'name', 'answer', 'rules', 'scenario', 'point', 'page', 'reference', 'studio']);\n\nexport const STUDIO_HELP = `\nStudio (guided building; all take --project DIR, default the current folder).\nKeep the project in a folder of its own, apart from any old app it replaces:\nthe studio reads every .bosatsu file in it.\n yichus studio [--port N] MCP server on stdio plus the studio page\n yichus studio --page [--port N] only the studio page, for the commands below\n yichus start \"DESCRIPTION\" record what the person wants built\n yichus next [--json] check the program and print the next step\n yichus name SUBJECT \"NAME\" ... plain names the person sees for parts of the program\n yichus answer QUESTION CHOICE [--words TEXT]\n yichus rules FILE.json the rules the person stated: {\"rules\": [{\"rule\": ..., \"laws\": [...]}]}\n yichus scenario FILE.json what should happen in actions: {\"scenarios\": [...], \"drop\": [...]}\n yichus point FILE.json point at parts of the page: {\"marks\": [{\"at\": ..., \"note\": ...}]}\n yichus page the page as the person sees it now, in words\n yichus reference [TOPIC] reference material a step asks for; no topic lists them\n`;\n\nexport interface StudioIo {\n engine(): Promise<StudioEngine>;\n serve(options: { root: string; port: number | null; pageOnly: boolean }): Promise<void>;\n stdout(text: string): void;\n stderr(text: string): void;\n now(): Date;\n locate: Locate;\n}\n\nexport async function runStudioCommand(argv: string[], io: StudioIo): Promise<number> {\n try {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, strict: true, options: {\n project: { type: 'string' }, json: { type: 'boolean' }, words: { type: 'string' }, page: { type: 'boolean' }, port: { type: 'string' },\n } });\n const [command, ...rest] = positionals;\n const root = path.resolve(values.project ?? '.');\n const expect = (n: number, usage: string) => { if (rest.length !== n) throw new Error(`Usage: ${usage}`); };\n if (command === 'start') {\n expect(1, 'yichus start \"DESCRIPTION\"');\n const result = recordStart(root, { description: rest[0]! }, CLI);\n if (!result.ok) throw new Error(result.error);\n io.stdout(`Recorded the description.\\n${pageNote(runningPageUrl(root), CLI)}\\nIf this replaces an app the person already has, run \\`yichus reference porting\\` first.\\nNext: yichus next\\n`);\n return 0;\n }\n if (command === 'name') {\n if (!rest.length || rest.length % 2) throw new Error('Usage: yichus name SUBJECT \"NAME\" [SUBJECT \"NAME\" ...]');\n const names = Object.fromEntries(rest.flatMap((s, i) => i % 2 ? [] : [[s, rest[i + 1]!]]));\n const result = recordNames(root, { names }, CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr(`Named ${Object.entries(names).map(([subject, name]) => `${subject} \"${name}\"`).join(', ')}. Next: yichus next\\n`);\n return 0;\n }\n if (command === 'answer') {\n expect(2, 'yichus answer QUESTION CHOICE [--words TEXT]');\n const [question, choice] = rest as [string, string];\n const result = recordAnswer(root, { question, choice, words: values.words ?? '' }, io.now(), CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr(`Recorded ${choice} for ${question}. Next: yichus next\\n`);\n return 0;\n }\n if (command === 'rules') {\n expect(1, 'yichus rules FILE.json');\n const result = recordRules(root, JSON.parse(fs.readFileSync(path.resolve(rest[0]!), 'utf8')), CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr('Recorded the rules. Next: yichus next\\n');\n return 0;\n }\n if (command === 'scenario') {\n expect(1, 'yichus scenario FILE.json');\n const result = recordScenarios(root, JSON.parse(fs.readFileSync(path.resolve(rest[0]!), 'utf8')), CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr('Recorded the scenarios. Next: yichus next\\n');\n return 0;\n }\n if (command === 'point') {\n expect(1, 'yichus point FILE.json');\n const result = recordMarks(root, JSON.parse(fs.readFileSync(path.resolve(rest[0]!), 'utf8')), io.now());\n if (!result.ok) throw new Error(result.error);\n io.stderr('The page shows the notes now.\\n');\n return 0;\n }\n if (command === 'page') {\n expect(0, 'yichus page');\n io.stdout(pageText(root, runningPageUrl(root), io.now(), CLI));\n return 0;\n }\n if (command === 'reference') {\n if (rest.length > 1) throw new Error('Usage: yichus reference [TOPIC]');\n const list = topicList(topic => `yichus reference ${topic}`);\n if (!rest.length) { io.stdout(`${list}\\n`); return 0; }\n const said = readReference(rest[0]!, io.locate);\n if (!said) throw new Error(`No reference topic ${rest[0]!}.\\n${list}`);\n io.stdout(`${CLI_LEGEND}\\n\\n${said}\\n`);\n return 0;\n }\n if (command === 'next') {\n expect(0, 'yichus next [--json]');\n const state = await direct({ root, engine: await io.engine(), requirements: loadRequirements(root), previous: readState(root), say: CLI });\n io.stdout(values.json ? `${JSON.stringify(state, null, 2)}\\n` : stepText(state, runningPageUrl(root)));\n return 0;\n }\n expect(0, 'yichus studio [--page] [--port N]');\n const port = values.port === undefined ? null : Number(values.port);\n if (port !== null && (!Number.isInteger(port) || port < 0 || port > 65535)) throw new Error('--port must be a port number');\n await io.serve({ root, port, pageOnly: values.page ?? false });\n return 0;\n } catch (error) {\n io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}\\n`);\n return 2;\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { buildSystemMap } from '../../../../web/system-map-record.js';\nimport { nameableParts } from '../../../../web/system-map-names.js';\nimport { buildWhatHappens } from '../../../../web/what-happens-record.js';\nimport { type SourceFile, caseSources, projectSources, sourcesHash } from './project.js';\nimport { ACCESS_RULES, HOST_SECTION, PAGE_ONLY, PLATFORM_SECTION, type Question, Report, Structure, hostQuestion, platform, questionsFor } from './questions.js';\nimport { type Answer, type Requirements, ensureStudioDir, studioDir } from './requirements.js';\nimport { WhatHappens, owed, replies, unfollowed } from './scenarios.js';\nimport { MCP, type Say } from './surface.js';\n\n// The director: from the program on disk, the person's answers and the\n// engine's verdicts, the one next step for the agent. Every status here is\n// copied from an engine result; the director only decides what to do next.\n\nexport interface StudioEngine {\n call(tool: string, args: Record<string, unknown>): Promise<Record<string, unknown>>;\n}\n\nexport type Status =\n | 'unanswered' | 'decided' | 'assumed' | 'proven' | 'bounded'\n | 'broken' | 'mismatch' | 'needs-case' | 'needs-law' | 'unused' | 'inconclusive' | 'no-check';\n\nexport interface Property {\n question: Question;\n answer: Answer | null;\n status: Status;\n /** Engine output that backs the status, verbatim. */\n evidence: string[];\n /** The engine check the status comes from. */\n check: string | null;\n /** For a failure question: the protocol case file, from the project folder. */\n casePath?: string;\n}\n\n/** One law the program declares (Yichus/Law), as api_law_check found it. */\nexport interface Law {\n /** The binding that declares it, Package::name. */\n binding: string;\n /** The law's own name, when the check could read it. */\n name: string | null;\n status: 'proven' | 'bounded' | 'broken' | 'inconclusive';\n /** The app's actions that call what the law checks; null when the app\n * has no actions to compare with. */\n usedBy: string[] | null;\n evidence: string[];\n}\n\n/** A rule the person stated, in their words, with the laws that check it. */\nexport interface Rule {\n rule: string;\n laws: string[];\n status: Status;\n evidence: string[];\n}\n\nexport type Stage = 'describe' | 'write' | 'fix-compile' | 'rules' | 'name' | 'ask' | 'declare' | 'fix' | 'scenarios' | 'write-case' | 'done';\nexport interface Step {\n stage: Stage;\n /** One sentence the page shows the person. */\n summary: string;\n /** What the agent does now, in order. */\n instructions: string[];\n /** What the instructions work through, one per line, apart from them. */\n items?: { heading: string; lines: string[] };\n ask?: Array<{ id: string; ask: string; why: string; choices: Question['choices'] }>;\n evidence?: string[];\n}\n\n// A warning with an accepted field is safe under an assumption the person\n// declared (one server); any other warning is not.\nconst VerifyProperty = z.looseObject({ id: z.string(), title: z.string(), status: z.string(), details: z.array(z.string()).default([]),\n accepted: z.unknown().optional() });\nconst Verify = z.looseObject({\n topology: z.string().optional(),\n verdict: z.looseObject({ proven: z.boolean(), properties: z.array(VerifyProperty) }),\n});\ntype VerifyProperty = z.infer<typeof VerifyProperty>;\nconst Protocol = z.looseObject({ protocol: z.looseObject({ status: z.string(), name: z.string().optional() }).optional(), error: z.string().optional() });\n// api_law_check: each obligation's verdict. With no laws declared, a\n// sampled check answers ok with no laws record.\n// An exhaustive row's scope says what \"every input\" covered: the input\n// type's every value, or only the values a FiniteObligation lists.\nconst LawRow = z.looseObject({ binding: z.string(), law: z.string().nullable().optional(), verdict: z.string(), complete: z.boolean().optional(),\n scope: z.looseObject({ kind: z.string() }).optional(),\n detail: z.string().optional(), reason: z.string().optional(), counterexample: z.string().optional() });\n// reach: for each law, the routes that call what it checks; absent when\n// the program declares no route.\nconst LawCheck = z.looseObject({ laws: z.looseObject({ obligations: z.array(LawRow) }).optional(), notSampled: z.array(z.looseObject({ binding: z.string() })).optional(),\n reach: z.array(z.looseObject({ binding: z.string(), usedBy: z.array(z.string()) })).optional() });\ntype Reach = Map<string, string[]>;\ntype LawRow = z.infer<typeof LawRow>;\n// What one mode of the law check answered.\ntype LawAnswer = { kind: 'rows'; rows: LawRow[]; reach: Reach | null } | { kind: 'refused'; reason: string };\n\nexport interface StudioState {\n schemaVersion: 'yichus-studio-state-1';\n project: string;\n updatedAt: string;\n sourcesHash: string;\n files: string[];\n description: string | null;\n names: Record<string, string>;\n topology: string | null;\n proven: boolean | null;\n properties: Property[];\n /** Verify properties no question covers that are not proven. */\n other: Array<{ id: string; title: string; status: string; details: string[] }>;\n /** Every law the program declares, checked. */\n laws: Law[];\n lawsError: string | null;\n /** Whether the agent has listed the rules the person stated (an empty\n * list says they stated none). */\n rulesListed: boolean;\n rules: Rule[];\n step: Step;\n map: unknown;\n mapError: string | null;\n /** api_organize lens=layers, for the layer stack. */\n layers: unknown;\n /** Whether the program has actions people call (it declares routes), or\n * null before it compiles; a calculation has none, so nothing is\n * followed through. */\n hasActions: boolean | null;\n /** Each action's decision tree with the scenarios checked on it\n * (web/what-happens-record.js). */\n whatHappens: WhatHappens | null;\n whatHappensError: string | null;\n}\n\n/** The protocol case file for a question, written by the agent. */\nexport const caseFile = (root: string, questionId: string) =>\n path.join(studioDir(root), 'cases', `${questionId.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '')}.json`);\n\nconst answerOf = (requirements: Requirements, id: string) => requirements.answers.find(a => a.question === id) ?? null;\n\nfunction instancesFor(requirements: Requirements): string | undefined {\n const choice = answerOf(requirements, 'topology')?.choice;\n return choice === 'one' ? '1' : choice === 'many' ? 'many' : undefined;\n}\n\n// The engine answers ok:false when it could not run a tool; that is never a verdict.\nasync function call(engine: StudioEngine, tool: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {\n const result = await engine.call(tool, args);\n if (result.ok !== true) throw new Error(`${tool} failed: ${typeof result.error === 'string' ? result.error : 'no reason given'}`);\n return result;\n}\n\nconst isAccepted = (p: VerifyProperty) => p.status === 'warning' && p.accepted !== undefined;\n// The table a race-free finding is about: \"race-free:books: ...\".\nconst raceCell = (detail: string) => /^race-free:([^:\\s]+):/.exec(detail)?.[1] ?? null;\n\nconst worst = (props: VerifyProperty[]): VerifyProperty | undefined =>\n props.find(p => p.status !== 'proven' && !isAccepted(p)) ?? props.find(isAccepted);\n\nasync function judge(root: string, engine: StudioEngine, sources: SourceFile[], question: Question, saved: Answer | null,\n report: Report, verify: VerifyProperty[], together: Set<string> = new Set()): Promise<Property> {\n // A saved choice the question no longer offers is no answer: the question is asked again.\n const answer = saved && question.choices.some(c => c.id === saved.choice) ? saved : null;\n const base = { question, answer, evidence: [] as string[], check: null as string | null };\n if (!answer) return { ...base, status: 'unanswered' };\n const byId = (id: string) => verify.find(p => p.id === id);\n switch (question.kind) {\n case 'platform':\n case 'host':\n case 'sign-in':\n case 'data':\n return { ...base, status: 'decided' };\n case 'topology':\n return { ...base, status: answer.choice === 'one' ? 'assumed' : 'decided',\n evidence: answer.choice === 'one' ? ['Every check below assumes exactly one copy of the server runs.'] : [] };\n case 'access': {\n const table = report.dataModel.tables.find(t => t.name === question.subject);\n const rule = ACCESS_RULES[answer.choice]!;\n const access = table?.access ?? null;\n const check = 'api_report dataModel.tables[].access';\n if (!access || !rule.declared(access)) {\n return { ...base, status: 'mismatch', check,\n evidence: [`\"${question.subject}\" is declared ${table?.policy ?? 'with no rule'}; the person chose ${rule.write}.`] };\n }\n // Only worker routes are the app's own server: a role a person holds is still a person.\n const personal = answer.choice === 'server-only'\n ? report.surface.routes.filter(r => r.tables.includes(question.subject!) && r.authority !== 'requires-worker') : [];\n if (personal.length) {\n return { ...base, status: 'mismatch', check: 'api_report surface.routes[].authority',\n 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.`) };\n }\n const prop = byId(`access:${question.subject}`) ?? byId('access-coverage');\n if (!prop) return { ...base, status: 'inconclusive', check: 'api_verify', evidence: ['api_verify reported no access property for this table.'] };\n return { ...base, check: `api_verify ${prop.id}`, evidence: prop.details,\n status: prop.status === 'proven' ? 'proven' : 'broken' };\n }\n case 'together': {\n // A race the engine names on another table that has its own question\n // is that question's, not this one's.\n const elsewhere = (p: VerifyProperty) => p.details.length > 0 && p.details.every(d => {\n const cell = raceCell(d);\n return cell !== null && cell !== question.subject && together.has(cell);\n });\n const props = verify.filter(p => (p.id === 'rmw-transactions' || p.id === 'integrity') && !elsewhere(p));\n const bad = worst(props);\n const mentions = (p: VerifyProperty) => p.details.filter(d => d.includes(`\"${question.subject}\"`) || raceCell(d) === question.subject);\n const evidence = props.flatMap(p => mentions(p).length ? mentions(p) : p.status === 'proven' ? [] : p.details);\n const check = `api_verify ${props.map(p => p.id).join(' + ')}`;\n if (!bad) return { ...base, check, evidence, status: props.length ? 'proven' : 'inconclusive' };\n return { ...base, check, evidence, status: isAccepted(bad) ? 'assumed' : 'broken' };\n }\n case 'partial':\n case 'outside': {\n if (answer.choice === 'partial-ok' || answer.choice === 'no-plan') return { ...base, status: 'no-check' };\n const file = caseFile(root, question.id);\n const rel = path.relative(root, file).split(path.sep).join('/');\n if (!fs.existsSync(file)) return { ...base, casePath: rel, status: 'needs-case', check: 'api_protocol_check', evidence: [`No protocol case at ${rel} yet.`] };\n let protocolCase: unknown;\n try { protocolCase = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (error) {\n return { ...base, casePath: rel, check: 'api_protocol_check', status: 'inconclusive',\n evidence: [`${rel} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`] };\n }\n const result = Protocol.parse(await engine.call('api_protocol_check', { sources: [...sources, ...caseSources(root)], case: protocolCase }));\n const status = result.protocol?.status;\n const check = `api_protocol_check ${rel}`;\n if (!status) return { ...base, casePath: rel, check, status: 'inconclusive', evidence: [result.error ?? 'The protocol check gave no status.'] };\n // A holds verdict covers the finite case only, never every input.\n return { ...base, casePath: rel, check, evidence: [`${result.protocol?.name ?? rel}: ${status}`],\n status: status === 'holds' ? 'bounded' : status === 'violated' ? 'broken' : 'inconclusive' };\n }\n }\n}\n\nconst reason = (result: Record<string, unknown>) => typeof result.error === 'string' ? result.error : 'no reason given';\n\n/** Every law the program declares, checked both ways the engine can: over\n * seeded inputs, and over every input where the domain is finite. A\n * sampled check leaves each FiniteObligation to the exhaustive one. */\nasync function checkLaws(engine: StudioEngine, sources: SourceFile[]): Promise<{ laws: Law[]; error: string | null }> {\n const answer = async (mode: 'sampled' | 'exhaustive'): Promise<{ answer: LawAnswer; finite: string[] }> => {\n const result = await engine.call('api_law_check', { sources, ...(mode === 'exhaustive' ? { mode } : {}) });\n if (result.ok !== true) return { answer: { kind: 'refused', reason: reason(result) }, finite: [] };\n const parsed = LawCheck.parse(result);\n const reach = parsed.reach ? new Map(parsed.reach.map(r => [r.binding, r.usedBy])) : null;\n return { answer: { kind: 'rows', rows: parsed.laws?.obligations ?? [], reach }, finite: (parsed.notSampled ?? []).map(n => n.binding) };\n };\n const sampled = await answer('sampled');\n // No law of either kind: nothing to check.\n if (sampled.answer.kind === 'rows' && !sampled.answer.rows.length && !sampled.finite.length) return { laws: [], error: null };\n const { answer: exhaustive } = await answer('exhaustive');\n if (sampled.answer.kind === 'refused' && exhaustive.kind === 'refused')\n return { laws: [], error: `api_law_check failed: ${sampled.answer.reason}; exhaustive: ${exhaustive.reason}` };\n const rowsOf = (a: LawAnswer) => a.kind === 'rows' ? a.rows : [];\n const reach = [sampled.answer, exhaustive].flatMap(a => a.kind === 'rows' && a.reach ? [a.reach] : [])[0] ?? null;\n // A law the sampled check left to the exhaustive one stays listed even when that check is refused.\n const bindings = [...new Set([...rowsOf(sampled.answer).map(r => r.binding), ...sampled.finite, ...rowsOf(exhaustive).map(r => r.binding)])];\n return { error: null, laws: bindings.map(binding => {\n const s = rowsOf(sampled.answer).find(r => r.binding === binding);\n const e = rowsOf(exhaustive).find(r => r.binding === binding);\n const listed = e?.scope !== undefined && e.scope.kind !== 'type-wide';\n const said = (mode: string, r: LawRow) =>\n `${mode}: ${r.verdict}${r.detail ? `; ${r.detail}` : ''}${r.reason ? `; ${r.reason}` : ''}${r.counterexample ? `; counterexample ${r.counterexample}` : ''}`;\n const evidence = [\n ...s ? [said('sampled', s)] : [],\n ...!s && sampled.answer.kind === 'refused' ? [`sampled: refused; ${sampled.answer.reason}`] : [],\n ...!s && sampled.finite.includes(binding) ? ['sampled: left to the check over its listed inputs'] : [],\n ...!e && exhaustive.kind === 'refused' ? [`every input: refused; ${exhaustive.reason}`] : [],\n ...e ? [said(listed ? 'only the listed inputs' : 'every input', e)] : []];\n const name = s?.law ?? e?.law ?? null;\n const usedBy = reach?.get(binding) ?? null;\n if (usedBy && !usedBy.length) evidence.push('used by: no action of the app reaches what its check calls');\n // Only a pass over every value of the input type is a proof; a pass\n // over listed inputs says nothing about the rest.\n const status: Law['status'] = s?.verdict === 'violated' || e?.verdict === 'violated' ? 'broken'\n : e?.verdict === 'holds-exhaustive' ? (e.complete && e.scope?.kind === 'type-wide' ? 'proven' : 'bounded')\n : s?.verdict === 'holds' ? 'bounded' : 'inconclusive';\n return { binding, name, status, usedBy, evidence };\n }) };\n}\n\n/** A law a rule names: by its binding, the binding's own name, or the law's name. */\nconst lawNamed = (laws: Law[], ref: string) => laws.find(l => l.binding === ref || l.binding.endsWith(`::${ref}`) || l.name === ref);\n\n/** A law whose check calls nothing an action reaches says nothing about the app. */\nconst unused = (law: Law) => law.usedBy !== null && !law.usedBy.length;\n\n/** A rule holds as well as its weakest law. */\nfunction judgeRule(rule: { rule: string; laws: string[] }, laws: Law[]): Rule {\n const found = rule.laws.map(ref => [ref, lawNamed(laws, ref)] as const);\n const missing = found.filter(([, law]) => !law).map(([ref]) => ref);\n const checked = found.flatMap(([, law]) => law ? [law] : []);\n const evidence = [...missing.map(ref => `No law named ${ref} in the program.`), ...checked.flatMap(l => l.evidence.map(e => `${l.name ?? l.binding}: ${e}`))];\n const status: Status = missing.length || !checked.length ? 'needs-law'\n : checked.some(l => l.status === 'broken') ? 'broken'\n : checked.some(l => l.status === 'inconclusive') ? 'inconclusive'\n : checked.some(unused) ? 'unused'\n : checked.every(l => l.status === 'proven') ? 'proven' : 'bounded';\n return { ...rule, status, evidence };\n}\n\nconst 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.';\n\nconst QUESTION_PROPERTIES = (id: string) => id.startsWith('access:') || id === 'access-coverage' || id === 'rmw-transactions' || id === 'integrity';\n\nconst GUIDE: Partial<Record<Question['kind'], string>> = {\n access: 'Owner-scoped data',\n together: 'Atomic commands with Yichus/Transaction',\n partial: 'Transaction protocols: finite cases, retries, and receipts',\n outside: 'Transaction protocols: finite cases, retries, and receipts',\n};\n\n// What api_scaffold takes, so the step can be followed without its schema;\n// a policy is owner or public.\nexport const SCAFFOLD_ARGS = { package_name: 'My/App/Api', service_name: 'my_app',\n resources: [{ name: 'record', fields: [{ name: 'title', type: 'String' }], policy: 'owner' }] };\n\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;\nconst capital = (s: string) => `${s[0]!.toUpperCase()}${s.slice(1)}`;\n\nconst askStep = (open: Property[], say: Say): Step => ({\n stage: 'ask',\n summary: `${plural(open.length, 'question', 'questions')} for you about how the app should behave.`,\n instructions: [\n 'Ask the person each question below, in its words, with its choices. They may also answer on the studio page.',\n 'Speak in product terms: never quote question ids, code names, file names, tool names or the programming language to the person.',\n '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.',\n `Record each answer: ${say.use('yichus_answer')} with the question id, the choice id, and their own words. Then ${say.use('yichus_next')}.`,\n ],\n ask: open.map(p => ({ id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices })),\n});\n\n/** Where the app's pieces run: the platform's section of the deploy\n * reference, and the server host's when the platform holds only pages.\n * None for a program with no server, which is never asked. */\nfunction deploySections(state: Omit<StudioState, 'step'>): string[] {\n const choice = (kind: Question['kind']) => state.properties.find(p => p.question.kind === kind)?.answer?.choice;\n const where = choice('platform');\n if (!where) return [];\n const host = choice('host');\n return host ? [PLATFORM_SECTION[where]!, HOST_SECTION[host]!] : [PLATFORM_SECTION[where]!];\n}\nconst sectionsText = (sections: string[]) => sections.map(s => `\"${s}\"`).join(' and ');\n\nexport function nextStep(state: Omit<StudioState, 'step'>, compileErrors: string[] | null, say: Say = MCP): Step {\n const next = `Then ${say.use('yichus_next')}.`;\n if (!state.description) return {\n stage: 'describe',\n summary: 'Waiting for a description of what to build.',\n instructions: [`Ask the person what they want to build, in their own words. ${capital(say.use('yichus_start'))} with their description, unchanged.`],\n };\n const sections = deploySections(state);\n if (!state.files.length) return {\n stage: 'write',\n summary: 'No program yet.',\n instructions: [\n `If this replaces an app the person already has, ${say.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.`,\n '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.',\n `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 ${say.reference('deploy')} then says how to put it online.`,\n `${capital(say.api('api_guide', { section: 'Required workflow' }))}, then write the program as .bosatsu files in this project folder.`,\n `For an app that stores records, ${say.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.`,\n `Shape the records to the people in the description before you show anything. The scaffold's owner and public records are only a start.`,\n '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.',\n `Records other people must see (a coordinator who sees every sign-up) need a rule that lets them in, not owner-only. ${capital(say.api('api_guide', { section: 'Guarded data' }))} for how to write one with roles.`,\n '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.',\n `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: ${say.reference('portable-programs')} before writing it.`,\n `Write each rule the person states about what the app must always or never do as a law: ${say.reference('laws')} for the syntax, the standard functions and a worked example.`,\n '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.',\n next,\n ],\n };\n if (compileErrors) return {\n stage: 'fix-compile',\n summary: 'The program does not compile yet.',\n instructions: [`Fix these compile errors in the files. ${next}`, `For the standard functions the language has, ${say.reference('laws')}.`],\n evidence: compileErrors,\n };\n if (!state.rulesListed) return {\n stage: 'rules',\n summary: 'Your agent is writing down the rules you gave for your app, so each one is checked.',\n instructions: [\n '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\").',\n `Write a law for each rule in a .bosatsu file of the app (${say.reference('laws')} for the syntax, the standard functions and a worked example). A law states the rule, never what the code happens to do.`,\n `${capital(say.use('yichus_next'))} so the studio finds the laws you wrote, then record the rules with the laws that check each: ${say.useWith('yichus_rules', '{\"rules\": [{\"rule\": their words, \"laws\": [law names]}]}')}. If they stated no rule, record an empty list.`,\n '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.',\n next,\n ],\n ...state.laws.length ? { items: { heading: 'Laws the program has', lines: state.laws.map(l => `${l.binding}${l.name ? ` (\"${l.name}\")` : ''}: ${l.status}`) } } : {},\n };\n // Questions name their subjects, the picture draws every part, and the\n // page says what each action answers.\n const unnamed = new Map<string, string[]>();\n for (const { question } of state.properties) {\n if (question.subject !== null && !(question.subject in state.names)) unnamed.set(question.subject, [...unnamed.get(question.subject) ?? [], question.fact]);\n }\n for (const { code, what } of drawnParts(state)) {\n if (!(code in state.names) && !unnamed.has(code)) unnamed.set(code, [`${capital(what)}.`]);\n }\n if (unnamed.size) return {\n stage: 'name',\n summary: 'Your agent is putting the parts of your app into plain words.',\n instructions: [\n '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\").',\n `${capital(say.use('yichus_name'))} with all of them at once. ${next}`,\n ],\n items: { heading: 'Parts to name', lines: [...unnamed].map(([subject, facts]) => `${subject}: ${facts.join(' ')}`) },\n };\n const unanswered = state.properties.filter(p => p.status === 'unanswered');\n if (unanswered.length) return askStep(unanswered, say);\n const mismatched = state.properties.filter(p => p.status === 'mismatch');\n if (mismatched.length) return {\n stage: 'declare',\n summary: 'The program\\'s declared rules do not match what you chose yet.',\n instructions: [\n ...mismatched.map(p => {\n const rule = ACCESS_RULES[p.answer!.choice]!;\n return `Make the AccessSpec rule for \"${p.question.subject}\" ${rule.write}${p.answer!.choice === 'server-only' ? ', and reach it only from worker routes' : ''} (${say.api('api_add_rule')} for the snippet; ${say.api('api_guide', { section: rule.guide })} for what it means).`;\n }),\n next,\n ],\n evidence: mismatched.flatMap(p => p.evidence),\n };\n // A broken property comes before describing what happens: an action that\n // leaks records is fixed, not described.\n const broken = state.properties.filter(p => p.status === 'broken' || p.status === 'inconclusive');\n const failing = state.other.filter(o => o.status !== 'warning');\n const warnings = state.other.filter(o => o.status === 'warning');\n const brokenRules = state.rules.filter(r => r.status !== 'proven' && r.status !== 'bounded');\n const ruled = new Set(state.rules.flatMap(r => r.laws.flatMap(ref => lawNamed(state.laws, ref)?.binding ?? [])));\n const brokenLaws = state.laws.filter(l => !ruled.has(l.binding) && (l.status === 'broken' || l.status === 'inconclusive' || unused(l)));\n const notHolding = broken.length + failing.length + brokenRules.length + brokenLaws.length + (state.lawsError ? 1 : 0);\n if (notHolding || warnings.length) return {\n stage: 'fix',\n summary: [notHolding ? `${notHolding === 1 ? '1 property is' : `${notHolding} properties are`} not holding yet.` : '',\n warnings.length ? `${plural(warnings.length, 'warning needs', 'warnings need')} a look.` : ''].filter(Boolean).join(' '),\n instructions: [\n 'Fix the program so each property below holds. The evidence lines are the engine\\'s own words.',\n ...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(say.api('api_guide', { section: GUIDE[p.question.kind]! }))} for how.` : ''}`),\n ...failing.map(o => `${o.title} (${o.id}) is ${o.status}.`),\n ...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.`),\n ...brokenRules.map(r => r.status === 'needs-law'\n ? `The person's rule \"${r.rule}\" has no law in the program that checks it. Write one (${say.reference('laws')} for how), then record the rules again with ${say.name('yichus_rules')}.`\n : 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}`\n : `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.`),\n ...brokenLaws.map(l => `The law ${l.name ? `\"${l.name}\" (${l.binding})` : l.binding} ${l.status === 'broken' ? 'is broken. Change the code, never the law.'\n : l.status === 'inconclusive' ? 'is not decided. Change the code, never the law.' : `checks code no action of the app reaches. ${USE_THE_LAW}`}`),\n ...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.'] : [],\n `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}`,\n ],\n evidence: [...broken.flatMap(p => p.evidence), ...state.other.flatMap(o => o.details), ...brokenRules.flatMap(r => r.evidence),\n ...brokenLaws.flatMap(l => l.evidence), ...state.lawsError ? [state.lawsError] : []],\n };\n const scenarios = state.whatHappens;\n const owes = scenarios ? owed(scenarios) : [];\n if (scenarios && (owes.length || scenarios.refused.length || scenarios.notes.length || scenarios.mismatches.length)) return {\n stage: 'scenarios',\n summary: 'Your agent is writing down, in your words, what should happen in each thing your app does.',\n instructions: [\n `Write down what should happen in each action listed below, as the person would say it, and ${say.use('yichus_scenario')} with all of them at once. For each action give:`,\n 'title: what the person does (\"You add a note\").',\n '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\").',\n '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.',\n '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.',\n ...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.'] : [],\n ...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.'] : [],\n next,\n ],\n ...owes.length ? { items: { heading: 'Actions to describe', lines: owes.flatMap(o => [\n `${o.entry}${o.undescribed ? ' (not described yet)' : ''}:`,\n ...o.unnamed.map(u => ` ${u.id}: ${u.what}`),\n ...o.uncovered.length ? [` outcomes no claim covers: ${o.uncovered.join(', ')}`] : [],\n ]) } } : {},\n evidence: [\n ...scenarios.refused.map(r => `${r.entry}: \"${r.words}\" at ${r.id} was refused: ${r.reason}`),\n ...scenarios.notes.map(n => `${n.entry}: \"${n.text}\" at ${n.at} is not a claim`),\n ...scenarios.mismatches.map(m => `${m.entry}: ${m.reason}`),\n ],\n };\n const claims = (scenarios?.claims ?? []).filter(c => c.verdict !== 'holds');\n // Scenarios that could not be checked never count as holding.\n const unfollowedEntries = scenarios ? unfollowed(scenarios) : [];\n const open = claims.length + (state.whatHappensError ? 1 : 0) + unfollowedEntries.length;\n if (open) return {\n stage: 'fix',\n summary: `${open === 1 ? '1 property is' : `${open} properties are`} not holding yet.`,\n instructions: [\n 'Fix the program so each property below holds. The evidence lines are the engine\\'s own words.',\n ...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.`),\n ...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.'] : [],\n ...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.'] : [],\n `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}`,\n ],\n evidence: [...claims.map(c => `${c.entry} at ${c.at}: ${c.parsed}: ${c.verdict}`), ...state.whatHappensError ? [state.whatHappensError] : [],\n ...unfollowedEntries.map(u => `${u.entry} could not be followed: ${u.why}`)],\n };\n const cases = state.properties.filter(p => p.status === 'needs-case');\n if (cases.length) return {\n stage: 'write-case',\n summary: 'Writing the failure scenarios that test your answers.',\n instructions: [\n `${capital(say.reference('protocol-case'))}: it gives the case specification and a complete worked case with its program.`,\n '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.',\n ...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.`),\n `State the person's rule exactly; never weaken it to match the code. ${next}`,\n ],\n };\n const assumed = state.properties.filter(p => p.status === 'assumed');\n const data = state.properties.find(p => p.question.kind === 'data')?.answer?.choice;\n return {\n stage: 'done',\n summary: assumed.length ? 'Everything you chose holds, under the assumptions shown.' : 'Everything you chose holds.',\n instructions: [\n 'Tell the person every property they chose holds, and point them at the studio page for the evidence.',\n ...(assumed.length ? ['Say plainly which results depend on running exactly one server.'] : []),\n ...(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(say.reference('porting'))} says how to bring the data over.`] : []),\n `When they describe a new feature, change the code and ${say.use('yichus_next')} again: new facts can raise new questions.`,\n sections.length\n ? `When they want the app online, follow the ${sectionsText(sections)} section${sections.length === 1 ? '' : 's'} of the deploy reference (${say.reference('deploy')}), and ${say.api('api_deploy')} to generate the server.`\n : `The program keeps no records and has no actions people call, so it needs no server. When they want it on a page, ${say.reference('calculator')}.`,\n ],\n };\n}\n\n/** Every part the person sees that wants a plain name, besides question\n * subjects: what the pictures draw from the program's own packages (the\n * library's parts are not the person's), and the answers its actions give. */\nexport function drawnParts(state: Pick<StudioState, 'map' | 'layers' | 'whatHappens'>): Array<{ code: string; what: string }> {\n return [...state.map ? nameableParts(state.map, ownPackages(state.layers)) : [],\n ...(state.whatHappens ? replies(state.whatHappens) : []).map(code => ({ code, what: 'an answer the app gives' }))];\n}\n\n/** The packages the program's own files declare, from the layers lens. */\nexport function ownPackages(layers: unknown): Set<string> | undefined {\n const parsed = z.looseObject({ layers: z.looseObject({ packages: z.array(z.looseObject({ name: z.string() })) }) }).safeParse(layers);\n return parsed.success ? new Set(parsed.data.layers.packages.map(p => p.name)) : undefined;\n}\n\n/** A program with records or actions people call runs as a server; any\n * other is a calculation, which needs none. */\nconst serves = (report: Report) => report.surface.routes.length > 0 || report.dataModel.tables.length > 0;\n\nexport interface RunOptions { root: string; engine: StudioEngine; requirements: Requirements; withMap?: boolean; previous?: StudioState | null; say?: Say }\n\n/** Read the program, run the checks, decide the next step, and write\n * .yichus/state.json for the page. */\nexport async function direct({ root, engine, requirements, withMap = true, previous = null, say = MCP }: RunOptions): Promise<StudioState> {\n const sources = projectSources(root);\n const hash = sourcesHash(sources);\n const instances = instancesFor(requirements);\n const base = {\n schemaVersion: 'yichus-studio-state-1' as const,\n project: path.basename(path.resolve(root)),\n updatedAt: new Date().toISOString(),\n sourcesHash: hash,\n files: sources.map(s => s.fileName),\n description: requirements.description,\n names: requirements.names ?? {},\n topology: null as string | null,\n proven: null as boolean | null,\n properties: [] as Property[],\n other: [] as StudioState['other'],\n laws: [] as Law[],\n lawsError: null as string | null,\n rulesListed: requirements.rules !== undefined,\n rules: [] as Rule[],\n map: null as unknown,\n mapError: null as string | null,\n layers: null as unknown,\n hasActions: null as boolean | null,\n whatHappens: null as WhatHappens | null,\n whatHappensError: null as string | null,\n };\n let compileErrors: string[] | null = null;\n if (requirements.description && sources.length) {\n const verify = Verify.parse(await call(engine, 'api_verify', { sources, ...(instances ? { instances } : {}) }));\n base.topology = verify.topology ?? null;\n base.proven = verify.verdict.proven;\n const compiles = verify.verdict.properties.find(p => p.id === 'compiles');\n if (compiles && compiles.status !== 'proven') compileErrors = compiles.details;\n else {\n const report = Report.parse(await call(engine, 'api_report', { sources }));\n // With the requirements, the lens also computes each entry's decision\n // tree and checks the scenarios on it.\n const structureRaw = await call(engine, 'api_organize', { sources, lens: 'structure', requirements });\n const structure = Structure.parse(structureRaw);\n const questions = questionsFor(report, structure, base.names);\n // Only a program with records or actions people call runs as a server, and the\n // program is the same wherever it runs, so where is asked with the\n // other questions and never holds up a check.\n if (serves(report)) {\n questions.push(platform);\n const where = answerOf(requirements, platform.id)?.choice;\n if (where && PAGE_ONLY.has(where)) questions.push(hostQuestion(platform.choices.find(c => c.id === where)!.label));\n }\n const together = new Set(questions.filter(q => q.kind === 'together').map(q => q.subject!));\n for (const question of questions) {\n base.properties.push(await judge(root, engine, sources, question, answerOf(requirements, question.id), report, verify.verdict.properties, together));\n }\n // A calculation (no routes, no records) has no route to check: the\n // engine's route warnings then say only that, and are nothing to fix.\n const routeless = (p: VerifyProperty) => !serves(report) && p.status === 'warning' && p.id.startsWith('route-');\n base.other = verify.verdict.properties\n .filter(p => !QUESTION_PROPERTIES(p.id) && p.status !== 'proven' && !isAccepted(p) && !routeless(p))\n .map(({ id, title, status, details }) => ({ id, title, status, details }));\n const checked = await checkLaws(engine, sources);\n base.laws = checked.laws;\n base.lawsError = checked.error;\n base.rules = (requirements.rules ?? []).map(r => judgeRule(r, base.laws));\n // Without routes the engine enters a program at its exported\n // definitions; those are calculations, not actions a person takes.\n base.hasActions = report.surface.routes.length > 0;\n // A program that lost all its actions still has the scenarios written\n // for them: the record keeps only those, reported as gone, so the\n // agent drops or moves them.\n if (base.hasActions || requirements.scenarios?.length) {\n try {\n const access = await call(engine, 'api_access_check', { sources });\n const record = WhatHappens.parse(buildWhatHappens({ structure: structureRaw, access }, { program: base.project }));\n base.whatHappens = base.hasActions ? record : { ...record, entries: [], ghosts: [], claims: [], witnesses: [], refused: [], notes: [] };\n } catch (error) {\n base.whatHappensError = error instanceof Error ? error.message : String(error);\n }\n }\n if (withMap) {\n if (previous?.sourcesHash === hash && previous.map) { base.map = previous.map; base.layers = previous.layers ?? null; }\n else {\n try {\n const [abstractions, layers] = [\n await call(engine, 'api_organize', { sources, lens: 'abstractions' }),\n await call(engine, 'api_organize', { sources, lens: 'layers' }),\n ];\n base.map = buildSystemMap({ report: report as Record<string, unknown>, structure: structureRaw, abstractions, layers }, { program: base.project });\n base.layers = layers;\n } catch (error) {\n base.mapError = error instanceof Error ? error.message : String(error);\n }\n }\n }\n }\n }\n const state: StudioState = { ...base, step: nextStep(base, compileErrors, say) };\n writeState(root, state);\n return state;\n}\n\nexport function writeState(root: string, state: StudioState): void {\n ensureStudioDir(root);\n fs.writeFileSync(path.join(studioDir(root), 'state.json'), `${JSON.stringify(state, null, 2)}\\n`);\n}\n\nexport function readState(root: string): StudioState | null {\n const file = path.join(studioDir(root), 'state.json');\n return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) as StudioState : null;\n}\n","// The system map's record (schema system-map-2, marks yichus-marks-3), built\n// from the engine's own output. web/system-map.js draws this record and\n// nothing else; every field names the engine field it was copied or derived\n// from (`from`). scripts/diagram-examples.mjs records one per program.\n//\n// The record joins four engine calls by full id:\n// api_report headline.class, surface.routes\n// api_organize lens=structure entries, supply, ioKinds, ports, applied,\n// chains, keyed, generic, combinations, phases,\n// programs\n// api_organize lens=abstractions generators, instantiations, routeShapes\n// api_organize lens=layers packages and their exported definitions\n// A name is copied as a label and never decides anything.\n\nexport const MARKS_VERSION = 'yichus-marks-3';\n\n// Each mark, where it sits, and the record field that draws it. It travels\n// with every record so the file describes itself.\nexport const VOCABULARY = {\n version: MARKS_VERSION,\n fixedPlaces: {\n 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[]',\n openings: 'the left wall: one opening per entry <- entries[]',\n hullBand: 'the middle band of the wall: wrappers sit here and nowhere else; empty band = no entry goes through a shared wrapper <- wrappers[]',\n 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',\n replyBars: 'one bar per entry at the same x, past the hull band <- entries[]',\n 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]',\n rack: 'right of the wall: db, model, net, always in this order; struck = the engine checked and found none <- resources[], ghostResources[]',\n 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[]',\n 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[]',\n },\n marks: {\n entryHead: 'arrowhead at an opening; solid = the entry writes, hollow = it only reads <- entries[].writes',\n 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',\n role: 'red word beside the lock: a role beyond sign-in <- entries[].roles',\n limit: 'gauge beside the path: a declared rate limit <- entries[].limits',\n 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',\n modelRing: 'violet ring: the entry reaches the model <- entries[].model',\n 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',\n netRing: 'orange ring: the entry reaches the network <- entries[].net',\n 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',\n 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[]',\n socket: 'broken-rim ring: a function the caller hands in runs here; its centre fills like a station <- entries[].passed[]',\n token: 'small grey word under a path: the value the caller fixes for the wrapper <- entries[].policy',\n afterDot: 'dot in the after band: a call the entry makes after its wrapper returns <- entries[].beside.calls',\n builder: 'plus-disc under a station with the call that builds the handle there <- uses[how=local].builtBy',\n 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]',\n 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[]',\n 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[]',\n 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',\n 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[]',\n loop: 'loop arc with package names: packages whose types lead back to themselves <- phases.cycles',\n composes: 'hull round a chain: a definition takes the type the chain hands in at each step and applies it <- library.applied[].fedBy',\n port: 'plug strip on the right: a record of functions; each adapter a plug, hollow when nothing plugs it in <- library.ports[]',\n generic: 'the letter ∀ with its variables over a part that never looks inside what it carries <- library.generic[]',\n 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[]',\n decision: 'bar and number in the program: its decisions, on one scale shared with its engines\\' bars <- programs[].decisions',\n struck: 'on a program, a struck \"effects\": no definition in its package performs an effect <- programs[].beside = []',\n programEffect: 'red disc and count on a program: definitions in its own package that perform effects, named in its title <- programs[].beside[]',\n request: 'opening on the program\\'s right edge: a request constructor its step can return, with its payload\\'s types <- programs[].requests[]',\n variant: 'short opening under a request: a constructor of a user sum type its payload carries, with what the program calls it (\"BriefCase → 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[]',\n 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]',\n gap: 'struck opening: a request constructor no engine handles <- programs[].gaps[]',\n 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',\n 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 → 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',\n laneFork: 'bar and number on a lane: the engine\\'s decisions, on the program\\'s scale; 0 = a rule-free engine <- programs[].engines[].decisions',\n 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 … runs it\" naming the routes that run the rounds <- programs[].engines[].replies, loop, starters',\n replaced: 'a check named \"(in place of …)\": 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[]',\n },\n 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.',\n};\n\nconst bare = id => String(id).split('::').pop();\nconst pkgOf = id => String(id).split('::')[0];\nconst uniq = xs => [...new Set(xs)];\n\n// An engine effect step ({kind, op, tables, resource}) as the table ops a\n// station draws: reads, deletes, and every other database op as a write.\nconst OPS = { read: 'read', query: 'read', delete: 'delete' };\nexport function effectsOf(steps) {\n return (steps || []).filter(e => e.resource === 'db').flatMap(e => e.tables.map(table => ({ op: OPS[e.op] || 'write', table })));\n}\nconst isWrite = op => op !== 'read';\nconst uniqBy = (xs, key) => { const seen = new Set(); return xs.filter(x => !seen.has(key(x)) && seen.add(key(x))); };\n// The resource an engine effect reaches; the program runner's two kinds by name of kind.\nconst RUNNER = { CompileProgram: 'compile', RunProgram: 'run' };\nexport const effectResource = e => e.resource || RUNNER[e.kind] || 'io';\nconst LANE_RES = ['db', 'model', 'net', 'compile', 'run', 'io'];\nconst resOrder = rs => LANE_RES.filter(r => rs.includes(r));\n\n// Programs: a pure step whose result carries a request, the engines that\n// perform each request, and the requests no engine handles.\nexport function programsOf(st, layers = null) {\n const found = (st.programs && st.programs.programs) || [];\n // a package's own definitions, counted as the layers lens counts them\n const ownCount = pkg => { const lp = layers && layers.packages.find(x => x.name === pkg); return lp ? lp.definitions.length : null; };\n return found.map(p => {\n const engines = p.engines.map(e => {\n const resources = resOrder(uniq(e.handles.flatMap(h => h.effects.map(effectResource))));\n return {\n id: e.id, label: bare(e.id), pkg: pkgOf(e.id), pkgLabel: pkgOf(e.id).split('/').pop(),\n handles: e.handles.map(h => h.constructor),\n resources,\n // effects the engine performs that are no request's: drawn, not hidden\n also: resOrder(uniq((e.effects || []).map(effectResource))).filter(r => !resources.includes(r)),\n replies: resOrder(uniq(e.replies.map(effectResource))),\n decisions: +e.decisions, entries: e.entries, truncated: e.truncated,\n 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 },\n starters: (p.starters || []).filter(s => s.advances && s.via.some(v => v === e.id || e.entries.includes(s.entry))).map(s => s.entry),\n // what it does, from its type: the program's own and standard parameters, and what its effect yields; the whole type on hover\n type: { takes: e.labels.takes, returns: e.labels.returns, plainTakes: e.labels.plainTakes, yields: e.labels.yields,\n from: 'structure.programs.programs[].engines[].labels' },\n from: 'structure.programs.programs[].engines[]',\n }; });\n const requests = p.requests.map(q => ({\n constructor: q.constructor, fields: q.fields.map(f => f.label),\n variants: (q.variants || []).map(v => ({ path: v.path, type: bare(v.type), constructors: v.constructors,\n // what the program calls each kind: total matches onto plain constructors, the type's own package first\n namings: (v.namings || []).slice().sort((a, b) => (pkgOf(b.definition) === pkgOf(v.type)) - (pkgOf(a.definition) === pkgOf(v.type))).map(n => ({\n definition: n.definition, label: bare(n.definition), type: bare(n.type), names: n.names.map(x => ({ constructor: x.constructor, name: x.name })),\n from: 'structure.programs.programs[].requests[].variants[].namings[]' })),\n from: 'structure.programs.programs[].requests[].variants[]' })),\n handledBy: p.engines.filter(e => e.handles.some(h => h.constructor === q.constructor)).map(e => ({\n engine: e.id, resources: resOrder(uniq(e.handles.find(h => h.constructor === q.constructor).effects.map(effectResource))) })),\n gap: p.gaps.some(g => g.constructor === q.constructor),\n from: 'structure.programs.programs[].requests[] + engines[].handles[]',\n }));\n return {\n id: p.step, label: bare(p.step), pkg: p.package, pkgLabel: p.package.split('/').pop(),\n result: bare(p.result), requestType: bare(p.requestType), carrier: p.carrier,\n decisions: +p.decisions, finishes: p.finishes,\n // definitions: the package's own, as the layer stack counts them; reached: everything the program's definitions use\n definitions: ownCount(p.package) ?? +(p.ownDefinitions || 0), reached: p.definitions.length,\n // of what it reaches, the definitions that live in other packages\n usesElsewhere: p.definitions.filter(d => pkgOf(d) !== p.package).length,\n // and which packages those are, the most used first\n elsewhere: Object.entries(p.definitions.filter(d => pkgOf(d) !== p.package).reduce((m, d) => ({ ...m, [pkgOf(d)]: (m[pkgOf(d)] || 0) + 1 }), {}))\n .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[]' })),\n requests, engines,\n starters: (p.starters || []).map(s => ({ entry: s.entry, path: s.entry.replace(/^route:/, ''), advances: s.advances, via: s.via,\n from: 'structure.programs.programs[].starters[]' })),\n // routes that call the step and act on nothing it says: they read where the program is\n replays: (p.replays || []).map(s => ({ entry: s.entry, path: s.entry.replace(/^route:/, ''), via: s.via, from: 'structure.programs.programs[].replays[]' })),\n // what each reaches, as the structure lens's effect sites say (io when none is a resource)\n beside: (p.beside || []).map(b => ({ id: b.definition, label: bare(b.definition), kinds: b.kinds,\n resources: resOrder(uniq((st.ioKinds || []).filter(k => k.definition === b.definition).flatMap(k => k.resources))),\n from: 'structure.programs.programs[].beside[], structure.ioKinds[].resources' })),\n gaps: p.gaps.map(g => ({ constructor: g.constructor, from: 'structure.programs.programs[].gaps[]' })),\n from: 'structure.programs.programs[]',\n };\n });\n}\n\nconst outsideResourcesOf = steps => uniq((steps || []).map(e => e.resource).filter(r => r === 'model' || r === 'net'));\n\nexport function buildSystemMap(engine, { program }) {\n for (const [k, v] of Object.entries(engine)) if (!v.ok) throw new Error(`${k}: ${v.error}`);\n const report = engine.report, st = engine.structure, abs = engine.abstractions.abstractions, layers = engine.layers.layers;\n const routes = (report.surface.routes || []).slice().sort((a, b) => a.path.localeCompare(b.path));\n const engEntry = new Map(st.entries.map(e => [e.entry, e]));\n const shapes = new Map(abs.routeShapes.map(r => [r.path, r]));\n const gens = new Map(abs.generators.map(g => [g.id, g]));\n const insts = abs.instantiations;\n const besideOf = inst => ({ calls: inst.besideCalls.map(bare), callIds: inst.besideCalls, guards: inst.besideGuards.map(bare), guardIds: inst.besideGuards,\n effects: effectsOf(inst.besideEffectSteps), resources: outsideResourcesOf(inst.besideEffectSteps), from: 'abstractions.instantiations[].beside*' });\n\n const entries = routes.map(r => {\n const key = `route:${r.path}`;\n const ee = engEntry.get(key);\n const rs = shapes.get(r.path);\n const wrapper = rs.shapedByGenerator;\n const inst = wrapper ? insts.find(i => i.callerId === rs.handlerId && i.generatorId === wrapper) : null;\n const passed = (inst ? inst.slotBindings : []).filter(sb => ['function', 'effect'].includes(sb.slotRole)).map(sb => ({\n slot: sb.slotName, id: sb.targetId || null, label: sb.targetId ? bare(sb.targetId) : null,\n kind: sb.passedKind, guards: (sb.guards || []).map(bare), guardIds: sb.guards || [], effects: effectsOf(sb.effectSteps),\n from: 'abstractions.instantiations[].slotBindings[slotRole=function|effect]',\n }));\n const reach = wrapper ? [\n ...effectsOf(rs.effectsInGeneratorSteps).map(e => ({ ...e, where: 'wrapper', from: 'abstractions.routeShapes[].effectsInGeneratorSteps' })),\n ...effectsOf(rs.effectsInPassedFunctionSteps).map(e => ({ ...e, where: 'passed', from: 'abstractions.routeShapes[].effectsInPassedFunctionSteps' })),\n ...effectsOf(rs.effectsDirectOrBesideSteps).map(e => ({ ...e, where: 'beside', from: 'abstractions.routeShapes[].effectsDirectOrBesideSteps' })),\n ] : uniqBy([\n ...effectsOf(r.inferredSteps).map(e => ({ ...e, where: 'direct', from: 'report.surface.routes[].inferredSteps' })),\n ...effectsOf(rs.effectsDirectOrBesideSteps).map(e => ({ ...e, where: 'direct', from: 'abstractions.routeShapes[].effectsDirectOrBesideSteps' })),\n ], e => `${e.op} ${e.table}`);\n const limits = ee.limits.written === 'literal' ? ee.limits.each.map(l => ({ requests: +l.requests, seconds: +l.seconds, by: l.by })) : [];\n return {\n key, path: r.path, handler: r.handler, handlerId: rs.handlerId,\n transport: ee.transport, authority: ee.authority,\n signedIn: !['public', 'anonymous'].includes(ee.authority),\n roles: r.requiredRoles || [],\n limits, limitComputed: ee.limits.written === 'computed',\n reachKinds: ee.reaches,\n db: ee.resources.includes('db'), model: ee.resources.includes('model'), net: ee.resources.includes('net'),\n writes: reach.some(e => isWrite(e.op)),\n guards: rs.handlerGuards.map(bare), guardIds: rs.handlerGuards,\n wrapper, via: rs.viaSpecialization ? bare(rs.viaSpecialization) : null,\n policy: (inst ? inst.slotBindings : []).filter(s => s.slotRole === 'semantic-object').map(s => s.value).filter(Boolean),\n passed, beside: inst ? besideOf(inst) : null, reach,\n from: { entry: 'report.surface.routes[]', transport: 'structure.entries[]', shape: 'abstractions.routeShapes[]', head: 'entries[].reach (writes)' },\n };\n });\n\n // Parts: every abstraction with an instantiation; each can be opened.\n const partOf = g => {\n const own = insts.filter(i => i.generatorId === g.id);\n return {\n id: g.id, label: g.name || bare(g.id), pkg: pkgOf(g.id),\n guards: g.envelope.guards.map(bare), guardIds: g.envelope.guards,\n effects: effectsOf(g.envelope.effectSteps),\n groups: (g.parameterGroups || []).map(grp => grp.map(sl => ({ name: sl.name, role: sl.role, type: sl.type, guardsFed: (sl.guardsFed || []).map(bare) }))),\n instantiationCount: own.length,\n instantiatingPackages: uniq(own.map(i => pkgOf(i.callerId))).sort(),\n besideEmpty: own.every(i => !i.besideCalls.length && !i.besideGuards.length && !i.besideEffects.length),\n callers: own.map(i => ({\n id: i.callerId, label: i.callerName || bare(i.callerId), pkg: pkgOf(i.callerId), routes: i.routes || [],\n via: i.viaSpecialization ? bare(i.viaSpecialization) : null,\n tokens: i.slotBindings.filter(s => s.slotRole === 'semantic-object').map(s => s.value).filter(Boolean),\n passed: i.slotBindings.filter(s => ['function', 'effect'].includes(s.slotRole)).map(s => ({\n slot: s.slotName, id: s.targetId || null, label: s.targetId ? bare(s.targetId) : null, guards: (s.guards || []).map(bare), guardIds: s.guards || [], effects: effectsOf(s.effectSteps) })),\n beside: besideOf(i),\n })),\n from: 'abstractions.generators[] + abstractions.instantiations[generatorId]',\n };\n };\n const parts = abs.generators.filter(g => insts.some(i => i.generatorId === g.id)).map(partOf);\n const wrapperIds = uniq(entries.map(e => e.wrapper).filter(Boolean)).sort();\n const wrappers = wrapperIds.map(id => ({ ...(parts.find(x => x.id === id) || partOf(gens.get(id))), entries: entries.filter(e => e.wrapper === id).map(e => e.key),\n from: 'abstractions.generators[] shaping routeShapes[].shapedByGenerator' }));\n\n // Supply: where each handle an effect or a record call uses comes from.\n const handlerToEntry = new Map(entries.map(e => [e.handlerId, e.key]));\n const passedToEntry = new Map(entries.flatMap(e => e.passed.filter(p => p.id).map(p => [p.id, e.key])));\n const uses = [];\n for (const s of st.supply) {\n const kind = s.via === 'record' ? 'record' : s.resource;\n if (kind !== 'db' && kind !== 'record') continue;\n const ids = new Set([s.definition]);\n for (const t of s.traces) {\n for (const id of t.through) ids.add(id);\n if (t.end.where) ids.add(t.end.where);\n if (t.end.referrer) ids.add(t.end.referrer);\n }\n let ats;\n if (handlerToEntry.has(s.definition)) ats = [{ node: 'entry', entry: handlerToEntry.get(s.definition) }];\n else if (wrapperIds.includes(s.definition)) ats = [{ node: 'wrapper', wrapper: s.definition }];\n else if (passedToEntry.has(s.definition)) ats = [{ node: 'passed', entry: passedToEntry.get(s.definition), id: s.definition }];\n else {\n // a helper: one use at every entry whose handler its traces run through\n const ents = uniq([...ids].map(i => handlerToEntry.get(i)).filter(Boolean));\n ats = ents.length ? ents.map(entry => ({ node: 'entry', entry, helper: bare(s.definition) })) : [{ node: 'definition', id: s.definition }];\n }\n 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;\n const anchor = !s.leaves ? 'none' : s.leaves.builtBy.length ? 'program' : 'platform';\n for (const at of ats) uses.push({ kind, how: s.supply, definition: s.definition, effect: s.effect || null, writes: s.via === 'effect' && isWrite(OPS[s.op] || 'write'), at, builtBy,\n untracedSource: s.traces.some(t => ['asValue', 'entry'].includes(t.end.kind)),\n anchor, handleBuiltBy: s.leaves ? s.leaves.builtBy : [], records: s.records || [],\n 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 })),\n from: 'structure.supply[]' });\n }\n\n const present = uniq(st.ioKinds.flatMap(b => b.resources));\n const tables = uniq(entries.flatMap(e => [...e.reach, ...(e.beside ? e.beside.effects : [])].map(r => r.table))).sort();\n const resources = ['db', 'model', 'net'].filter(k => present.includes(k)).map(k => ({ kind: k, ...(k === 'db' ? { tables } : {}), from: 'structure.ioKinds[].resources' }));\n const ghostResources = ['db', 'model', 'net'].filter(k => !present.includes(k)).map(k => ({ kind: k, from: 'structure.ioKinds[] checked: no site of this kind' }));\n\n const transports = uniq(st.entries.map(e => e.transport));\n const callers = [];\n if (transports.includes('http')) callers.push({ kind: 'http', keyKinds: uniq(entries.map(keyKindOf)), from: 'structure.entries[transport=http] + authority' });\n if (transports.includes('link')) callers.push({ kind: 'link', from: 'structure.entries[transport=link]' });\n const ghostCallers = ['http', 'link'].filter(k => !transports.includes(k)).map(k => ({ kind: k, from: 'structure.entries[]: no entry with this transport' }));\n\n const library = routes.length ? null : {\n packages: layers.packages.map(p => ({ name: p.name, label: p.name.split('/').pop(), exports: p.definitions.filter(d => d.exported).map(d => d.name) })),\n ports: st.ports.map(p => ({ id: p.id, label: bare(p.id), pkg: pkgOf(p.id), fields: p.fields, heldBy: p.heldBy,\n 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) })) })),\n from: 'structure.ports[]' })),\n chains: st.chains.map(c => ({ value: c.value, label: bare(c.value), pkg: pkgOf(c.value), by: bare(c.by),\n start: c.start.map(i => i.id ? bare(i.id) : i.text),\n 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 }))),\n from: 'structure.chains[]' })),\n combinations: st.combinations,\n applied: st.applied.map(a => ({ id: a.definition, label: bare(a.definition), pkg: pkgOf(a.definition), fn: a.function, insideBranch: a.insideBranch,\n fedBy: a.fedBy, from: 'structure.applied[]' })),\n generic: st.generic.map(g => ({ id: g.definition, label: bare(g.definition), vars: g.vars, signature: g.signature, from: 'structure.generic[]' })),\n exported: st.entries.filter(e => e.transport === 'link').map(e => e.entry),\n };\n 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' })));\n 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[]' }));\n\n return {\n schema: 'system-map-2', marks: MARKS_VERSION, vocabulary: VOCABULARY,\n program, class: report.headline.class,\n kind: routes.length ? 'service' : 'library',\n callers, ghostCallers, entries, wrappers, parts, uses, resources, ghostResources,\n library, keyed, steps,\n programs: programsOf(st, layers),\n bundles: routes.length > 12 ? bundlesOf(entries, uses, keyed) : null,\n phases: st.phases,\n evidence: { tools: ['api_report', 'api_organize:abstractions', 'api_organize:structure', 'api_organize:layers'], headline: report.headline,\n derived: ['bundles: entries grouped by wrapper and identical marks'] },\n };\n}\n\n// Two versions of one program: a check whose place on a route's path (the\n// handler's own checks, the handed-in function's, the after band's, by\n// position) holds a different definition in the head than in the base,\n// where neither definition is anywhere else on that route, took the old\n// one's place. That is all it says: nothing here shows the two do the\n// same. A route only in one version is left alone.\nexport function replacedGuards(base, head) {\n const slots = e => [['handler', e.guardIds], ['passed', e.passed[0]?.guardIds || []], ['after', e.beside?.guardIds || []]];\n const byPath = new Map(base.entries.map(e => [e.path, e]));\n const out = [];\n for (const e of head.entries) {\n const b = byPath.get(e.path);\n if (!b) continue;\n const all = x => new Set(slots(x).flatMap(([, ids]) => ids));\n const ba = all(b), ha = all(e);\n for (const [[slot, hs], [, bs]] of slots(e).map((s, i) => [s, slots(b)[i]]))\n hs.forEach((id, i) => {\n const was = bs[i];\n if (was && was !== id && !ha.has(was) && !ba.has(id)) {\n // the label tells the two apart: the old one's package too when both have one name\n const wasLabel = bare(was) === bare(id) ? `${pkgOf(was).split('/').pop()}::${bare(was)}` : bare(was);\n out.push({ entry: e.key, within: slot, at: i, guard: id, was, wasLabel, from: 'derived: the same place on the same route in the base record' });\n }\n });\n }\n return out;\n}\n\nexport const keyKindOf = e => e.authority === 'publishable' ? 'publishable' : e.signedIn ? 'secret' : 'public';\n\n// Bundles: entries that share a wrapper and draw identical marks. Names,\n// tables and role words are labels, drawn when the bundle is opened.\nexport function bundlesOf(entries, uses, keyed) {\n const keyedIds = new Set(keyed.map(k => k.id));\n 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(' ');\n const fill = l => l.length ? (l.some(x => isWrite(x.op)) ? 'W' : 'R') : '-';\n const sig = e => {\n const p = e.passed[0], b = e.beside;\n return JSON.stringify([e.wrapper, keyKindOf(e), e.roles.length > 0, e.writes,\n e.guards.length > 0, fill(e.reach.filter(r => r.where === 'direct')), fill(e.reach.filter(r => r.where === 'passed')), !!(p && p.guards.length),\n e.model, e.net, sup(e), e.limits.length > 0, !!(b && b.calls.length), !!(b && b.guards.length), fill(b ? b.effects : []),\n e.policy.length > 0, [e.handlerId, ...e.guardIds, ...(p ? [p.id, ...p.guardIds] : [])].some(id => keyedIds.has(id))]);\n };\n const groups = new Map();\n for (const e of entries) { const k = sig(e); if (!groups.has(k)) groups.set(k, []); groups.get(k).push(e.key); }\n const pathOf = new Map(entries.map(e => [e.key, e.path]));\n return [...groups.values()].map((keys, i) => ({ id: `bundle:${i + 1}`, entries: keys, count: keys.length, label: pathPattern(keys.map(k => pathOf.get(k))),\n from: 'derived: entries[] grouped by wrapper and identical marks' }));\n}\n\n// The paths' shared segments, * where they differ, /** for differing depths.\nexport function pathPattern(paths) {\n if (paths.length === 1) return paths[0];\n const segs = paths.map(p => p.split('/'));\n const n = Math.min(...segs.map(s => s.length));\n const out = [];\n for (let i = 0; i < n; i++) { const v = uniq(segs.map(s => s[i])); out.push(v.length === 1 ? v[0] : '*'); }\n if (segs.every(s => s.length === n)) return out.join('/');\n let k = 0; while (k < n && out[k] !== '*') k++;\n return out.slice(0, Math.max(k, 1)).join('/') + '/**';\n}\n","// Plain names on a system map record: the person's words in place of the\n// code's. A record is relabeled before it is drawn, so web/system-map.js\n// draws the person's words wherever it would draw a code name, in every\n// view. Names are labels only; relabeling never adds, drops or moves a mark.\n\n// Fields that describe the record or how a mark is drawn, never a name. A\n// `from` that is a list holds definitions (a combination's inputs); any other\n// `from` says which engine field a value came from.\nconst SKIP = new Set(['vocabulary', 'evidence', 'schema', 'marks', 'program', 'class']);\nconst skipped = (key, v) => SKIP.has(key) || key === 'from' && !Array.isArray(v);\nconst STRUCTURAL = new Set(['kind', 'op', 'how', 'transport', 'authority', 'where', 'slotRole', 'role', 'passedKind', 'anchor', 'node',\n 'keyKinds', 'reachKinds', 'resources', 'replies', 'also', 'kinds', 'within', 'vars', 'id']);\n// What each named field holds, said to the agent that names it.\nconst WHAT = {\n path: 'an action the app answers', routes: 'an action the app answers', table: 'a kind of record the app keeps', tables: 'a kind of record the app keeps',\n roles: 'a permission an action requires, held by a person\\'s role or by the app\\'s own server', policy: 'a setting an action passes to shared code', tokens: 'a setting an action passes to shared code',\n fields: 'an operation a pluggable part offers',\n};\nconst PACKAGE = 'a section of the program';\nconst DEFINITION = 'a piece of the program';\nconst VALUE = 'a kind of value';\nconst TYPES = new Set(['type', 'types', 'signature']);\nconst WORD = /[A-Za-z_][\\w/]*::\\w+|[A-Za-z_]\\w*/g;\n// The language's own kinds of value, said plainly once for every program.\nexport const PREDEF_WORDS = { String: 'text', Int: 'a number', Bool: 'yes or no', Float64: 'a decimal number', Char: 'a letter', Unit: 'nothing',\n List: 'a list', Option: 'maybe one', Dict: 'a lookup table' };\n\nconst leaves = (record, visit) => {\n const walk = (v, key) => {\n if (typeof v === 'string') visit(v, key);\n else if (Array.isArray(v)) v.forEach(x => walk(x, key));\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) if (!skipped(k, x)) walk(x, k);\n };\n walk(record, null);\n};\n\n/** Every code name the map draws, once, with what it is: the parts the\n * person's names replace. Given the program's own packages, a part of any\n * other package (the library) is left out: it is not the person's to name. */\nexport function nameableParts(map, own) {\n const found = new Map();\n const theirs = pkg => !own || own.has(pkg);\n const add = (code, what) => { if (code && !found.has(code) && !(code in PREDEF_WORDS) && (what !== PACKAGE || theirs(code))) found.set(code, what); };\n const idParts = id => { const i = id.lastIndexOf('::'); if (!theirs(id.slice(0, i))) return; add(id.slice(0, i), PACKAGE); add(id.slice(i + 2), DEFINITION); };\n leaves(map, (s, key) => {\n if (s.startsWith('route:')) return add(s.slice(6), WHAT.path);\n if (TYPES.has(key)) { for (const w of s.match(WORD) ?? []) if (w.includes('::')) idParts(w); else if (w.length > 1) add(w, VALUE); return; }\n if (s.includes('::')) { for (const w of s.match(WORD)) if (w.includes('::')) idParts(w); return; }\n if (STRUCTURAL.has(key)) return;\n if (key === 'name' || key === 'package' || key === 'pkg' || key === 'instantiatingPackages' || key === 'cycles' || key === 'to') return add(s, s.includes('/') ? PACKAGE : DEFINITION);\n add(s, WHAT[key] ?? DEFINITION);\n });\n for (const b of map.bundles ?? []) if (b.count > 1) found.delete(b.label);\n return [...found].map(([code, what]) => ({ code, what })).sort((a, b) => a.code.localeCompare(b.code));\n}\n\n// The person's names, made safe to stand where a code name stood: no\n// package separators, and no two code names sharing one plain name.\nfunction plainNames(names) {\n const out = new Map(), taken = new Set();\n for (const [code, name] of Object.entries(names).sort(([a], [b]) => a.localeCompare(b))) {\n const base = name.replace(/::|\\//g, ' ').replace(/\\s+/g, ' ').trim();\n if (!base) continue;\n let plain = base;\n for (let n = 2; taken.has(plain); n++) plain = `${base} (${n})`;\n taken.add(plain);\n out.set(code, plain);\n }\n return out;\n}\n\n/** The map with every named part drawn under the person's name; a part\n * without a name keeps its code name. */\nexport function relabelSystemMap(map, names) {\n const plain = plainNames({ ...PREDEF_WORDS, ...names });\n const word = w => plain.get(w) ?? w;\n const id = w => { const i = w.lastIndexOf('::'); return `${word(w.slice(0, i))}::${word(w.slice(i + 2))}`; };\n const text = (s, key) => {\n if (s.startsWith('route:')) return `route:${word(s.slice(6))}`;\n if (plain.has(s) && !STRUCTURAL.has(key)) return plain.get(s);\n if (s.startsWith('/')) return s;\n return s.replace(WORD, w => w.includes('::') ? id(w) : STRUCTURAL.has(key) ? w : word(w));\n };\n const walk = (v, key) => {\n if (typeof v === 'string') return text(v, key);\n if (Array.isArray(v)) return v.map(x => walk(x, key));\n if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, skipped(k, x) ? x : walk(x, k)]));\n return v;\n };\n const out = walk(map, null);\n // A bundle's label is its routes' shared pattern; once a route has a plain\n // name the pattern means nothing, so the label names the first route.\n const pathOf = new Map(map.entries.map(e => [e.key, e.path]));\n out.bundles = map.bundles && map.bundles.map((b, i) => {\n const paths = b.entries.map(k => pathOf.get(k));\n if (!paths.some(p => plain.has(p))) return out.bundles[i];\n return { ...out.bundles[i], label: b.count === 1 ? word(paths[0]) : `${word(paths[0])} and ${b.count - 1} more` };\n });\n return out;\n}\n","// The what-happens record (schema what-happens-1, marks yichus-marks-3 plus\n// the outcome leaf), built from the engine's own output. web/what-happens.js\n// draws this record and nothing else; every element names the engine field\n// it was copied or derived from (`from`). scripts/what-happens-examples.mjs\n// records one per program.\n//\n// The record joins, by computed id:\n// api_organize lens=structure (with requirements) scenarios[], claims\n// api_access_check report.findings[]\n// another what-happens record of the same program its red leaves (base)\n// The author's words are copied as labels onto the ids they name and never\n// decide anything: colour comes only from a claim's verdict or a check's\n// witness, and structure only from the engine's trees.\n\nimport { MARKS_VERSION } from './system-map-record.js';\n\nexport const SCHEMA = 'what-happens-1';\n\nexport const VOCABULARY = {\n version: MARKS_VERSION,\n added: ['outcome'],\n marks: {\n 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[]',\n 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',\n 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',\n station: 'ring on a line: an effect on that path, its verb and table beside it; filled = it writes <- arms[].effects, entry.effects',\n modelRing: 'violet ring: the path reaches the model <- effects[resource=model]',\n netRing: 'orange ring: the path reaches the network <- effects[resource=net]',\n 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',\n 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',\n 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',\n 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',\n compared: 'a line under the rack, always there: \"compared with <base> · N fixed · M still failing\", or \"no base compared\" in faint text <- diff',\n 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',\n },\n 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.',\n 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.',\n};\n\nconst bare = id => String(id).split('::').pop();\nconst claimKey = (entry, c) => `${entry}\\u0000${c.at}\\u0000${c.parsed}`;\n\nexport function walk(tree, f, path = []) {\n if (!tree) return;\n f(tree, path);\n if (tree.kind === 'node') for (const arm of tree.arms) { f(arm, path); walk(arm.next, f, [...path, arm]); }\n}\nexport const leavesOf = tree => { const out = []; walk(tree, t => { if (t.kind === 'leaf') out.push(t); }); return out; };\n// A leaf's effects are the entry's leading effects and those of each arm on\n// its path; the record keeps them once, on the arms, and these rebuild them.\nexport function pathEffects(entry) {\n const out = new Map();\n const go = (t, acc) => {\n if (!t) return;\n if (t.kind === 'leaf') { out.set(t.id, acc); return; }\n for (const a of t.arms) go(a.next, [...acc, ...a.effects]);\n };\n go(entry.tree, entry.effects || []);\n return out;\n}\nexport const allEffects = entry => { const out = [...(entry.effects || [])]; walk(entry.tree, t => { if (!t.kind) out.push(...t.effects); }); return out; };\n\n// The access check's findings that report a violation at an effect: the\n// leaves whose path runs that effect, at that definition, on that table.\n// A finding with a path condition (pathCondition.unlessHeld: the guards the\n// write sits under no branch on) is witnessed only on the paths where none\n// of those guards was tested and held: a path through a guard's True arm is\n// the guarded case, even when the write ran before the test.\nfunction heldOn(tree, guards) {\n const out = new Set();\n const go = (t, held) => {\n if (!t) return;\n if (t.kind === 'leaf') { if (held) out.add(t.id); return; }\n const isGuard = t.from?.kind === 'call' && guards.includes(bare(t.from.callee));\n for (const a of t.arms) go(a.next, held || (isGuard && a.arm === 'True'));\n };\n go(tree, false);\n return out;\n}\nfunction witnessesOf(access, entries) {\n if (!access) return [];\n const findings = (access.report?.findings || []).filter(f => f.status === 'violated');\n return findings.map((f, i) => {\n const site = `${f.package}::${f.binding}`;\n const guards = f.pathCondition?.unlessHeld || [];\n const leaves = entries.flatMap(e => {\n const held = heldOn(e.tree, guards);\n return leavesOf(e.tree).filter(l => !held.has(l.id) && l.effects.some(x => x.site === site && bare(x.primitive) === f.operation && x.tables.includes(f.resource)));\n }).map(l => l.id);\n return { id: `witness:${i + 1}`, check: 'access', resource: f.resource, site, operation: f.operation, kind: f.kind, detail: f.detail, leaves,\n ...(guards.length ? { unlessHeld: guards } : {}),\n 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]' };\n });\n}\n\n/**\n * engine: { structure, access? } structure = api_organize lens=structure\n * output (with requirements), access = api_access_check output.\n * base: the record of the program before a change, for the diff marks.\n */\nexport function buildWhatHappens(engine, { program, base = null, baseLabel = 'base' } = {}) {\n for (const [k, v] of Object.entries(engine)) if (v && !v.ok) throw new Error(`${k}: ${v.error}`);\n const st = engine.structure;\n const claims = st.claims || { scenarios: [], undescribed: (st.scenarios || []).map(s => s.entry) };\n const byEntry = new Map(claims.scenarios.filter(s => s.status === 'matched').map(s => [s.entry, s]));\n const routes = new Map((st.entries || []).map(e => [e.entry, e]));\n const entries = st.scenarios.map(s => {\n const meta = routes.get(s.entry) || {};\n const sc = byEntry.get(s.entry);\n const names = new Map((sc?.names || []).filter(n => n.status === 'named').map(n => [n.id, n.words]));\n // copy the tree, putting the author's words on the ids they name\n const copy = t => {\n if (!t) return null;\n if (t.kind === 'leaf') return { ...t, words: names.get(t.id) || null, claims: [], witnesses: [], status: 'grey' };\n return { ...t, words: names.get(t.id) || null, arms: t.arms.map(a => ({ ...a, words: names.get(a.id) || null, next: copy(a.next) })) };\n };\n return {\n entry: s.entry, handler: s.handler, label: s.entry.replace(/^route:/, ''),\n authority: meta.authority || null, transport: meta.transport || null,\n title: sc?.title || null, described: !!sc,\n effects: s.effects, tree: copy(s.tree), leafCount: Number(s.leafCount), truncated: s.truncated, unsupported: s.unsupported || null,\n wrapper: s.wrapper || null, steps: s.steps || [],\n from: 'structure.scenarios[]',\n };\n });\n const entryOf = new Map(entries.map(e => [e.entry, e]));\n const leafById = new Map(entries.flatMap(e => leavesOf(e.tree).map(l => [l.id, l])));\n\n // claims onto the leaves they are about\n const checked = [], notes = [], refused = [], mismatches = [];\n for (const sc of claims.scenarios) {\n if (sc.status !== 'matched') { mismatches.push({ entry: sc.entry, title: sc.title || null, reason: sc.reason, from: 'structure.claims.scenarios[status=mismatch]' }); continue; }\n 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]' });\n for (const x of sc.expect) {\n if (x.verdict === 'not-a-claim') { notes.push({ entry: sc.entry, at: x.at, text: x.claim, from: 'structure.claims.scenarios[].expect[verdict=not-a-claim]' }); continue; }\n if (x.verdict === 'refused') { refused.push({ entry: sc.entry, id: x.at, words: x.claim, reason: x.reason, from: 'structure.claims.scenarios[].expect[verdict=refused]' }); continue; }\n const open = new Map((x.inconclusive || []).map(o => [o.leaf, o.reasons]));\n const c = { id: `claim:${checked.length + 1}`, entry: sc.entry, at: x.at, claim: x.claim, parsed: x.parsed, property: x.property, verdict: x.verdict, leaves: x.leaves, failing: x.failing,\n inconclusive: x.inconclusive || [], from: 'structure.claims.scenarios[].expect[]' };\n checked.push(c);\n for (const id of x.leaves) {\n const l = leafById.get(id);\n if (!l) continue;\n const verdict = x.failing.includes(id) ? 'fails' : open.has(id) ? 'inconclusive' : 'holds';\n l.claims.push({ id: c.id, at: x.at, parsed: x.parsed, property: x.property, verdict, ...(verdict === 'inconclusive' ? { reasons: open.get(id) } : {}) });\n }\n }\n }\n const witnesses = witnessesOf(engine.access, entries);\n // the base record keeps its leaves' effects on its arms\n const basePaths = base ? new Map(base.entries.flatMap(e => [...pathEffects(e)])) : null;\n for (const w of witnesses) for (const id of w.leaves) leafById.get(id)?.witnesses.push(w.id);\n for (const l of leafById.values()) {\n if (l.claims.some(c => c.verdict === 'fails') || l.witnesses.length) l.status = 'red';\n else if (l.claims.some(c => c.verdict === 'inconclusive')) l.status = 'unchecked';\n }\n\n // the diff: a leaf red at the base is fixed only when every obligation\n // that failed there (a claim, by entry, at and parsed claim; an access\n // witness, by the check running here and naming no witness on the leaf)\n // is checked here and holds; the base's red\n // leaf travels with it, drawn faded beside it. An obligation that is gone\n // or inconclusive here leaves the leaf unchecked, never green.\n let diff = null;\n if (base) {\n 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 }])));\n const baseWitness = new Map((base.witnesses || []).map(w => [w.id, w]));\n const fixed = [], still = [], gone = [], unresolved = [];\n for (const [id, { entry, leaf: bl }] of baseRed) {\n const here = leafById.get(id);\n if (!here) { gone.push(id); continue; }\n if (here.status === 'red') { still.push(id); continue; }\n const reasons = [\n ...bl.claims.filter(c => c.verdict === 'fails').flatMap(c => {\n const now = here.claims.find(h => claimKey(entry, h) === claimKey(entry, c));\n if (!now) return [`the claim ${c.parsed} at ${c.at} failed here at the base and is not checked here`];\n return now.verdict === 'holds' ? [] : [`the claim ${c.parsed} at ${c.at} failed here at the base and is inconclusive here`];\n }),\n ...(bl.witnesses.length && !engine.access ? [`the access check reported a witness here at the base and did not run here`] : []),\n ];\n const baseClaims = bl.claims, baseWitnesses = bl.witnesses.map(w => baseWitness.get(w)).filter(Boolean);\n here.base = { outcome: bl.outcome, effects: bl.effects || basePaths.get(id) || [], claims: baseClaims, witnesses: baseWitnesses };\n if (reasons.length) { here.status = 'unchecked'; unresolved.push({ id, reasons }); continue; }\n here.status = 'green';\n fixed.push(id);\n }\n diff = { base: baseLabel, fixed, stillRed: still, goneAtHead: gone, unresolved,\n 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' };\n }\n\n const ghosts = entries.filter(e => !e.described).map(e => ({ entry: e.entry, from: 'structure.claims.undescribed[]' }));\n // a leaf's effects are kept once, on the arms of its path (pathEffects)\n for (const l of leafById.values()) delete l.effects;\n return {\n schema: SCHEMA, marks: MARKS_VERSION, vocabulary: VOCABULARY, program,\n entries, ghosts, claims: checked, witnesses, notes, refused, mismatches, diff,\n counts: { entries: entries.length, described: entries.length - ghosts.length, leaves: leafById.size,\n steps: entries.reduce((n, e) => n + e.steps.length, 0), wrapped: entries.filter(e => e.wrapper && e.wrapper.wraps).length,\n red: [...leafById.values()].filter(l => l.status === 'red').length, green: [...leafById.values()].filter(l => l.status === 'green').length,\n unchecked: [...leafById.values()].filter(l => l.status === 'unchecked').length },\n evidence: { tools: ['api_organize:structure', ...(engine.access ? ['api_access_check'] : [])], derived: ['diff: base red leaves matched by id, their failed obligations by identity'] },\n };\n}\n\n// Small helpers the renderer and tests share.\nexport const isWriteOp = op => !['read', 'runs', 'effect', 'random', 'trace', 'capture', 'init', 'mint id'].includes(op) && op !== 'call model' && op !== 'fetch article';\nexport function stationLabel(e) {\n const verb = e.op === 'mint id' ? 'mint' : e.op;\n if (e.tables.length) return `${verb} · ${e.tables.join(', ')}`;\n if (e.resource === 'model' || e.resource === 'net') return verb;\n return `${verb} · ${bare(e.primitive)}`;\n}\n// an unknown answer a station gave back (outcome.from), or a field of it,\n// said in the station's words; any other answer keeps its key\nconst said = f => {\n if (f.kind !== 'read') return null;\n const gives = `what ${f.op} · ${f.table || bare(f.primitive)} gives back`;\n return f.path && f.path.length ? `the ${f.path.join('.')} of ${gives}` : gives;\n};\nexport function outcomeLabel(o) {\n if (o.status && !o.constructors.length) return o.shown;\n const head = o.constructors.length ? o.constructors.join(' | ') : ((o.from && said(o.from)) || (o.value ? `the ${o.value}` : o.shown));\n return head;\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface SourceFile { fileName: string; source: string }\n\n// Folders a project keeps generated or third-party files in. A dot folder\n// (.git, .yichus) is skipped too.\nconst SKIPPED = new Set(['node_modules', 'dist', 'build', 'target', 'out']);\n\n/** Every .bosatsu file under root, named by its path from root with forward\n * slashes, in a stable order. The studio reads the program from disk so the\n * agent never pastes code into a call. */\nexport function projectSources(root: string): SourceFile[] {\n const files: SourceFile[] = [];\n const walk = (dir: string) => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n if (entry.name.startsWith('.') || SKIPPED.has(entry.name)) continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && entry.name.endsWith('.bosatsu')) {\n files.push({ fileName: path.relative(root, full).split(path.sep).join('/'), source: fs.readFileSync(full, 'utf8') });\n }\n }\n };\n walk(root);\n return files;\n}\n\nexport function sourcesHash(files: SourceFile[]): string {\n const hash = createHash('sha256');\n for (const file of files) hash.update(`${file.fileName}\\0${file.source}\\0`);\n return hash.digest('hex');\n}\n\n/** Bosatsu helpers for protocol cases (observation predicates the agent\n * writes in .yichus/cases/). They join protocol checks only, so they never\n * count as part of the app. */\nexport function caseSources(root: string): SourceFile[] {\n const dir = path.join(root, '.yichus', 'cases');\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir).filter(name => name.endsWith('.bosatsu')).sort()\n .map(name => ({ fileName: `cases/${name}`, source: fs.readFileSync(path.join(dir, name), 'utf8') }));\n}\n","import { z } from 'zod';\n\n// The property interview. Each question is pre-written and appears only when\n// an engine fact in api_report calls for it; a name never decides anything.\n// The wording is for a person who will never read the code: it says what\n// could happen to their users, not how the program is built.\n\nexport interface Choice { id: string; label: string; means: string }\nexport type QuestionKind = 'platform' | 'host' | 'sign-in' | 'data' | 'topology' | 'access' | 'together' | 'partial' | 'outside';\nexport interface Question {\n id: string;\n kind: QuestionKind;\n /** The table or route the question is about, as the engine names it. */\n subject: string | null;\n ask: string;\n why: string;\n choices: Choice[];\n /** The engine fact that raised the question, in words. */\n fact: string;\n}\n\nconst Step = z.looseObject({ op: z.string(), tables: z.array(z.string()).default([]), resource: z.string() });\n// authority: who may call the route (anonymous, authenticated, publishable,\n// requires-roles, requires-worker).\nconst Route = z.looseObject({ path: z.string(), handler: z.string(), authority: z.string().optional(), tables: z.array(z.string()).default([]),\n inferredSteps: z.array(Step).default([]) });\n// A table's declared policy: `policy` as the report prints it, `access` as data.\n// A kind this studio does not know matches no choice, so it reads as a mismatch.\nconst Access = z.looseObject({ kind: z.string(),\n guards: z.array(z.string()).default([]), roles: z.array(z.string()).default([]) });\nexport type Access = z.infer<typeof Access>;\nconst Table = z.looseObject({\n name: z.string(),\n policy: z.string().nullable().optional(),\n access: Access.nullable().optional(),\n readers: z.array(z.string()).default([]),\n writers: z.array(z.string()).default([]),\n});\nexport const Report = z.looseObject({\n surface: z.looseObject({ routes: z.array(Route).default([]) }).default({ routes: [] }),\n dataModel: z.looseObject({ tables: z.array(Table).default([]) }).default({ tables: [] }),\n});\nexport type Report = z.infer<typeof Report>;\n\n// api_organize lens=structure: which outside resources each entry reaches.\n// api_report's steps list only database operations.\nconst Entry = z.looseObject({ entry: z.string(), resources: z.array(z.string()).default([]) });\nexport const Structure = z.looseObject({ entries: z.array(Entry).default([]) });\nexport type Structure = z.infer<typeof Structure>;\n\n/** What each access choice needs the program to declare: the policy it\n * takes, how to write it, and the guide section on it. */\nexport interface AccessRule { declared(access: Access): boolean; write: string; guide: string }\nexport const ACCESS_RULES: Record<string, AccessRule> = {\n owner: { declared: a => a.kind === 'OwnerScoped', write: 'OwnerScoped', guide: 'Owner-scoped data' },\n // A guard every person passes through; a role may pass it only where every route that reaches it requires the role.\n shared: { declared: a => (a.kind === 'Guarded' || a.kind === 'GuardedOrRoles') && a.guards.length > 0,\n write: 'Guarded([the guard that says who may see a record]), or GuardedOrRoles([the guard], [the roles that may pass it])', guide: 'Guarded data' },\n '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' },\n 'everyone-reads': { declared: a => a.kind === 'PublicReadRoleWrite', write: 'PublicReadRoleWrite([the roles that may change it])', guide: 'Public data' },\n public: { declared: a => a.kind === 'Public', write: 'Public', guide: 'Public data' },\n};\n\n// Asked before any code is written, because it decides what to build: the\n// one question no engine fact raises. Each choice names a section of the\n// deploy reference (yichus_reference topic \"deploy\").\nexport const platform: Question = {\n id: 'platform',\n kind: 'platform',\n subject: null,\n ask: 'Where do you want your app to run once it is ready?',\n 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.',\n choices: [\n { id: 'render', label: 'Render', means: 'The server, its database, the page and background jobs all run on Render.' },\n { 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.' },\n { 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.' },\n { id: 'aws', label: 'Amazon Web Services', means: 'The server runs on App Runner or ECS with an RDS database.' },\n { id: 'gcp', label: 'Google Cloud', means: 'The server runs on Cloud Run with a Cloud SQL database.' },\n { id: 'azure', label: 'Microsoft Azure', means: 'The server runs on Container Apps or App Service with an Azure PostgreSQL database.' },\n { 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.' },\n ],\n fact: 'Every app runs somewhere.',\n};\n\n/** The deploy reference's section for each platform choice. */\nexport const PLATFORM_SECTION: Record<string, string> = {\n render: 'Render', vercel: 'Vercel', netlify: 'Netlify', aws: 'AWS', gcp: 'Google Cloud', azure: 'Microsoft Azure', undecided: 'Not decided yet',\n};\n\n/** The platforms that hold only the page people open: the server goes on a\n * second service, which the person picks. */\nexport const PAGE_ONLY = new Set(['vercel', 'netlify']);\n\n/** The deploy reference's section for each server host choice. */\nexport const HOST_SECTION: Record<string, string> = { render: 'Render', gcp: 'Google Cloud', aws: 'AWS', azure: 'Microsoft Azure', undecided: 'Render' };\n\n/** Asked once the person picks a platform that cannot keep a server running. */\nexport function hostQuestion(platformLabel: string): Question {\n return {\n id: 'host',\n kind: 'host',\n subject: null,\n 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?`,\n 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.',\n choices: [\n { id: 'render', label: 'Render', means: 'The server and its database run on Render, set up from one file in your project.' },\n { id: 'gcp', label: 'Google Cloud', means: 'The server runs on Cloud Run with a Cloud SQL database.' },\n { id: 'aws', label: 'Amazon Web Services', means: 'The server runs on App Runner with an RDS database.' },\n { id: 'azure', label: 'Microsoft Azure', means: 'The server runs on Container Apps with an Azure PostgreSQL database.' },\n { id: 'undecided', label: 'Not sure yet', means: 'Your agent builds for Render; moving later changes configuration, not the app.' },\n ],\n fact: `${platformLabel} does not keep a server running.`,\n };\n}\n\nconst topology: Question = {\n id: 'topology',\n kind: 'topology',\n subject: null,\n 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?',\n 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.',\n choices: [\n { id: 'many', label: 'Several copies', means: 'Every check assumes requests can run at the same moment on different copies.' },\n { 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.' },\n ],\n fact: 'The program serves routes.',\n};\n\n/** Plain names the agent gave the program's records and actions, keyed by\n * the engine's name; the person never sees the code name once one is given. */\nexport type Names = Record<string, string>;\nconst shown = (names: Names, subject: string) => names[subject] ?? subject;\n\nfunction accessQuestion(table: Report['dataModel']['tables'][number], names: Names): Question {\n return {\n id: `access:${table.name}`,\n kind: 'access',\n subject: table.name,\n 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?`,\n 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.',\n choices: [\n { 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.' },\n { 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.' },\n { 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.' },\n { 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.' },\n { id: 'public', label: 'Anyone, even without signing in', means: 'Nothing in these records is private.' },\n ],\n fact: `The program stores rows in \"${table.name}\" (policy declared: ${table.policy ?? 'none'}).`,\n };\n}\n\nfunction togetherQuestion(table: Report['dataModel']['tables'][number], handlers: string[], names: Names): Question {\n // Only its owner reaches an owner-scoped record, so two requests on one\n // are that person's own, from two devices; any other record is shared.\n 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';\n return {\n id: `together:${table.name}`,\n kind: 'together',\n subject: table.name,\n ask: `Two requests change the same record in \"${shown(names, table.name)}\" at the same moment (${who}). What should happen?`,\n 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.',\n choices: [\n { 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.' },\n { 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.' },\n ],\n fact: `${handlers.join(', ')} ${handlers.length === 1 ? 'reads' : 'read'} \"${table.name}\" and then ${handlers.length === 1 ? 'writes' : 'write'} it.`,\n };\n}\n\nfunction partialQuestion(route: Report['surface']['routes'][number], tables: string[], names: Names): Question {\n return {\n id: `partial:${route.path}`,\n kind: 'partial',\n subject: route.path,\n 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?`,\n 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.`,\n choices: [\n { 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.' },\n { id: 'partial-ok', label: 'Partial is fine', means: 'No check is added for this action.' },\n ],\n fact: `${route.handler} writes ${tables.map(t => `\"${t}\"`).join(', ')} in more than one step.`,\n };\n}\n\nfunction outsideQuestion(route: Report['surface']['routes'][number], kinds: string[], names: Names): Question {\n const service = kinds.includes('model') ? 'an AI model' : 'another service on the internet';\n return {\n id: `outside:${route.path}`,\n kind: 'outside',\n subject: route.path,\n ask: `\"${shown(names, route.path)}\" calls ${service}. If that service is down or slow, what should the person using your app see?`,\n why: 'Outside services fail often. Without a plan, a failure can leave a half-finished record or charge for work that never happened.',\n choices: [\n { id: 'fail-clean', label: 'An error, with nothing saved', means: 'Yichus makes the service fail and checks that nothing from this action stays saved.' },\n { 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.' },\n { id: 'no-plan', label: 'No preference', means: 'No check is added for this action.' },\n ],\n fact: `${route.handler} reaches ${kinds.join(' and ')}.`,\n };\n}\n\n// The authorities a signed-in person calls with; a worker route is the\n// app's own server, and an anonymous one needs no sign-in.\nconst PERSON_SIGNS_IN = new Set(['authenticated', 'publishable', 'requires-roles']);\n\nconst signIn: Question = {\n id: 'sign-in',\n kind: 'sign-in',\n subject: null,\n ask: 'How do people sign in to your app?',\n 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.',\n choices: [\n { id: 'new', label: 'They don\\'t yet', means: 'Your agent adds sign-in with a provider that runs it for you, such as Clerk.' },\n { id: 'clerk', label: 'Clerk', means: 'The server checks each person\\'s Clerk session.' },\n { 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.' },\n { id: 'other', label: 'Another sign-in provider', means: 'Auth0, Google, Firebase, Cognito, Microsoft Entra or another provider that publishes its signing keys.' },\n { id: 'keys', label: 'Only programs call it, with keys', means: 'No person signs in: scripts and other servers call the app with API keys.' },\n ],\n fact: 'Some actions are for signed-in people only.',\n};\n\nconst existingData: Question = {\n id: 'data',\n kind: 'data',\n subject: null,\n ask: 'Are there records somewhere today, such as in an app you already run, that this app must start with?',\n 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.',\n choices: [\n { id: 'new', label: 'No, it starts empty', means: 'Nothing is moved.' },\n { 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.' },\n { 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.' },\n ],\n fact: 'The program keeps records.',\n};\n\nexport function questionsFor(report: Report, structure: Structure, names: Names = {}): Question[] {\n const questions: Question[] = [];\n if (report.surface.routes.length) questions.push(topology);\n for (const table of report.dataModel.tables) questions.push(accessQuestion(table, names));\n for (const table of report.dataModel.tables) {\n const both = table.readers.filter(h => table.writers.includes(h));\n if (both.length) questions.push(togetherQuestion(table, both, names));\n }\n for (const route of report.surface.routes) {\n const writes = route.inferredSteps.filter(s => s.resource === 'db' && s.op !== 'read' && s.op !== 'query');\n const tables = [...new Set(writes.flatMap(s => s.tables))];\n if (writes.length >= 2) questions.push(partialQuestion(route, tables, names));\n }\n for (const route of report.surface.routes) {\n const entry = structure.entries.find(e => e.entry === `route:${route.path}`);\n const kinds = (entry?.resources ?? []).filter(r => r === 'model' || r === 'net');\n if (kinds.length) questions.push(outsideQuestion(route, kinds, names));\n }\n // How the app meets the world it replaces: asked last, since nothing in\n // the program waits on them.\n if (report.surface.routes.some(r => r.authority !== undefined && PERSON_SIGNS_IN.has(r.authority))) questions.push(signIn);\n if (report.dataModel.tables.length) questions.push(existingData);\n return questions;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\n\n// What the person decided, in their own words, kept beside the code so a new\n// agent session starts from the same decisions. .yichus/requirements.json is\n// meant to be committed; .yichus/state.json is derived and ignored.\n\nconst Answer = z.object({\n question: z.string().min(1),\n choice: z.string().min(1),\n words: z.string(),\n answeredAt: z.string(),\n});\nexport type Answer = z.infer<typeof Answer>;\n\n/** What the person or their agent says happens when an entry runs. The\n * engine (api_organize lens=structure with requirements) checks each claim\n * against the tree it computes and refuses ids it did not compute; here it\n * is only kept, so saving the file never drops it. */\nexport const Scenario = z.object({\n entry: z.string().min(1),\n title: z.string().optional(),\n names: z.record(z.string(), z.string()).optional(),\n expect: z.array(z.object({ at: z.string(), claim: z.string() }).strict()).optional(),\n}).strict();\nexport type Scenario = z.infer<typeof Scenario>;\n\n/** A rule the person stated about what the app must always or never do, in\n * their words, with the laws (Yichus/Law) that check it. */\nexport const RuleRecord = z.object({ rule: z.string().trim().min(1), laws: z.array(z.string().min(1)).min(1) }).strict();\nexport type RuleRecord = z.infer<typeof RuleRecord>;\n\nconst Requirements = z.object({\n schemaVersion: z.literal('yichus-requirements-1'),\n description: z.string().nullable(),\n answers: z.array(Answer),\n /** Plain names for the program's records and actions, keyed by code name. */\n names: z.record(z.string(), z.string()).optional(),\n scenarios: z.array(Scenario).optional(),\n /** The rules the agent listed; absent until it has looked, empty when the\n * person stated none. */\n rules: z.array(RuleRecord).optional(),\n});\nexport type Requirements = z.infer<typeof Requirements>;\n\nexport const studioDir = (root: string) => path.join(root, '.yichus');\nconst requirementsPath = (root: string) => path.join(studioDir(root), 'requirements.json');\n\nexport function loadRequirements(root: string): Requirements {\n const file = requirementsPath(root);\n if (!fs.existsSync(file)) return { schemaVersion: 'yichus-requirements-1', description: null, answers: [] };\n const parsed = Requirements.safeParse(JSON.parse(fs.readFileSync(file, 'utf8')));\n if (!parsed.success) throw new Error(`${file} is not a yichus-requirements-1 file: ${parsed.error.issues[0]?.message ?? 'invalid'}`);\n return parsed.data;\n}\n\nexport function saveRequirements(root: string, requirements: Requirements): void {\n ensureStudioDir(root);\n fs.writeFileSync(requirementsPath(root), `${JSON.stringify(Requirements.parse(requirements), null, 2)}\\n`);\n}\n\nexport function withNames(requirements: Requirements, names: Record<string, string>): Requirements {\n return { ...requirements, names: { ...requirements.names, ...names } };\n}\n\n/** A scenario replaces any earlier one for the same entry, and a dropped\n * entry loses its scenario. */\nexport function withScenarios(requirements: Requirements, scenarios: Scenario[], drop: string[] = []): Requirements {\n const replaced = new Set([...scenarios.map(s => s.entry), ...drop]);\n return { ...requirements, scenarios: [...(requirements.scenarios ?? []).filter(s => !replaced.has(s.entry)), ...scenarios] };\n}\n\n/** The latest answer to a question replaces any earlier one. */\nexport function withAnswer(requirements: Requirements, answer: Answer): Requirements {\n return { ...requirements, answers: [...requirements.answers.filter(a => a.question !== answer.question), answer] };\n}\n\nexport function ensureStudioDir(root: string): void {\n const dir = studioDir(root);\n fs.mkdirSync(dir, { recursive: true });\n // What the studio derives, what the agent points at while it talks, what\n // the person has in view and where the page runs stay out of the person's\n // commits.\n const ignore = path.join(dir, '.gitignore');\n // The file is the person's too: what is in it stays as it is, and only\n // the missing lines are added at its end.\n const before = fs.existsSync(ignore) ? fs.readFileSync(ignore, 'utf8') : '';\n const kept = new Set(before.split('\\n').map(line => line.trim()));\n const missing = ['state.json', 'marks.json', 'viewing.json', 'pages/'].filter(name => !kept.has(name));\n if (missing.length) fs.appendFileSync(ignore, `${before && !before.endsWith('\\n') ? '\\n' : ''}${missing.map(line => `${line}\\n`).join('')}`);\n}\n","import { z } from 'zod';\nimport { outcomeLabel, stationLabel } from '../../../../web/what-happens-record.js';\n\n// What happens when: each entry's decision tree as the engine computes it,\n// with the scenarios the agent wrote in the person's words checked against\n// it. The record is web/what-happens-record.js's; this module reads it to\n// say what the agent still owes: an entry nobody described, a computed id\n// without the person's words, an outcome no claim covers, a name or claim\n// the engine refused, an expectation that is not a claim, and the claims\n// that fail; and which entries the engine could not follow, so that\n// nothing said about them is checked.\n\nconst Effect = z.looseObject({ op: z.string(), tables: z.array(z.string()).default([]) });\nconst Claim = z.looseObject({ verdict: z.string(), parsed: z.string(), at: z.string(),\n property: z.looseObject({ is: z.string(), subject: z.string().optional() }).optional() });\nconst Leaf = z.looseObject({ kind: z.literal('leaf'), id: z.string(), words: z.string().nullable(), outcome: z.unknown(), claims: z.array(Claim).default([]) });\ntype Node = { kind: 'node'; id: string; test: string; words: string | null; arms: Arm[] };\ntype Arm = { id: string; pattern: string; words: string | null; effects: z.infer<typeof Effect>[]; next: Tree };\ntype Tree = Node | z.infer<typeof Leaf>;\nconst Tree: z.ZodType<Tree> = z.lazy(() => z.union([Leaf, z.looseObject({\n kind: z.literal('node'), id: z.string(), test: z.string(), words: z.string().nullable(),\n arms: z.array(z.looseObject({ id: z.string(), pattern: z.string(), words: z.string().nullable(), effects: z.array(Effect).default([]), next: Tree })),\n})])) as z.ZodType<Tree>;\n// An entry the engine could not follow has no tree, and says why.\nconst Entry = z.looseObject({ entry: z.string(), title: z.string().nullable(), described: z.boolean(), effects: z.array(Effect).default([]), tree: Tree.nullable(),\n unsupported: z.string().nullable() });\nconst Checked = z.looseObject({ entry: z.string(), at: z.string(), claim: z.string(), parsed: z.string(), verdict: z.string() });\nconst Refused = z.looseObject({ entry: z.string(), id: z.string(), words: z.string(), reason: z.string() });\nexport const WhatHappens = z.looseObject({\n entries: z.array(Entry),\n claims: z.array(Checked),\n refused: z.array(Refused),\n /** Expectations that are not claims in the grammar, so nothing checks them. */\n notes: z.array(z.looseObject({ entry: z.string(), at: z.string(), text: z.string() })),\n mismatches: z.array(z.looseObject({ entry: z.string(), reason: z.string() })),\n});\nexport type WhatHappens = z.infer<typeof WhatHappens>;\n\n/** One computed id the person's words are still missing on, with what the\n * engine computed there, for the agent. */\nexport interface Unnamed { id: string; what: string }\n\nexport interface Owed {\n entry: string;\n /** No scenario describes the entry yet. */\n undescribed: boolean;\n unnamed: Unnamed[];\n /** Outcomes no claim says anything about. */\n uncovered: string[];\n}\n\nconst effectsText = (effects: z.infer<typeof Effect>[]) => effects.length ? `; effects: ${effects.map(stationLabel).join(', ')}` : '';\n\nfunction walk(tree: Tree | null, visit: (id: string, what: string, words: string | null, leaf: boolean, claims: number) => void) {\n if (!tree) return;\n if (tree.kind === 'leaf') { visit(tree.id, `outcome: ${outcomeLabel(tree.outcome)}`, tree.words, true, tree.claims.length); return; }\n visit(tree.id, `the program checks ${tree.test}`, tree.words, false, 0);\n for (const arm of tree.arms) {\n // An arm that ends at once shares its id with its outcome.\n if (arm.next.id !== arm.id) visit(arm.id, `when ${arm.pattern}${effectsText(arm.effects)}`, arm.words, false, 0);\n else if (arm.next.kind === 'leaf') {\n const leaf = arm.next;\n visit(leaf.id, `when ${arm.pattern}${effectsText(arm.effects)}, outcome: ${outcomeLabel(leaf.outcome)}`, leaf.words ?? arm.words, true, leaf.claims.length);\n continue;\n }\n walk(arm.next, visit);\n }\n}\n\n/** What the agent still owes for each entry. */\nexport function owed(record: WhatHappens): Owed[] {\n return record.entries.map(e => {\n const unnamed: Unnamed[] = [], uncovered: string[] = [];\n walk(e.tree, (id, what, words, leaf, claims) => {\n if (!words) unnamed.push({ id, what });\n if (leaf && !claims) uncovered.push(id);\n });\n return { entry: e.entry, undescribed: !e.described, unnamed, uncovered };\n }).filter(o => o.undescribed || o.unnamed.length || o.uncovered.length);\n}\n\n/** What the person's claims say actions answer (returns CONSTRUCTOR): the\n * page says each in the person's words, so each wants a name. */\nexport function replies(record: WhatHappens): string[] {\n const found = new Set<string>();\n const visit = (tree: Tree | null) => {\n if (!tree) return;\n if (tree.kind === 'leaf') { for (const c of tree.claims) if (c.property?.is === 'returns' && c.property.subject) found.add(c.property.subject); return; }\n for (const arm of tree.arms) visit(arm.next);\n };\n for (const e of record.entries) visit(e.tree);\n return [...found].sort();\n}\n\n/** The entries the engine could not follow, with why: nothing the person\n * expects of them is checked. */\nexport function unfollowed(record: WhatHappens): Array<{ entry: string; why: string }> {\n return record.entries.filter(e => !e.tree).map(e => ({\n entry: e.entry, why: e.unsupported ?? 'the engine gave no reason' }));\n}\n","// How the studio's words name its tools: as MCP tools for an agent on the\n// MCP connection, or as shell commands for an agent in a terminal. Every\n// step, reply and error goes through one of these, so neither agent reads\n// the other's names.\n\nexport type StudioTool = 'yichus_start' | 'yichus_next' | 'yichus_name' | 'yichus_answer' | 'yichus_rules' | 'yichus_scenario' | 'yichus_point' | 'yichus_page';\n\nexport interface Say {\n surface: 'mcp' | 'cli';\n /** The tool's name where a sentence names it (\"the latest yichus_next\"). */\n name(tool: StudioTool): string;\n /** An instruction to use a studio tool: \"call yichus_next\". */\n use(tool: StudioTool): string;\n /** An instruction to use a studio tool with this input. */\n useWith(tool: StudioTool, input: string): string;\n /** An instruction to read a reference topic. */\n reference(topic: string): string;\n /** An instruction to call an engine tool with these arguments. */\n api(tool: string, args?: Record<string, unknown>): string;\n}\n\nexport const MCP: Say = {\n surface: 'mcp',\n name: tool => tool,\n use: tool => `call ${tool}`,\n useWith: (tool, input) => `call ${tool} with ${input}`,\n reference: topic => `call yichus_reference with topic \"${topic}\"`,\n api: (tool, args) => {\n const given = Object.entries(args ?? {}).map(([key, value]) => `${key} ${JSON.stringify(value)}`);\n return `call ${tool}${given.length ? ` with ${given.join(' and ')}` : ''}`;\n },\n};\n\nconst COMMAND: Record<StudioTool, string> = {\n yichus_start: 'yichus start \"DESCRIPTION\"',\n yichus_next: 'yichus next',\n yichus_name: 'yichus name CODE \"NAME\" [CODE \"NAME\" ...]',\n yichus_answer: 'yichus answer QUESTION CHOICE --words \"THEIR WORDS\"',\n yichus_rules: 'yichus rules FILE.json',\n yichus_scenario: 'yichus scenario FILE.json',\n yichus_point: 'yichus point FILE.json',\n yichus_page: 'yichus page',\n};\n\nexport const CLI: Say = {\n surface: 'cli',\n name: tool => `\\`${COMMAND[tool].split(' ').slice(0, 2).join(' ')}\\``,\n use: tool => `run \\`${COMMAND[tool]}\\``,\n // A command that takes input reads it from the FILE.json it names.\n useWith: (tool, input) => `run \\`${COMMAND[tool]}\\` with FILE.json holding ${input}`,\n reference: topic => `run \\`yichus reference ${topic}\\``,\n api: (tool, args) => {\n // A tool that requires sources reads the project folder, as the studio does.\n // The guide answers {sections: [{title, body}]}; one section is the first.\n const select = tool === 'api_guide' && args?.section !== undefined ? ' --select /sections/0/body' : '';\n if (!args || !Object.keys(args).length) return `run \\`yichus call ${tool}${select}\\``;\n return `run \\`yichus call ${tool} --args ARGS.json${select}\\` with ARGS.json holding ${JSON.stringify(args)}`;\n },\n};\n\n/** The command-line names of the tools reference documents call by their\n * MCP names. */\nexport const CLI_LEGEND = [\n 'On the command line, the tools this document names are commands:',\n ...Object.entries(COMMAND).map(([tool, command]) => ` ${tool}: ${command}`),\n ' yichus_reference: yichus reference TOPIC',\n ' 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',\n].join('\\n');\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema, type CallToolResult, type Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport { type StudioEngine, type StudioState, direct, drawnParts, readState } from './director.js';\nimport { caseSources, projectSources, sourcesHash } from './project.js';\nimport { recordMarks } from './marks.js';\nimport { pageText } from './page-view.js';\nimport { type Locate, REFERENCE, TOPICS, builtCopy, readReference, topicList } from './reference.js';\nimport { RuleRecord, loadRequirements, saveRequirements, withAnswer, withNames, withScenarios } from './requirements.js';\nimport { MCP, type Say } from './surface.js';\nimport { stepText } from './text.js';\n\n// The studio's MCP face. The instructions travel in the MCP handshake, so\n// an agent learns the loop before it reads a single tool description.\nexport const 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.\n\nWhy 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?\".\n\nThe loop:\n1. 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.\n2. 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.\n3. 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.\n4. 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.\n5. 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.\n6. 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.\n7. 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\").\n8. 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.\n9. 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.\n\nEvery 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.`;\n\nconst START = { name: 'yichus_start', description: 'Record what the person wants built, in their own words, and get the studio page link to give them. Call this first.',\n inputSchema: { type: 'object' as const, properties: { description: { type: 'string', description: 'The person\\'s description of the software, unchanged.' } }, required: ['description'] } };\nconst NEXT = { name: 'yichus_next', 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.',\n inputSchema: { type: 'object' as const, properties: {} } };\nconst ANSWER = { name: 'yichus_answer', 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.',\n inputSchema: { type: 'object' as const, properties: {\n question: { type: 'string', description: 'The question id from yichus_next.' },\n choice: { type: 'string', description: 'The id of the choice the person picked.' },\n words: { type: 'string', description: 'What the person said, in their words.' },\n }, required: ['question', 'choice', 'words'] } };\n\nconst NAME = { name: 'yichus_name', 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.',\n inputSchema: { type: 'object' as const, properties: {\n names: { type: 'object', additionalProperties: { type: 'string' },\n 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\".' },\n }, required: ['names'] } };\n\nconst SCENARIO = { name: 'yichus_scenario', 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.',\n inputSchema: { type: 'object' as const, properties: {\n scenarios: { type: 'array', items: { type: 'object', properties: {\n entry: { type: 'string', description: 'The action, as yichus_next listed it (route:/path).' },\n title: { type: 'string', description: 'What the person does, in their words.' },\n names: { type: 'object', additionalProperties: { type: 'string' }, description: 'Each id yichus_next listed under the action, with the person\\'s words for it.' },\n expect: { type: 'array', items: { type: 'object', properties: { at: { type: 'string' }, claim: { type: 'string' } }, required: ['at', 'claim'] },\n description: 'What must and must not happen: [not] reads TABLE, writes TABLE, refused, returns CONSTRUCTOR, reaches model or reaches net, at an id.' },\n }, required: ['entry', 'title', 'names', 'expect'] } },\n drop: { type: 'array', items: { type: 'string' }, description: 'Actions yichus_next reports the app no longer has, whose scenarios to remove.' },\n } } };\n\nconst RULES = { name: 'yichus_rules', 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.',\n inputSchema: { type: 'object' as const, properties: {\n rules: { type: 'array', items: { type: 'object', properties: {\n rule: { type: 'string', description: 'The rule, in the person\\'s words.' },\n 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.' },\n }, required: ['rule', 'laws'] } },\n }, required: ['rules'] } };\n\nconst POINT = { name: 'yichus_point', 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.',\n inputSchema: { type: 'object' as const, properties: {\n marks: { type: 'array', items: { type: 'object', properties: {\n 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.' },\n note: { type: 'string', description: 'What you are saying about it, in the person\\'s words, at most 280 characters.' },\n }, required: ['at', 'note'] } },\n }, required: ['marks'] } };\n\nconst PAGE = { name: 'yichus_page', 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.',\n inputSchema: { type: 'object' as const, properties: {} } };\n\nconst REFERENCE_TOOL = { name: 'yichus_reference', description: `Reference material yichus_next asks for. ${TOPICS.map(t => `${t}: ${REFERENCE[t].about}`).join(' ')}`,\n inputSchema: { type: 'object' as const, properties: { topic: { type: 'string', enum: TOPICS, description: 'The topic yichus_next named.' } }, required: ['topic'] } };\n\nconst StartArgs = z.object({ description: z.string().min(1) }).strict();\nconst AnswerArgs = z.object({ question: z.string().min(1), choice: z.string().min(1), words: z.string() }).strict();\n// What the tool takes: every field of a scenario, unlike the stored file,\n// which keeps whatever an earlier version wrote.\nconst ScenarioInput = z.object({\n entry: z.string().min(1), title: z.string().trim().min(1), names: z.record(z.string().min(1), z.string().trim().min(1)),\n expect: z.array(z.object({ at: z.string().min(1), claim: z.string().trim().min(1) }).strict()),\n}).strict();\nconst ScenarioArgs = z.object({ scenarios: z.array(ScenarioInput).default([]), drop: z.array(z.string().min(1)).default([]) })\n .refine(a => a.scenarios.length + a.drop.length > 0, 'give at least one scenario or one action to drop');\nconst RulesArgs = z.object({ rules: z.array(RuleRecord) }).strict();\nconst NameArgs = z.object({ names: z.record(z.string().min(1), z.string().trim().min(1)).refine(names => Object.keys(names).length > 0) });\n\nexport interface StudioMcpOptions {\n root: string;\n engine: StudioEngine;\n /** The engine's catalog, as tools/list advertises it. */\n catalog: () => Promise<Tool[]>;\n pageUrl: string | null;\n now?: () => Date;\n /** Where the reference files are (default: copied beside the built CLI). */\n locate?: Locate;\n}\n\nconst text = (body: string, structured?: Record<string, unknown>, isError = false): CallToolResult =>\n ({ content: [{ type: 'text', text: body }], ...(structured ? { structuredContent: structured } : {}), isError });\n\n/** A catalog tool as the studio offers it: sources become optional. */\nexport function studioTool(tool: Tool): Tool {\n const schema = tool.inputSchema;\n if (!schema.properties || !('sources' in schema.properties)) return tool;\n return {\n ...tool,\n description: [tool.description, 'In the studio, leave out sources to check every .bosatsu file in the project folder.'].filter(Boolean).join(' '),\n inputSchema: { ...schema, required: (schema.required ?? []).filter(name => name !== 'sources') },\n };\n}\n\n/** The person's description of what to build. */\nexport function recordStart(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = StartArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_start')} needs the person's description, and nothing else. ${z.prettifyError(parsed.error)}` };\n saveRequirements(root, { ...loadRequirements(root), description: parsed.data.description });\n return { ok: true };\n}\n\n/** Answer a question for an agent: validates the ids against the latest state. */\nexport function recordAnswer(root: string, args: unknown, now: Date, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = AnswerArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_answer')} needs question, choice and words, and nothing else. ${z.prettifyError(parsed.error)}` };\n const state = readState(root);\n const property = state?.properties.find(p => p.question.id === parsed.data.question);\n if (!property) return { ok: false, error: `No question ${parsed.data.question} in the latest ${say.name('yichus_next')}; ${say.use('yichus_next')} and use its ids.` };\n if (!property.question.choices.some(c => c.id === parsed.data.choice)) {\n 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(', ')}.` };\n }\n saveRequirements(root, withAnswer(loadRequirements(root), { ...parsed.data, answeredAt: now.toISOString() }));\n return { ok: true };\n}\n\n/** Name parts of the program for the person: each must be one the latest\n * state asks about or draws. */\nexport function recordNames(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = NameArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_name')} needs names: each code name ${say.name('yichus_next')} listed, with its plain name.` };\n const state = readState(root);\n const parts = new Set([...state?.properties.flatMap(p => p.question.subject ?? []) ?? [], ...state ? drawnParts(state).map(p => p.code) : []]);\n const unknown = Object.keys(parsed.data.names).filter(code => !parts.has(code));\n if (unknown.length) {\n const listed = [...parts].slice(0, 20).join(', ') + (parts.size > 20 ? `, and ${parts.size - 20} more` : '');\n // A part the program gained since then is named once the studio has seen it.\n const changed = state && state.sourcesHash !== sourcesHash(projectSources(root)) ? ` The program changed since then: ${say.use('yichus_next')} first.` : '';\n return { ok: false, error: `No part named ${unknown.join(', ')} in the latest ${say.name('yichus_next')}; the parts are ${listed || 'none yet'}.${changed}` };\n }\n saveRequirements(root, withNames(loadRequirements(root), parsed.data.names));\n return { ok: true };\n}\n\n/** Describe actions for the person: each must be one the latest state\n * computed a decision tree for. The engine checks the ids and claims on\n * the next yichus_next. */\nexport function recordScenarios(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = ScenarioArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_scenario')} needs scenarios, each with entry, title, names and expect, or drop. ${z.prettifyError(parsed.error)}` };\n const happens = readState(root)?.whatHappens;\n const entries = new Set(happens?.entries.map(e => e.entry) ?? []);\n const unknown = parsed.data.scenarios.map(s => s.entry).filter(e => !entries.has(e));\n if (unknown.length) return { ok: false, error: `No action ${unknown.join(', ')} in the latest ${say.name('yichus_next')}; the actions are ${[...entries].join(', ') || 'none yet'}.` };\n // Only a scenario whose action is gone can be dropped: a scenario of an\n // action the app still has is replaced, never removed.\n const gone = new Set(happens?.mismatches.map(m => m.entry));\n const kept = parsed.data.drop.filter(e => !gone.has(e));\n if (kept.length) return { ok: false, error: `The latest ${say.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.` };\n saveRequirements(root, withScenarios(loadRequirements(root), parsed.data.scenarios, parsed.data.drop));\n return { ok: true };\n}\n\n/** The rules the person stated, each with the laws that check it: every\n * law must be one the latest state found in the program. */\nexport function recordRules(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = RulesArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_rules')} needs rules: a list of {\"rule\": the person's words, \"laws\": [law names]}, empty if they stated none. ${z.prettifyError(parsed.error)}` };\n const laws = readState(root)?.laws ?? [];\n const known = (ref: string) => laws.some(l => l.binding === ref || l.binding.endsWith(`::${ref}`) || l.name === ref);\n const unknown = [...new Set(parsed.data.rules.flatMap(r => r.laws).filter(ref => !known(ref)))];\n if (unknown.length) {\n const listed = laws.map(l => l.binding.slice(l.binding.lastIndexOf('::') + 2)).join(', ');\n return { ok: false, error: `No law named ${unknown.join(', ')} in the latest ${say.name('yichus_next')}; the laws are ${listed || 'none yet'}. Write the law, ${say.use('yichus_next')}, then record the rules.` };\n }\n saveRequirements(root, { ...loadRequirements(root), rules: parsed.data.rules });\n return { ok: true };\n}\n\n/** What yichus_start says about the studio page: its link when one runs,\n * and that it opens only on the computer it runs on. */\nexport function pageNote(pageUrl: string | null, say: Say): string {\n 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 ${say.name('yichus_page')}.`;\n if (!pageUrl) return [`The studio page is not running yet. Start it in the background in this folder with \\`yichus studio --page\\` and leave it running; ${say.name('yichus_start')}, ${say.name('yichus_next')} and ${say.name('yichus_page')} then give its link. It opens only in a browser on the computer it runs on.`,\n `${elsewhere} Before you give them the link, ${say.reference('guiding')}.`].join('\\n');\n return [`Read the \"guiding\" reference (${say.reference('guiding')}), then give the person this link and ask them to keep it open: ${pageUrl}`,\n `It opens only in a browser on the computer the studio runs on. ${elsewhere}`].join('\\n');\n}\n\nexport interface StudioMcpServer {\n server: Server;\n /** Resolves once every accepted request has been answered. */\n idle(): Promise<void>;\n}\n\nexport function createStudioMcpServer({ root, engine, catalog, pageUrl, now = () => new Date(), locate = builtCopy }: StudioMcpOptions): StudioMcpServer {\n const server = new Server({ name: 'yichus-studio', version: '0.3.1' }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });\n const active = new Set<Promise<unknown>>();\n const track = <T>(task: Promise<T>): Promise<T> => {\n active.add(task);\n void task.finally(() => active.delete(task)).catch(() => {});\n return task;\n };\n let tools: Tool[] | null = null;\n const catalogTools = async () => (tools ??= (await catalog()).map(studioTool));\n let last: StudioState | null = readState(root);\n\n server.setRequestHandler(ListToolsRequestSchema, () => track((async () => ({ tools: [START, NEXT, NAME, ANSWER, RULES, SCENARIO, POINT, PAGE, REFERENCE_TOOL, ...await catalogTools()] }))()));\n\n server.setRequestHandler(CallToolRequestSchema, request => track(callTool(request.params)));\n\n async function callTool(params: { name: string; arguments?: Record<string, unknown> }): Promise<CallToolResult> {\n const { name, arguments: args = {} } = params;\n if (name === 'yichus_start') {\n const result = recordStart(root, args);\n if (!result.ok) return text(result.error, undefined, true);\n return text(`${pageNote(pageUrl, MCP)}\\nIf this replaces an app the person already has, read yichus_reference topic \"porting\" first.\\nNext: call yichus_next.`, { pageUrl });\n }\n if (name === 'yichus_next') {\n last = await direct({ root, engine, requirements: loadRequirements(root), previous: last });\n const { map: _map, layers: _layers, whatHappens: _whatHappens, ...rest } = last;\n return text(stepText(last, pageUrl), rest as unknown as Record<string, unknown>);\n }\n if (name === 'yichus_answer') {\n const result = recordAnswer(root, args, now());\n return result.ok ? text('Recorded. Ask any remaining questions, then call yichus_next.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_name') {\n const result = recordNames(root, args);\n return result.ok ? text('Recorded. Call yichus_next.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_rules') {\n const result = recordRules(root, args);\n return result.ok ? text('Recorded. Call yichus_next: it runs every law and says how each rule stands.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_scenario') {\n const result = recordScenarios(root, args);\n return result.ok ? text('Recorded. Call yichus_next: the engine checks every name and claim.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_point') {\n const result = recordMarks(root, args, now());\n return result.ok ? text('The page shows your notes now. Go on talking with the person.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_page') {\n if (Object.keys(args).length) return text('yichus_page takes no arguments.', undefined, true);\n return text(pageText(root, pageUrl, now(), MCP));\n }\n if (name === 'yichus_reference') {\n const said = readReference(String(args.topic), locate);\n return said ? text(said) : text(`No reference topic ${String(args.topic)}.\\n${topicList(topic => `topic \"${topic}\"`)}`, undefined, true);\n }\n const tool = (await catalogTools()).find(t => t.name === name);\n if (!tool) return text(`Unknown tool ${name}.`, undefined, true);\n const filled: Record<string, unknown> = { ...args };\n const props = tool.inputSchema.properties ?? {};\n if ('sources' in props && filled.sources === undefined) {\n filled.sources = name === 'api_protocol_check' ? [...projectSources(root), ...caseSources(root)] : projectSources(root);\n }\n // The person's answer about servers is the topology every check uses.\n const topology = loadRequirements(root).answers.find(a => a.question === 'topology')?.choice;\n if ('instances' in props && filled.instances === undefined && topology) filled.instances = topology === 'one' ? '1' : 'many';\n const result = await engine.call(name, filled);\n // The whole guide is over 100 KB; in the studio it is read a section at a time.\n if (name === 'api_guide' && filled.section === undefined && Array.isArray(result.sections)) {\n const titles = { ok: true, tool: 'api_guide', titles: (result.sections as Array<{ title: string }>).map(s => s.title),\n note: 'The whole guide is long. Call api_guide with section set to one of these titles, or to part of one.' };\n return text(JSON.stringify(titles), titles);\n }\n return text(JSON.stringify(result), result, result.ok !== true);\n }\n return {\n server,\n async idle() {\n while (active.size) await Promise.allSettled(active);\n // The SDK writes a handler's response a few microtasks after it settles.\n await new Promise(resolve => setImmediate(resolve));\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { readState } from './director.js';\nimport { personDiagrams } from './person.js';\nimport { ensureStudioDir, loadRequirements, studioDir } from './requirements.js';\n\n// What the agent is pointing at on the studio page while it talks with the\n// person: each mark names a part the page draws (a section of the app, an\n// action, or a step inside one) and carries the agent's short note. The\n// page lays the notes over the diagrams as the agent's words, never inside\n// them. Marks are part of the conversation, not of what the person decided,\n// so .yichus/marks.json is not committed; each call replaces the last.\n\nconst Mark = z.object({ at: z.string().min(1), note: z.string().trim().min(1).max(280) }).strict();\nexport type Mark = z.infer<typeof Mark>;\nconst Marks = z.object({ schemaVersion: z.literal('yichus-marks-1'), said: z.string(), marks: z.array(Mark) });\nexport type Marks = z.infer<typeof Marks>;\nconst PointArgs = z.object({ marks: z.array(Mark) }).strict();\n\nconst marksPath = (root: string) => path.join(studioDir(root), 'marks.json');\n\nexport function loadMarks(root: string): Marks | null {\n const file = marksPath(root);\n if (!fs.existsSync(file)) return null;\n const parsed = Marks.safeParse(JSON.parse(fs.readFileSync(file, 'utf8')));\n if (!parsed.success) throw new Error(`${file} is not a yichus-marks-1 file: ${z.prettifyError(parsed.error)}`);\n return parsed.data;\n}\n\n/** Every id a mark may name: exactly the parts the page draws now, the\n * sections it stacks, the described actions, and each step inside one. */\nexport function pointable(root: string): Set<string> {\n const state = readState(root);\n return new Set(state ? personDiagrams(state, loadRequirements(root).names ?? {}).anchors.keys() : []);\n}\n\n/** Point at parts of the page: replaces the marks before, and an empty\n * list clears them. */\nexport function recordMarks(root: string, args: unknown, now: Date): { ok: true } | { ok: false; error: string } {\n const parsed = PointArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `yichus_point needs marks, each with at and a note of at most 280 characters. ${z.prettifyError(parsed.error)}` };\n const known = pointable(root);\n const unknown = parsed.data.marks.map(m => m.at).filter(at => !known.has(at));\n 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.` };\n ensureStudioDir(root);\n fs.writeFileSync(marksPath(root), `${JSON.stringify(Marks.parse({ schemaVersion: 'yichus-marks-1', said: now.toISOString(), marks: parsed.data.marks }), null, 2)}\\n`);\n return { ok: true };\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { usesElsewhere } from '../../../../web/layer-groups.js';\n\n// The two diagrams the studio page draws, made from the engine's records with\n// nothing in them but the person's words: the sections of the app stacked\n// on what they are built from, and what happens in each action. A record\n// built here holds no code name, test, pattern or status code; a part\n// nobody has named yet is drawn as not named, never under its code name.\n// Each part carries an opaque anchor, its place in the picture, so the agent\n// can point at it (marks.ts) without the page learning its code name.\n\ntype Names = Record<string, string>;\nconst named = (names: Names, code: string) => names[code] ?? null;\n\n/** Words the page draws: computed text, and the agent's own words, which\n * the page sets apart as unchecked. */\nexport type Phrase = Array<string | { theirs: string }>;\nconst theirs = (words: string | null, missing: string): Phrase[number] => words === null ? missing : { theirs: words };\n\n// ---------------------------------------------------------------- sections\n\nconst Package = z.looseObject({\n name: z.string(), level: z.number(),\n reads: z.array(z.string()), writes: z.array(z.string()), handedIn: z.array(z.string()),\n});\nconst Layers = z.looseObject({\n layers: z.looseObject({ packages: z.array(Package), packageEdges: z.array(z.looseObject({})), crossEdges: z.array(z.looseObject({})) }),\n});\n\n/** Where each code name is drawn: code name to anchor. */\nexport type Anchors = Map<string, string>;\n\nexport interface Section {\n anchor: string;\n /** The person's name for the section, or null while it has none. */\n name: string | null;\n /** The records it changes, then the ones it only looks at: the person's\n * name for each, or null for a kind of record not named yet. */\n changes: Array<string | null>;\n looks: Array<string | null>;\n /** How much of the rest of the app is built on it. */\n uses: number;\n}\n\n/** The app's sections in layers, the top first: each layer is built only\n * from the layers below it. */\nexport function personSections(layers: unknown, names: Names, anchors: Anchors = new Map()): Section[][] | null {\n const parsed = Layers.safeParse(layers);\n if (!parsed.success) return null;\n const data = parsed.data.layers;\n const uses = usesElsewhere(data);\n const levels = [...new Set(data.packages.map(p => p.level))].sort((a, b) => b - a);\n return levels.map((level, i) => data.packages.filter(p => p.level === level).map(p => {\n // Records a caller hands in are the caller's, so a section counts its own.\n const own = (tables: string[]) => [...new Set(tables.filter(t => !p.handedIn.includes(t)).map(t => named(names, t)))];\n const changes = own(p.writes);\n return { code: p.name, name: named(names, p.name), changes, looks: own(p.reads).filter(t => !changes.includes(t)), uses: uses.get(p.name)! };\n }).sort((a, b) => b.uses - a.uses).map(({ code, ...section }, k) => {\n const anchor = `section-${i}-${k}`;\n anchors.set(code, anchor);\n return { anchor, ...section };\n }));\n}\n\n// ------------------------------------------------------------ what happens\n\n// The engine sends each claim's fields as well as its text, so nothing here\n// parses the text back.\nconst Property = z.object({ negated: z.boolean(), is: z.enum(['reads', 'writes', 'refused', 'returns', 'reaches']), subject: z.string().optional() });\nexport type Property = z.infer<typeof Property>;\nconst Claim = z.looseObject({ property: Property, verdict: z.enum(['holds', 'fails', 'inconclusive']) });\nconst Leaf = z.looseObject({\n kind: z.literal('leaf'), id: z.string(), words: z.string().nullable(), status: z.enum(['grey', 'red', 'green', 'unchecked']),\n outcome: z.looseObject({ kind: z.string() }), claims: z.array(Claim), witnesses: z.array(z.string()),\n});\ntype Node = { kind: 'node'; id: string; words: string | null; arms: Arm[] };\ntype Arm = { id: string; words: string | null; next: Tree };\ntype Tree = Node | z.infer<typeof Leaf>;\nconst Tree: z.ZodType<Tree> = z.lazy(() => z.union([Leaf, z.looseObject({\n kind: z.literal('node'), id: z.string(), words: z.string().nullable(),\n arms: z.array(z.looseObject({ id: z.string(), words: z.string().nullable(), next: Tree })),\n})])) as z.ZodType<Tree>;\nconst Happens = z.looseObject({\n entries: z.array(z.looseObject({ entry: z.string(), title: z.string().nullable(), described: z.boolean(), tree: Tree.nullable() })),\n witnesses: z.array(z.looseObject({ id: z.string(), resource: z.string() })),\n});\n\nexport type Verdict = 'holds' | 'fails' | 'cannot say';\nexport interface Check { says: Phrase; verdict: Verdict }\nexport interface Outcome {\n kind: 'outcome';\n anchor: string;\n /** The person's words for what happens, or null while there are none. */\n words: string | null;\n /** The request is turned away here rather than answered. */\n refused: boolean;\n /** red: something the person expects is false here; unchecked: the engine cannot say. */\n status: 'grey' | 'red' | 'green' | 'unchecked';\n checks: Check[];\n}\nexport interface Choice { kind: 'choice'; anchor: string; words: string | null; ways: Array<{ anchor: string; words: string | null; then: Step }> }\nexport type Step = Outcome | Choice;\nexport interface Action {\n anchor: string;\n /** The person's title for the action, or null while it has none. */\n title: string | null;\n first: Step | null;\n}\nexport interface PersonWhatHappens {\n /** The actions the person has described. */\n actions: Action[];\n /** How many actions nobody has described yet. */\n waiting: number;\n}\n\n/** A checked claim, said the way the person would say it. */\nexport function sayClaim({ negated, is, subject }: Property, names: Names): Phrase {\n const thing = theirs(subject === undefined ? null : named(names, subject), 'something not named yet');\n const said: Phrase = is === 'refused' ? ['turned away']\n : is === 'reaches' ? [subject === 'model' ? 'asks the AI model' : 'reaches the internet']\n : [is === 'reads' ? 'looks at ' : is === 'writes' ? 'changes ' : 'answers ', thing];\n return !negated ? said : is === 'refused' ? ['not turned away'] : ['never ', ...said];\n}\n\n/** What happens in each described action, in the person's words only. */\nexport function personWhatHappens(record: unknown, names: Names, anchors: Anchors = new Map()): PersonWhatHappens | null {\n const parsed = Happens.safeParse(record);\n if (!parsed.success) return null;\n const reach = new Map(parsed.data.witnesses.map(w => [w.id, named(names, w.resource)]));\n const VERDICT = { holds: 'holds', fails: 'fails', inconclusive: 'cannot say' } as const;\n const at = (id: string, anchor: string) => { anchors.set(id, anchor); return anchor; };\n const step = (t: Tree, said: string | null, place: string): Step => {\n if (t.kind === 'leaf') return {\n kind: 'outcome', anchor: at(t.id, place), words: t.words === said ? null : t.words, refused: t.outcome.kind === 'refused', status: t.status,\n checks: [\n ...t.claims.map(c => ({ says: sayClaim(c.property, names), verdict: VERDICT[c.verdict] })),\n ...t.witnesses.map(w => ({ says: ['someone else\\'s ', theirs(reach.get(w) ?? null, 'records'), ' can be reached here'], verdict: 'fails' as const })),\n ],\n };\n // An arm that ends at once shares its id, and its words, with its outcome,\n // so pointing at either points at the outcome.\n return { kind: 'choice', anchor: at(t.id, place), words: t.words, ways: t.arms.map((a, k) => {\n const then = step(a.next, a.next.id === a.id ? a.words : null, `${place}-${k}`);\n return { anchor: a.next.id === a.id ? then.anchor : at(a.id, `${place}-${k}-way`), words: a.words, then };\n }) };\n };\n const described = parsed.data.entries.filter(e => e.described);\n return {\n actions: described.map((e, i) => ({ anchor: at(e.entry, `action-${i}`), title: e.title, first: e.tree && step(e.tree, null, `action-${i}-step`) })),\n waiting: parsed.data.entries.length - described.length,\n };\n}\n\n/** Both diagrams, where each part the agent may point at is drawn, and\n * which drawing that is: an anchor names the same part only while the\n * drawing stays the same. */\nexport function personDiagrams(state: { layers: unknown; whatHappens: unknown }, names: Names) {\n const anchors: Anchors = new Map();\n const sections = personSections(state.layers, names, anchors);\n const whatHappens = state.whatHappens ? personWhatHappens(state.whatHappens, names, anchors) : null;\n const drawing = createHash('sha256').update(JSON.stringify([...anchors])).digest('hex').slice(0, 16);\n return { sections, whatHappens, anchors, drawing };\n}\n","// Groups and weights for the layer diagram, computed from the layers\n// lens output alone. Packages are alike on one chosen dimension: the\n// packages they connect to, the types they share, or the tables they\n// touch. Names are only labels here; a group comes from shared facts.\n\nexport const dimensions = Object.freeze({\n connections: 'packages they connect to',\n types: 'types they share',\n tables: 'tables they touch',\n none: 'no grouping',\n});\n\n// Two groups merge while their members are, on average, at least this\n// alike (Jaccard similarity of the chosen facts).\nconst together = 0.3;\n\n// What a package has on one dimension, as a set of fact keys. A type is\n// shared by the package that defines it and every package importing it.\nfunction facts(data, dimension) {\n const sets = new Map(data.packages.map(p => [p.name, new Set()]));\n for (const p of data.packages) {\n const f = sets.get(p.name);\n if (dimension === 'tables') [...p.reads, ...p.writes].forEach(t => f.add(t));\n if (dimension === 'connections') f.add(p.name);\n }\n for (const e of data.packageEdges) {\n if (dimension === 'connections') { sets.get(e.from).add(e.to); sets.get(e.to).add(e.from); }\n if (dimension === 'types') for (const t of e.typeNames) {\n sets.get(e.from).add(`${e.to}::${t}`);\n sets.get(e.to).add(`${e.to}::${t}`);\n }\n }\n return sets;\n}\n\nconst alike = (a, b) => {\n if (a.size === 0 || b.size === 0) return 0;\n let shared = 0;\n for (const x of a) if (b.has(x)) shared++;\n return shared / (a.size + b.size - shared);\n};\n\n// Whether folding each group into one node leaves a graph with no cycle.\nfunction foldsToLayers(data, groups) {\n const nodeOf = new Map(groups.flatMap((g, i) => g.map(m => [m, i])));\n const out = groups.map(() => new Set());\n for (const e of data.packageEdges) if (nodeOf.get(e.from) !== nodeOf.get(e.to)) out[nodeOf.get(e.from)].add(nodeOf.get(e.to));\n const state = groups.map(() => 0);\n const acyclic = i => {\n if (state[i]) return state[i] === 2;\n state[i] = 1;\n const ok = [...out[i]].every(acyclic);\n state[i] = 2;\n return ok;\n };\n return groups.every((_, i) => acyclic(i));\n}\n\n// Average-linkage clustering. Two groups merge only if folding every group\n// into one box still leaves arrows that all point down. Members keep the order they\n// were merged in, so the most alike packages sit next to each other.\nexport function groupPackages(data, dimension) {\n const sets = facts(data, dimension);\n let groups = data.packages.map(p => [p.name]);\n // A group of more than half the program would say nothing about it.\n const half = Math.max(2, Math.floor(data.packages.length / 2));\n if (dimension === 'none') return groups.map(members => ({ members, shared: [] }));\n const score = (x, y) => x.reduce((s, a) => s + y.reduce((t, b) => t + alike(sets.get(a), sets.get(b)), 0), 0) / (x.length * y.length);\n for (;;) {\n const pairs = [];\n for (let i = 0; i < groups.length; i++)\n for (let j = i + 1; j < groups.length; j++) {\n const s = score(groups[i], groups[j]);\n if (s >= together) pairs.push({ s, i, j });\n }\n const best = pairs.sort((a, b) => b.s - a.s).find(({ i, j }) => groups[i].length + groups[j].length <= half && foldsToLayers(data, groups.map((g, k) => k === i ? [...g, ...groups[j]] : g).filter((_, k) => k !== j)));\n if (!best) break;\n groups[best.i] = [...groups[best.i], ...groups[best.j]];\n groups = groups.filter((_, k) => k !== best.j);\n }\n return groups.map(members => ({ members, shared: members.length > 1 ? sharedFacts(members, sets) : [] }));\n}\n\n// The facts at least half the members have, most common first.\nfunction sharedFacts(members, sets) {\n const count = new Map();\n for (const m of members) for (const x of sets.get(m)) count.set(x, (count.get(x) ?? 0) + 1);\n return [...count].filter(([, n]) => n * 2 >= members.length)\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([x]) => x);\n}\n\n// How much the rest of the program leans on each node (a package, or a\n// folded group): references from definitions outside it to definitions in\n// it, plus each type imported into it from outside.\nexport function usesElsewhere(data, nodeOf = new Map(data.packages.map(p => [p.name, p.name]))) {\n const pkg = id => id.slice(0, id.indexOf('::'));\n const uses = new Map([...new Set(nodeOf.values())].map(n => [n, 0]));\n const add = (from, to, n) => { if (nodeOf.get(from) !== nodeOf.get(to)) uses.set(nodeOf.get(to), uses.get(nodeOf.get(to)) + n); };\n for (const e of data.crossEdges) add(pkg(e.from), pkg(e.to), 1);\n for (const e of data.packageEdges) add(e.from, e.to, e.typeNames.length);\n return uses;\n}\n\n// Each folded group of two or more as one node; every other package stays\n// itself. A fold of groups that folds to layers (see groupPackages) has no\n// cycle whichever groups are folded, so a node's level is one more than\n// the highest level it is built from.\nexport function foldGroups(data, groups, folded = () => true) {\n const nodes = groups.flatMap((g, i) => g.members.length > 1 && folded(i)\n ? [{ name: `group:${i}`, group: g, members: g.members }]\n : g.members.map(m => ({ name: m, members: [m] })));\n const nodeOf = new Map(nodes.flatMap(n => n.members.map(m => [m, n.name])));\n const edges = new Map();\n for (const e of data.packageEdges) {\n const from = nodeOf.get(e.from), to = nodeOf.get(e.to);\n if (from === to) continue;\n const key = `${from}\\n${to}`;\n const sum = edges.get(key) ?? { from, to, refs: 0, types: 0 };\n edges.set(key, { ...sum, refs: sum.refs + e.refs, types: sum.types + e.typeNames.length });\n }\n const below = new Map(nodes.map(n => [n.name, []]));\n for (const e of edges.values()) below.get(e.from).push(e.to);\n const level = new Map();\n const visit = n => {\n if (!level.has(n)) level.set(n, below.get(n).reduce((l, m) => Math.max(l, visit(m) + 1), 0));\n return level.get(n);\n };\n return { nodes: nodes.map(n => ({ ...n, level: visit(n.name) })), edges: [...edges.values()], nodeOf };\n}\n","import type { Status } from './director.js';\nimport type { PageSection } from './viewing.js';\n\n// The studio page: what the person asked for, questions waiting for them,\n// each property they chose with the engine's status, what happens in each\n// action, the sections their app is built from, and the system map of their\n// own program. Everything inside a \"Yichus output\" frame is copied\n// from the engine's results or the studio's pre-written questions; the\n// person's own words are labeled as theirs, and the diagrams that carry the\n// agent's words sit outside those frames, labeled unchecked. What the agent\n// points at while it talks floats in a layer above everything, each note\n// marked as the agent's and not checked. Text goes in through textContent\n// only. The page tells the studio what the person has in view, by id only,\n// so the agent can see it too (yichus_page).\n\n/** Each property status as the page says it, and its tone. yichus_page\n * says the same words. */\nexport const PAGE_STATUS: Record<Status | 'pending', [string, 'quiet' | 'good' | 'warn' | 'bad']> = {\n unanswered: ['waiting for your answer', 'quiet'], decided: ['decided', 'good'], assumed: ['holds, under an assumption', 'warn'],\n proven: ['proven', 'good'], bounded: ['holds in every scenario checked', 'good'], broken: ['broken', 'bad'],\n mismatch: ['the code says otherwise', 'bad'], 'needs-case': ['scenario being written', 'quiet'],\n 'needs-law': ['check being written', 'quiet'], unused: ['checked, but your app does not use it yet', 'bad'],\n inconclusive: ['not decided yet', 'warn'], 'no-check': ['no check needed', 'quiet'], pending: ['answered, waiting for your agent to check', 'quiet'],\n};\n\n/** The page's sections and their headings, which yichus_page says too. */\nexport const PAGE_HEADINGS: Record<PageSection, string> = {\n asked: 'What you asked for',\n now: 'What is happening now',\n questions: 'Questions for you',\n props: 'What your program must do',\n happens: 'What happens when',\n sections: 'How your app is built',\n map: 'The shape of your program',\n};\n\n/** What happens when, for a program with no actions people take. */\nexport const 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.';\n\nexport const STUDIO_PAGE = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Yichus studio</title>\n<link rel=\"stylesheet\" href=\"system-map.css\">\n<style>\n :root { --ink:#0f172a; --muted:#475569; --faint:#94a3b8; --rule:#e2e8f0; --paper:#ffffff; --page:#f6f8fb;\n --good:#047857; --goodSoft:#ecfdf5; --bad:#b91c1c; --badSoft:#fef2f2; --warn:#92400e; --warnSoft:#fffbeb; --accent:#22675e;\n --agent:#4f46e5; --agentSoft:rgba(79,70,229,0.16); }\n * { box-sizing:border-box; }\n body { margin:0; background:var(--page); color:var(--ink); font:16px/1.55 Inter, system-ui, sans-serif; }\n main { max-width:1100px; margin:0 auto; padding:24px 16px 64px; }\n header p { margin:4px 0 0; color:var(--muted); }\n h1 { font-size:1.6rem; margin:0; font-weight:600; }\n h2 { font-size:1.15rem; margin:32px 0 8px; }\n section > p.lede { color:var(--muted); margin:0 0 12px; max-width:70ch; }\n .frame { background:var(--paper); border:1px solid var(--rule); border-radius:10px; padding:16px; position:relative; }\n .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; }\n .yours { border-left:3px solid var(--accent); padding:4px 12px; margin:0; font-style:italic; }\n .label { font-size:0.75rem; color:var(--muted); text-transform:uppercase; letter-spacing:0.06em; margin:0 0 4px; }\n .now { font-weight:600; }\n .question { border-top:1px solid var(--rule); padding:14px 0; }\n .question:first-of-type { border-top:none; padding-top:4px; }\n .question .ask { font-weight:600; margin:0 0 4px; }\n .question .why { color:var(--muted); margin:0 0 8px; font-size:0.94rem; }\n .choice { display:flex; gap:8px; align-items:flex-start; margin:6px 0; }\n .choice span small { display:block; color:var(--muted); }\n textarea { width:100%; min-height:3.2em; font:inherit; border:1px solid var(--rule); border-radius:8px; padding:8px; margin:6px 0; }\n button { font:inherit; font-weight:600; border:none; border-radius:8px; padding:8px 14px; background:var(--accent); color:#fff; cursor:pointer; }\n button:disabled { opacity:0.5; cursor:default; }\n .props { list-style:none; margin:0; padding:0; }\n .props li { border-top:1px solid var(--rule); padding:12px 0; display:grid; grid-template-columns:1fr auto; gap:4px 16px; }\n .props li:first-child { border-top:none; }\n .chip { font-size:0.8rem; font-weight:700; border-radius:999px; padding:2px 10px; white-space:nowrap; align-self:start; justify-self:start; }\n .chip.good { color:var(--good); background:var(--goodSoft); }\n .chip.bad { color:var(--bad); background:var(--badSoft); }\n .chip.warn { color:var(--warn); background:var(--warnSoft); }\n .chip.quiet { color:var(--muted); background:var(--rule); }\n .props .choice-said { color:var(--muted); font-size:0.94rem; grid-column:1 / -1; }\n details { grid-column:1 / -1; font-size:0.88rem; }\n 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; }\n .empty { color:var(--muted); }\n .studio-action { border-top:1px solid var(--rule); padding:12px 0; }\n .studio-action:first-child { border-top:none; padding-top:0; }\n .studio-action h3 { font-size:1rem; margin:0 0 8px; font-weight:600; }\n .studio-ask, .studio-way { margin:0; }\n .studio-ways { list-style:none; margin:4px 0 0 9px; padding:0 0 0 14px; border-left:2px solid var(--rule); }\n .studio-ways > li { position:relative; padding:4px 0; }\n .studio-ways > li::before { content:''; position:absolute; left:-14px; top:15px; width:10px; border-top:2px solid var(--rule); }\n .studio-way, .studio-on { color:var(--muted); }\n .studio-on { margin:4px 0 0; }\n .studio-fold summary { cursor:pointer; color:var(--muted); }\n .studio-folded { margin:4px 0 0; padding-left:10px; border-left:2px dashed var(--rule); }\n .studio-outcome { display:grid; grid-template-columns:20px minmax(0, 1fr); align-items:center; gap:2px 8px; margin:2px 0 0; }\n .studio-said, .studio-ask, .studio-way, .studio-checks li { overflow-wrap:anywhere; }\n .studio-end { font-weight:600; }\n .studio-outcome[data-status=\"red\"] .studio-end { color:var(--bad); }\n .studio-outcome[data-status=\"green\"] .studio-end { color:var(--good); }\n .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); }\n .studio-checks li { min-width:0; }\n .studio-checks [data-verdict=\"fails\"] { color:var(--bad); font-weight:600; }\n .studio-checks [data-verdict=\"cannot say\"] { color:var(--warn); }\n .studio-unnamed, .studio-waiting { color:var(--faint); }\n .studio-stack { display:block; max-width:100%; height:auto; }\n .studio-band { fill:var(--page); }\n .studio-band[data-shade=\"1\"] { fill:#eef2f7; }\n .studio-section rect { fill:var(--paper); stroke:var(--faint); }\n .studio-canvas { fill:var(--paper); }\n .studio-section-name { fill:var(--ink); }\n .studio-section[data-named=\"false\"] .studio-section-name { fill:var(--faint); }\n .studio-section-does { fill:var(--muted); }\n .agent-layer { position:absolute; left:0; top:0; width:0; height:0; z-index:20; pointer-events:none; }\n .agent-ring { position:absolute; border-radius:10px; box-shadow:0 0 0 2px var(--agent), 0 0 0 8px var(--agentSoft); }\n .agent-bubble { position:absolute; pointer-events:auto; background:var(--paper); border:1px solid var(--agent); border-radius:4px 14px 14px 14px;\n padding:8px 30px 10px 12px; box-shadow:0 10px 28px rgba(15,23,42,0.18); font-size:0.94rem; }\n .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); }\n .agent-bubble[data-side=\"right\"] { border-radius:14px 14px 14px 14px; }\n .agent-bubble[data-side=\"right\"] .agent-tail { transform:rotate(-45deg); }\n .agent-who { margin:0 0 2px; font-size:0.72rem; font-weight:700; letter-spacing:0.06em; text-transform:uppercase; color:var(--agent); }\n .agent-who span { color:var(--muted); font-weight:600; }\n .agent-says { margin:0; overflow-wrap:anywhere; }\n .agent-close { position:absolute; top:4px; right:4px; background:none; color:var(--muted); padding:2px 8px; font-size:1rem; line-height:1; }\n .agent-in { animation:agent-in 280ms ease-out both; }\n @keyframes agent-in { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }\n @media (prefers-reduced-motion: reduce) { .agent-in { animation:none; } }\n @media (max-width:640px) { .props li { grid-template-columns:1fr; } }\n</style>\n</head>\n<body>\n<main>\n <header>\n <h1>Yichus studio<span id=\"project\"></span></h1>\n <p id=\"updated\">Waiting for your agent.</p>\n <p>Ask your agent what anything here means.</p>\n </header>\n <section aria-labelledby=\"h-asked\" data-section=\"asked\">\n <h2 id=\"h-asked\">${PAGE_HEADINGS.asked}</h2>\n <p class=\"label\">Your words</p>\n <p class=\"yours\" id=\"description\">Nothing yet. Tell your agent what you want to build.</p>\n </section>\n <section aria-labelledby=\"h-now\" data-section=\"now\">\n <h2 id=\"h-now\">${PAGE_HEADINGS.now}</h2>\n <div class=\"frame\"><span class=\"tag\">Yichus output</span>\n <p class=\"now\" id=\"summary\">No checks have run yet.</p>\n </div>\n </section>\n <section aria-labelledby=\"h-questions\" id=\"questions-section\" data-section=\"questions\" hidden>\n <h2 id=\"h-questions\">${PAGE_HEADINGS.questions}</h2>\n <p class=\"lede\">Your agent will ask you these too. Answer here or in the chat, whichever is easier.</p>\n <div class=\"frame\"><span class=\"tag\">Yichus output</span><div id=\"questions\"></div></div>\n </section>\n <section aria-labelledby=\"h-props\" data-section=\"props\">\n <h2 id=\"h-props\">${PAGE_HEADINGS.props}</h2>\n <div class=\"frame\"><span class=\"tag\">Yichus output</span><ul class=\"props\" id=\"props\"><li class=\"empty\">No properties chosen yet.</li></ul></div>\n </section>\n <section aria-labelledby=\"h-happens\" data-section=\"happens\">\n <h2 id=\"h-happens\">${PAGE_HEADINGS.happens}</h2>\n <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>\n <p class=\"label\">Drawn by Yichus. Words in italics are your agent's, not checked</p>\n <div class=\"frame\"><div id=\"happens\"><p class=\"empty\">This appears once the program compiles.</p></div></div>\n </section>\n <section aria-labelledby=\"h-sections\" data-section=\"sections\">\n <h2 id=\"h-sections\">${PAGE_HEADINGS.sections}</h2>\n <p class=\"lede\">The parts of your app, stacked: each layer is built only from the layers below it.</p>\n <p class=\"label\">Drawn by Yichus. Words in italics are your agent's, not checked</p>\n <div class=\"frame\"><div id=\"sections\"><p class=\"empty\">This appears once the program compiles.</p></div></div>\n </section>\n <section aria-labelledby=\"h-map\" data-section=\"map\">\n <h2 id=\"h-map\">${PAGE_HEADINGS.map}</h2>\n <div class=\"frame\"><div class=\"system-map\" id=\"map\"><p class=\"empty\">The map appears once the program compiles.</p></div></div>\n </section>\n</main>\n<script type=\"module\">\nimport { mount } from './system-map.js';\nimport { mountSections, mountWhatHappens, reportViewing, showMarks } from './studio-views.js';\n\nconst STATUS = ${JSON.stringify(PAGE_STATUS)};\nconst NO_ACTIONS = ${JSON.stringify(NO_ACTIONS)};\nconst el = (tag, props = {}, ...kids) => { const n = Object.assign(document.createElement(tag), props); n.append(...kids); return n; };\nlet mapHash = null, drawn = '';\n\nfunction questionCard(q, saved) {\n const card = el('div', { className: 'question' });\n card.dataset.question = q.id;\n card.append(el('p', { className: 'ask', textContent: q.ask }), el('p', { className: 'why', textContent: q.why }));\n const name = 'q-' + q.id;\n for (const c of q.choices) {\n const input = el('input', { type: 'radio', name, value: c.id, checked: saved?.choice === c.id });\n card.append(el('label', { className: 'choice' }, input, el('span', {}, c.label, el('small', { textContent: c.means }))));\n }\n const words = el('textarea', { placeholder: 'In your own words (optional)', value: saved?.words ?? '' });\n const status = el('span', { className: 'empty', textContent: saved ? ' Saved. Your agent will check it next.' : '' });\n const save = el('button', { type: 'button', textContent: 'Save answer' });\n save.addEventListener('click', async () => {\n const picked = card.querySelector('input[name=\"' + CSS.escape(name) + '\"]:checked');\n if (!picked) { status.textContent = ' Pick one of the choices first.'; return; }\n save.disabled = true;\n const label = q.choices.find(c => c.id === picked.value).label;\n const response = await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ question: q.id, choice: picked.value, words: words.value.trim() || label }) });\n const result = await response.json();\n status.textContent = result.ok ? ' Saved. Your agent will check it next.' : ' ' + result.error;\n save.disabled = false;\n });\n card.append(el('p', { className: 'label', textContent: 'Your words' }), words, save, status);\n return card;\n}\n\nfunction ruleRow(r) {\n const [words, tone] = STATUS[r.status];\n const li = el('li', {}, el('span', { textContent: 'A rule you gave: ' }, el('em', { textContent: r.rule })), el('span', { className: 'chip ' + tone, textContent: words }));\n li.append(el('span', { className: 'choice-said', textContent: 'Checked with ' + (r.laws === 1 ? '1 law' : r.laws + ' laws') + ' your agent wrote.' }));\n return li;\n}\n\nfunction propertyRow(p, saved) {\n const stale = saved && (!p.answer || p.answer.answeredAt !== saved.answeredAt);\n const [words, tone] = STATUS[stale ? 'pending' : p.status];\n const answer = stale ? saved : p.answer;\n const label = p.question.choices.find(c => c.id === answer.choice)?.label ?? answer.choice;\n const li = el('li', {}, el('span', { textContent: p.question.ask }), el('span', { className: 'chip ' + tone, textContent: words }));\n li.dataset.property = p.question.id;\n li.append(el('span', { className: 'choice-said', textContent: 'You chose: ' + label + (answer.words && answer.words !== label ? ' (\"' + answer.words + '\")' : '') }));\n return li;\n}\n\nasync function refresh() {\n const { state, requirements } = await (await fetch('/state')).json();\n const savedOf = id => requirements.answers.find(a => a.question === id);\n if (requirements.description) document.getElementById('description').textContent = requirements.description;\n if (!state) return;\n document.getElementById('project').textContent = ': ' + state.project;\n document.getElementById('updated').textContent = 'Last checked ' + new Date(state.updatedAt).toLocaleTimeString() + '.';\n document.getElementById('summary').textContent = state.summary;\n const open = state.properties.filter(p => p.status === 'unanswered' && !savedOf(p.question.id));\n document.getElementById('questions-section').hidden = !open.length;\n // Keep a half-written answer: only rebuild cards when the questions change.\n const qs = document.getElementById('questions');\n const ids = open.map(p => p.question.id).join(' ');\n if (qs.dataset.ids !== ids) { qs.dataset.ids = ids; qs.replaceChildren(...open.map(p => questionCard(p.question, savedOf(p.question.id)))); }\n const chosen = state.properties.filter(p => p.answer || savedOf(p.question.id));\n const rows = [...state.rules.map(ruleRow), ...chosen.map(p => propertyRow(p, savedOf(p.question.id)))];\n document.getElementById('props').replaceChildren(...(rows.length ? rows : [el('li', { className: 'empty', textContent: 'No properties chosen yet.' })]));\n // Redrawn only when the words or the program change.\n const views = JSON.stringify([state.hasActions, state.whatHappens, state.sections]);\n if (views !== drawn) {\n drawn = views;\n const happens = document.getElementById('happens');\n if (state.hasActions === false) happens.replaceChildren(el('p', { className: 'empty', textContent: NO_ACTIONS }));\n else if (state.whatHappens) mountWhatHappens(happens, state.whatHappens);\n else happens.replaceChildren(el('p', { className: 'empty', textContent: 'This appears once the program compiles.' }));\n if (state.sections) mountSections(document.getElementById('sections'), state.sections);\n }\n const map = document.getElementById('map');\n if (state.map && state.sourcesHash !== mapHash) { mapHash = state.sourcesHash; mount(map, state.map); }\n else if (!state.map && state.mapError) map.replaceChildren(el('p', { className: 'empty', textContent: 'The map could not be drawn: ' + state.mapError }));\n // Last, so each note is placed over the pictures as they are now drawn.\n showMarks(state.marks);\n viewing(state.drawing);\n}\n\n// What the person has in view goes to the studio, so their agent can follow\n// along when they say \"this one\".\nconst viewing = reportViewing(body => fetch('/viewing', { method: 'POST', headers: { 'content-type': 'application/json' }, body }));\n\nnew EventSource('/events').addEventListener('change', () => refresh());\nrefresh();\n</script>\n</body>\n</html>\n`;\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { ensureStudioDir, studioDir } from './requirements.js';\n\n// What the person has in view on the studio page, as the page last said:\n// the page's sections on screen, the drawn parts on screen, the questions\n// shown, the folds open, and the last thing the person clicked. The page\n// sends ids only, never words; page-view.ts says the words from the records\n// the page drew them from. Like the marks, this is the conversation's and\n// not the person's decisions, so .yichus/viewing.json is not committed. The\n// page server does not watch it, so a report never makes the page redraw.\n\n/** The page's sections, in the order the page shows them. */\nexport const PAGE_SECTIONS = ['asked', 'now', 'questions', 'props', 'happens', 'sections', 'map'] as const;\nexport type PageSection = (typeof PAGE_SECTIONS)[number];\n\nconst Id = z.string().min(1).max(200);\nconst Ids = z.array(Id).max(1000);\nconst Section = z.enum(PAGE_SECTIONS);\nconst Touched = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('section'), id: Section }).strict(),\n z.object({ kind: z.enum(['part', 'question', 'property']), id: Id }).strict(),\n]);\nconst Report = z.object({\n /** The page's tab is the one in front. */\n shown: z.boolean(),\n sections: z.array(Section).max(PAGE_SECTIONS.length),\n /** Anchors of the drawn parts on screen (person.ts). */\n parts: Ids,\n questions: Ids,\n /** Question ids of the properties shown. */\n properties: Ids,\n /** Anchors of the folds the person opened. */\n open: Ids,\n touched: Touched.nullable(),\n /** The drawing the anchors belong to (person.ts), or null before one is drawn. */\n drawing: z.string().max(64).nullable(),\n}).strict();\nexport type ViewingReport = z.infer<typeof Report>;\nconst Viewing = Report.extend({ schemaVersion: z.literal('yichus-viewing-1'), at: z.string() }).strict();\nexport type Viewing = z.infer<typeof Viewing>;\n\nconst viewingPath = (root: string) => path.join(studioDir(root), 'viewing.json');\n\nexport function loadViewing(root: string): Viewing | null {\n const file = viewingPath(root);\n if (!fs.existsSync(file)) return null;\n const parsed = Viewing.safeParse(JSON.parse(fs.readFileSync(file, 'utf8')));\n if (!parsed.success) throw new Error(`${file} is not a yichus-viewing-1 file: ${z.prettifyError(parsed.error)}`);\n return parsed.data;\n}\n\n/** The page's latest report replaces the one before. */\nexport function recordViewing(root: string, report: unknown, now: Date): { ok: true } | { ok: false; error: string } {\n const parsed = Report.safeParse(report);\n if (!parsed.success) return { ok: false, error: `The page's report is not one this studio reads. ${z.prettifyError(parsed.error)}` };\n ensureStudioDir(root);\n // Written beside it and renamed over it, so a reader never sees half a report.\n const file = viewingPath(root), written = `${file}.${process.pid}.tmp`;\n fs.writeFileSync(written, `${JSON.stringify(Viewing.parse({ schemaVersion: 'yichus-viewing-1', at: now.toISOString(), ...parsed.data }), null, 2)}\\n`);\n fs.renameSync(written, file);\n return { ok: true };\n}\n","import { ownPackages, readState } from './director.js';\nimport { loadMarks } from './marks.js';\nimport { NO_ACTIONS, PAGE_HEADINGS, PAGE_STATUS } from './page.js';\nimport { type Phrase, type Section, type Step, personDiagrams } from './person.js';\nimport { loadRequirements } from './requirements.js';\nimport { type Viewing, loadViewing } from './viewing.js';\nimport type { Say } from './surface.js';\nimport { nameableParts } from '../../../../web/system-map-names.js';\n\n// The studio page in words, for the agent driving the conversation: what the\n// page shows the person now, from the same records the page draws, and what\n// the person has in view. Everything here is computed; words in quotes are\n// the ones the agent or the person gave. Each part the agent can point at\n// carries, in brackets, the id yichus_point takes.\n\nconst quoted = (words: string | null, missing: string) => words === null ? missing : `\"${words}\"`;\nconst say = (phrase: Phrase) => phrase.map(p => typeof p === 'string' ? p : `\"${p.theirs}\"`).join('');\nconst TICK = { holds: '✓', fails: '✗', 'cannot say': '?' } as const;\nconst ENDING = {\n grey: 'no expectation is false here', red: 'something expected is false here', green: 'an ending that was broken is fixed', unchecked: 'the check cannot say',\n} as const;\n\n/** Seconds, minutes or hours, said plainly. */\nfunction ago(from: string, now: Date): string {\n const seconds = Math.max(0, Math.round((now.getTime() - Date.parse(from)) / 1000));\n const [n, unit] = seconds < 120 ? [seconds, 'second'] : seconds < 7200 ? [Math.round(seconds / 60), 'minute'] : [Math.round(seconds / 3600), 'hour'];\n return `${n} ${unit}${n === 1 ? '' : 's'} ago`;\n}\n\nexport function pageText(root: string, pageUrl: string | null, now: Date, surface: Say): string {\n const state = readState(root);\n const { description, answers, names = {} } = loadRequirements(root);\n const marks = loadMarks(root);\n const { sections, whatHappens, anchors, drawing } = state ? personDiagrams(state, names) : { sections: null, whatHappens: null, anchors: new Map<string, string>(), drawing: null };\n const codeAt = new Map([...anchors].map(([code, anchor]) => [anchor, code]));\n // What each part the agent can point at says, for the lines about what is in view.\n const said = new Map<string, string>();\n const part = (anchor: string, words: string) => { said.set(codeAt.get(anchor)!, words); return `[${codeAt.get(anchor)}]`; };\n\n const out: string[] = [`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.`];\n const heading = (key: keyof typeof PAGE_HEADINGS) => out.push('', `## ${PAGE_HEADINGS[key]}`);\n // Filled in last, once every part has its words.\n out.push('', '## What the person has in view');\n const inView = out.length;\n\n heading('asked');\n out.push(description ? `\"${description}\"` : 'Nothing yet.');\n heading('now');\n out.push(state ? state.step.summary : 'No checks have run yet.');\n\n const savedOf = (id: string) => answers.find(a => a.question === id);\n const open = (state?.properties ?? []).filter(p => p.status === 'unanswered' && !savedOf(p.question.id));\n if (open.length) {\n heading('questions');\n for (const { question: q } of open) out.push(`question ${q.id}: ${q.ask}`, ...q.choices.map(c => ` - ${c.label}: ${c.means}`));\n }\n heading('props');\n const chosen = (state?.properties ?? []).filter(p => p.answer || savedOf(p.question.id));\n const rules = state?.rules ?? [];\n if (!chosen.length && !rules.length) out.push('No properties chosen yet.');\n 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.`);\n for (const p of chosen) {\n const saved = savedOf(p.question.id);\n const stale = saved && (!p.answer || p.answer.answeredAt !== saved.answeredAt);\n const answer = stale ? saved : p.answer!;\n const label = p.question.choices.find(c => c.id === answer.choice)?.label ?? answer.choice;\n out.push(`question ${p.question.id}: ${p.question.ask} Status: ${PAGE_STATUS[stale ? 'pending' : p.status][0]}. They chose ${label}${answer.words && answer.words !== label ? ` (\"${answer.words}\")` : ''}.`);\n }\n\n heading('happens');\n const step = (s: Step, pad: string): string[] => {\n if (s.kind === 'outcome') {\n const end = `${s.refused ? 'turned away' : 'answered'}${s.words ? ` \"${s.words}\"` : ''}`;\n return [`${pad}${part(s.anchor, end)} ${end}: ${ENDING[s.status]}`, ...s.checks.map(c => `${pad} ${TICK[c.verdict]} ${say(c.says)}`)];\n }\n const asks = quoted(s.words, 'a check not described yet');\n return [`${pad}${part(s.anchor, asks)} checks ${asks}`, ...s.ways.flatMap(w => {\n const words = quoted(w.words, 'a way not described yet');\n return [`${pad} way ${words}${w.anchor === w.then.anchor ? '' : ` ${part(w.anchor, words)}`}:`, ...step(w.then, `${pad} `)];\n })];\n };\n if (state?.hasActions === false) out.push(NO_ACTIONS);\n else if (!whatHappens) out.push(state?.whatHappensError ? `It could not be drawn: ${state.whatHappensError}` : 'This appears once the program compiles.');\n else {\n if (!whatHappens.actions.length && !whatHappens.waiting) out.push('The app has no actions yet.');\n for (const a of whatHappens.actions) {\n const title = quoted(a.title, 'an action not described yet');\n out.push(`${part(a.anchor, title)} ${title}`, ...(a.first ? step(a.first, ' ') : [' This action could not be followed.']));\n }\n if (whatHappens.waiting) out.push(`${whatHappens.waiting} more ${whatHappens.waiting === 1 ? 'action is' : 'actions are'} not described yet.`);\n }\n\n heading('sections');\n const records = (verb: string, names: Array<string | null>) => names.length ? [`${verb} ${names.map(n => quoted(n, 'a kind of record not named yet')).join(', ')}`] : [];\n const does = (s: Section) => [...records('changes', s.changes), ...records('looks at', s.looks)].join(' · ') || 'keeps no records itself';\n if (!sections) out.push('This appears once the program compiles.');\n else sections.forEach((layer, i) => {\n out.push(`layer ${i + 1} of ${sections.length}${i === 0 ? ', the top' : ''}:`);\n for (const s of layer) {\n const name = quoted(s.name, 'a part not named yet');\n out.push(` ${part(s.anchor, name)} ${name}: ${does(s)}`);\n }\n });\n\n heading('map');\n if (state?.map) {\n const parts = nameableParts(state.map, ownPackages(state.layers));\n const unnamed = parts.filter(p => !(p.code in names)).length;\n 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.`);\n } else out.push(state?.mapError ? `The map could not be drawn: ${state.mapError}` : 'The map appears once the program compiles.');\n\n out.push('', '## Your notes on the page');\n // A report about another drawing says nothing about which part is which.\n const report = loadViewing(root);\n const viewing = report && { ...report, current: report.drawing === drawing };\n const visible = new Set(!viewing?.current ? [] : viewing.parts.flatMap(a => codeAt.has(a) ? [codeAt.get(a)!] : []));\n const notes = marks?.marks.filter(m => anchors.has(m.at)) ?? [];\n if (!notes.length) out.push(`None. ${surface.name('yichus_point')} puts a note over a part of the page.`);\n else out.push(`Said ${ago(marks!.said, now)}:`, ...notes.map(m => ` [${m.at}] \"${m.note}\"${visible.has(m.at) ? ' (on screen)' : ''}`));\n\n out.splice(inView, 0, ...inViewLines(viewing, codeAt, said, now, pageUrl));\n return `${out.join('\\n')}\\n`;\n}\n\nfunction inViewLines(viewing: (Viewing & { current: boolean }) | null, codeAt: Map<string, string>, said: Map<string, string>, now: Date, pageUrl: string | null): string[] {\n 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.'}`];\n const parts = (anchors: string[]) => !viewing.current ? [] : anchors.flatMap(a => codeAt.has(a) ? [`[${codeAt.get(a)}] ${said.get(codeAt.get(a)!)}`] : []);\n const list = (what: string, items: string[]) => items.length ? [`${what}:`, ...items.map(i => ` ${i}`)] : [];\n const { touched } = viewing;\n const clicked = !touched ? [] : touched.kind === 'section' ? [`Last clicked: in ${PAGE_HEADINGS[touched.id]}.`]\n : touched.kind === 'question' ? [`Last clicked: question ${touched.id}.`] : touched.kind === 'property' ? [`Last clicked: the property of question ${touched.id}.`]\n : parts([touched.id]).map(p => `Last clicked: ${p}`);\n return [\n `The page said this ${ago(viewing.at, now)}. ${viewing.shown ? 'Its tab is in front.' : 'Its tab is behind another one.'}`,\n `On screen: ${viewing.sections.map(s => PAGE_HEADINGS[s]).join(', ') || 'nothing of the page'}.`,\n ...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.'],\n ...list('Parts on screen', parts(viewing.parts)),\n ...list('Questions on screen', viewing.questions.map(q => `question ${q}`)),\n ...list('Properties on screen', viewing.properties.map(q => `question ${q}`)),\n ...list('Folds the person opened', parts(viewing.open)),\n ...clicked,\n ];\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport REFERENCE from './reference.json' with { type: 'json' };\n\n// Reference material the agent needs and cannot be expected to fetch: how\n// to guide the person, porting, deploying, laws, step programs and protocol\n// cases, each with worked files. The build copies each file next to the CLI\n// (scripts/copy-studio-assets.mjs) from the repository path reference.json\n// names. A file that names sections is given from those sections only: the\n// rest of it is about the Yichus repository, which the agent does not have.\nexport { REFERENCE };\nexport type Topic = keyof typeof REFERENCE;\nexport const TOPICS = Object.keys(REFERENCE) as Topic[];\ninterface File { name: string; from: string; sections?: string[] }\n\nexport const BUILT_REFERENCE = fileURLToPath(new URL('./studio-reference/', import.meta.url));\nexport const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url));\n\n/** Where a reference file is: the built copy, or the repository source. */\nexport type Locate = (file: { name: string; from: string }) => string;\nexport const builtCopy: Locate = file => path.join(BUILT_REFERENCE, file.name);\nexport const repoSource: Locate = file => path.join(REPO_ROOT, file.from);\n\n/** The parts of a Markdown file under the named headings, each up to the\n * next heading of the same or a higher level; the file's title gives the\n * text before its first section. */\nexport function sectionsOf(text: string, titles: string[]): string {\n const lines = text.split('\\n');\n // A line in a fenced code block is never a heading, whatever it starts with.\n let fenced = false;\n const headings = lines.map(line => {\n if (line.startsWith('```')) fenced = !fenced;\n const match = fenced ? null : /^(#+) (.*)$/.exec(line);\n return match ? { level: match[1]!.length, title: match[2]! } : null;\n });\n const parts = titles.map(title => {\n const start = headings.findIndex(h => h?.title === title);\n if (start < 0) throw new Error(`No section \"${title}\" in the reference file`);\n const level = Math.max(headings[start]!.level, 2);\n const end = headings.findIndex((h, i) => i > start && h !== null && h.level <= level);\n return lines.slice(start, end < 0 ? undefined : end).join('\\n').trim();\n });\n return `${parts.join('\\n\\n')}\\n`;\n}\n\n/** Every topic with what it is about, for an agent that has not picked one. */\nexport const topicList = (ask: (topic: string) => string) =>\n ['Reference topics:', ...TOPICS.map(topic => ` ${topic}: ${REFERENCE[topic].about} (${ask(topic)})`)].join('\\n');\n\nexport function readReference(topic: string, locate: Locate): string | null {\n if (!(TOPICS as string[]).includes(topic)) return null;\n return (REFERENCE[topic as Topic].files as File[]).map(file => {\n const text = fs.readFileSync(locate(file), 'utf8');\n return `===== ${file.name} =====\\n${file.sections ? sectionsOf(text, file.sections) : text}`;\n }).join('\\n\\n');\n}\n","{\n \"guiding\": {\n \"about\": \"How to guide the person through the studio page: what each part shows and when to bring it up.\",\n \"files\": [\n { \"name\": \"the-page.md\", \"from\": \"docs/studio/the-page.md\" }\n ]\n },\n \"porting\": {\n \"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.\",\n \"files\": [\n { \"name\": \"porting.md\", \"from\": \"docs/studio/porting.md\" },\n { \"name\": \"worker-authority.md\", \"from\": \"docs/runtime/worker-authority.md\", \"sections\": [\"Worker authority in generated APIs\", \"Secret bootstrap\"] }\n ]\n },\n \"deploy\": {\n \"about\": \"What to build for each place the app can run, with a working server, store and Render Blueprint to start from.\",\n \"files\": [\n { \"name\": \"deploy-platforms.md\", \"from\": \"docs/studio/deploy-platforms.md\" },\n { \"name\": \"server.mjs\", \"from\": \"docs/studio/deploy-example/server.mjs\" },\n { \"name\": \"store.mjs\", \"from\": \"docs/studio/deploy-example/store.mjs\" },\n { \"name\": \"render.yaml\", \"from\": \"docs/studio/deploy-example/render.yaml\" }\n ]\n },\n \"laws\": {\n \"about\": \"Writing a rule the person stated as a law the studio checks, and the standard functions the language has.\",\n \"files\": [\n { \"name\": \"laws.md\", \"from\": \"docs/studio/laws.md\" },\n { \"name\": \"consent.bosatsu\", \"from\": \"docs/studio/laws-example/consent.bosatsu\" },\n { \"name\": \"consent-laws.bosatsu\", \"from\": \"docs/studio/laws-example/consent-laws.bosatsu\" },\n { \"name\": \"balance.bosatsu\", \"from\": \"docs/studio/laws-example/limits/balance.bosatsu\" },\n { \"name\": \"balance-listed-laws.bosatsu\", \"from\": \"docs/studio/laws-example/limits/balance-listed-laws.bosatsu\" }\n ]\n },\n \"portable-programs\": {\n \"about\": \"Work that takes several steps or waits on an outside service, written as one pure step program a rule-free engine drives.\",\n \"files\": [\n { \"name\": \"portable-programs.md\", \"from\": \"docs/studio/portable-programs.md\" },\n { \"name\": \"refund-policy.bosatsu\", \"from\": \"demos/portable/refund-policy.bosatsu\" },\n { \"name\": \"refund-desk.bosatsu\", \"from\": \"demos/portable/refund-desk.bosatsu\" },\n { \"name\": \"refund-test.bosatsu\", \"from\": \"demos/portable/refund-test.bosatsu\" },\n { \"name\": \"refund-desk-one-round.bosatsu\", \"from\": \"demos/portable/limits/refund-desk-one-round.bosatsu\" }\n ]\n },\n \"protocol-case\": {\n \"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.\",\n \"files\": [\n { \"name\": \"protocol-cases.md\", \"from\": \"docs/studio/protocol-cases.md\" },\n { \"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\"] },\n { \"name\": \"withdrawal-case.json\", \"from\": \"eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/case.json\" },\n { \"name\": \"withdrawal.bosatsu\", \"from\": \"eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/ledger.bosatsu\" }\n ]\n },\n \"calculator\": {\n \"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.\",\n \"files\": [\n { \"name\": \"calculator.md\", \"from\": \"docs/studio/calculator.md\" }\n ]\n }\n}\n","import type { Status, StudioState } from './director.js';\n\n// The director's step in words, for an agent reading a tool result or a\n// terminal. The same state drives the page.\n\nexport const STATUS_WORDS: Record<Status, string> = {\n unanswered: 'not answered yet',\n decided: 'decided',\n assumed: 'holds under an assumption',\n proven: 'proven',\n bounded: 'holds in every scenario checked',\n broken: 'broken',\n mismatch: 'declared differently from the answer',\n 'needs-case': 'needs a failure scenario',\n 'needs-law': 'needs a law that checks it',\n unused: 'checked, but no action of the app uses what the law checks',\n inconclusive: 'not decided by the check',\n 'no-check': 'no check needed',\n};\n\nexport function stepText(state: StudioState, pageUrl: string | null): string {\n const { step } = state;\n const lines = [`Stage: ${step.stage}. ${step.summary}`, '', 'Do this:', ...step.instructions.map((s, i) => `${i + 1}. ${s}`)];\n if (step.items) lines.push('', `${step.items.heading}:`, ...step.items.lines.map(l => ` ${l}`));\n for (const q of step.ask ?? []) {\n lines.push('', `Question ${q.id}: ${q.ask}`, ` Why it matters: ${q.why}`);\n for (const c of q.choices) lines.push(` - ${c.id}: ${c.label}. ${c.means}`);\n }\n if (step.evidence?.length) lines.push('', 'Evidence (engine output):', ...step.evidence.map(e => ` ${e}`));\n const answered = state.properties.filter(p => p.status !== 'unanswered');\n if (answered.length) {\n lines.push('', 'Properties:');\n for (const p of answered) {\n const choice = p.question.choices.find(c => c.id === p.answer?.choice)?.label ?? p.answer?.choice;\n lines.push(` ${p.question.id} (${choice}): ${STATUS_WORDS[p.status]}`);\n }\n }\n if (state.rules.length) {\n lines.push('', 'Rules the person stated:');\n for (const r of state.rules) lines.push(` \"${r.rule}\" (${r.laws.join(', ')}): ${STATUS_WORDS[r.status]}`);\n }\n if (pageUrl) lines.push('', `Studio page: ${pageUrl}`);\n return `${lines.join('\\n')}\\n`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { ensureStudioDir, studioDir } from './requirements.js';\n\n// Where the running studio pages are, so the terminal commands can hand the\n// person a link. Each page server writes its own file in .yichus/pages/\n// when it starts and removes only that file when it stops, so a second page\n// for the folder stopping never hides one still running. A file whose server\n// died without removing it names a process that no longer runs: it is never\n// read as a link, and the next command to look removes it. A server that\n// starts also removes any other file for its own port, since it holds that\n// port now, so a dead server's file is gone even when its process id has\n// been reused.\n\nconst PageLink = z.object({ schemaVersion: z.literal('yichus-page-2'), url: z.string().url(), pid: z.number().int().positive(),\n startedAt: z.number().int().nonnegative() }).strict();\ntype PageLink = z.infer<typeof PageLink>;\n\nconst pagesDir = (root: string) => path.join(studioDir(root), 'pages');\n// One server per process and port: two servers never listen on one port.\nconst linkPath = (root: string, url: string, pid: number) => path.join(pagesDir(root), `${pid}-${new URL(url).port}.json`);\n\nexport function writePageLink(root: string, url: string, pid: number = process.pid, startedAt: number = Date.now()): void {\n ensureStudioDir(root);\n fs.mkdirSync(pagesDir(root), { recursive: true });\n // The one link file studios before .yichus/pages/ kept.\n fs.rmSync(path.join(studioDir(root), 'page.json'), { force: true });\n const port = new URL(url).port;\n for (const { file, link } of liveLinks(root)) if (new URL(link.url).port === port) fs.rmSync(file, { force: true });\n const file = linkPath(root, url, pid), written = `${file}.tmp`;\n fs.writeFileSync(written, `${JSON.stringify(PageLink.parse({ schemaVersion: 'yichus-page-2', url, pid, startedAt }), null, 2)}\\n`);\n fs.renameSync(written, file);\n}\n\n/** Remove the link of the page this process serves at `url`; every other page's stays. */\nexport function clearPageLink(root: string, url: string, pid: number = process.pid): void {\n fs.rmSync(linkPath(root, url, pid), { force: true });\n}\n\nconst running = (pid: number): boolean => {\n try { process.kill(pid, 0); return true; } catch (error) {\n // EPERM: the process runs, under another user.\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n};\n\n/** The links whose server still runs; the files of the others are removed. */\nfunction liveLinks(root: string): Array<{ file: string; link: PageLink }> {\n const dir = pagesDir(root);\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir).filter(name => name.endsWith('.json')).flatMap(name => {\n const file = path.join(dir, name);\n // A file cut short or edited by hand names no page; it never stops a command.\n let raw: unknown;\n try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { raw = null; }\n const parsed = PageLink.safeParse(raw);\n if (parsed.success && running(parsed.data.pid)) return [{ file, link: parsed.data }];\n fs.rmSync(file, { force: true });\n return [];\n });\n}\n\n/** The link of the studio page serving this folder now, the newest when several do. */\nexport function runningPageUrl(root: string): string | null {\n const live = liveLinks(root).map(({ link }) => link);\n return live.length ? live.reduce((a, b) => b.startedAt > a.startedAt ? b : a).url : null;\n}\n","import { once } from 'node:events';\nimport type { Readable, Writable } from 'node:stream';\nimport { fileURLToPath } from 'node:url';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { type ApiEngine, EngineWorkerClient, catalogTools } from '@yichus/api-mcp';\nimport type { StudioEngine } from './director.js';\nimport { createStudioMcpServer } from './mcp.js';\nimport { clearPageLink, writePageLink } from './page-link.js';\nimport { startPageServer } from './page-server.js';\n\nconst objectResult = (raw: string, tool: string): Record<string, unknown> => {\n const value: unknown = JSON.parse(raw);\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${tool} returned no JSON object`);\n return value as Record<string, unknown>;\n};\n\n/** The in-process engine, for one-shot commands. */\nexport const inProcessEngine = (engine: ApiEngine): StudioEngine => ({\n async call(tool, args) { return objectResult(engine.callTool(tool, JSON.stringify(args)), tool); },\n});\n\n/** The engine in a worker process: a long check never stalls the page or\n * the MCP stream, and a timed-out check is killed rather than left running.\n * A large program's report can take minutes, so the deadline is generous. */\nexport function workerEngine(bundle: string): StudioEngine & { catalog(): Promise<Tool[]>; close(): Promise<void> } {\n const worker = new EngineWorkerClient(bundle, 900_000);\n let id = 0;\n return {\n async call(tool, args) { return objectResult(await worker.callTool(tool, JSON.stringify(args), `studio-${++id}`), tool); },\n async catalog() { return catalogTools(await worker.listTools(`studio-${++id}`)); },\n close: () => worker.close(),\n };\n}\n\n// The page assets are copied next to the built CLI (scripts/copy-studio-assets.mjs).\nexport const BUILT_ASSETS = fileURLToPath(new URL('./studio-page/', import.meta.url));\n\nexport interface ServeOptions {\n root: string;\n /** null: the first free studio port. */\n port: number | null;\n pageOnly: boolean;\n bundle: string;\n stderr(text: string): void;\n assetsDir?: string;\n stdin?: Readable;\n stdout?: Writable;\n /** Page-only mode runs until this settles (default: Ctrl-C or a stop signal). */\n stopped?: Promise<unknown>;\n}\n\nexport async function serveStudio(options: ServeOptions): Promise<void> {\n const started = await startPageServer(options.root, options.assetsDir ?? BUILT_ASSETS, options.port);\n // The terminal commands read the link from the project folder.\n writePageLink(options.root, started.url);\n const page = { url: started.url, async close() { clearPageLink(options.root, started.url); await started.close(); } };\n options.stderr(`Yichus studio page: ${page.url}\\n`);\n if (options.pageOnly) {\n await (options.stopped ?? Promise.race([once(process, 'SIGINT'), once(process, 'SIGTERM')]));\n await page.close();\n return;\n }\n const engine = workerEngine(options.bundle);\n const { server, idle } = createStudioMcpServer({ root: options.root, engine, pageUrl: page.url, catalog: engine.catalog });\n const stdin = options.stdin ?? process.stdin;\n const closed = once(stdin, 'end');\n try {\n await server.connect(new StdioServerTransport(stdin, options.stdout ?? process.stdout));\n await closed;\n await idle();\n } finally {\n await server.close();\n await engine.close();\n await page.close();\n }\n}\n","import fs from 'node:fs';\nimport http from 'node:http';\nimport path from 'node:path';\nimport type { AddressInfo } from 'node:net';\nimport { type StudioState, readState } from './director.js';\nimport { recordAnswer } from './mcp.js';\nimport { STUDIO_PAGE } from './page.js';\nimport { relabelSystemMap } from '../../../../web/system-map-names.js';\nimport ASSETS from './page-assets.json' with { type: 'json' };\nimport { type Marks, loadMarks } from './marks.js';\nimport { personDiagrams } from './person.js';\nimport { ensureStudioDir, loadRequirements, studioDir } from './requirements.js';\nimport { recordViewing } from './viewing.js';\n\n// The page the person keeps open. It serves the latest .yichus/state.json,\n// requirements.json and marks.json, pushes a change event whenever one changes\n// (whoever ran the director: the MCP studio or `yichus next`), and takes the\n// person's answers and what they have in view (viewing.ts). It listens on loopback only and refuses requests from\n// any other origin or host name.\n\n/** The site's modules the page draws with; the build copies them next to the CLI. */\nexport const PAGE_ASSETS: readonly string[] = ASSETS;\n\n/** What the page may show: the person's own words, the questions, statuses\n * the map under the person's names, and the sections and what happens in\n * each action in the person's words only. Evidence, check names, file names\n * and the agent's instructions stay with the agent. What the agent points\n * at comes as anchors into those diagrams, each with the agent's note. */\nexport function personView(state: StudioState | null, names: Record<string, string>, marks: Marks | null = null) {\n if (!state) return null;\n const { sections, whatHappens, anchors, drawing } = personDiagrams(state, names);\n return {\n project: state.project,\n updatedAt: state.updatedAt,\n sourcesHash: state.sourcesHash,\n summary: state.step.summary,\n properties: state.properties.map(p => ({\n question: { id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices },\n answer: p.answer,\n status: p.status,\n })),\n // A state written before rules were kept has none.\n rules: (state.rules ?? []).map(r => ({ rule: r.rule, status: r.status, laws: r.laws.length })),\n map: state.map ? relabelSystemMap(state.map, names) : null,\n mapError: state.mapError,\n sections,\n // A state written before this field says nothing either way.\n hasActions: state.hasActions ?? null,\n whatHappens,\n // Sent back with what the person has in view, so a report about an\n // older drawing is not read against this one.\n drawing,\n // A mark on a part the page no longer draws is left out.\n marks: marks && { said: marks.said, marks: marks.marks.flatMap(m => anchors.has(m.at) ? [{ anchor: anchors.get(m.at)!, note: m.note }] : []) },\n };\n}\n\n// The names come from requirements.json, so a name shows as soon as the\n// agent records it.\nfunction stateBody(root: string) {\n const { description, answers, names } = loadRequirements(root);\n return { state: personView(readState(root), names ?? {}, loadMarks(root)), requirements: { description, answers } };\n}\n\nexport interface PageServer { url: string; close(): Promise<void> }\n\n/** Ports tried in order when none is asked for, so the page keeps its address\n * when the agent restarts the studio. A random port is the last resort. */\nexport const STUDIO_PORTS = [4317, 4318, 4319, 4320, 4321, 0];\n\nexport async function startPageServer(root: string, assetsDir: string, port: number | null = null, now = () => new Date()): Promise<PageServer> {\n ensureStudioDir(root);\n const clients = new Set<http.ServerResponse>();\n // Polled rather than fs.watch: macOS FSEvents can miss a write made just\n // after the watch starts, and polling also works on network folders.\n const watched = ['state.json', 'requirements.json', 'marks.json'].map(name => path.join(studioDir(root), name));\n const changed = (now: fs.Stats, before: fs.Stats) => {\n if (now.mtimeMs !== before.mtimeMs || now.size !== before.size) for (const res of clients) res.write('event: change\\ndata: {}\\n\\n');\n };\n for (const file of watched) fs.watchFile(file, { interval: 250 }, changed);\n const hosts = new Set<string>();\n const takes = new Map<string, (args: unknown) => { ok: boolean }>([\n ['/answer', args => recordAnswer(root, args, now())],\n ['/viewing', args => recordViewing(root, args, now())],\n ]);\n const server = http.createServer((req, res) => {\n const send = (status: number, type: string, body: string) => {\n res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });\n res.end(body);\n };\n // A page on another site, or a host name rebound to 127.0.0.1, is refused.\n const host = req.headers.host ?? '';\n if (!hosts.has(host) || (req.headers.origin && req.headers.origin !== `http://${host}`)) {\n send(403, 'text/plain', 'This studio only answers its own page.');\n return;\n }\n const url = new URL(req.url ?? '/', `http://${host}`);\n if (req.method === 'GET' && url.pathname === '/') return send(200, 'text/html; charset=utf-8', STUDIO_PAGE);\n if (req.method === 'GET' && url.pathname === '/state') {\n return send(200, 'application/json', JSON.stringify(stateBody(root)));\n }\n if (req.method === 'GET' && url.pathname === '/events') {\n res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });\n res.write(': connected\\n\\n');\n clients.add(res);\n req.on('close', () => clients.delete(res));\n return;\n }\n const asset = PAGE_ASSETS.find(a => url.pathname === `/${a}`);\n if (req.method === 'GET' && asset) {\n return send(200, asset.endsWith('.css') ? 'text/css' : 'text/javascript', fs.readFileSync(path.join(assetsDir, asset), 'utf8'));\n }\n // The person's answer, and what they have in view, as JSON.\n const take = req.method === 'POST' ? takes.get(url.pathname) : undefined;\n if (take) {\n if (req.headers['content-type'] !== 'application/json') return send(415, 'text/plain', 'Send JSON.');\n let body = '';\n req.setEncoding('utf8');\n req.on('data', chunk => { body += chunk; if (body.length > 65536) req.destroy(); });\n req.on('end', () => {\n let args: unknown;\n try { args = JSON.parse(body); } catch { return send(400, 'application/json', JSON.stringify({ ok: false, error: 'The request is not JSON.' })); }\n const result = take(args);\n send(result.ok ? 200 : 400, 'application/json', JSON.stringify(result));\n });\n return;\n }\n send(404, 'text/plain', 'Not found.');\n });\n for (const candidate of port === null ? STUDIO_PORTS : [port]) {\n const error = await new Promise<NodeJS.ErrnoException | null>(resolve => {\n server.once('error', resolve);\n server.listen(candidate, '127.0.0.1', () => { server.off('error', resolve); resolve(null); });\n });\n if (!error) break;\n if (error.code !== 'EADDRINUSE' || candidate === port) throw error;\n }\n const bound = (server.address() as AddressInfo).port;\n hosts.add(`127.0.0.1:${bound}`).add(`localhost:${bound}`);\n return {\n url: `http://127.0.0.1:${bound}/`,\n async close() {\n for (const file of watched) fs.unwatchFile(file, changed);\n // Stop taking connections, then drop every open one: an open page\n // reconnects over its keep-alive socket, which would hold close() open.\n const closed = new Promise<void>(resolve => server.close(() => resolve()));\n server.closeAllConnections();\n await closed;\n },\n };\n}\n","[\"system-map.js\", \"label-fit.js\", \"system-map-record.js\", \"system-map.css\", \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AAY,EAAE,GAAG,SAAS,QAAQ,cAAc,GAAG,QAAQ,CAACC,UAAS,QAAQ,OAAO,MAAMA,KAAI,EAAE,CAAC;AAAA,EACnH,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EAC3C,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EAC3C,KAAK,MAAM,oBAAI,KAAK;AAAA,EACpB,QAAQ;AACV,CAAC,IACC,MAAM,OAAO,MAAM;AAAA,EACnB,MAAM,WAAW,QAAQ;AACvB,WAAO,cAAc,cAAc,MAAM,CAAC;AAAA,EAC5C;AAAA,EACA,MAAM,cAAc,QAAQ,MAAM,SAAS,WAAW;AACpD,WAAO,qBAAqB,cAAc,MAAM,GAAG,MAAM,SAAS,SAAS;AAAA,EAC7E;AAAA;AAAA;AAAA,EAGA,WAAW,MAAMA,MAAK,QAAQ,KAAK;AAAA,EACnC,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EAC3C,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAC7C,CAAC;","names":["text","fs","path","parseArgs","z","text","said","reason","errors","lines","topology","shown","z","indent","EngineError","checker","plural","said","fs","path","fs","path","z","walk","theirs","text","VOCABULARY","bare","path","bare","leaves","VOCABULARY","bare","walk","z","fs","path","z","z","z","Entry","walk","z","path","fs","reach","said","plural","say","title","z","fs","path","z","createHash","z","z","Property","Claim","Leaf","Tree","said","createHash","z","path","fs","fs","path","z","z","Report","path","fs","said","label","title","names","fs","path","path","text","title","fs","z","say","catalogTools","result","said","topology","fs","path","z","z","path","fs","file","argv","path","fs","said","label","z","argv","parseArgs","named","path","fs","said","text","fileURLToPath","fs","path","path","now","fs","fileURLToPath","text"]}
1
+ {"version":3,"sources":["../src/main.ts","../src/run.ts","../src/engine-results.ts","../src/verdict.ts","../src/lean-verdict.ts","../src/call-summary.ts","../src/studio/command.ts","../src/studio/director.ts","../../../web/system-map-record.js","../../../web/system-map-names.js","../../../web/what-happens-record.js","../src/studio/project.ts","../src/studio/questions.ts","../src/studio/requirements.ts","../src/studio/scenarios.ts","../src/studio/surface.ts","../src/studio/mcp.ts","../src/studio/marks.ts","../src/studio/person.ts","../../../web/layer-groups.js","../src/studio/page.ts","../src/studio/viewing.ts","../src/studio/page-view.ts","../src/studio/reference.ts","../src/studio/reference.json","../src/studio/text.ts","../src/studio/page-link.ts","../src/studio/serve.ts","../src/studio/page-server.ts","../src/studio/page-assets.json"],"sourcesContent":["import { text } from 'node:stream/consumers';\nimport { checkLeanWasmSources, findApiMcpBundle, loadApiEngine } from '@yichus/api-mcp';\nimport { runCli } from './run.js';\nimport { STUDIO_COMMANDS, runStudioCommand } from './studio/command.js';\nimport { builtCopy } from './studio/reference.js';\nimport { inProcessEngine, serveStudio } from './studio/serve.js';\n\nconst bundleOrThrow = (bundle?: string): string => {\n const resolved = bundle ?? findApiMcpBundle();\n if (!resolved) throw new Error('Yichus engine bundle missing. Reinstall @yichus/api-mcp or pass --bundle.');\n return resolved;\n};\n\nconst argv = process.argv.slice(2);\nprocess.exitCode = STUDIO_COMMANDS.has(argv[0] ?? '')\n ? await runStudioCommand(argv, {\n engine: async () => inProcessEngine(await loadApiEngine(bundleOrThrow())),\n serve: options => serveStudio({ ...options, bundle: bundleOrThrow(), stderr: (text) => process.stderr.write(text) }),\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n now: () => new Date(),\n locate: builtCopy,\n })\n : await runCli(argv, {\n async loadEngine(bundle) {\n return loadApiEngine(bundleOrThrow(bundle));\n },\n async checkLeanWasm(bundle, root, sources, timeoutMs) {\n return checkLeanWasmSources(bundleOrThrow(bundle), root, sources, timeoutMs);\n },\n // A stream, not readFileSync(0): a pipe the parent has not written yet\n // fails a synchronous read with EAGAIN on macOS.\n readStdin: () => text(process.stdin),\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n });\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { isDeepStrictEqual, parseArgs } from 'node:util';\nimport type { ApiEngine } from '@yichus/api-mcp';\nimport { z } from 'zod';\nimport { verifySummary } from './verdict.js';\nimport { leanSummary } from './lean-verdict.js';\nimport { callFailure, callProgress, callSummary } from './call-summary.js';\nimport { EngineError } from './engine-results.js';\nimport { STUDIO_HELP } from './studio/command.js';\nimport { projectSources } from './studio/project.js';\n\nexport interface CliIo {\n loadEngine(bundle?: string): Promise<ApiEngine>;\n checkLeanWasm?(bundle: string | undefined, root: string,\n sources: Array<{ fileName: string; source: string }>, timeoutMs: number): Promise<unknown>;\n readStdin(): Promise<string>;\n stdout(text: string): void;\n stderr(text: string): void;\n}\n\nconst HELP = `yichus — the Yichus WebMCP analysis engine, locally\n\n yichus tools\n yichus call TOOL [--args JSON_FILE|-] [--arg-file NAME=JSON_FILE ...] [--source FILE ... | --project DIR]\n yichus verify FILE ... [--instances 1|many] [--block-on-warning ID ...]\n yichus lean FILE ... --lean-wasm-root DIRECTORY [--timeout-ms N]\n${STUDIO_HELP}\nOptions:\n --source FILE Add a Bosatsu source (repeatable; call only). Files\n sharing a basename are named by their folders.\n --project DIR For a tool that requires sources, given no --source\n and no args.sources: every .bosatsu file under DIR\n (default the current folder), as the studio reads\n it (call only).\n --args FILE|- Tool arguments as a JSON object; - reads stdin.\n --arg-file NAME=FILE Set one argument to the JSON in FILE, such as a\n saved snapshot (repeatable; call only).\n --block-on-warning ID A property id whose warning blocks the verdict, as a\n violation would (repeatable; all names every property;\n verify only). An id the verdict lacks exits 2.\n --output FILE Write the result to this file instead of stdout.\n --select /POINTER Extract a JSON field; strings are written verbatim.\n --expect /PTR=JSON Fail unless a result field exactly equals JSON (repeatable).\n --bundle FILE Explicit Scala.js engine override.\n --lean-wasm-root DIR Pinned local Lean Wasm installation (lean only).\n --timeout-ms N Total proof budget, at most 300000 (lean only).\n --help, -h Show this help without loading the engine.\n\ntools and call expose Yichus/Mcp::catalog without a second analysis layer.\nverify runs api_verify and requires verdict.proven to be exactly true.\nIts JSON opens with proven, the verdict; ok only says the check ran.\nIt always prints a plain summary of the verdict to stderr: each property's\nstatus, the first failure's evidence (parse errors carry file:line:col),\nand where the full JSON verdict went.\nlean runs the pinned Wasm kernel and requires all discovered obligations to be verified.\nIt prints on stderr whether each law was proven and, if not, why: Lean\nrejected it (with Lean's words), the law is outside what Lean Wasm admits,\nthe --timeout-ms budget ran out, or no runtime is installed (with the\ninstall command).\ncall requires ok:true; use --expect to gate on a check's actual verdict.\nWhen the tool fails, stderr gives its error as plain text, what to do\ninstead when the engine names the failure's kind (errorKinds), and where\nthe JSON result went. An unmet --expect is one JSON line on stderr.\nWith --output it says on stderr where the result went; api_abstraction_map\nalso says what it is mapping before it starts, and afterwards its layer,\nreuse and copy counts in words, each with the JSON field that lists them.\nNo browser is needed. Page editing, visible feedback and app sessions use\nthe separate @yichus/mcp browser relay.\n\nExit status: 0 = completed and expectations met; 1 = tool/check rejected;\n2 = invalid invocation (including a --block-on-warning id the verdict lacks), malformed engine result, or execution/IO failure\n(for lean: no runtime, the budget ran out, or the runtime failed).\nJSON diagnostics remain available for rejected checks: the result JSON,\nor, when --select withheld it, a JSON line on stderr. --select emits no\nartifact on rejection. A named output is removed before execution so a\nfailed check cannot leave yesterday's artifact behind.\n`;\n\ninterface Options {\n command: 'tools' | 'call' | 'verify' | 'lean';\n tool?: string;\n args?: string;\n argFiles: Array<{ name: string; file: string }>;\n sources: string[];\n project?: string;\n instances?: string;\n blockOnWarnings: string[];\n output?: string;\n select?: string;\n expects: Array<{ pointer: string; value: unknown }>;\n bundle?: string;\n leanWasmRoot?: string;\n timeoutMs?: number;\n}\n\nfunction pointerParts(pointer: string): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/') || /~(?:[^01]|$)/u.test(pointer)) {\n throw new Error(`Invalid JSON Pointer: ${pointer}`);\n }\n return pointer.slice(1).split('/').map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\nfunction readPointer(value: unknown, pointer: string): unknown {\n for (const part of pointerParts(pointer)) {\n if (value === null || typeof value !== 'object' || !Object.hasOwn(value, part)) return undefined;\n value = (value as Record<string, unknown>)[part];\n }\n return value;\n}\n\nfunction objectValue(value: unknown, label: string): Record<string, unknown> {\n const parsed = z.record(z.string(), z.unknown()).safeParse(value);\n if (!parsed.success) throw new Error(`${label} must be a JSON object`);\n return parsed.data;\n}\n\nconst objectJson = (raw: string, label: string): Record<string, unknown> => objectValue(JSON.parse(raw), label);\n\nconst FLAGS = {\n source: { type: 'string', multiple: true },\n args: { type: 'string' },\n 'arg-file': { type: 'string', multiple: true },\n project: { type: 'string' },\n instances: { type: 'string' },\n 'block-on-warning': { type: 'string', multiple: true },\n output: { type: 'string' },\n bundle: { type: 'string' },\n 'lean-wasm-root': { type: 'string' },\n 'timeout-ms': { type: 'string' },\n select: { type: 'string' },\n expect: { type: 'string', multiple: true },\n} as const;\n\nconst TimeoutMs = z.coerce.number().int().min(1).max(300_000);\n\nfunction parse(argv: string[]): Options {\n const { values, positionals, tokens } = parseArgs({ args: argv, options: FLAGS, allowPositionals: true, strict: true, tokens: true });\n // parseArgs keeps the last of a repeated single-valued flag; a repeat is a mistake here.\n const named = tokens.flatMap((token) => token.kind === 'option' ? [token.name as keyof typeof FLAGS] : []);\n const repeated = named.find((name, i) => !('multiple' in FLAGS[name]) && named.indexOf(name) !== i);\n if (repeated) throw new Error(`Repeated --${repeated}`);\n const [command, ...rest] = positionals;\n if (command !== 'tools' && command !== 'call' && command !== 'verify' && command !== 'lean') {\n throw new Error('Expected tools, call TOOL, verify FILE, or lean FILE; use --help for usage.');\n }\n const opts: Options = { command, sources: [], argFiles: [], expects: [], blockOnWarnings: values['block-on-warning'] ?? [] };\n if (command === 'call') {\n opts.tool = rest.shift();\n if (!opts.tool) throw new Error('call requires a tool name');\n }\n if ((command === 'tools' || command === 'call') && rest.length) throw new Error(`Unexpected argument: ${rest[0]}`);\n opts.sources = [...rest, ...(values.source ?? [])];\n opts.args = values.args;\n for (const value of values['arg-file'] ?? []) {\n const equal = value.indexOf('=');\n if (equal <= 0 || equal === value.length - 1) throw new Error('--arg-file requires NAME=FILE');\n const name = value.slice(0, equal);\n if (opts.argFiles.some((a) => a.name === name)) throw new Error(`--arg-file names ${name} twice`);\n opts.argFiles.push({ name, file: value.slice(equal + 1) });\n }\n if (opts.argFiles.length && command !== 'call') throw new Error('--arg-file is for call');\n opts.project = values.project;\n if (opts.project !== undefined && command !== 'call') throw new Error('--project is for call');\n if (opts.project !== undefined && opts.sources.length) throw new Error('Use either --source files or --project, not both');\n opts.instances = values.instances;\n opts.output = values.output;\n opts.bundle = values.bundle;\n opts.leanWasmRoot = values['lean-wasm-root'];\n if (values['timeout-ms'] !== undefined) {\n const timeout = TimeoutMs.safeParse(values['timeout-ms']);\n if (!timeout.success) throw new Error('--timeout-ms must be an integer from 1 to 300000');\n opts.timeoutMs = timeout.data;\n }\n if (values.select !== undefined) {\n pointerParts(values.select);\n opts.select = values.select;\n }\n for (const value of values.expect ?? []) {\n const equal = value.indexOf('=');\n if (equal < 0) throw new Error('--expect requires /POINTER=JSON');\n const pointer = value.slice(0, equal);\n pointerParts(pointer);\n opts.expects.push({ pointer, value: JSON.parse(value.slice(equal + 1)) });\n }\n if (command === 'tools' && (opts.sources.length || opts.args || opts.instances)) {\n throw new Error('tools does not accept sources or tool arguments');\n }\n if (command === 'verify') {\n if (!opts.sources.length) throw new Error('verify requires at least one Bosatsu file');\n if (opts.args) throw new Error('verify accepts --instances; use call for arbitrary arguments');\n if (values.source !== undefined) throw new Error('verify takes positional files; --source is for call');\n if (opts.instances && opts.instances !== '1' && opts.instances !== 'many') {\n throw new Error('--instances must be 1 or many');\n }\n opts.expects.push({ pointer: '/verdict/proven', value: true });\n } else if (command === 'lean') {\n if (!opts.sources.length) throw new Error('lean requires at least one Bosatsu file');\n if (!opts.leanWasmRoot) throw new Error('lean requires --lean-wasm-root');\n if (opts.args || opts.instances || values.source !== undefined)\n throw new Error('lean takes positional files and a Wasm root');\n opts.expects.push({ pointer: '/allVerified', value: true });\n } else if (opts.instances) {\n throw new Error('--instances is for verify; pass catalog arguments through --args for call');\n }\n if (command !== 'verify' && opts.blockOnWarnings.length)\n throw new Error('--block-on-warning is for verify; pass block_on_warnings through --args for call');\n if (command !== 'lean' && (opts.leanWasmRoot || opts.timeoutMs !== undefined))\n throw new Error('--lean-wasm-root and --timeout-ms are for lean');\n return opts;\n}\n\n// The closest name in the same directory, for a mistyped input path.\nfunction closestSibling(file: string): string | undefined {\n const dir = path.dirname(file);\n const want = path.basename(file);\n let names: string[];\n try { names = fs.readdirSync(dir); } catch { return undefined; }\n const distance = (a: string, b: string): number => {\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let diagonal = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const above = row[j]!;\n row[j] = Math.min(row[j]! + 1, row[j - 1]! + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));\n diagonal = above;\n }\n }\n return row[b.length]!;\n };\n const scored = names.map((name) => ({ name, d: distance(want, name) })).filter(({ d }) => d <= 2).sort((x, y) => x.d - y.d);\n return scored.length ? path.join(dir, scored[0]!.name) : undefined;\n}\n\n// An input file the user named, read or explained in words: the error's\n// own code and path say what went wrong, never its message text.\nfunction readInput(file: string): string {\n try {\n return fs.readFileSync(file, 'utf8');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code;\n if (code === 'ENOENT') {\n const near = closestSibling(file);\n throw new Error(`File not found: ${file}${near ? `. Did you mean ${near}?` : ''}`);\n }\n if (code === 'EISDIR') throw new Error(`${file} is a directory; name a file instead.`);\n if (code === 'EACCES' || code === 'EPERM') throw new Error(`Permission denied reading ${file}.`);\n throw error;\n }\n}\n\n// The one place a --source path becomes the name the engine knows the file\n// by: its basename, or, where two files share a basename, the fewest\n// trailing folders of each path that tell them apart\n// (\"billing/api.bosatsu\" and \"notes/api.bosatsu\"). The same file named\n// twice is refused, since it would compile twice.\nfunction sourceNames(paths: string[]): string[] {\n const parts = paths.map((p) => path.resolve(p).split(path.sep).filter((s) => s !== ''));\n const seen = new Set<string>();\n parts.forEach((segments, i) => {\n const full = segments.join('/');\n if (seen.has(full)) throw new Error(`${paths[i]} names the same file as an earlier --source; name each source once`);\n seen.add(full);\n });\n const tail = (segments: string[], n: number) => segments.slice(-n).join('/');\n return parts.map((segments, i) => {\n let n = 1;\n while (parts.some((other, j) => j !== i && tail(other, n) === tail(segments, n))) n += 1;\n return tail(segments, n);\n });\n}\n\nasync function argumentsFor(opts: Options, io: CliIo): Promise<Record<string, unknown>> {\n const args = opts.args\n ? objectJson(opts.args === '-' ? await io.readStdin() : readInput(opts.args), 'Arguments')\n : {};\n for (const { name, file } of opts.argFiles) {\n if (Object.hasOwn(args, name)) throw new Error(`Use either --arg-file ${name}=... or args.${name}, not both`);\n try { args[name] = JSON.parse(readInput(file)); } catch (error) {\n if (error instanceof SyntaxError) throw new Error(`--arg-file ${name}: ${file} is not JSON (${error.message})`);\n throw error;\n }\n }\n if (opts.sources.length) {\n if (Object.hasOwn(args, 'sources')) throw new Error('Use either --source files or args.sources, not both');\n const names = sourceNames(opts.sources);\n args.sources = opts.sources.map((sourcePath, i) => ({ fileName: names[i]!, source: readInput(sourcePath) }));\n }\n if (opts.instances) args.instances = opts.instances;\n if (opts.blockOnWarnings.length) args.block_on_warnings = [...new Set(opts.blockOnWarnings)];\n return args;\n}\n\n// A tool that requires sources reads the program; given none, it reads the\n// program in the project folder, the same files the studio checks. A tool\n// whose sources are optional means something else without them (a generic\n// template, a cached receipt), so it is left as called.\nconst Catalog = z.looseObject({ tools: z.array(z.looseObject({ name: z.string(),\n inputSchema: z.looseObject({ required: z.array(z.string()).default([]) }).optional() })).default([]) });\n\nfunction readsProgram(engine: ApiEngine, tool: string): boolean {\n const catalog = Catalog.safeParse(JSON.parse(engine.listTools()));\n return catalog.success && (catalog.data.tools.find(t => t.name === tool)?.inputSchema?.required.includes('sources') ?? false);\n}\n\nfunction folderSources(tool: string, project: string | undefined): Array<{ fileName: string; source: string }> {\n const root = path.resolve(project ?? '.');\n const files = projectSources(root);\n 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.`);\n return files;\n}\n\nfunction clearOutput(opts: Options): void {\n if (!opts.output) return;\n const output = path.resolve(opts.output);\n // Protect named inputs even through symlinks and hard links. Only the\n // output path itself is removed; never follow it to remove a target.\n const outputStat = fs.existsSync(output) ? fs.statSync(output) : undefined;\n for (const input of [...opts.sources, ...opts.argFiles.map((a) => a.file), opts.args, opts.bundle].filter((p): p is string => !!p && p !== '-')) {\n const inputStat = fs.existsSync(input) ? fs.statSync(input) : undefined;\n if (path.resolve(input) === output || (outputStat && inputStat && inputStat.dev === outputStat.dev && inputStat.ino === outputStat.ino)) {\n throw new Error('--output must not overwrite an input file');\n }\n }\n fs.rmSync(output, { force: true });\n}\n\n// Why a completed run did not pass. A tool that failed (ok: false) is\n// reported in its own words; expectations are blamed only when the tool\n// succeeded and an --expect did not match.\nfunction rejection(result: Record<string, unknown>, unmet: number): string {\n if (result.ok) return `${unmet} --expect ${unmet === 1 ? 'expectation was' : 'expectations were'} not met`;\n const said = EngineError.safeParse(result);\n return said.success ? said.data.error : 'The tool failed without saying why; see its result';\n}\n\nexport async function runCli(argv: string[], io: CliIo): Promise<number> {\n try {\n if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {\n io.stdout(HELP);\n return 0;\n }\n const opts = parse(argv);\n // Protect inputs before removing stale output, but remove output before\n // reading arguments or loading the engine: either can fail this run.\n clearOutput(opts);\n const args = await argumentsFor(opts, io);\n let result: Record<string, unknown>;\n const timeoutMs = opts.timeoutMs ?? 180_000;\n if (opts.command === 'lean') {\n if (!io.checkLeanWasm) throw new Error('Lean Wasm backend is unavailable');\n io.stderr(`Checking the laws in ${opts.sources.join(', ')} with Lean Wasm at ${opts.leanWasmRoot!} `\n + `(budget ${timeoutMs} ms)...\\n`);\n result = objectValue(await io.checkLeanWasm(opts.bundle, opts.leanWasmRoot!,\n args.sources as Array<{ fileName: string; source: string }>, timeoutMs), 'Lean result');\n } else {\n if (opts.command === 'call') {\n const files = Array.isArray(args.sources) ? args.sources.length : undefined;\n const progress = callProgress(opts.tool!, files);\n if (progress) io.stderr(progress);\n }\n const engine = await io.loadEngine(opts.bundle);\n if (opts.command === 'call' && !Object.hasOwn(args, 'sources') && readsProgram(engine, opts.tool!)) {\n args.sources = folderSources(opts.tool!, opts.project);\n }\n const raw = opts.command === 'tools'\n ? engine.listTools()\n : engine.callTool(opts.command === 'verify' ? 'api_verify' : opts.tool!, JSON.stringify(args));\n result = objectJson(raw, 'Engine result');\n }\n if (typeof result.ok !== 'boolean') throw new Error('Engine result must explicitly contain boolean ok');\n const unmet = opts.expects.filter(({ pointer, value }) => !isDeepStrictEqual(readPointer(result, pointer), value));\n const passed = result.ok && unmet.length === 0;\n if (opts.select === undefined || passed) {\n const selected = opts.select === undefined ? result : readPointer(result, opts.select);\n if (selected === undefined) throw new Error(`Result field missing: ${opts.select}`);\n const text = opts.select !== undefined && typeof selected === 'string'\n ? selected : `${JSON.stringify(selected, null, 2)}\\n`;\n if (opts.output) fs.writeFileSync(opts.output, text);\n else io.stdout(text);\n }\n // verify and lean always read their verdict aloud on stderr; the JSON\n // artifact (stdout or --output) is unchanged. The generic envelope\n // below is only repeated when --select withheld the verdict JSON.\n const artifact = opts.select !== undefined ? 'the unselected result; run without --select to see it'\n : opts.output ?? 'the JSON on standard output';\n let exit: number = passed ? 0 : 1;\n if (opts.command === 'verify') {\n io.stderr(verifySummary(result, passed, artifact));\n // An id the verdict does not have is the caller's mistake, not a\n // rejected check: the engine says so by errorKind.\n if (!result.ok && result.errorKind === 'invalid-arguments') exit = 2;\n } else if (opts.command === 'lean') {\n const reading = leanSummary(result, artifact, timeoutMs, opts.sources);\n io.stderr(reading.text);\n exit = reading.exit;\n } else if (!result.ok) {\n // A failed tool is read aloud in its own words, with the next step\n // when the engine names the failure's kind; its JSON is the artifact.\n io.stderr(callFailure(opts.tool ?? 'tools', result, artifact));\n } else if (passed && opts.select === undefined && opts.command === 'call') {\n const said = callSummary(opts.tool!, result, opts.output);\n if (said) io.stderr(said);\n }\n // The JSON line is the machine-readable diagnostic wherever no JSON\n // artifact carries the failure: an unmet --expect on a completed tool,\n // and any rejection whose result --select withheld.\n const generic = opts.command === 'call' || opts.command === 'tools';\n if (!passed && (opts.select !== undefined || (generic && result.ok))) {\n io.stderr(`${JSON.stringify({ ok: false, error: rejection(result, unmet.length), unmet, result: opts.select === undefined ? undefined : result })}\\n`);\n }\n return exit;\n } catch (error) {\n // A run that could not start (bad arguments, an unreadable file, an\n // engine that would not load) is reported as a sentence; the JSON\n // envelopes above are for results the engine actually produced.\n io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}\\n`);\n return 2;\n }\n}\n","import { z } from 'zod';\n\n// The engine results this CLI reads aloud, as the engine writes them.\n\n/** ApiSafety.PropertyStatus.render: every status an api_verify property can have. */\nexport const PropertyStatus = z.enum(['proven', 'warning', 'violated', 'blocked']);\nexport type PropertyStatus = z.infer<typeof PropertyStatus>;\n\nconst Property = z.looseObject({\n id: z.string(),\n title: z.string().optional(),\n status: PropertyStatus,\n details: z.array(z.string()),\n // The declared assumption an accepted warning rests on, e.g. \"instances=1\".\n accepted: z.string().optional(),\n});\nexport type Property = z.infer<typeof Property>;\n\nexport const VerifyResult = z.looseObject({\n topology: z.string().optional(),\n verdict: z.looseObject({\n properties: z.array(Property),\n errors: z.array(z.string()).default([]),\n // Present only when the caller passed block_on_warnings: the warnings\n // among the listed properties, which made the verdict not proven.\n blockedWarnings: z.array(z.string()).optional(),\n }),\n});\n\n/** What is left to say when the verdict cannot be read: its errors, if those can. */\nexport const VerdictErrors = z.object({ verdict: z.object({ errors: z.array(z.string()) }) });\n/** ApiChecks.fail / compileFailure: a tool's error, and the kinds of compile\n * failure it names (CompileKernel.CompileErrorKind codes) when it names any. */\nexport const EngineError = z.object({ error: z.string(), errorKinds: z.array(z.string()).optional() });\n\nconst Count = z.int().nonnegative();\nexport const AbstractionMap = z.looseObject({\n measures: z.looseObject({\n definitions: Count, edges: Count, layers: Count, layerSkips: Count, usedOnce: Count, usedMany: Count,\n clonePairs: Count, duplicatedMass: Count, maxSize: Count,\n largestDefinition: z.string().optional(),\n }),\n});\n","// The human reading of an api_verify result. It is rendered from the\n// api-safety verdict's own fields (verdict.proven, verdict.properties[]\n// with id/title/status/details, verdict.errors[]) and never from the\n// narrative text or any string matching. The headline comes from the\n// same `proven === true` test that decides the exit status, so the words\n// and the exit code cannot disagree. A result whose shape cannot be read\n// says so instead of inheriting a label.\n\nimport { EngineError, VerdictErrors, VerifyResult, type Property, type PropertyStatus } from './engine-results.js';\n\nconst title = (p: Property) => p.title ?? p.id;\n\n// What each status word means, in the engine's own terms\n// (VerdictNarrative.propertyStatus).\nconst MEANING: Record<PropertyStatus, string> = {\n proven: 'holds for every input',\n warning: 'holds only under the acceptance its details name',\n violated: 'is broken; the details are the evidence',\n blocked: 'was not checked: the check could not run, could not finish, or could not see its subject',\n};\n\n// An accepted warning is safe as deployed; say so, and say what the\n// details ask for before the assumption is dropped. An acceptance this\n// CLI does not know is named verbatim.\nconst ACCEPTANCE: Record<string, string> = {\n 'instances=1': 'Safe while you run one instance (--instances 1). Before running more than one:',\n};\nconst acceptance = (a: string) => ACCEPTANCE[a] ?? `Safe under the declared ${a}. Before dropping it:`;\n\n// The word in the status column: an accepted warning reads \"accepted\".\nconst label = (p: Property) => p.status === 'warning' && p.accepted !== undefined ? 'accepted' : p.status;\n\nconst indent = (text: string, prefix: string) => text.split('\\n').map((line) => prefix + line).join('\\n');\n\nfunction count(props: Property[]): string {\n const order: string[] = [];\n const counts = new Map<string, number>();\n for (const p of props) {\n const status = label(p);\n if (!counts.has(status)) order.push(status);\n counts.set(status, (counts.get(status) ?? 0) + 1);\n }\n return order.map((status) => `${counts.get(status)} ${status}`).join(', ');\n}\n\n/** Plain-language summary of an api_verify result, ending in a newline. */\nexport function verifySummary(result: Record<string, unknown>, proven: boolean, artifact: string): string {\n const parsed = VerifyResult.safeParse(result);\n if (!parsed.success) {\n const said = EngineError.safeParse(result);\n const reason = said.success ? ` The engine said: ${said.data.error}` : '';\n const errors = VerdictErrors.safeParse(result);\n const lines = [\n proven\n ? 'Proven, but the verdict has no readable property list.'\n : `Not proven. The engine returned no readable verdict.${reason}`,\n ];\n if (errors.success && errors.data.verdict.errors.length)\n lines.push('Errors:', ...errors.data.verdict.errors.map((e) => indent(e, ' ')));\n lines.push(`The full result is in ${artifact}.`);\n return `${lines.join('\\n')}\\n`;\n }\n const checked = parsed.data.verdict.properties;\n const errors = parsed.data.verdict.errors;\n const topology = parsed.data.topology !== undefined ? ` Topology: ${parsed.data.topology}.` : '';\n const lines: string[] = [];\n if (proven) {\n lines.push(`Proven: ${checked.length} properties checked (${count(checked)}).${topology}`);\n } else {\n lines.push(`Not proven: ${checked.length} properties checked (${count(checked)}).${topology}`);\n // The first failure a reader should fix: the first violated property,\n // otherwise the first one that is neither proven nor accepted,\n // otherwise a warning the caller chose to block on.\n const blocking = new Set(parsed.data.verdict.blockedWarnings ?? []);\n const first = checked.find((p) => p.status === 'violated')\n ?? checked.find((p) => p.status !== 'proven' && p.status !== 'warning')\n ?? checked.find((p) => blocking.has(p.id));\n if (first) {\n const why = blocking.has(first.id) && first.status === 'warning'\n ? ' It blocks because --block-on-warning named it.' : '';\n lines.push(`First failure (${first.status}): ${title(first)}. This property ${MEANING[first.status]}.${why}`);\n for (const detail of first.details) lines.push(indent(detail, ' '));\n }\n }\n lines.push('Every property:');\n const width = Math.max(...checked.map((p) => label(p).length));\n for (const p of checked) {\n lines.push(` ${label(p).padEnd(width)} ${title(p)}`);\n // Warnings name the acceptance they rest on; show it beside the property.\n const pad = ` ${' '.repeat(width)} `;\n if (p.status === 'warning' && p.accepted !== undefined) lines.push(pad + acceptance(p.accepted));\n if (p.status === 'warning') for (const detail of p.details) lines.push(indent(detail, pad));\n }\n const shown = new Set(checked.flatMap((p) => p.details));\n const unshown = errors.filter((e) => !shown.has(e));\n if (unshown.length) lines.push('Errors:', ...unshown.map((e) => indent(e, ' ')));\n lines.push(`The full verdict, with every property's details, is in ${artifact}.`);\n return `${lines.join('\\n')}\\n`;\n}\n","// The human reading of a `yichus lean` result. It is rendered from the\n// Lean Wasm run's own typed fields (allVerified, proof.status,\n// proof.obligations[] with binding/status/cause/reason/diagnostics, and\n// proof.cause for a run with no rows) and never from message text. The\n// same reading decides the exit status, so the words and the exit code\n// cannot disagree:\n// 0 every discovered law was verified;\n// 1 the checker answered and something did not verify (Lean rejected a\n// theorem or its axiom audit, or a law is outside what it admits);\n// 2 the check could not finish (no runtime, the budget ran out, the\n// runtime failed) or the result could not be read.\n// A cause this CLI does not know is never mapped onto one it does.\nimport { LEAN_WASM_INSTALL_COMMAND, LeanCheckResult } from '@yichus/api-mcp';\nimport { z } from 'zod';\n\nexport interface LeanReading { text: string; exit: 0 | 1 | 2 }\n\ntype Run = LeanCheckResult['proof'];\ntype Cause = NonNullable<Run['cause']> | Extract<Run['obligations'][number], { status: 'inconclusive' }>['cause'];\n\nconst plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;\nconst indent = (value: string, prefix: string) => value.split('\\n').map((line) => prefix + line).join('\\n');\n\n// Which side of the boundary each cause is on: the checker answered, or\n// the check could not finish.\nconst SIDE: Record<Cause, 'checker' | 'harness'> = {\n rejected: 'checker', 'axiom-audit': 'checker', 'not-admitted': 'checker',\n 'runtime-missing': 'harness', timeout: 'harness', 'runtime-error': 'harness',\n};\n\nconst DEFAULT_TIMEOUT_MS = 180_000;\nconst MAX_TIMEOUT_MS = 300_000;\n\n// What to do about each cause, said once per run.\nfunction remedy(cause: Cause, timeoutMs: number, files: string[]): string[] {\n const sources = files.map((f) => `--source ${f}`).join(' ');\n switch (cause) {\n case 'runtime-missing':\n return ['Install the pinned runtime once (about 290 MB to download), then pass that folder as --lean-wasm-root:',\n ` ${LEAN_WASM_INSTALL_COMMAND.replace('NEW_DIRECTORY', '/absolute/new/folder')}`];\n case 'timeout':\n return [timeoutMs < MAX_TIMEOUT_MS\n ? `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}).`\n : `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.`];\n case 'runtime-error':\n return ['The Lean Wasm runtime could not run. If it was changed or only partly installed, install a fresh copy into a new folder:',\n ` ${LEAN_WASM_INSTALL_COMMAND.replace('NEW_DIRECTORY', '/absolute/new/folder')}`];\n case 'rejected':\n return ['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.',\n `To see a failing input, run: yichus call api_law_check ${sources}. Fix the code, not the law.`];\n case 'axiom-audit':\n 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.'];\n case 'not-admitted':\n return ['Lean Wasm proves Bool and structural List[Bool] laws with one direct witness. Check other laws with: '\n + `yichus call api_law_check ${sources}`];\n }\n}\n\nconst unreadable = (artifact: string, why: string): LeanReading => ({\n exit: 2,\n text: `Not checked: the Lean result could not be read (${why}). The full result is in ${artifact}.\\n`,\n});\n\nconst EngineError = z.object({ ok: z.literal(false), error: z.string().min(1), proof: z.undefined().optional() });\n\nconst issue = (error: z.ZodError): string => {\n const first = error.issues[0]!;\n return first.path.length ? `${first.path.join('.')}: ${first.message}` : first.message;\n};\n\n/** Plain-language reading of a `yichus lean` result, ending in a newline. */\nexport function leanSummary(raw: unknown, artifact: string, timeoutMs: number, files: string[]): LeanReading {\n const refused = EngineError.safeParse(raw);\n if (refused.success) return unreadable(artifact, `the engine said: ${refused.data.error}`);\n const parsed = LeanCheckResult.safeParse(raw);\n if (!parsed.success) return unreadable(artifact, issue(parsed.error));\n const proof = parsed.data.proof;\n const laws = proof.obligations;\n const lines: string[] = [];\n\n if (proof.status === 'verified') {\n lines.push(`Proven: ${plural(laws.length, 'law')} verified by the pinned Lean Wasm kernel.`);\n for (const row of laws) {\n if (row.status !== 'verified') continue;\n const { check, witness, domain } = row.proof.subject;\n lines.push(` ${row.binding}: ${check} holds for ${domain}, and ${witness} holds for at least one.`);\n }\n lines.push(`The proof receipt is in ${artifact}. It is a local Wasm kernel check (independentKernelReplay: false).`);\n return { exit: 0, text: `${lines.join('\\n')}\\n` };\n }\n\n // Nothing to report per law: the run itself names why.\n if (!laws.length) {\n const cause = proof.cause!;\n const checker = SIDE[cause] === 'checker';\n lines.push(`${checker ? 'Not proven' : 'Not checked'}: ${proof.reason!}.`);\n if (cause === 'not-admitted') lines.push('Fix the source, or add a Yichus/Law Obligation for lean to prove.');\n else lines.push(...remedy(cause, timeoutMs, files));\n lines.push(`The full result is in ${artifact}.`);\n return { exit: checker ? 1 : 2, text: `${lines.join('\\n')}\\n` };\n }\n\n const failed = laws.flatMap((row) => row.status === 'inconclusive' ? [row] : []);\n const causes = [...new Set(failed.map((row) => row.cause))];\n const checker = causes.some((cause) => SIDE[cause] === 'checker');\n lines.push(checker\n ? `Not proven: ${failed.length} of ${plural(laws.length, 'law')} did not verify.`\n : `Not checked: ${failed.length} of ${plural(laws.length, 'law')} could not be checked.`);\n for (const row of laws) {\n if (row.status === 'verified') { lines.push(` verified ${row.binding}`); continue; }\n lines.push(` ${row.cause.padEnd(12)} ${row.binding}: ${row.reason}.`);\n if (row.diagnostics?.length) lines.push(' Lean said:', ...row.diagnostics.map((d) => indent(d, ' ')));\n }\n for (const cause of causes) lines.push(...remedy(cause, timeoutMs, files));\n lines.push(`The full result is in ${artifact}.`);\n return { exit: checker ? 1 : 2, text: `${lines.join('\\n')}\\n` };\n}\n","// What `yichus call` says on stderr around its result. The JSON artifact\n// (stdout or --output) is unchanged; these lines only say what a slow tool\n// is doing before it starts, where the result went, and, for tools with a\n// summary block, read that block's own fields aloud in words, each with\n// the JSON field to read next. When a tool fails, it gives the tool's error\n// in plain text and, from the engine's errorKinds, what to do instead.\n// Nothing here is parsed from text.\n\nimport { AbstractionMap, EngineError } from './engine-results.js';\n\nconst plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;\n\n// api_abstraction_map's `measures` block: layers, reuse and copies.\nfunction mapSummary(result: Record<string, unknown>): string[] {\n const parsed = AbstractionMap.safeParse(result);\n if (!parsed.success) return ['The map has no readable measures block; read the JSON for its contents.'];\n const m = parsed.data.measures;\n const lines = [\n `Layers: ${plural(m.definitions, 'definition')} stacked ${plural(m.layers, 'layer')} deep `\n + '(a definition sits one layer above the highest one it uses).',\n m.layerSkips === 0\n ? `Layer skips: none of the ${plural(m.edges, 'dependency edge')} reaches past the layer just below.`\n : `Layer skips: ${m.layerSkips} of ${plural(m.edges, 'dependency edge')} reach past the layer just below, `\n + 'using a definition two or more layers down; they are the \"edges\" with \"span\" above 1.',\n `Reuse: ${plural(m.usedMany, 'definition is', 'definitions are')} used by several others, `\n + `${m.usedOnce} by exactly one (each node's \"fanIn\").`,\n m.clonePairs === 0\n ? 'Copies: no two definitions have the same compiled body.'\n : `Copies: ${plural(m.clonePairs, 'pair')} of definitions have the same compiled body; see \"clonePairs\".`,\n m.duplicatedMass === 0\n ? 'Repeats: no block of code repeats inside a definition.'\n : `Repeats: blocks repeated inside one definition add ${plural(m.duplicatedMass, 'node')}; `\n + 'nodes with \"repeatedBlockMass\" above 0 list each block\\'s places in \"repeatedBlocks\".',\n ];\n if (m.largestDefinition !== undefined)\n lines.push(`Largest definition: ${m.largestDefinition} (${m.maxSize} nodes).`);\n return lines;\n}\n\ninterface Known {\n noun: string;\n // Said before the tool runs, so a long run is not silence.\n progress: (files: number | undefined) => string;\n summary: (r: Record<string, unknown>) => string[];\n}\n\nconst SUMMARIES: Record<string, Known> = {\n api_abstraction_map: {\n noun: 'the abstraction map',\n progress: (files) => `Mapping ${files === undefined ? 'the program' : plural(files, 'Bosatsu file')}: `\n + 'compiling it and measuring every definition, which can take half a minute or more for a large program...',\n summary: mapSummary,\n },\n};\n\n/** A line for stderr before a slow tool runs, or undefined for any other tool. */\nexport function callProgress(tool: string, files: number | undefined): string | undefined {\n const known = SUMMARIES[tool];\n return known ? `${known.progress(files)}\\n` : undefined;\n}\n\n/** Lines for stderr after a successful call, or undefined when there is nothing to say. */\nexport function callSummary(tool: string, result: Record<string, unknown>, output: string | undefined): string | undefined {\n const known = SUMMARIES[tool];\n const lines: string[] = [];\n if (output) lines.push(`Wrote ${known?.noun ?? `the ${tool} result`} to ${output}.`);\n if (known) lines.push(...known.summary(result));\n return lines.length ? `${lines.join('\\n')}\\n` : undefined;\n}\n\n// What to do instead, for each compile-failure kind the engine names\n// (CompileKernel.CompileErrorKind codes). A kind not listed here gets no\n// advice line; the error's own words still say what went wrong.\nconst NEXT_STEP: Record<string, string> = {\n 'duplicate-package': 'Each package can be declared by only one file. '\n + 'Give each file its own package name, or pass only one of them.',\n};\n\n/**\n * Lines for stderr when a tool returned ok:false: the tool's error as plain\n * text, what to do instead when the engine names the failure's kind, and\n * where the full JSON result is.\n */\nexport function callFailure(tool: string, result: Record<string, unknown>, artifact: string): string {\n const said = EngineError.safeParse(result);\n const lines = said.success\n ? [`${tool} failed:`, said.data.error]\n : [`${tool} failed without saying why.`];\n if (said.success)\n for (const kind of said.data.errorKinds ?? []) if (Object.hasOwn(NEXT_STEP, kind)) lines.push(`Next: ${NEXT_STEP[kind]}`);\n lines.push(`The full result is in ${artifact}.`);\n return `${lines.join('\\n')}\\n`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { type StudioEngine, direct, readState } from './director.js';\nimport { pageNote, recordAnswer, recordNames, recordRules, recordScenarios, recordStart } from './mcp.js';\nimport { type Locate, readReference, topicList } from './reference.js';\nimport { recordMarks } from './marks.js';\nimport { runningPageUrl } from './page-link.js';\nimport { pageText } from './page-view.js';\nimport { loadRequirements } from './requirements.js';\nimport { CLI, CLI_LEGEND } from './surface.js';\nimport { stepText } from './text.js';\n\n// The studio from a terminal: the same director as the MCP tools, for an\n// agent that runs shell commands, or a person who wants to look.\n//\n// yichus start \"what to build\" record the description\n// yichus next [--json] run the checks and print the next step\n// yichus name SUBJECT \"NAME\" ... plain names for parts of the program\n// yichus answer QUESTION CHOICE [--words TEXT]\n// yichus rules FILE.json the rules the person stated, with the laws that check each\n// yichus scenario FILE.json what should happen in actions, in the person's words\n// yichus point FILE.json point at parts of the page, with notes\n// yichus page the page as the person sees it, in words\n// yichus reference [TOPIC] reference material a step asks for; no topic lists them\n// yichus studio [--page] [--port N] the MCP server and page (--page: page only)\n\nexport const STUDIO_COMMANDS = new Set(['start', 'next', 'name', 'answer', 'rules', 'scenario', 'point', 'page', 'reference', 'studio']);\n\nexport const STUDIO_HELP = `\nStudio (guided building; all take --project DIR, default the current folder).\nKeep the project in a folder of its own, apart from any old app it replaces:\nthe studio reads every .bosatsu file in it.\n yichus studio [--port N] MCP server on stdio plus the studio page\n yichus studio --page [--port N] only the studio page, for the commands below\n yichus start \"DESCRIPTION\" record what the person wants built\n yichus next [--json] check the program and print the next step\n yichus name SUBJECT \"NAME\" ... plain names the person sees for parts of the program\n yichus answer QUESTION CHOICE [--words TEXT]\n yichus rules FILE.json the rules the person stated: {\"rules\": [{\"rule\": ..., \"laws\": [...]}]}\n yichus scenario FILE.json what should happen in actions: {\"scenarios\": [...], \"drop\": [...]}\n yichus point FILE.json point at parts of the page: {\"marks\": [{\"at\": ..., \"note\": ...}]}\n yichus page the page as the person sees it now, in words\n yichus reference [TOPIC] reference material a step asks for; no topic lists them\n`;\n\nexport interface StudioIo {\n engine(): Promise<StudioEngine>;\n serve(options: { root: string; port: number | null; pageOnly: boolean }): Promise<void>;\n stdout(text: string): void;\n stderr(text: string): void;\n now(): Date;\n locate: Locate;\n}\n\nexport async function runStudioCommand(argv: string[], io: StudioIo): Promise<number> {\n try {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, strict: true, options: {\n project: { type: 'string' }, json: { type: 'boolean' }, words: { type: 'string' }, page: { type: 'boolean' }, port: { type: 'string' },\n } });\n const [command, ...rest] = positionals;\n const root = path.resolve(values.project ?? '.');\n const expect = (n: number, usage: string) => { if (rest.length !== n) throw new Error(`Usage: ${usage}`); };\n if (command === 'start') {\n expect(1, 'yichus start \"DESCRIPTION\"');\n const result = recordStart(root, { description: rest[0]! }, CLI);\n if (!result.ok) throw new Error(result.error);\n io.stdout(`Recorded the description.\\n${pageNote(runningPageUrl(root), CLI)}\\nIf this replaces an app the person already has, run \\`yichus reference porting\\` first.\\nNext: yichus next\\n`);\n return 0;\n }\n if (command === 'name') {\n if (!rest.length || rest.length % 2) throw new Error('Usage: yichus name SUBJECT \"NAME\" [SUBJECT \"NAME\" ...]');\n const names = Object.fromEntries(rest.flatMap((s, i) => i % 2 ? [] : [[s, rest[i + 1]!]]));\n const result = recordNames(root, { names }, CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr(`Named ${Object.entries(names).map(([subject, name]) => `${subject} \"${name}\"`).join(', ')}. Next: yichus next\\n`);\n return 0;\n }\n if (command === 'answer') {\n expect(2, 'yichus answer QUESTION CHOICE [--words TEXT]');\n const [question, choice] = rest as [string, string];\n const result = recordAnswer(root, { question, choice, words: values.words ?? '' }, io.now(), CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr(`Recorded ${choice} for ${question}. Next: yichus next\\n`);\n return 0;\n }\n if (command === 'rules') {\n expect(1, 'yichus rules FILE.json');\n const result = recordRules(root, JSON.parse(fs.readFileSync(path.resolve(rest[0]!), 'utf8')), CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr('Recorded the rules. Next: yichus next\\n');\n return 0;\n }\n if (command === 'scenario') {\n expect(1, 'yichus scenario FILE.json');\n const result = recordScenarios(root, JSON.parse(fs.readFileSync(path.resolve(rest[0]!), 'utf8')), CLI);\n if (!result.ok) throw new Error(result.error);\n io.stderr('Recorded the scenarios. Next: yichus next\\n');\n return 0;\n }\n if (command === 'point') {\n expect(1, 'yichus point FILE.json');\n const result = recordMarks(root, JSON.parse(fs.readFileSync(path.resolve(rest[0]!), 'utf8')), io.now());\n if (!result.ok) throw new Error(result.error);\n io.stderr('The page shows the notes now.\\n');\n return 0;\n }\n if (command === 'page') {\n expect(0, 'yichus page');\n io.stdout(pageText(root, runningPageUrl(root), io.now(), CLI));\n return 0;\n }\n if (command === 'reference') {\n if (rest.length > 1) throw new Error('Usage: yichus reference [TOPIC]');\n const list = topicList(topic => `yichus reference ${topic}`);\n if (!rest.length) { io.stdout(`${list}\\n`); return 0; }\n const said = readReference(rest[0]!, io.locate);\n if (!said) throw new Error(`No reference topic ${rest[0]!}.\\n${list}`);\n io.stdout(`${CLI_LEGEND}\\n\\n${said}\\n`);\n return 0;\n }\n if (command === 'next') {\n expect(0, 'yichus next [--json]');\n const state = await direct({ root, engine: await io.engine(), requirements: loadRequirements(root), previous: readState(root), say: CLI });\n io.stdout(values.json ? `${JSON.stringify(state, null, 2)}\\n` : stepText(state, runningPageUrl(root)));\n return 0;\n }\n expect(0, 'yichus studio [--page] [--port N]');\n const port = values.port === undefined ? null : Number(values.port);\n if (port !== null && (!Number.isInteger(port) || port < 0 || port > 65535)) throw new Error('--port must be a port number');\n await io.serve({ root, port, pageOnly: values.page ?? false });\n return 0;\n } catch (error) {\n io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}\\n`);\n return 2;\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { buildSystemMap } from '../../../../web/system-map-record.js';\nimport { nameableParts } from '../../../../web/system-map-names.js';\nimport { buildWhatHappens } from '../../../../web/what-happens-record.js';\nimport { type SourceFile, caseSources, projectSources, sourcesHash } from './project.js';\nimport { ACCESS_RULES, HOST_SECTION, PAGE_ONLY, PLATFORM_SECTION, type Question, Report, Structure, hostQuestion, platform, questionsFor } from './questions.js';\nimport { type Answer, type Requirements, ensureStudioDir, studioDir } from './requirements.js';\nimport { WhatHappens, owed, replies, unfollowed } from './scenarios.js';\nimport { MCP, type Say } from './surface.js';\n\n// The director: from the program on disk, the person's answers and the\n// engine's verdicts, the one next step for the agent. Every status here is\n// copied from an engine result; the director only decides what to do next.\n\nexport interface StudioEngine {\n call(tool: string, args: Record<string, unknown>): Promise<Record<string, unknown>>;\n}\n\nexport type Status =\n | 'unanswered' | 'decided' | 'assumed' | 'proven' | 'bounded'\n | 'broken' | 'mismatch' | 'needs-case' | 'needs-law' | 'unused' | 'inconclusive' | 'no-check';\n\nexport interface Property {\n question: Question;\n answer: Answer | null;\n status: Status;\n /** Engine output that backs the status, verbatim. */\n evidence: string[];\n /** The engine check the status comes from. */\n check: string | null;\n /** For a failure question: the protocol case file, from the project folder. */\n casePath?: string;\n}\n\n/** One law the program declares (Yichus/Law), as api_law_check found it. */\nexport interface Law {\n /** The binding that declares it, Package::name. */\n binding: string;\n /** The law's own name, when the check could read it. */\n name: string | null;\n status: 'proven' | 'bounded' | 'broken' | 'inconclusive';\n /** The app's actions that call what the law checks; null when the app\n * has no actions to compare with. */\n usedBy: string[] | null;\n evidence: string[];\n}\n\n/** A rule the person stated, in their words, with the laws that check it. */\nexport interface Rule {\n rule: string;\n laws: string[];\n status: Status;\n evidence: string[];\n}\n\nexport type Stage = 'describe' | 'write' | 'fix-compile' | 'rules' | 'name' | 'ask' | 'declare' | 'fix' | 'scenarios' | 'write-case' | 'done';\nexport interface Step {\n stage: Stage;\n /** One sentence the page shows the person. */\n summary: string;\n /** What the agent does now, in order. */\n instructions: string[];\n /** What the instructions work through, one per line, apart from them. */\n items?: { heading: string; lines: string[] };\n ask?: Array<{ id: string; ask: string; why: string; choices: Question['choices'] }>;\n evidence?: string[];\n}\n\n// A warning with an accepted field is safe under an assumption the person\n// declared (one server); any other warning is not.\nconst VerifyProperty = z.looseObject({ id: z.string(), title: z.string(), status: z.string(), details: z.array(z.string()).default([]),\n accepted: z.unknown().optional() });\nconst Verify = z.looseObject({\n topology: z.string().optional(),\n verdict: z.looseObject({ proven: z.boolean(), properties: z.array(VerifyProperty) }),\n});\ntype VerifyProperty = z.infer<typeof VerifyProperty>;\nconst Protocol = z.looseObject({ protocol: z.looseObject({ status: z.string(), name: z.string().optional() }).optional(), error: z.string().optional() });\n// api_law_check: each obligation's verdict. With no laws declared, a\n// sampled check answers ok with no laws record.\n// An exhaustive row's scope says what \"every input\" covered: the input\n// type's every value, or only the values a FiniteObligation lists.\nconst LawRow = z.looseObject({ binding: z.string(), law: z.string().nullable().optional(), verdict: z.string(), complete: z.boolean().optional(),\n scope: z.looseObject({ kind: z.string() }).optional(),\n detail: z.string().optional(), reason: z.string().optional(), counterexample: z.string().optional() });\n// reach: for each law, the routes that call what it checks; absent when\n// the program declares no route.\nconst LawCheck = z.looseObject({ laws: z.looseObject({ obligations: z.array(LawRow) }).optional(), notSampled: z.array(z.looseObject({ binding: z.string() })).optional(),\n reach: z.array(z.looseObject({ binding: z.string(), usedBy: z.array(z.string()) })).optional() });\ntype Reach = Map<string, string[]>;\ntype LawRow = z.infer<typeof LawRow>;\n// What one mode of the law check answered.\ntype LawAnswer = { kind: 'rows'; rows: LawRow[]; reach: Reach | null } | { kind: 'refused'; reason: string };\n\nexport interface StudioState {\n schemaVersion: 'yichus-studio-state-1';\n project: string;\n updatedAt: string;\n sourcesHash: string;\n files: string[];\n description: string | null;\n names: Record<string, string>;\n topology: string | null;\n proven: boolean | null;\n properties: Property[];\n /** Verify properties no question covers that are not proven. */\n other: Array<{ id: string; title: string; status: string; details: string[] }>;\n /** Every law the program declares, checked. */\n laws: Law[];\n lawsError: string | null;\n /** Whether the agent has listed the rules the person stated (an empty\n * list says they stated none). */\n rulesListed: boolean;\n rules: Rule[];\n step: Step;\n map: unknown;\n mapError: string | null;\n /** api_organize lens=layers, for the layer stack. */\n layers: unknown;\n /** Whether the program has actions people call (it declares routes), or\n * null before it compiles; a calculation has none, so nothing is\n * followed through. */\n hasActions: boolean | null;\n /** Each action's decision tree with the scenarios checked on it\n * (web/what-happens-record.js). */\n whatHappens: WhatHappens | null;\n whatHappensError: string | null;\n}\n\n/** The protocol case file for a question, written by the agent. */\nexport const caseFile = (root: string, questionId: string) =>\n path.join(studioDir(root), 'cases', `${questionId.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '')}.json`);\n\nconst answerOf = (requirements: Requirements, id: string) => requirements.answers.find(a => a.question === id) ?? null;\n\nfunction instancesFor(requirements: Requirements): string | undefined {\n const choice = answerOf(requirements, 'topology')?.choice;\n return choice === 'one' ? '1' : choice === 'many' ? 'many' : undefined;\n}\n\n// The engine answers ok:false when it could not run a tool; that is never a verdict.\nasync function call(engine: StudioEngine, tool: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {\n const result = await engine.call(tool, args);\n if (result.ok !== true) throw new Error(`${tool} failed: ${typeof result.error === 'string' ? result.error : 'no reason given'}`);\n return result;\n}\n\nconst isAccepted = (p: VerifyProperty) => p.status === 'warning' && p.accepted !== undefined;\n// The table a race-free finding is about: \"race-free:books: ...\".\nconst raceCell = (detail: string) => /^race-free:([^:\\s]+):/.exec(detail)?.[1] ?? null;\n\nconst worst = (props: VerifyProperty[]): VerifyProperty | undefined =>\n props.find(p => p.status !== 'proven' && !isAccepted(p)) ?? props.find(isAccepted);\n\nasync function judge(root: string, engine: StudioEngine, sources: SourceFile[], question: Question, saved: Answer | null,\n report: Report, verify: VerifyProperty[], together: Set<string> = new Set()): Promise<Property> {\n // A saved choice the question no longer offers is no answer: the question is asked again.\n const answer = saved && question.choices.some(c => c.id === saved.choice) ? saved : null;\n const base = { question, answer, evidence: [] as string[], check: null as string | null };\n if (!answer) return { ...base, status: 'unanswered' };\n const byId = (id: string) => verify.find(p => p.id === id);\n switch (question.kind) {\n case 'platform':\n case 'host':\n case 'sign-in':\n case 'data':\n return { ...base, status: 'decided' };\n case 'topology':\n return { ...base, status: answer.choice === 'one' ? 'assumed' : 'decided',\n evidence: answer.choice === 'one' ? ['Every check below assumes exactly one copy of the server runs.'] : [] };\n case 'access': {\n const table = report.dataModel.tables.find(t => t.name === question.subject);\n const rule = ACCESS_RULES[answer.choice]!;\n const access = table?.access ?? null;\n const check = 'api_report dataModel.tables[].access';\n if (!access || !rule.declared(access)) {\n return { ...base, status: 'mismatch', check,\n evidence: [`\"${question.subject}\" is declared ${table?.policy ?? 'with no rule'}; the person chose ${rule.write}.`] };\n }\n // Only worker routes are the app's own server: a role a person holds is still a person.\n const personal = answer.choice === 'server-only'\n ? report.surface.routes.filter(r => r.tables.includes(question.subject!) && r.authority !== 'requires-worker') : [];\n if (personal.length) {\n return { ...base, status: 'mismatch', check: 'api_report surface.routes[].authority',\n 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.`) };\n }\n const prop = byId(`access:${question.subject}`) ?? byId('access-coverage');\n if (!prop) return { ...base, status: 'inconclusive', check: 'api_verify', evidence: ['api_verify reported no access property for this table.'] };\n return { ...base, check: `api_verify ${prop.id}`, evidence: prop.details,\n status: prop.status === 'proven' ? 'proven' : 'broken' };\n }\n case 'together': {\n // A race the engine names on another table that has its own question\n // is that question's, not this one's.\n const elsewhere = (p: VerifyProperty) => p.details.length > 0 && p.details.every(d => {\n const cell = raceCell(d);\n return cell !== null && cell !== question.subject && together.has(cell);\n });\n const props = verify.filter(p => (p.id === 'rmw-transactions' || p.id === 'integrity') && !elsewhere(p));\n const bad = worst(props);\n const mentions = (p: VerifyProperty) => p.details.filter(d => d.includes(`\"${question.subject}\"`) || raceCell(d) === question.subject);\n const evidence = props.flatMap(p => mentions(p).length ? mentions(p) : p.status === 'proven' ? [] : p.details);\n const check = `api_verify ${props.map(p => p.id).join(' + ')}`;\n if (!bad) return { ...base, check, evidence, status: props.length ? 'proven' : 'inconclusive' };\n return { ...base, check, evidence, status: isAccepted(bad) ? 'assumed' : 'broken' };\n }\n case 'partial':\n case 'outside': {\n if (answer.choice === 'partial-ok' || answer.choice === 'no-plan') return { ...base, status: 'no-check' };\n const file = caseFile(root, question.id);\n const rel = path.relative(root, file).split(path.sep).join('/');\n if (!fs.existsSync(file)) return { ...base, casePath: rel, status: 'needs-case', check: 'api_protocol_check', evidence: [`No protocol case at ${rel} yet.`] };\n let protocolCase: unknown;\n try { protocolCase = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (error) {\n return { ...base, casePath: rel, check: 'api_protocol_check', status: 'inconclusive',\n evidence: [`${rel} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`] };\n }\n const result = Protocol.parse(await engine.call('api_protocol_check', { sources: [...sources, ...caseSources(root)], case: protocolCase }));\n const status = result.protocol?.status;\n const check = `api_protocol_check ${rel}`;\n if (!status) return { ...base, casePath: rel, check, status: 'inconclusive', evidence: [result.error ?? 'The protocol check gave no status.'] };\n // A holds verdict covers the finite case only, never every input.\n return { ...base, casePath: rel, check, evidence: [`${result.protocol?.name ?? rel}: ${status}`],\n status: status === 'holds' ? 'bounded' : status === 'violated' ? 'broken' : 'inconclusive' };\n }\n }\n}\n\nconst reason = (result: Record<string, unknown>) => typeof result.error === 'string' ? result.error : 'no reason given';\n\n/** Every law the program declares, checked both ways the engine can: over\n * seeded inputs, and over every input where the domain is finite. A\n * sampled check leaves each FiniteObligation to the exhaustive one. */\nasync function checkLaws(engine: StudioEngine, sources: SourceFile[]): Promise<{ laws: Law[]; error: string | null }> {\n const answer = async (mode: 'sampled' | 'exhaustive'): Promise<{ answer: LawAnswer; finite: string[] }> => {\n const result = await engine.call('api_law_check', { sources, ...(mode === 'exhaustive' ? { mode } : {}) });\n if (result.ok !== true) return { answer: { kind: 'refused', reason: reason(result) }, finite: [] };\n const parsed = LawCheck.parse(result);\n const reach = parsed.reach ? new Map(parsed.reach.map(r => [r.binding, r.usedBy])) : null;\n return { answer: { kind: 'rows', rows: parsed.laws?.obligations ?? [], reach }, finite: (parsed.notSampled ?? []).map(n => n.binding) };\n };\n const sampled = await answer('sampled');\n // No law of either kind: nothing to check.\n if (sampled.answer.kind === 'rows' && !sampled.answer.rows.length && !sampled.finite.length) return { laws: [], error: null };\n const { answer: exhaustive } = await answer('exhaustive');\n if (sampled.answer.kind === 'refused' && exhaustive.kind === 'refused')\n return { laws: [], error: `api_law_check failed: ${sampled.answer.reason}; exhaustive: ${exhaustive.reason}` };\n const rowsOf = (a: LawAnswer) => a.kind === 'rows' ? a.rows : [];\n const reach = [sampled.answer, exhaustive].flatMap(a => a.kind === 'rows' && a.reach ? [a.reach] : [])[0] ?? null;\n // A law the sampled check left to the exhaustive one stays listed even when that check is refused.\n const bindings = [...new Set([...rowsOf(sampled.answer).map(r => r.binding), ...sampled.finite, ...rowsOf(exhaustive).map(r => r.binding)])];\n return { error: null, laws: bindings.map(binding => {\n const s = rowsOf(sampled.answer).find(r => r.binding === binding);\n const e = rowsOf(exhaustive).find(r => r.binding === binding);\n const listed = e?.scope !== undefined && e.scope.kind !== 'type-wide';\n const said = (mode: string, r: LawRow) =>\n `${mode}: ${r.verdict}${r.detail ? `; ${r.detail}` : ''}${r.reason ? `; ${r.reason}` : ''}${r.counterexample ? `; counterexample ${r.counterexample}` : ''}`;\n const evidence = [\n ...s ? [said('sampled', s)] : [],\n ...!s && sampled.answer.kind === 'refused' ? [`sampled: refused; ${sampled.answer.reason}`] : [],\n ...!s && sampled.finite.includes(binding) ? ['sampled: left to the check over its listed inputs'] : [],\n ...!e && exhaustive.kind === 'refused' ? [`every input: refused; ${exhaustive.reason}`] : [],\n ...e ? [said(listed ? 'only the listed inputs' : 'every input', e)] : []];\n const name = s?.law ?? e?.law ?? null;\n const usedBy = reach?.get(binding) ?? null;\n if (usedBy && !usedBy.length) evidence.push('used by: no action of the app reaches what its check calls');\n // Only a pass over every value of the input type is a proof; a pass\n // over listed inputs says nothing about the rest.\n const status: Law['status'] = s?.verdict === 'violated' || e?.verdict === 'violated' ? 'broken'\n : e?.verdict === 'holds-exhaustive' ? (e.complete && e.scope?.kind === 'type-wide' ? 'proven' : 'bounded')\n : s?.verdict === 'holds' ? 'bounded' : 'inconclusive';\n return { binding, name, status, usedBy, evidence };\n }) };\n}\n\n/** A law a rule names: by its binding, the binding's own name, or the law's name. */\nconst lawNamed = (laws: Law[], ref: string) => laws.find(l => l.binding === ref || l.binding.endsWith(`::${ref}`) || l.name === ref);\n\n/** A law whose check calls nothing an action reaches says nothing about the app. */\nconst unused = (law: Law) => law.usedBy !== null && !law.usedBy.length;\n\n/** A rule holds as well as its weakest law. */\nfunction judgeRule(rule: { rule: string; laws: string[] }, laws: Law[]): Rule {\n const found = rule.laws.map(ref => [ref, lawNamed(laws, ref)] as const);\n const missing = found.filter(([, law]) => !law).map(([ref]) => ref);\n const checked = found.flatMap(([, law]) => law ? [law] : []);\n const evidence = [...missing.map(ref => `No law named ${ref} in the program.`), ...checked.flatMap(l => l.evidence.map(e => `${l.name ?? l.binding}: ${e}`))];\n const status: Status = missing.length || !checked.length ? 'needs-law'\n : checked.some(l => l.status === 'broken') ? 'broken'\n : checked.some(l => l.status === 'inconclusive') ? 'inconclusive'\n : checked.some(unused) ? 'unused'\n : checked.every(l => l.status === 'proven') ? 'proven' : 'bounded';\n return { ...rule, status, evidence };\n}\n\nconst 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.';\n\nconst QUESTION_PROPERTIES = (id: string) => id.startsWith('access:') || id === 'access-coverage' || id === 'rmw-transactions' || id === 'integrity';\n\nconst GUIDE: Partial<Record<Question['kind'], string>> = {\n access: 'Owner-scoped data',\n together: 'Atomic commands with Yichus/Transaction',\n partial: 'Transaction protocols: finite cases, retries, and receipts',\n outside: 'Transaction protocols: finite cases, retries, and receipts',\n};\n\n// What api_scaffold takes, so the step can be followed without its schema;\n// a policy is owner or public.\nexport const SCAFFOLD_ARGS = { package_name: 'My/App/Api', service_name: 'my_app',\n resources: [{ name: 'record', fields: [{ name: 'title', type: 'String' }], policy: 'owner' }] };\n\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;\nconst capital = (s: string) => `${s[0]!.toUpperCase()}${s.slice(1)}`;\n\nconst askStep = (open: Property[], say: Say): Step => ({\n stage: 'ask',\n summary: `${plural(open.length, 'question', 'questions')} for you about how the app should behave.`,\n instructions: [\n 'Ask the person each question below, in its words, with its choices. They may also answer on the studio page.',\n 'Speak in product terms: never quote question ids, code names, file names, tool names or the programming language to the person.',\n '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.',\n `Record each answer: ${say.use('yichus_answer')} with the question id, the choice id, and their own words. Then ${say.use('yichus_next')}.`,\n ],\n ask: open.map(p => ({ id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices })),\n});\n\n/** Where the app's pieces run: the platform's section of the deploy\n * reference, and the server host's when the platform holds only pages.\n * None for a program with no server, which is never asked. */\nfunction deploySections(state: Omit<StudioState, 'step'>): string[] {\n const choice = (kind: Question['kind']) => state.properties.find(p => p.question.kind === kind)?.answer?.choice;\n const where = choice('platform');\n if (!where) return [];\n const host = choice('host');\n return host ? [PLATFORM_SECTION[where]!, HOST_SECTION[host]!] : [PLATFORM_SECTION[where]!];\n}\nconst sectionsText = (sections: string[]) => sections.map(s => `\"${s}\"`).join(' and ');\n\nexport function nextStep(state: Omit<StudioState, 'step'>, compileErrors: string[] | null, say: Say = MCP): Step {\n const next = `Then ${say.use('yichus_next')}.`;\n if (!state.description) return {\n stage: 'describe',\n summary: 'Waiting for a description of what to build.',\n instructions: [`Ask the person what they want to build, in their own words. ${capital(say.use('yichus_start'))} with their description, unchanged.`],\n };\n const sections = deploySections(state);\n if (!state.files.length) return {\n stage: 'write',\n summary: 'No program yet.',\n instructions: [\n `If this replaces an app the person already has, ${say.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.`,\n '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.',\n `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 ${say.reference('deploy')} then says how to put it online.`,\n `${capital(say.api('api_guide', { section: 'Required workflow' }))}, then write the program as .bosatsu files in this project folder.`,\n `For an app that stores records, ${say.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.`,\n `Shape the records to the people in the description before you show anything. The scaffold's owner and public records are only a start.`,\n '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.',\n `Records other people must see (a coordinator who sees every sign-up) need a rule that lets them in, not owner-only. ${capital(say.api('api_guide', { section: 'Guarded data' }))} for how to write one with roles.`,\n '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.',\n `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: ${say.reference('portable-programs')} before writing it.`,\n `Write each rule the person states about what the app must always or never do as a law: ${say.reference('laws')} for the syntax, the standard functions and a worked example.`,\n '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.',\n next,\n ],\n };\n if (compileErrors) return {\n stage: 'fix-compile',\n summary: 'The program does not compile yet.',\n instructions: [`Fix these compile errors in the files. ${next}`, `For the standard functions the language has, ${say.reference('laws')}.`],\n evidence: compileErrors,\n };\n if (!state.rulesListed) return {\n stage: 'rules',\n summary: 'Your agent is writing down the rules you gave for your app, so each one is checked.',\n instructions: [\n '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\").',\n `Write a law for each rule in a .bosatsu file of the app (${say.reference('laws')} for the syntax, the standard functions and a worked example). A law states the rule, never what the code happens to do.`,\n `${capital(say.use('yichus_next'))} so the studio finds the laws you wrote, then record the rules with the laws that check each: ${say.useWith('yichus_rules', '{\"rules\": [{\"rule\": their words, \"laws\": [law names]}]}')}. If they stated no rule, record an empty list.`,\n '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.',\n next,\n ],\n ...state.laws.length ? { items: { heading: 'Laws the program has', lines: state.laws.map(l => `${l.binding}${l.name ? ` (\"${l.name}\")` : ''}: ${l.status}`) } } : {},\n };\n // Questions name their subjects, the picture draws every part, and the\n // page says what each action answers.\n const unnamed = new Map<string, string[]>();\n for (const { question } of state.properties) {\n if (question.subject !== null && !(question.subject in state.names)) unnamed.set(question.subject, [...unnamed.get(question.subject) ?? [], question.fact]);\n }\n for (const { code, what } of drawnParts(state)) {\n if (!(code in state.names) && !unnamed.has(code)) unnamed.set(code, [`${capital(what)}.`]);\n }\n if (unnamed.size) return {\n stage: 'name',\n summary: 'Your agent is putting the parts of your app into plain words.',\n instructions: [\n '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\").',\n `${capital(say.use('yichus_name'))} with all of them at once. ${next}`,\n ],\n items: { heading: 'Parts to name', lines: [...unnamed].map(([subject, facts]) => `${subject}: ${facts.join(' ')}`) },\n };\n const unanswered = state.properties.filter(p => p.status === 'unanswered');\n if (unanswered.length) return askStep(unanswered, say);\n const mismatched = state.properties.filter(p => p.status === 'mismatch');\n if (mismatched.length) return {\n stage: 'declare',\n summary: 'The program\\'s declared rules do not match what you chose yet.',\n instructions: [\n ...mismatched.map(p => {\n const rule = ACCESS_RULES[p.answer!.choice]!;\n return `Make the AccessSpec rule for \"${p.question.subject}\" ${rule.write}${p.answer!.choice === 'server-only' ? ', and reach it only from worker routes' : ''} (${say.api('api_add_rule')} for the snippet; ${say.api('api_guide', { section: rule.guide })} for what it means).`;\n }),\n next,\n ],\n evidence: mismatched.flatMap(p => p.evidence),\n };\n // A broken property comes before describing what happens: an action that\n // leaks records is fixed, not described.\n const broken = state.properties.filter(p => p.status === 'broken' || p.status === 'inconclusive');\n const failing = state.other.filter(o => o.status !== 'warning');\n const warnings = state.other.filter(o => o.status === 'warning');\n const brokenRules = state.rules.filter(r => r.status !== 'proven' && r.status !== 'bounded');\n const ruled = new Set(state.rules.flatMap(r => r.laws.flatMap(ref => lawNamed(state.laws, ref)?.binding ?? [])));\n const brokenLaws = state.laws.filter(l => !ruled.has(l.binding) && (l.status === 'broken' || l.status === 'inconclusive' || unused(l)));\n const notHolding = broken.length + failing.length + brokenRules.length + brokenLaws.length + (state.lawsError ? 1 : 0);\n if (notHolding || warnings.length) return {\n stage: 'fix',\n summary: [notHolding ? `${notHolding === 1 ? '1 property is' : `${notHolding} properties are`} not holding yet.` : '',\n warnings.length ? `${plural(warnings.length, 'warning needs', 'warnings need')} a look.` : ''].filter(Boolean).join(' '),\n instructions: [\n 'Fix the program so each property below holds. The evidence lines are the engine\\'s own words.',\n ...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(say.api('api_guide', { section: GUIDE[p.question.kind]! }))} for how.` : ''}`),\n ...failing.map(o => `${o.title} (${o.id}) is ${o.status}.`),\n ...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.`),\n ...brokenRules.map(r => r.status === 'needs-law'\n ? `The person's rule \"${r.rule}\" has no law in the program that checks it. Write one (${say.reference('laws')} for how), then record the rules again with ${say.name('yichus_rules')}.`\n : 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}`\n : `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.`),\n ...brokenLaws.map(l => `The law ${l.name ? `\"${l.name}\" (${l.binding})` : l.binding} ${l.status === 'broken' ? 'is broken. Change the code, never the law.'\n : l.status === 'inconclusive' ? 'is not decided. Change the code, never the law.' : `checks code no action of the app reaches. ${USE_THE_LAW}`}`),\n ...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.'] : [],\n `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}`,\n ],\n evidence: [...broken.flatMap(p => p.evidence), ...state.other.flatMap(o => o.details), ...brokenRules.flatMap(r => r.evidence),\n ...brokenLaws.flatMap(l => l.evidence), ...state.lawsError ? [state.lawsError] : []],\n };\n const scenarios = state.whatHappens;\n const owes = scenarios ? owed(scenarios) : [];\n if (scenarios && (owes.length || scenarios.refused.length || scenarios.notes.length || scenarios.mismatches.length)) return {\n stage: 'scenarios',\n summary: 'Your agent is writing down, in your words, what should happen in each thing your app does.',\n instructions: [\n `Write down what should happen in each action listed below, as the person would say it, and ${say.use('yichus_scenario')} with all of them at once. For each action give:`,\n 'title: what the person does (\"You add a note\").',\n '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\").',\n '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.',\n '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.',\n ...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.'] : [],\n ...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.'] : [],\n next,\n ],\n ...owes.length ? { items: { heading: 'Actions to describe', lines: owes.flatMap(o => [\n `${o.entry}${o.undescribed ? ' (not described yet)' : ''}:`,\n ...o.unnamed.map(u => ` ${u.id}: ${u.what}`),\n ...o.uncovered.length ? [` outcomes no claim covers: ${o.uncovered.join(', ')}`] : [],\n ]) } } : {},\n evidence: [\n ...scenarios.refused.map(r => `${r.entry}: \"${r.words}\" at ${r.id} was refused: ${r.reason}`),\n ...scenarios.notes.map(n => `${n.entry}: \"${n.text}\" at ${n.at} is not a claim`),\n ...scenarios.mismatches.map(m => `${m.entry}: ${m.reason}`),\n ],\n };\n const claims = (scenarios?.claims ?? []).filter(c => c.verdict !== 'holds');\n // Scenarios that could not be checked never count as holding.\n const unfollowedEntries = scenarios ? unfollowed(scenarios) : [];\n const open = claims.length + (state.whatHappensError ? 1 : 0) + unfollowedEntries.length;\n if (open) return {\n stage: 'fix',\n summary: `${open === 1 ? '1 property is' : `${open} properties are`} not holding yet.`,\n instructions: [\n 'Fix the program so each property below holds. The evidence lines are the engine\\'s own words.',\n ...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.`),\n ...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.'] : [],\n ...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.'] : [],\n `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}`,\n ],\n evidence: [...claims.map(c => `${c.entry} at ${c.at}: ${c.parsed}: ${c.verdict}`), ...state.whatHappensError ? [state.whatHappensError] : [],\n ...unfollowedEntries.map(u => `${u.entry} could not be followed: ${u.why}`)],\n };\n const cases = state.properties.filter(p => p.status === 'needs-case');\n if (cases.length) return {\n stage: 'write-case',\n summary: 'Writing the failure scenarios that test your answers.',\n instructions: [\n `${capital(say.reference('protocol-case'))}: it gives the case specification and a complete worked case with its program.`,\n '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.',\n ...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.`),\n `State the person's rule exactly; never weaken it to match the code. ${next}`,\n ],\n };\n const assumed = state.properties.filter(p => p.status === 'assumed');\n const data = state.properties.find(p => p.question.kind === 'data')?.answer?.choice;\n return {\n stage: 'done',\n summary: assumed.length ? 'Everything you chose holds, under the assumptions shown.' : 'Everything you chose holds.',\n instructions: [\n 'Tell the person every property they chose holds, and point them at the studio page for the evidence.',\n ...(assumed.length ? ['Say plainly which results depend on running exactly one server.'] : []),\n ...(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(say.reference('porting'))} says how to bring the data over.`] : []),\n `When they describe a new feature, change the code and ${say.use('yichus_next')} again: new facts can raise new questions.`,\n sections.length\n ? `When they want the app online, follow the ${sectionsText(sections)} section${sections.length === 1 ? '' : 's'} of the deploy reference (${say.reference('deploy')}), and ${say.api('api_deploy')} to generate the server.`\n : `The program keeps no records and has no actions people call, so it needs no server. When they want it on a page, ${say.reference('calculator')}.`,\n ],\n };\n}\n\n/** Every part the person sees that wants a plain name, besides question\n * subjects: what the pictures draw from the program's own packages (the\n * library's parts are not the person's), and the answers its actions give. */\nexport function drawnParts(state: Pick<StudioState, 'map' | 'layers' | 'whatHappens'>): Array<{ code: string; what: string }> {\n return [...state.map ? nameableParts(state.map, ownPackages(state.layers)) : [],\n ...(state.whatHappens ? replies(state.whatHappens) : []).map(code => ({ code, what: 'an answer the app gives' }))];\n}\n\n/** The packages the program's own files declare, from the layers lens. */\nexport function ownPackages(layers: unknown): Set<string> | undefined {\n const parsed = z.looseObject({ layers: z.looseObject({ packages: z.array(z.looseObject({ name: z.string() })) }) }).safeParse(layers);\n return parsed.success ? new Set(parsed.data.layers.packages.map(p => p.name)) : undefined;\n}\n\n/** A program with records or actions people call runs as a server; any\n * other is a calculation, which needs none. */\nconst serves = (report: Report) => report.surface.routes.length > 0 || report.dataModel.tables.length > 0;\n\nexport interface RunOptions { root: string; engine: StudioEngine; requirements: Requirements; withMap?: boolean; previous?: StudioState | null; say?: Say }\n\n/** Read the program, run the checks, decide the next step, and write\n * .yichus/state.json for the page. */\nexport async function direct({ root, engine, requirements, withMap = true, previous = null, say = MCP }: RunOptions): Promise<StudioState> {\n const sources = projectSources(root);\n const hash = sourcesHash(sources);\n const instances = instancesFor(requirements);\n const base = {\n schemaVersion: 'yichus-studio-state-1' as const,\n project: path.basename(path.resolve(root)),\n updatedAt: new Date().toISOString(),\n sourcesHash: hash,\n files: sources.map(s => s.fileName),\n description: requirements.description,\n names: requirements.names ?? {},\n topology: null as string | null,\n proven: null as boolean | null,\n properties: [] as Property[],\n other: [] as StudioState['other'],\n laws: [] as Law[],\n lawsError: null as string | null,\n rulesListed: requirements.rules !== undefined,\n rules: [] as Rule[],\n map: null as unknown,\n mapError: null as string | null,\n layers: null as unknown,\n hasActions: null as boolean | null,\n whatHappens: null as WhatHappens | null,\n whatHappensError: null as string | null,\n };\n let compileErrors: string[] | null = null;\n if (requirements.description && sources.length) {\n const verify = Verify.parse(await call(engine, 'api_verify', { sources, ...(instances ? { instances } : {}) }));\n base.topology = verify.topology ?? null;\n base.proven = verify.verdict.proven;\n const compiles = verify.verdict.properties.find(p => p.id === 'compiles');\n if (compiles && compiles.status !== 'proven') compileErrors = compiles.details;\n else {\n const report = Report.parse(await call(engine, 'api_report', { sources }));\n // With the requirements, the lens also computes each entry's decision\n // tree and checks the scenarios on it.\n const structureRaw = await call(engine, 'api_organize', { sources, lens: 'structure', requirements });\n const structure = Structure.parse(structureRaw);\n const questions = questionsFor(report, structure, base.names);\n // Only a program with records or actions people call runs as a server, and the\n // program is the same wherever it runs, so where is asked with the\n // other questions and never holds up a check.\n if (serves(report)) {\n questions.push(platform);\n const where = answerOf(requirements, platform.id)?.choice;\n if (where && PAGE_ONLY.has(where)) questions.push(hostQuestion(platform.choices.find(c => c.id === where)!.label));\n }\n const together = new Set(questions.filter(q => q.kind === 'together').map(q => q.subject!));\n for (const question of questions) {\n base.properties.push(await judge(root, engine, sources, question, answerOf(requirements, question.id), report, verify.verdict.properties, together));\n }\n // A calculation (no routes, no records) has no route to check: the\n // engine's route warnings then say only that, and are nothing to fix.\n const routeless = (p: VerifyProperty) => !serves(report) && p.status === 'warning' && p.id.startsWith('route-');\n base.other = verify.verdict.properties\n .filter(p => !QUESTION_PROPERTIES(p.id) && p.status !== 'proven' && !isAccepted(p) && !routeless(p))\n .map(({ id, title, status, details }) => ({ id, title, status, details }));\n const checked = await checkLaws(engine, sources);\n base.laws = checked.laws;\n base.lawsError = checked.error;\n base.rules = (requirements.rules ?? []).map(r => judgeRule(r, base.laws));\n // Without routes the engine enters a program at its exported\n // definitions; those are calculations, not actions a person takes.\n base.hasActions = report.surface.routes.length > 0;\n let access: Record<string, unknown> | null = null;\n // A program that lost all its actions still has the scenarios written\n // for them: the record keeps only those, reported as gone, so the\n // agent drops or moves them.\n if (base.hasActions || requirements.scenarios?.length) {\n try {\n access = await call(engine, 'api_access_check', { sources });\n const record = WhatHappens.parse(buildWhatHappens({ structure: structureRaw, access }, { program: base.project }));\n base.whatHappens = base.hasActions ? record : { ...record, entries: [], ghosts: [], claims: [], witnesses: [], refused: [], notes: [] };\n } catch (error) {\n base.whatHappensError = error instanceof Error ? error.message : String(error);\n }\n }\n if (withMap) {\n if (previous?.sourcesHash === hash && previous.map) { base.map = previous.map; base.layers = previous.layers ?? null; }\n else {\n try {\n const [abstractions, layers] = [\n await call(engine, 'api_organize', { sources, lens: 'abstractions' }),\n await call(engine, 'api_organize', { sources, lens: 'layers' }),\n ];\n base.map = buildSystemMap({ report: report as Record<string, unknown>, structure: structureRaw, abstractions, layers, ...(access ? { access } : {}) }, { program: base.project });\n base.layers = layers;\n } catch (error) {\n base.mapError = error instanceof Error ? error.message : String(error);\n }\n }\n }\n }\n }\n const state: StudioState = { ...base, step: nextStep(base, compileErrors, say) };\n writeState(root, state);\n return state;\n}\n\nexport function writeState(root: string, state: StudioState): void {\n ensureStudioDir(root);\n fs.writeFileSync(path.join(studioDir(root), 'state.json'), `${JSON.stringify(state, null, 2)}\\n`);\n}\n\nexport function readState(root: string): StudioState | null {\n const file = path.join(studioDir(root), 'state.json');\n return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) as StudioState : null;\n}\n","// The system map's record (schema system-map-2, marks yichus-marks-3), built\n// from the engine's own output. web/system-map.js draws this record and\n// nothing else; every field names the engine field it was copied or derived\n// from (`from`). scripts/diagram-examples.mjs records one per program.\n//\n// The record joins four engine calls by full id:\n// api_report headline.class, surface.routes\n// api_organize lens=structure entries, supply, ioKinds, ports, applied,\n// chains, keyed, generic, combinations, phases,\n// programs\n// api_organize lens=abstractions generators, instantiations, routeShapes\n// api_organize lens=layers packages and their exported definitions\n// A name is copied as a label and never decides anything.\n\nexport const MARKS_VERSION = 'yichus-marks-3';\n\n// Each mark, where it sits, and the record field that draws it. It travels\n// with every record so the file describes itself.\nexport const VOCABULARY = {\n version: MARKS_VERSION,\n fixedPlaces: {\n 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[]',\n openings: 'the left wall: one opening per entry <- entries[]',\n hullBand: 'the middle band of the wall: wrappers sit here and nowhere else; empty band = no entry goes through a shared wrapper <- wrappers[]',\n 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',\n replyBars: 'one bar per entry at the same x, past the hull band <- entries[]',\n 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]',\n rack: 'right of the wall: db, model, net, always in this order; struck = the engine checked and found none <- resources[], ghostResources[]',\n 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[]',\n 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[]',\n },\n marks: {\n entryHead: 'arrowhead at an opening; solid = the entry writes, hollow = it only reads <- entries[].writes',\n 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',\n role: 'red word beside the lock: a role beyond sign-in <- entries[].roles',\n limit: 'gauge beside the path: a declared rate limit <- entries[].limits',\n 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',\n modelRing: 'violet ring: the entry reaches the model <- entries[].model',\n 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',\n netRing: 'orange ring: the entry reaches the network <- entries[].net',\n guard: 'red diamond on the path where the route can refuse, the check named above it (the program\\u2019s definition it calls, \"<table> row found\", \"<table> row\\u2019s <field>\" for a branch on a field of a read row, or \"a test in <definition>\" for a comparison or library answer that definition branches on), failure stem below; a branch no path refuses on is not drawn here <- entries[].guards (structure.scenarios[]: branches where one arm ends only in refusals), wrappers[].guards, entries[].passed[].guards, entries[].beside.guards',\n policy: 'under the db, each table with its access policy as the access check proves it: own = each caller reads and writes only their own row; no row rule = the access check holds no rule over its rows, so who reads or writes which row is decided only by the code drawn on the routes; guarded = rows pass the named guard; role … only = only callers with that role reach its rows; unchecked = the access check gave this table no verdict; a policy ending \\u201cbroken\\u201d is one the code breaks, and \\u201cnot proven\\u201d one the check could not settle; counted when the tables are too many to list <- resources[kind=db].policies',\n 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[]',\n socket: 'broken-rim ring: a function the caller hands in runs here; its centre fills like a station <- entries[].passed[]',\n token: 'small grey word under a path: the value the caller fixes for the wrapper <- entries[].policy',\n afterDot: 'dot in the after band: a call the entry makes after its wrapper returns <- entries[].beside.calls',\n builder: 'plus-disc under a station with the call that builds the handle there <- uses[how=local].builtBy',\n 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]',\n fork: 'three prongs and a type: a choice keyed on a plain String or Int; under the mark that makes it (under a list of checks, named by the check it is inside: \"can_see on String\"), else on the quiet line <- keyed[]',\n bundle: 'one cable with how many routes it carries (\"4 routes\"): entries with the same wrapper and identical marks; its title names every route: by the one part of the path that differs, among at most six (\"/{tags, tasks}/sync\"), or each by name when there are at most four; else a pattern with *; opening it draws each one <- bundles[]',\n 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',\n 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[]',\n loop: 'loop arc with package names: packages whose types lead back to themselves <- phases.cycles',\n composes: 'hull round a chain: a definition takes the type the chain hands in at each step and applies it <- library.applied[].fedBy',\n port: 'plug strip on the right: a record of functions; each adapter a plug, hollow when nothing plugs it in <- library.ports[]',\n generic: 'the letter ∀ with its variables over a part that never looks inside what it carries <- library.generic[]',\n 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[]',\n decision: 'bar and number in the program: its decisions, on one scale shared with its engines\\' bars <- programs[].decisions',\n struck: 'on a program, a struck \"effects\": no definition in its package performs an effect <- programs[].beside = []',\n programEffect: 'red disc and count on a program: definitions in its own package that perform effects, named in its title <- programs[].beside[]',\n request: 'opening on the program\\'s right edge: a request constructor its step can return, with its payload\\'s types <- programs[].requests[]',\n variant: 'short opening under a request: a constructor of a user sum type its payload carries, with what the program calls it (\"BriefCase → 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[]',\n 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]',\n gap: 'struck opening: a request constructor no engine handles <- programs[].gaps[]',\n 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',\n 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 → 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',\n laneFork: 'bar and number on a lane: the engine\\'s decisions, on the program\\'s scale; 0 = a rule-free engine <- programs[].engines[].decisions',\n 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 … runs it\" naming the routes that run the rounds <- programs[].engines[].replies, loop, starters',\n replaced: 'a check named \"(in place of …)\": 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[]',\n },\n names: 'every check, call and table name is a label the code\\'s author (often an AI) chose; the picture proves where a check runs, what it is given and what happens when it fails, never what it decides: a reader who doubts the author reads that rule itself.',\n 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.',\n};\n\nconst bare = id => String(id).split('::').pop();\nconst pkgOf = id => String(id).split('::')[0];\nconst uniq = xs => [...new Set(xs)];\n\n// An engine effect step ({kind, op, tables, resource}) as the table ops a\n// station draws: reads, deletes, and every other database op as a write.\nconst OPS = { read: 'read', query: 'read', delete: 'delete' };\nexport function effectsOf(steps) {\n return (steps || []).filter(e => e.resource === 'db').flatMap(e => e.tables.map(table => ({ op: OPS[e.op] || 'write', table })));\n}\nconst isWrite = op => op !== 'read';\nconst uniqBy = (xs, key) => { const seen = new Set(); return xs.filter(x => !seen.has(key(x)) && seen.add(key(x))); };\n// The resource an engine effect reaches; the program runner's two kinds by name of kind.\nconst RUNNER = { CompileProgram: 'compile', RunProgram: 'run' };\nexport const effectResource = e => e.resource || RUNNER[e.kind] || 'io';\nconst LANE_RES = ['db', 'model', 'net', 'compile', 'run', 'io'];\nconst resOrder = rs => LANE_RES.filter(r => rs.includes(r));\n\n// Programs: a pure step whose result carries a request, the engines that\n// perform each request, and the requests no engine handles.\nexport function programsOf(st, layers = null) {\n const found = (st.programs && st.programs.programs) || [];\n // a package's own definitions, counted as the layers lens counts them\n const ownCount = pkg => { const lp = layers && layers.packages.find(x => x.name === pkg); return lp ? lp.definitions.length : null; };\n return found.map(p => {\n const engines = p.engines.map(e => {\n const resources = resOrder(uniq(e.handles.flatMap(h => h.effects.map(effectResource))));\n return {\n id: e.id, label: bare(e.id), pkg: pkgOf(e.id), pkgLabel: pkgOf(e.id).split('/').pop(),\n handles: e.handles.map(h => h.constructor),\n resources,\n // effects the engine performs that are no request's: drawn, not hidden\n also: resOrder(uniq((e.effects || []).map(effectResource))).filter(r => !resources.includes(r)),\n replies: resOrder(uniq(e.replies.map(effectResource))),\n decisions: +e.decisions, entries: e.entries, truncated: e.truncated,\n 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 },\n starters: (p.starters || []).filter(s => s.advances && s.via.some(v => v === e.id || e.entries.includes(s.entry))).map(s => s.entry),\n // what it does, from its type: the program's own and standard parameters, and what its effect yields; the whole type on hover\n type: { takes: e.labels.takes, returns: e.labels.returns, plainTakes: e.labels.plainTakes, yields: e.labels.yields,\n from: 'structure.programs.programs[].engines[].labels' },\n from: 'structure.programs.programs[].engines[]',\n }; });\n const requests = p.requests.map(q => ({\n constructor: q.constructor, fields: q.fields.map(f => f.label),\n variants: (q.variants || []).map(v => ({ path: v.path, type: bare(v.type), constructors: v.constructors,\n // what the program calls each kind: total matches onto plain constructors, the type's own package first\n namings: (v.namings || []).slice().sort((a, b) => (pkgOf(b.definition) === pkgOf(v.type)) - (pkgOf(a.definition) === pkgOf(v.type))).map(n => ({\n definition: n.definition, label: bare(n.definition), type: bare(n.type), names: n.names.map(x => ({ constructor: x.constructor, name: x.name })),\n from: 'structure.programs.programs[].requests[].variants[].namings[]' })),\n from: 'structure.programs.programs[].requests[].variants[]' })),\n handledBy: p.engines.filter(e => e.handles.some(h => h.constructor === q.constructor)).map(e => ({\n engine: e.id, resources: resOrder(uniq(e.handles.find(h => h.constructor === q.constructor).effects.map(effectResource))) })),\n gap: p.gaps.some(g => g.constructor === q.constructor),\n from: 'structure.programs.programs[].requests[] + engines[].handles[]',\n }));\n return {\n id: p.step, label: bare(p.step), pkg: p.package, pkgLabel: p.package.split('/').pop(),\n result: bare(p.result), requestType: bare(p.requestType), carrier: p.carrier,\n decisions: +p.decisions, finishes: p.finishes,\n // definitions: the package's own, as the layer stack counts them; reached: everything the program's definitions use\n definitions: ownCount(p.package) ?? +(p.ownDefinitions || 0), reached: p.definitions.length,\n // of what it reaches, the definitions that live in other packages\n usesElsewhere: p.definitions.filter(d => pkgOf(d) !== p.package).length,\n // and which packages those are, the most used first\n elsewhere: Object.entries(p.definitions.filter(d => pkgOf(d) !== p.package).reduce((m, d) => ({ ...m, [pkgOf(d)]: (m[pkgOf(d)] || 0) + 1 }), {}))\n .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[]' })),\n requests, engines,\n starters: (p.starters || []).map(s => ({ entry: s.entry, path: s.entry.replace(/^route:/, ''), advances: s.advances, via: s.via,\n from: 'structure.programs.programs[].starters[]' })),\n // routes that call the step and act on nothing it says: they read where the program is\n replays: (p.replays || []).map(s => ({ entry: s.entry, path: s.entry.replace(/^route:/, ''), via: s.via, from: 'structure.programs.programs[].replays[]' })),\n // what each reaches, as the structure lens's effect sites say (io when none is a resource)\n beside: (p.beside || []).map(b => ({ id: b.definition, label: bare(b.definition), kinds: b.kinds,\n resources: resOrder(uniq((st.ioKinds || []).filter(k => k.definition === b.definition).flatMap(k => k.resources))),\n from: 'structure.programs.programs[].beside[], structure.ioKinds[].resources' })),\n gaps: p.gaps.map(g => ({ constructor: g.constructor, from: 'structure.programs.programs[].gaps[]' })),\n from: 'structure.programs.programs[]',\n };\n });\n}\n\nconst outsideResourcesOf = steps => uniq((steps || []).map(e => e.resource).filter(r => r === 'model' || r === 'net'));\n\n// The branches of an entry's what-happens tree where a path can refuse:\n// one arm ends only in refusals and another does not (structure.scenarios[],\n// present when the structure lens is asked with requirements). The\n// platform's own sign-in or role check is the lock's, and its transaction's\n// busy or unconfirmed answers are the transaction's, not a branch here.\nconst leavesUnder = t => (t.kind === 'leaf' ? [t] : t.arms.flatMap(a => leavesUnder(a.next)));\nfunction refusingForks(tree) {\n const out = [];\n const go = t => {\n if (!t || t.kind !== 'node') return;\n const refused = t.arms.map(a => leavesUnder(a.next).every(l => l.outcome.kind === 'refused'));\n if (t.concern?.layer !== 'platform' && refused.some(Boolean) && !refused.every(Boolean)) out.push(t);\n t.arms.forEach(a => go(a.next));\n };\n go(tree);\n return out;\n}\n// a refusing branch by what it tests: the program's definition it calls, or the read whose row it needs;\n// a branch on a library's answer (a comparison, a platform helper) is a test the calling definition\n// writes, so it is named by that definition, the rule a reader would open\nconst forkId = (n, own) => (n.from.kind === 'call' && own.has(n.from.callee) ? n.from.callee : n.id);\n// what a check's label is made of, so each code name in it can be named: the definition it names, or the table and field it reads\nconst forkParts = (n, own) => (n.from.kind === 'call' && own.has(n.from.callee) ? { definition: n.from.callee }\n : n.from.kind === 'read' && n.from.table ? { table: n.from.table, ...(n.from.path?.length ? { field: n.from.path.join('.') } : {}) }\n : n.from.site ? { definition: n.from.site } : {});\n// the same check met on several paths: a definition by its id, any other test by what it asks where\nconst forkKey = own => n => (n.from.kind === 'call' && own.has(n.from.callee) ? n.from.callee : `${forkLabel(n, own)} ${n.from.site}`);\n// a branch on a read row itself asks whether it was found; on a field of it, what that field holds\nconst forkLabel = (n, own) => (n.from.kind === 'call' ? (own.has(n.from.callee) ? bare(n.from.callee) : `a test in ${bare(n.from.site)}`)\n : n.from.kind === 'read' && n.from.table ? (n.from.path?.length ? `${n.from.table} row\\u2019s ${n.from.path.join('.')}` : `${n.from.table} row found`) : n.from.site ? `a test in ${bare(n.from.site)}` : 'a computed branch');\n// a table's access policy as the access check states it (report.resources[].policy),\n// and whether the check proved the code keeps it: a rule the code breaks says so, and\n// one it could not settle (or no route reaches) is not proven\n// a table the access check gave no verdict is 'unchecked', as the key says\nconst policyWord = r => {\n const rule = policyRule(r);\n if (rule === 'unchecked') return rule;\n return r.status === 'violated' ? `${rule}, broken` : r.proven ? rule : `${rule}, not proven`;\n};\nconst policyRule = r => {\n const roles = () => r.roles.join(', '), guards = () => r.guards.join(', ');\n switch (r.policyKind) {\n case 'OwnerScoped': return 'own';\n case 'Public': return 'no row rule';\n case 'Guarded': return `guarded by ${guards()}`;\n // with no guard, only the roles reach its rows\n case 'GuardedOrRoles': return r.guards.length ? `guarded by ${guards()} or role ${roles()}` : `role ${roles()} only`;\n case 'PublicReadRoleWrite': return `anyone reads; role ${roles()} writes`;\n default: return 'unchecked';\n }\n};\n\nexport function buildSystemMap(engine, { program }) {\n for (const [k, v] of Object.entries(engine)) if (!v.ok) throw new Error(`${k}: ${v.error}`);\n const report = engine.report, st = engine.structure, abs = engine.abstractions.abstractions, layers = engine.layers.layers;\n // a tree the engine stopped before finishing (truncated, or a construct it does not follow) says nothing\n // about where its entry refuses; such an entry keeps the checks its definitions hold\n const whole = s => s.tree && !s.truncated && !s.unsupported;\n const trees = new Map((st.scenarios || []).filter(whole).map(s => [s.entry, refusingForks(s.tree)]));\n // the program's own definitions, as the layers lens lists them; anything else a fork calls is a library's\n const ownDefs = new Set(layers.packages.flatMap(p => p.definitions.map(d => `${p.name}::${d.name}`)));\n const routes = (report.surface.routes || []).slice().sort((a, b) => a.path.localeCompare(b.path));\n const engEntry = new Map(st.entries.map(e => [e.entry, e]));\n const shapes = new Map(abs.routeShapes.map(r => [r.path, r]));\n const gens = new Map(abs.generators.map(g => [g.id, g]));\n const insts = abs.instantiations;\n const besideOf = inst => ({ calls: inst.besideCalls.map(bare), callIds: inst.besideCalls, guards: inst.besideGuards.map(bare), guardIds: inst.besideGuards,\n effects: effectsOf(inst.besideEffectSteps), resources: outsideResourcesOf(inst.besideEffectSteps), from: 'abstractions.instantiations[].beside*' });\n\n // a generator wraps a route only when, by its type, it can: it runs effects, or IO is in its signature, or it\n // checks or dispatches and returns whatever its caller's code returns (a type variable, or the type a function\n // handed to it returns); a pure helper that returns a List or an Int shapes values, and cannot refuse or wrap the route\n const resultOf = sig => (sig.includes('->') ? sig.slice(sig.lastIndexOf('->') + 2).trim() : null);\n const returnsCallers = g => {\n const result = resultOf(g.signature);\n return result !== null && (/^[a-z]\\w*$/.test(result)\n || (g.parameterGroups || []).flat().some(sl => sl.role === 'function' && sl.returnType === result));\n };\n const wraps = g => !!g && (/\\bIO\\[/.test(g.signature) || g.envelope.effects.length > 0\n || (returnsCallers(g) && (g.envelope.guards.length > 0 || g.envelope.dispatchesOn.length > 0)));\n const entries = routes.map(r => {\n const key = `route:${r.path}`;\n const ee = engEntry.get(key);\n const rs = shapes.get(r.path);\n const wrapper = wraps(gens.get(rs.shapedByGenerator)) ? rs.shapedByGenerator : null;\n const inst = wrapper ? insts.find(i => i.callerId === rs.handlerId && i.generatorId === wrapper) : null;\n const passed = (inst ? inst.slotBindings : []).filter(sb => ['function', 'effect'].includes(sb.slotRole)).map(sb => ({\n slot: sb.slotName, id: sb.targetId || null, label: sb.targetId ? bare(sb.targetId) : null,\n kind: sb.passedKind, guards: (sb.guards || []).map(bare), guardIds: sb.guards || [], effects: effectsOf(sb.effectSteps),\n from: 'abstractions.instantiations[].slotBindings[slotRole=function|effect]',\n }));\n const reach = wrapper ? [\n ...effectsOf(rs.effectsInGeneratorSteps).map(e => ({ ...e, where: 'wrapper', from: 'abstractions.routeShapes[].effectsInGeneratorSteps' })),\n ...effectsOf(rs.effectsInPassedFunctionSteps).map(e => ({ ...e, where: 'passed', from: 'abstractions.routeShapes[].effectsInPassedFunctionSteps' })),\n ...effectsOf(rs.effectsDirectOrBesideSteps).map(e => ({ ...e, where: 'beside', from: 'abstractions.routeShapes[].effectsDirectOrBesideSteps' })),\n ] : uniqBy([\n ...effectsOf(r.inferredSteps).map(e => ({ ...e, where: 'direct', from: 'report.surface.routes[].inferredSteps' })),\n ...effectsOf(rs.effectsDirectOrBesideSteps).map(e => ({ ...e, where: 'direct', from: 'abstractions.routeShapes[].effectsDirectOrBesideSteps' })),\n ], e => `${e.op} ${e.table}`);\n const limits = ee.limits.written === 'literal' ? ee.limits.each.map(l => ({ requests: +l.requests, seconds: +l.seconds, by: l.by })) : [];\n return {\n key, path: r.path, handler: r.handler, handlerId: rs.handlerId,\n transport: ee.transport, authority: ee.authority,\n signedIn: !['public', 'anonymous'].includes(ee.authority),\n roles: r.requiredRoles || [],\n limits, limitComputed: ee.limits.written === 'computed',\n reachKinds: ee.reaches,\n db: ee.resources.includes('db'), model: ee.resources.includes('model'), net: ee.resources.includes('net'),\n writes: reach.some(e => isWrite(e.op)),\n // every branch of the entry's own where a path refuses (a wrapper's are\n // its own, and a function handed to it keeps its own slot)\n ...(trees.has(key)\n // one mark per check, though the tree meets it on several paths\n ? (forks => ({ guards: forks.map(n => forkLabel(n, ownDefs)), guardIds: forks.map(n => forkId(n, ownDefs)), guardParts: forks.map(n => forkParts(n, ownDefs)) }))(uniqBy(trees.get(key).filter(n => n.concern?.layer !== 'cross'\n && !(inst ? inst.slotBindings : []).some(sb => (sb.guards || []).includes(forkId(n, ownDefs)))), forkKey(ownDefs)))\n : { guards: rs.handlerGuards.map(bare), guardIds: rs.handlerGuards }),\n wrapper, via: rs.viaSpecialization ? bare(rs.viaSpecialization) : null,\n policy: (inst ? inst.slotBindings : []).filter(s => s.slotRole === 'semantic-object').map(s => s.value).filter(Boolean),\n passed, beside: inst ? besideOf(inst) : null, reach,\n from: { entry: 'report.surface.routes[]', transport: 'structure.entries[]', shape: 'abstractions.routeShapes[]', head: 'entries[].reach (writes)' },\n };\n });\n\n // Parts: every abstraction with an instantiation; each can be opened.\n const partOf = g => {\n const own = insts.filter(i => i.generatorId === g.id);\n return {\n id: g.id, label: g.name || bare(g.id), pkg: pkgOf(g.id),\n guards: g.envelope.guards.map(bare), guardIds: g.envelope.guards,\n effects: effectsOf(g.envelope.effectSteps),\n groups: (g.parameterGroups || []).map(grp => grp.map(sl => ({ name: sl.name, role: sl.role, type: sl.type, guardsFed: (sl.guardsFed || []).map(bare) }))),\n instantiationCount: own.length,\n instantiatingPackages: uniq(own.map(i => pkgOf(i.callerId))).sort(),\n besideEmpty: own.every(i => !i.besideCalls.length && !i.besideGuards.length && !i.besideEffects.length),\n callers: own.map(i => ({\n id: i.callerId, label: i.callerName || bare(i.callerId), pkg: pkgOf(i.callerId), routes: i.routes || [],\n via: i.viaSpecialization ? bare(i.viaSpecialization) : null,\n tokens: i.slotBindings.filter(s => s.slotRole === 'semantic-object').map(s => s.value).filter(Boolean),\n passed: i.slotBindings.filter(s => ['function', 'effect'].includes(s.slotRole)).map(s => ({\n slot: s.slotName, id: s.targetId || null, label: s.targetId ? bare(s.targetId) : null, guards: (s.guards || []).map(bare), guardIds: s.guards || [], effects: effectsOf(s.effectSteps) })),\n beside: besideOf(i),\n })),\n from: 'abstractions.generators[] + abstractions.instantiations[generatorId]',\n };\n };\n const parts = abs.generators.filter(g => insts.some(i => i.generatorId === g.id)).map(partOf);\n const wrapperIds = uniq(entries.map(e => e.wrapper).filter(Boolean)).sort();\n const wrappers = wrapperIds.map(id => ({ ...(parts.find(x => x.id === id) || partOf(gens.get(id))), entries: entries.filter(e => e.wrapper === id).map(e => e.key),\n from: 'abstractions.generators[] shaping routeShapes[].shapedByGenerator' }));\n\n // Supply: where each handle an effect or a record call uses comes from.\n const handlerToEntry = new Map(entries.map(e => [e.handlerId, e.key]));\n const passedToEntry = new Map(entries.flatMap(e => e.passed.filter(p => p.id).map(p => [p.id, e.key])));\n const uses = [];\n for (const s of st.supply) {\n const kind = s.via === 'record' ? 'record' : s.resource;\n if (kind !== 'db' && kind !== 'record') continue;\n const ids = new Set([s.definition]);\n for (const t of s.traces) {\n for (const id of t.through) ids.add(id);\n if (t.end.where) ids.add(t.end.where);\n if (t.end.referrer) ids.add(t.end.referrer);\n }\n let ats;\n if (handlerToEntry.has(s.definition)) ats = [{ node: 'entry', entry: handlerToEntry.get(s.definition) }];\n else if (wrapperIds.includes(s.definition)) ats = [{ node: 'wrapper', wrapper: s.definition }];\n else if (passedToEntry.has(s.definition)) ats = [{ node: 'passed', entry: passedToEntry.get(s.definition), id: s.definition }];\n else {\n // a helper: one use at every entry whose handler its traces run through\n const ents = uniq([...ids].map(i => handlerToEntry.get(i)).filter(Boolean));\n ats = ents.length ? ents.map(entry => ({ node: 'entry', entry, helper: bare(s.definition) })) : [{ node: 'definition', id: s.definition }];\n }\n 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;\n const anchor = !s.leaves ? 'none' : s.leaves.builtBy.length ? 'program' : 'platform';\n for (const at of ats) uses.push({ kind, how: s.supply, definition: s.definition, effect: s.effect || null, writes: s.via === 'effect' && isWrite(OPS[s.op] || 'write'), at, builtBy,\n untracedSource: s.traces.some(t => ['asValue', 'entry'].includes(t.end.kind)),\n anchor, handleBuiltBy: s.leaves ? s.leaves.builtBy : [], records: s.records || [],\n 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 })),\n from: 'structure.supply[]' });\n }\n\n const present = uniq(st.ioKinds.flatMap(b => b.resources));\n const tables = uniq(entries.flatMap(e => [...e.reach, ...(e.beside ? e.beside.effects : [])].map(r => r.table))).sort();\n const policies = engine.access ? Object.fromEntries(engine.access.report.resources.filter(r => tables.includes(r.resource)).map(r => [r.resource, policyWord(r)])) : null;\n const resources = ['db', 'model', 'net'].filter(k => present.includes(k)).map(k => ({ kind: k,\n ...(k === 'db' ? { tables, ...(policies ? { policies, policyFrom: 'access.report.resources[].policyKind, guards, roles' } : {}) } : {}), from: 'structure.ioKinds[].resources' }));\n const ghostResources = ['db', 'model', 'net'].filter(k => !present.includes(k)).map(k => ({ kind: k, from: 'structure.ioKinds[] checked: no site of this kind' }));\n\n const transports = uniq(st.entries.map(e => e.transport));\n const callers = [];\n if (transports.includes('http')) callers.push({ kind: 'http', keyKinds: uniq(entries.map(keyKindOf)), from: 'structure.entries[transport=http] + authority' });\n if (transports.includes('link')) callers.push({ kind: 'link', from: 'structure.entries[transport=link]' });\n const ghostCallers = ['http', 'link'].filter(k => !transports.includes(k)).map(k => ({ kind: k, from: 'structure.entries[]: no entry with this transport' }));\n\n const library = routes.length ? null : {\n packages: layers.packages.map(p => ({ name: p.name, label: p.name.split('/').pop(), exports: p.definitions.filter(d => d.exported).map(d => d.name) })),\n ports: st.ports.map(p => ({ id: p.id, label: bare(p.id), pkg: pkgOf(p.id), fields: p.fields, heldBy: p.heldBy,\n 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) })) })),\n from: 'structure.ports[]' })),\n chains: st.chains.map(c => ({ value: c.value, label: bare(c.value), pkg: pkgOf(c.value), by: bare(c.by),\n start: c.start.map(i => i.id ? bare(i.id) : i.text),\n 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 }))),\n from: 'structure.chains[]' })),\n combinations: st.combinations,\n applied: st.applied.map(a => ({ id: a.definition, label: bare(a.definition), pkg: pkgOf(a.definition), fn: a.function, insideBranch: a.insideBranch,\n fedBy: a.fedBy, from: 'structure.applied[]' })),\n generic: st.generic.map(g => ({ id: g.definition, label: bare(g.definition), vars: g.vars, signature: g.signature, from: 'structure.generic[]' })),\n exported: st.entries.filter(e => e.transport === 'link').map(e => e.entry),\n };\n 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' })));\n 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[]' }));\n\n return {\n schema: 'system-map-2', marks: MARKS_VERSION, vocabulary: VOCABULARY,\n program, class: report.headline.class,\n kind: routes.length ? 'service' : 'library',\n callers, ghostCallers, entries, wrappers, parts, uses, resources, ghostResources,\n library, keyed, steps,\n programs: programsOf(st, layers),\n bundles: routes.length > 12 ? bundlesOf(entries, uses, keyed) : null,\n phases: st.phases,\n evidence: { tools: ['api_report', 'api_organize:abstractions', 'api_organize:structure', 'api_organize:layers'], headline: report.headline,\n derived: ['bundles: entries grouped by wrapper and identical marks'] },\n };\n}\n\n// Two versions of one program: a check whose place on a route's path (the\n// handler's own checks, the handed-in function's, the after band's, by\n// position) holds a different definition in the head than in the base,\n// where neither definition is anywhere else on that route, took the old\n// one's place. That is all it says: nothing here shows the two do the\n// same. A route only in one version is left alone.\nexport function replacedGuards(base, head) {\n const slots = e => [['handler', e.guardIds], ['passed', e.passed[0]?.guardIds || []], ['after', e.beside?.guardIds || []]];\n const byPath = new Map(base.entries.map(e => [e.path, e]));\n const out = [];\n for (const e of head.entries) {\n const b = byPath.get(e.path);\n if (!b) continue;\n const all = x => new Set(slots(x).flatMap(([, ids]) => ids));\n const ba = all(b), ha = all(e);\n for (const [[slot, hs], [, bs]] of slots(e).map((s, i) => [s, slots(b)[i]]))\n hs.forEach((id, i) => {\n const was = bs[i];\n if (was && was !== id && !ha.has(was) && !ba.has(id)) {\n // the label tells the two apart: the old one's package too when both have one name\n const wasLabel = bare(was) === bare(id) ? `${pkgOf(was).split('/').pop()}::${bare(was)}` : bare(was);\n out.push({ entry: e.key, within: slot, at: i, guard: id, was, wasLabel, from: 'derived: the same place on the same route in the base record' });\n }\n });\n }\n return out;\n}\n\nexport const keyKindOf = e => e.authority === 'publishable' ? 'publishable' : e.signedIn ? 'secret' : 'public';\n\n// Bundles: entries that share a wrapper and draw identical marks. Names,\n// tables and role words are labels, drawn when the bundle is opened.\nexport function bundlesOf(entries, uses, keyed) {\n const keyedIds = new Set(keyed.map(k => k.id));\n 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(' ');\n const fill = l => l.length ? (l.some(x => isWrite(x.op)) ? 'W' : 'R') : '-';\n const sig = e => {\n const p = e.passed[0], b = e.beside;\n return JSON.stringify([e.wrapper, keyKindOf(e), e.roles.length > 0, e.writes,\n e.guards.length > 0, fill(e.reach.filter(r => r.where === 'direct')), fill(e.reach.filter(r => r.where === 'passed')), !!(p && p.guards.length),\n e.model, e.net, sup(e), e.limits.length > 0, !!(b && b.calls.length), !!(b && b.guards.length), fill(b ? b.effects : []),\n e.policy.length > 0, [e.handlerId, ...e.guardIds, ...(p ? [p.id, ...p.guardIds] : [])].some(id => keyedIds.has(id))]);\n };\n const groups = new Map();\n for (const e of entries) { const k = sig(e); if (!groups.has(k)) groups.set(k, []); groups.get(k).push(e.key); }\n const pathOf = new Map(entries.map(e => [e.key, e.path]));\n return [...groups.values()].map((keys, i) => ({ id: `bundle:${i + 1}`, entries: keys, count: keys.length, label: pathPattern(keys.map(k => pathOf.get(k))),\n from: 'derived: entries[] grouped by wrapper and identical marks' }));\n}\n\n// The paths' shared segments, * where they differ, /** for differing depths.\nexport function pathPattern(paths) {\n if (paths.length === 1) return paths[0];\n const sorted = [...paths].sort();\n const segs = paths.map(p => p.split('/'));\n const n = Math.min(...segs.map(s => s.length));\n const out = [];\n const vary = [];\n for (let i = 0; i < n; i++) { const v = uniq(segs.map(s => s[i])); out.push(v.length === 1 ? v[0] : '*'); if (v.length > 1) vary.push([i, v]); }\n // one part of the path differs among a few: the title names every route by it, \"/{tasks,tags}/sync\"\n if (segs.every(s => s.length === n) && vary.length === 1 && vary[0][1].length <= 6) { const [[i, v]] = vary; out[i] = `{${[...v].sort().join(', ')}}`; }\n if (segs.every(s => s.length === n) && vary.length <= 1) return out.join('/');\n // a few routes that differ in more than one part: each by name\n if (paths.length <= 4) return sorted.join(', ');\n if (segs.every(s => s.length === n)) return out.join('/');\n let k = 0; while (k < n && out[k] !== '*') k++;\n return out.slice(0, Math.max(k, 1)).join('/') + '/**';\n}\n","// Plain names on a system map record: the person's words in place of the\n// code's. A record is relabeled before it is drawn, so web/system-map.js\n// draws the person's words wherever it would draw a code name, in every\n// view. Names are labels only; relabeling never adds, drops or moves a mark.\n\n// Fields that describe the record or how a mark is drawn, never a name. A\n// `from` that is a list holds definitions (a combination's inputs); any other\n// `from` says which engine field a value came from.\nconst SKIP = new Set(['vocabulary', 'evidence', 'schema', 'marks', 'program', 'class']);\nconst skipped = (key, v) => SKIP.has(key) || key === 'from' && !Array.isArray(v);\nconst STRUCTURAL = new Set(['kind', 'op', 'how', 'transport', 'authority', 'where', 'slotRole', 'role', 'passedKind', 'anchor', 'node',\n 'keyKinds', 'reachKinds', 'resources', 'replies', 'also', 'kinds', 'within', 'vars', 'id']);\n// Words the record writes about a part (a check's label, a table's policy and where it came from)\n// name nothing of their own: what a check's label is made of is in guardParts, and the tables and\n// guards a policy mentions are named where they are drawn.\nconst DESCRIBED = new Set(['guards', 'policies', 'policyFrom']);\n// What each named field holds, said to the agent that names it.\nconst WHAT = {\n path: 'an action the app answers', routes: 'an action the app answers', table: 'a kind of record the app keeps', tables: 'a kind of record the app keeps',\n roles: 'a permission an action requires, held by a person\\'s role or by the app\\'s own server', policy: 'a setting an action passes to shared code', tokens: 'a setting an action passes to shared code',\n fields: 'an operation a pluggable part offers', field: 'a field of a kind of record the app keeps',\n};\nconst PACKAGE = 'a section of the program';\nconst DEFINITION = 'a piece of the program';\nconst VALUE = 'a kind of value';\nconst TYPES = new Set(['type', 'types', 'signature']);\nconst WORD = /[A-Za-z_][\\w/]*::\\w+|[A-Za-z_]\\w*/g;\n// The language's own kinds of value, said plainly once for every program.\nexport const PREDEF_WORDS = { String: 'text', Int: 'a number', Bool: 'yes or no', Float64: 'a decimal number', Char: 'a letter', Unit: 'nothing',\n List: 'a list', Option: 'maybe one', Dict: 'a lookup table' };\n\nconst leaves = (record, visit) => {\n const walk = (v, key) => {\n if (typeof v === 'string') visit(v, key);\n else if (Array.isArray(v)) v.forEach(x => walk(x, key));\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) if (!skipped(k, x) && !DESCRIBED.has(k)) walk(x, k);\n };\n walk(record, null);\n};\n\n/** Every code name the map draws, once, with what it is: the parts the\n * person's names replace. Given the program's own packages, a part of any\n * other package (the library) is left out: it is not the person's to name. */\nexport function nameableParts(map, own) {\n const found = new Map();\n const theirs = pkg => !own || own.has(pkg);\n const add = (code, what) => { if (code && !found.has(code) && !(code in PREDEF_WORDS) && (what !== PACKAGE || theirs(code))) found.set(code, what); };\n const idParts = id => { const i = id.lastIndexOf('::'); if (!theirs(id.slice(0, i))) return; add(id.slice(0, i), PACKAGE); add(id.slice(i + 2), DEFINITION); };\n leaves(map, (s, key) => {\n // a check on a read row is known by its place in the route's tree, not by a name\n if (key === 'guardIds' && s.startsWith('route:')) return;\n if (s.startsWith('route:')) return add(s.slice(6), WHAT.path);\n if (TYPES.has(key)) { for (const w of s.match(WORD) ?? []) if (w.includes('::')) idParts(w); else if (w.length > 1) add(w, VALUE); return; }\n if (s.includes('::')) { for (const w of s.match(WORD)) if (w.includes('::')) idParts(w); return; }\n if (STRUCTURAL.has(key)) return;\n if (key === 'name' || key === 'package' || key === 'pkg' || key === 'instantiatingPackages' || key === 'cycles' || key === 'to') return add(s, s.includes('/') ? PACKAGE : DEFINITION);\n add(s, WHAT[key] ?? DEFINITION);\n });\n for (const b of map.bundles ?? []) if (b.count > 1) found.delete(b.label);\n return [...found].map(([code, what]) => ({ code, what })).sort((a, b) => a.code.localeCompare(b.code));\n}\n\n// The person's names, made safe to stand where a code name stood: no\n// package separators, and no two code names sharing one plain name.\nfunction plainNames(names) {\n const out = new Map(), taken = new Set();\n for (const [code, name] of Object.entries(names).sort(([a], [b]) => a.localeCompare(b))) {\n const base = name.replace(/::|\\//g, ' ').replace(/\\s+/g, ' ').trim();\n if (!base) continue;\n let plain = base;\n for (let n = 2; taken.has(plain); n++) plain = `${base} (${n})`;\n taken.add(plain);\n out.set(code, plain);\n }\n return out;\n}\n\n/** The map with every named part drawn under the person's name; a part\n * without a name keeps its code name. */\nexport function relabelSystemMap(map, names) {\n const plain = plainNames({ ...PREDEF_WORDS, ...names });\n const word = w => plain.get(w) ?? w;\n const id = w => { const i = w.lastIndexOf('::'); return `${word(w.slice(0, i))}::${word(w.slice(i + 2))}`; };\n const text = (s, key) => {\n if (s.startsWith('route:')) return `route:${word(s.slice(6))}`;\n if (plain.has(s) && !STRUCTURAL.has(key)) return plain.get(s);\n if (s.startsWith('/')) return s;\n return s.replace(WORD, w => w.includes('::') ? id(w) : STRUCTURAL.has(key) ? w : word(w));\n };\n const walk = (v, key) => {\n if (typeof v === 'string') return text(v, key);\n if (Array.isArray(v)) return v.map(x => walk(x, key));\n if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, skipped(k, x) ? x : walk(x, k)]));\n return v;\n };\n const out = walk(map, null);\n // A bundle's label is its routes' shared pattern; once a route has a plain\n // name the pattern means nothing, so the label names the first route.\n const pathOf = new Map(map.entries.map(e => [e.key, e.path]));\n out.bundles = map.bundles && map.bundles.map((b, i) => {\n const paths = b.entries.map(k => pathOf.get(k));\n if (!paths.some(p => plain.has(p))) return out.bundles[i];\n return { ...out.bundles[i], label: b.count === 1 ? word(paths[0]) : `${word(paths[0])} and ${b.count - 1} more` };\n });\n return out;\n}\n","// The what-happens record (schema what-happens-1, marks yichus-marks-3 plus\n// the outcome leaf), built from the engine's own output. web/what-happens.js\n// draws this record and nothing else; every element names the engine field\n// it was copied or derived from (`from`). scripts/what-happens-examples.mjs\n// records one per program.\n//\n// The record joins, by computed id:\n// api_organize lens=structure (with requirements) scenarios[], claims\n// api_access_check report.findings[]\n// another what-happens record of the same program its red leaves (base)\n// The author's words are copied as labels onto the ids they name and never\n// decide anything: colour comes only from a claim's verdict or a check's\n// witness, and structure only from the engine's trees.\n\nimport { MARKS_VERSION } from './system-map-record.js';\n\nexport const SCHEMA = 'what-happens-1';\n\nexport const VOCABULARY = {\n version: MARKS_VERSION,\n added: ['outcome'],\n marks: {\n 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 (when no entry is described, that one line is all the rack draws, and it only counts them: \"8 entries\"; a scenario is a requirement someone wrote, so its absence says nothing about tests); under the head, \"same steps as …\" names the entries whose trees take the same steps on their own tables and checks <- entries[], ghosts[], entries[].sameShape',\n 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',\n fork: 'three prongs: a branch the code takes on the request, the caller, a value read from a table, or a call result, with \"← request\", \"← caller\" or \"← <table> as read\" saying where what it tests comes from; the arm each line takes is written where it leaves <- tree nodes, nodes[].from.sources',\n docs: 'under the names line, in italic, the comment the author wrote above each named check, marked unchecked: what the author says it decides, which the engine does not confirm <- docs (structure.docs)',\n rows: 'under the tree, for each table its stations touch (and those of the entries named in \"same steps as\"), what one row holds, by its checked type: \"posts holds List[Post(id: String, …, edited: Bool)]\"; a field that is a record gives only its type\\'s name, a choice of bare cases its cases (\"visibility: Open | Members\") <- rows (structure.rows)',\n station: 'ring on a line: an effect on that path, its verb and table beside it; filled = it writes; mint = the platform hands out a fresh row id. Under it, in grey, the row it touches (the caller\\'s row; the row named by a request field; one fixed row; a new row; every row, and the guard that keeps them) and, for a write, whether the row is replaced whole or updated from what it read, then where what it writes comes from, field by field (← caller, ← request.<field>, ← a literal, ← new id, ← a call and what it was computed from) <- arms[].effects[].key, value, kept (access report.findings[operation=keep_visible].provenBy)',\n modelRing: 'violet ring: the path reaches the model <- effects[resource=model]',\n netRing: 'orange ring: the path reaches the network <- effects[resource=net]',\n 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',\n 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',\n 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',\n 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',\n compared: 'a line under the rack when a base was compared: \"compared with <base> · N fixed · M still failing\"; with no base, no line <- diff',\n 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',\n },\n names: 'every check, call and table name is a label the code\\'s author (often an AI) chose; the picture proves where a check runs, what it is given and what happens when it fails, never what it decides: a reader who doubts the author reads that rule itself.',\n 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.',\n 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.',\n};\n\nconst bare = id => String(id).split('::').pop();\nconst claimKey = (entry, c) => `${entry}\\u0000${c.at}\\u0000${c.parsed}`;\n\nexport function walk(tree, f, path = []) {\n if (!tree) return;\n f(tree, path);\n if (tree.kind === 'node') for (const arm of tree.arms) { f(arm, path); walk(arm.next, f, [...path, arm]); }\n}\nexport const leavesOf = tree => { const out = []; walk(tree, t => { if (t.kind === 'leaf') out.push(t); }); return out; };\n// A leaf's effects are the entry's leading effects and those of each arm on\n// its path; the record keeps them once, on the arms, and these rebuild them.\nexport function pathEffects(entry) {\n const out = new Map();\n const go = (t, acc) => {\n if (!t) return;\n if (t.kind === 'leaf') { out.set(t.id, acc); return; }\n for (const a of t.arms) go(a.next, [...acc, ...a.effects]);\n };\n go(entry.tree, entry.effects || []);\n return out;\n}\nexport const allEffects = entry => { const out = [...(entry.effects || [])]; walk(entry.tree, t => { if (!t.kind) out.push(...t.effects); }); return out; };\n\n// The access check's findings that report a violation at an effect: the\n// leaves whose path runs that effect, at that definition, on that table.\n// A finding with a path condition (pathCondition.unlessHeld: the guards the\n// write sits under no branch on) is witnessed only on the paths where none\n// of those guards was tested and held: a path through a guard's True arm is\n// the guarded case, even when the write ran before the test.\nfunction heldOn(tree, guards) {\n const out = new Set();\n const go = (t, held) => {\n if (!t) return;\n if (t.kind === 'leaf') { if (held) out.add(t.id); return; }\n const isGuard = t.from?.kind === 'call' && guards.includes(bare(t.from.callee));\n for (const a of t.arms) go(a.next, held || (isGuard && a.arm === 'True'));\n };\n go(tree, false);\n return out;\n}\nfunction witnessesOf(access, entries) {\n if (!access) return [];\n const findings = (access.report?.findings || []).filter(f => f.status === 'violated');\n return findings.map((f, i) => {\n const site = `${f.package}::${f.binding}`;\n const guards = f.pathCondition?.unlessHeld || [];\n const leaves = entries.flatMap(e => {\n const held = heldOn(e.tree, guards);\n return leavesOf(e.tree).filter(l => !held.has(l.id) && l.effects.some(x => x.site === site && bare(x.primitive) === f.operation && x.tables.includes(f.resource)));\n }).map(l => l.id);\n return { id: `witness:${i + 1}`, check: 'access', resource: f.resource, site, operation: f.operation, kind: f.kind, detail: f.detail, leaves,\n ...(guards.length ? { unlessHeld: guards } : {}),\n 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]' };\n });\n}\n\n/**\n * engine: { structure, access? } structure = api_organize lens=structure\n * output (with requirements), access = api_access_check output.\n * base: the record of the program before a change, for the diff marks.\n */\nexport function buildWhatHappens(engine, { program, base = null, baseLabel = 'base' } = {}) {\n for (const [k, v] of Object.entries(engine)) if (v && !v.ok) throw new Error(`${k}: ${v.error}`);\n const st = engine.structure;\n const claims = st.claims || { scenarios: [], undescribed: (st.scenarios || []).map(s => s.entry) };\n const byEntry = new Map(claims.scenarios.filter(s => s.status === 'matched').map(s => [s.entry, s]));\n const routes = new Map((st.entries || []).map(e => [e.entry, e]));\n // a query's rows the access check proves are kept only where a guard\n // holds (report.findings[operation=keep_visible, kind=GuardProven])\n const kept = new Map((engine.access?.report?.findings || []).filter(f => f.operation === 'keep_visible' && f.kind === 'GuardProven' && f.status === 'holds')\n .map(f => [`${f.package}::${f.binding}\\u0000${f.resource}`, `${(f.provenBy || []).join(' and ')} passes for the caller and the row`]));\n const withKept = es => es.map(e => {\n const by = e.kind === 'DbQuery' && e.tables.length === 1 ? kept.get(`${e.site}\\u0000${e.tables[0]}`) : null;\n return by ? { ...e, kept: by } : e;\n });\n const entries = st.scenarios.map(s => {\n const meta = routes.get(s.entry) || {};\n const sc = byEntry.get(s.entry);\n const names = new Map((sc?.names || []).filter(n => n.status === 'named').map(n => [n.id, n.words]));\n // copy the tree, putting the author's words on the ids they name\n const copy = t => {\n if (!t) return null;\n if (t.kind === 'leaf') return { ...t, words: names.get(t.id) || null, claims: [], witnesses: [], status: 'grey' };\n return { ...t, words: names.get(t.id) || null, arms: t.arms.map(a => ({ ...a, effects: withKept(a.effects), words: names.get(a.id) || null, next: copy(a.next) })) };\n };\n return {\n entry: s.entry, handler: s.handler, label: s.entry.replace(/^route:/, ''),\n authority: meta.authority || null, transport: meta.transport || null,\n title: sc?.title || null, described: !!sc,\n effects: withKept(s.effects), tree: copy(s.tree), leafCount: Number(s.leafCount), truncated: s.truncated, unsupported: s.unsupported || null,\n wrapper: s.wrapper || null, steps: s.steps || [],\n from: 'structure.scenarios[]',\n };\n });\n // entries whose trees take the same steps in the same order and end the\n // same ways, whatever tables and checks they name, share a shape\n const shapeOf = e => {\n const eff = x => `${x.op}${x.key ? `@${x.key.kind}` : ''}${x.value ? `<${x.value.kind}` : ''}${x.kept ? '|kept' : ''}`;\n const go = t => (!t ? '' : t.kind === 'leaf' ? `(${t.outcome.kind}:${(t.outcome.statuses || (t.outcome.status ? [t.outcome.status] : [])).join('/')})`\n : `[${t.from.kind}${t.arms.map(a => `{${a.effects.map(eff).join(',')}${go(a.next)}}`).join('')}]`);\n return `${(e.effects || []).map(eff).join(',')}${go(e.tree)}`;\n };\n const byShape = new Map();\n for (const e of entries) byShape.set(shapeOf(e), [...(byShape.get(shapeOf(e)) || []), e.entry]);\n for (const e of entries) {\n const same = byShape.get(shapeOf(e)).filter(x => x !== e.entry);\n if (same.length) e.sameShape = { entries: same, from: 'derived: entries[] trees equal in node kinds, arms, effect verbs, row keys and value kinds, and outcomes' };\n }\n const entryOf = new Map(entries.map(e => [e.entry, e]));\n const leafById = new Map(entries.flatMap(e => leavesOf(e.tree).map(l => [l.id, l])));\n\n // claims onto the leaves they are about\n const checked = [], notes = [], refused = [], mismatches = [];\n for (const sc of claims.scenarios) {\n if (sc.status !== 'matched') { mismatches.push({ entry: sc.entry, title: sc.title || null, reason: sc.reason, from: 'structure.claims.scenarios[status=mismatch]' }); continue; }\n 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]' });\n for (const x of sc.expect) {\n if (x.verdict === 'not-a-claim') { notes.push({ entry: sc.entry, at: x.at, text: x.claim, from: 'structure.claims.scenarios[].expect[verdict=not-a-claim]' }); continue; }\n if (x.verdict === 'refused') { refused.push({ entry: sc.entry, id: x.at, words: x.claim, reason: x.reason, from: 'structure.claims.scenarios[].expect[verdict=refused]' }); continue; }\n const open = new Map((x.inconclusive || []).map(o => [o.leaf, o.reasons]));\n const c = { id: `claim:${checked.length + 1}`, entry: sc.entry, at: x.at, claim: x.claim, parsed: x.parsed, property: x.property, verdict: x.verdict, leaves: x.leaves, failing: x.failing,\n inconclusive: x.inconclusive || [], from: 'structure.claims.scenarios[].expect[]' };\n checked.push(c);\n for (const id of x.leaves) {\n const l = leafById.get(id);\n if (!l) continue;\n const verdict = x.failing.includes(id) ? 'fails' : open.has(id) ? 'inconclusive' : 'holds';\n l.claims.push({ id: c.id, at: x.at, parsed: x.parsed, property: x.property, verdict, ...(verdict === 'inconclusive' ? { reasons: open.get(id) } : {}) });\n }\n }\n }\n const witnesses = witnessesOf(engine.access, entries);\n // the base record keeps its leaves' effects on its arms\n const basePaths = base ? new Map(base.entries.flatMap(e => [...pathEffects(e)])) : null;\n for (const w of witnesses) for (const id of w.leaves) leafById.get(id)?.witnesses.push(w.id);\n for (const l of leafById.values()) {\n if (l.claims.some(c => c.verdict === 'fails') || l.witnesses.length) l.status = 'red';\n else if (l.claims.some(c => c.verdict === 'inconclusive')) l.status = 'unchecked';\n }\n\n // the diff: a leaf red at the base is fixed only when every obligation\n // that failed there (a claim, by entry, at and parsed claim; an access\n // witness, by the check running here and naming no witness on the leaf)\n // is checked here and holds; the base's red\n // leaf travels with it, drawn faded beside it. An obligation that is gone\n // or inconclusive here leaves the leaf unchecked, never green.\n let diff = null;\n if (base) {\n 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 }])));\n const baseWitness = new Map((base.witnesses || []).map(w => [w.id, w]));\n const fixed = [], still = [], gone = [], unresolved = [];\n for (const [id, { entry, leaf: bl }] of baseRed) {\n const here = leafById.get(id);\n if (!here) { gone.push(id); continue; }\n if (here.status === 'red') { still.push(id); continue; }\n const reasons = [\n ...bl.claims.filter(c => c.verdict === 'fails').flatMap(c => {\n const now = here.claims.find(h => claimKey(entry, h) === claimKey(entry, c));\n if (!now) return [`the claim ${c.parsed} at ${c.at} failed here at the base and is not checked here`];\n return now.verdict === 'holds' ? [] : [`the claim ${c.parsed} at ${c.at} failed here at the base and is inconclusive here`];\n }),\n ...(bl.witnesses.length && !engine.access ? [`the access check reported a witness here at the base and did not run here`] : []),\n ];\n const baseClaims = bl.claims, baseWitnesses = bl.witnesses.map(w => baseWitness.get(w)).filter(Boolean);\n here.base = { outcome: bl.outcome, effects: bl.effects || basePaths.get(id) || [], claims: baseClaims, witnesses: baseWitnesses };\n if (reasons.length) { here.status = 'unchecked'; unresolved.push({ id, reasons }); continue; }\n here.status = 'green';\n fixed.push(id);\n }\n diff = { base: baseLabel, fixed, stillRed: still, goneAtHead: gone, unresolved,\n 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' };\n }\n\n const ghosts = entries.filter(e => !e.described).map(e => ({ entry: e.entry, from: 'structure.claims.undescribed[]' }));\n // a leaf's effects are kept once, on the arms of its path (pathEffects)\n for (const l of leafById.values()) delete l.effects;\n return {\n schema: SCHEMA, marks: MARKS_VERSION, vocabulary: VOCABULARY, program,\n entries, ghosts, claims: checked, witnesses, notes, refused, mismatches, diff,\n // the comment above each definition, as its author wrote it (structure.docs); never checked\n docs: (callees => Object.fromEntries(Object.entries(st.docs || {}).filter(([id]) => callees.has(id))))(\n new Set(entries.flatMap(e => { const ids = []; walk(e.tree, n => { if (n.kind === 'node' && n.from?.kind === 'call') ids.push(n.from.callee); }); return ids; }))),\n // what each table holds, by its checked row type (structure.rows)\n rows: Object.fromEntries(Object.entries(st.rows || {}).map(([table, schema]) => [table, rowShape(schema)])),\n counts: { entries: entries.length, described: entries.length - ghosts.length, leaves: leafById.size,\n steps: entries.reduce((n, e) => n + e.steps.length, 0), wrapped: entries.filter(e => e.wrapper && e.wrapper.wraps).length,\n red: [...leafById.values()].filter(l => l.status === 'red').length, green: [...leafById.values()].filter(l => l.status === 'green').length,\n unchecked: [...leafById.values()].filter(l => l.status === 'unchecked').length },\n evidence: { tools: ['api_organize:structure', ...(engine.access ? ['api_access_check'] : [])], derived: ['diff: base red leaves matched by id, their failed obligations by identity'] },\n };\n}\n\n// Small helpers the renderer and tests share.\n// A table's row type in a line: List[Post(id: String, edited: Bool)]; a\n// field that is itself a record, or a choice whose cases carry fields,\n// gives only its type's name; a choice of bare cases gives its cases.\nconst typeName = s => (s.type ? s.type.split('::').pop() : null);\nconst fieldType = s => ({ string: 'String', int: 'Int', float64: 'Float64', bool: 'Bool', unit: 'Unit', json: 'Json' })[s.kind]\n || (s.kind === 'list' ? `List[${fieldType(s.element)}]` : s.kind === 'unsupported' ? s.rendered\n // a choice of bare cases is its cases: Open | Members\n : s.kind === 'union' && s.variants.length && s.variants.every(v => !v.fields.length) ? s.variants.map(v => v.tag).join(' | ') : typeName(s));\nexport function rowShape(s) {\n if (s.kind === 'list') return `List[${rowShape(s.element)}]`;\n if (s.kind === 'struct') return `${typeName(s)}(${s.fields.map(f => `${f.name}: ${fieldType(f)}`).join(', ')})`;\n if (s.kind === 'union') return s.variants.map(v => (v.fields.length ? `${v.tag}(${v.fields.map(f => `${f.name}: ${fieldType(f)}`).join(', ')})` : v.tag)).join(' | ');\n return fieldType(s);\n}\nexport const isWriteOp = op => !['read', 'runs', 'effect', 'random', 'trace', 'capture', 'init', 'mint id'].includes(op) && op !== 'call model' && op !== 'fetch article';\nexport function stationLabel(e) {\n const verb = e.op === 'mint id' ? 'mint' : e.op;\n if (e.tables.length) return `${verb} · ${e.tables.join(', ')}`;\n if (e.resource === 'model' || e.resource === 'net') return verb;\n return `${verb} · ${bare(e.primitive)}`;\n}\n// Where a value came from (effects[].key, effects[].value), in a few words:\n// the caller, a request field, a fixed literal, what a read or a new id\n// gave, or a call and what it was computed from.\nexport const fromWord = w => (w === 'caller' ? 'caller' : w === 'request' ? 'request' : w.startsWith('mint id:') ? 'new id'\n : w.startsWith('read:') ? `${w.slice(5)} as read` : w);\nexport function sourceText(f) {\n switch (f.kind) {\n case 'caller': return 'caller';\n case 'request': return ['request', ...(f.path || [])].join('.');\n case 'literal': return f.text;\n case 'read': return f.op === 'mint id' ? 'new id' : `${f.table || bare(f.primitive)} as read${f.path?.length ? `.${f.path.join('.')}` : ''}`;\n case 'call': return `${bare(f.callee)}(${(f.from || []).map(fromWord).join(', ')})${f.path?.length ? `.${f.path.join('.')}` : ''}`;\n case 'built': return f.fields ? `${f.ctor}(${f.fields.map(x => `${x.name} ← ${sourceText(x.from)}`).join(', ')})` : `${f.ctor}(${(f.from || []).map(fromWord).join(', ')})`;\n case 'derived': return (f.from || []).map(fromWord).join(', ') || 'computed';\n default: return 'computed';\n }\n}\n// The row a station touches and, for a write, whether the row it writes\n// carries what it read from that table (an update) or not (a replacement).\nexport function rowText(e) {\n if (!e.key) return e.value ? 'adds a row' : null;\n const k = e.key;\n return k.kind === 'caller' ? \"the caller's row\" : k.kind === 'literal' ? `one fixed row ${k.text}`\n : k.kind === 'read' && k.op === 'mint id' ? 'a new row' : `the row named by ${sourceText(k)}`;\n}\nconst readsOwn = (v, table) => {\n if (!v) return false;\n if (v.kind === 'read') return v.table === table && v.op !== 'mint id';\n if (v.fields) return v.fields.some(x => readsOwn(x.from, table));\n return (v.from || []).includes(`read:${table}`);\n};\nexport function stationDetail(e) {\n if (e.kind === 'DbQuery') return `every row${e.kept ? `, kept only where ${e.kept}` : ''}`;\n const row = rowText(e);\n if (!row) return null;\n if (!e.value) return row;\n const fresh = !e.key || e.key.kind === 'read' && e.key.op === 'mint id';\n const mode = fresh ? '' : readsOwn(e.value, e.tables[0]) ? ' · updated from what it read' : ' · replaced whole';\n return `${row}${mode} ← ${sourceText(e.value)}`;\n}\n// an unknown answer a station gave back (outcome.from), or a field of it,\n// said in the station's words; any other answer keeps its key\nconst said = f => {\n if (f.kind !== 'read') return null;\n const gives = `what ${f.op} · ${f.table || bare(f.primitive)} gives back`;\n return f.path && f.path.length ? `the ${f.path.join('.')} of ${gives}` : gives;\n};\nexport function outcomeLabel(o) {\n if (o.status && !o.constructors.length) return o.shown;\n const head = o.constructors.length ? o.constructors.join(' | ') : ((o.from && said(o.from)) || (o.value ? `the ${o.value}` : o.shown));\n return head;\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface SourceFile { fileName: string; source: string }\n\n// Folders a project keeps generated or third-party files in. A dot folder\n// (.git, .yichus) is skipped too.\nconst SKIPPED = new Set(['node_modules', 'dist', 'build', 'target', 'out']);\n\n/** Every .bosatsu file under root, named by its path from root with forward\n * slashes, in a stable order. The studio reads the program from disk so the\n * agent never pastes code into a call. */\nexport function projectSources(root: string): SourceFile[] {\n const files: SourceFile[] = [];\n const walk = (dir: string) => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n if (entry.name.startsWith('.') || SKIPPED.has(entry.name)) continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && entry.name.endsWith('.bosatsu')) {\n files.push({ fileName: path.relative(root, full).split(path.sep).join('/'), source: fs.readFileSync(full, 'utf8') });\n }\n }\n };\n walk(root);\n return files;\n}\n\nexport function sourcesHash(files: SourceFile[]): string {\n const hash = createHash('sha256');\n for (const file of files) hash.update(`${file.fileName}\\0${file.source}\\0`);\n return hash.digest('hex');\n}\n\n/** Bosatsu helpers for protocol cases (observation predicates the agent\n * writes in .yichus/cases/). They join protocol checks only, so they never\n * count as part of the app. */\nexport function caseSources(root: string): SourceFile[] {\n const dir = path.join(root, '.yichus', 'cases');\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir).filter(name => name.endsWith('.bosatsu')).sort()\n .map(name => ({ fileName: `cases/${name}`, source: fs.readFileSync(path.join(dir, name), 'utf8') }));\n}\n","import { z } from 'zod';\n\n// The property interview. Each question is pre-written and appears only when\n// an engine fact in api_report calls for it; a name never decides anything.\n// The wording is for a person who will never read the code: it says what\n// could happen to their users, not how the program is built.\n\nexport interface Choice { id: string; label: string; means: string }\nexport type QuestionKind = 'platform' | 'host' | 'sign-in' | 'data' | 'topology' | 'access' | 'together' | 'partial' | 'outside';\nexport interface Question {\n id: string;\n kind: QuestionKind;\n /** The table or route the question is about, as the engine names it. */\n subject: string | null;\n ask: string;\n why: string;\n choices: Choice[];\n /** The engine fact that raised the question, in words. */\n fact: string;\n}\n\nconst Step = z.looseObject({ op: z.string(), tables: z.array(z.string()).default([]), resource: z.string() });\n// authority: who may call the route (anonymous, authenticated, publishable,\n// requires-roles, requires-worker).\nconst Route = z.looseObject({ path: z.string(), handler: z.string(), authority: z.string().optional(), tables: z.array(z.string()).default([]),\n inferredSteps: z.array(Step).default([]) });\n// A table's declared policy: `policy` as the report prints it, `access` as data.\n// A kind this studio does not know matches no choice, so it reads as a mismatch.\nconst Access = z.looseObject({ kind: z.string(),\n guards: z.array(z.string()).default([]), roles: z.array(z.string()).default([]) });\nexport type Access = z.infer<typeof Access>;\nconst Table = z.looseObject({\n name: z.string(),\n policy: z.string().nullable().optional(),\n access: Access.nullable().optional(),\n readers: z.array(z.string()).default([]),\n writers: z.array(z.string()).default([]),\n});\nexport const Report = z.looseObject({\n surface: z.looseObject({ routes: z.array(Route).default([]) }).default({ routes: [] }),\n dataModel: z.looseObject({ tables: z.array(Table).default([]) }).default({ tables: [] }),\n});\nexport type Report = z.infer<typeof Report>;\n\n// api_organize lens=structure: which outside resources each entry reaches.\n// api_report's steps list only database operations.\nconst Entry = z.looseObject({ entry: z.string(), resources: z.array(z.string()).default([]) });\nexport const Structure = z.looseObject({ entries: z.array(Entry).default([]) });\nexport type Structure = z.infer<typeof Structure>;\n\n/** What each access choice needs the program to declare: the policy it\n * takes, how to write it, and the guide section on it. */\nexport interface AccessRule { declared(access: Access): boolean; write: string; guide: string }\nexport const ACCESS_RULES: Record<string, AccessRule> = {\n owner: { declared: a => a.kind === 'OwnerScoped', write: 'OwnerScoped', guide: 'Owner-scoped data' },\n // A guard every person passes through; a role may pass it only where every route that reaches it requires the role.\n shared: { declared: a => (a.kind === 'Guarded' || a.kind === 'GuardedOrRoles') && a.guards.length > 0,\n write: 'Guarded([the guard that says who may see a record]), or GuardedOrRoles([the guard], [the roles that may pass it])', guide: 'Guarded data' },\n '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' },\n 'everyone-reads': { declared: a => a.kind === 'PublicReadRoleWrite', write: 'PublicReadRoleWrite([the roles that may change it])', guide: 'Public data' },\n public: { declared: a => a.kind === 'Public', write: 'Public', guide: 'Public data' },\n};\n\n// Asked before any code is written, because it decides what to build: the\n// one question no engine fact raises. Each choice names a section of the\n// deploy reference (yichus_reference topic \"deploy\").\nexport const platform: Question = {\n id: 'platform',\n kind: 'platform',\n subject: null,\n ask: 'Where do you want your app to run once it is ready?',\n 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.',\n choices: [\n { id: 'render', label: 'Render', means: 'The server, its database, the page and background jobs all run on Render.' },\n { 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.' },\n { 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.' },\n { id: 'aws', label: 'Amazon Web Services', means: 'The server runs on App Runner or ECS with an RDS database.' },\n { id: 'gcp', label: 'Google Cloud', means: 'The server runs on Cloud Run with a Cloud SQL database.' },\n { id: 'azure', label: 'Microsoft Azure', means: 'The server runs on Container Apps or App Service with an Azure PostgreSQL database.' },\n { 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.' },\n ],\n fact: 'Every app runs somewhere.',\n};\n\n/** The deploy reference's section for each platform choice. */\nexport const PLATFORM_SECTION: Record<string, string> = {\n render: 'Render', vercel: 'Vercel', netlify: 'Netlify', aws: 'AWS', gcp: 'Google Cloud', azure: 'Microsoft Azure', undecided: 'Not decided yet',\n};\n\n/** The platforms that hold only the page people open: the server goes on a\n * second service, which the person picks. */\nexport const PAGE_ONLY = new Set(['vercel', 'netlify']);\n\n/** The deploy reference's section for each server host choice. */\nexport const HOST_SECTION: Record<string, string> = { render: 'Render', gcp: 'Google Cloud', aws: 'AWS', azure: 'Microsoft Azure', undecided: 'Render' };\n\n/** Asked once the person picks a platform that cannot keep a server running. */\nexport function hostQuestion(platformLabel: string): Question {\n return {\n id: 'host',\n kind: 'host',\n subject: null,\n 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?`,\n 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.',\n choices: [\n { id: 'render', label: 'Render', means: 'The server and its database run on Render, set up from one file in your project.' },\n { id: 'gcp', label: 'Google Cloud', means: 'The server runs on Cloud Run with a Cloud SQL database.' },\n { id: 'aws', label: 'Amazon Web Services', means: 'The server runs on App Runner with an RDS database.' },\n { id: 'azure', label: 'Microsoft Azure', means: 'The server runs on Container Apps with an Azure PostgreSQL database.' },\n { id: 'undecided', label: 'Not sure yet', means: 'Your agent builds for Render; moving later changes configuration, not the app.' },\n ],\n fact: `${platformLabel} does not keep a server running.`,\n };\n}\n\nconst topology: Question = {\n id: 'topology',\n kind: 'topology',\n subject: null,\n 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?',\n 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.',\n choices: [\n { id: 'many', label: 'Several copies', means: 'Every check assumes requests can run at the same moment on different copies.' },\n { 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.' },\n ],\n fact: 'The program serves routes.',\n};\n\n/** Plain names the agent gave the program's records and actions, keyed by\n * the engine's name; the person never sees the code name once one is given. */\nexport type Names = Record<string, string>;\nconst shown = (names: Names, subject: string) => names[subject] ?? subject;\n\nfunction accessQuestion(table: Report['dataModel']['tables'][number], names: Names): Question {\n return {\n id: `access:${table.name}`,\n kind: 'access',\n subject: table.name,\n 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?`,\n 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.',\n choices: [\n { 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.' },\n { 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.' },\n { 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.' },\n { 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.' },\n { id: 'public', label: 'Anyone, even without signing in', means: 'Nothing in these records is private.' },\n ],\n fact: `The program stores rows in \"${table.name}\" (policy declared: ${table.policy ?? 'none'}).`,\n };\n}\n\nfunction togetherQuestion(table: Report['dataModel']['tables'][number], handlers: string[], names: Names): Question {\n // Only its owner reaches an owner-scoped record, so two requests on one\n // are that person's own, from two devices; any other record is shared.\n 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';\n return {\n id: `together:${table.name}`,\n kind: 'together',\n subject: table.name,\n ask: `Two requests change the same record in \"${shown(names, table.name)}\" at the same moment (${who}). What should happen?`,\n 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.',\n choices: [\n { 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.' },\n { 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.' },\n ],\n fact: `${handlers.join(', ')} ${handlers.length === 1 ? 'reads' : 'read'} \"${table.name}\" and then ${handlers.length === 1 ? 'writes' : 'write'} it.`,\n };\n}\n\nfunction partialQuestion(route: Report['surface']['routes'][number], tables: string[], names: Names): Question {\n return {\n id: `partial:${route.path}`,\n kind: 'partial',\n subject: route.path,\n 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?`,\n 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.`,\n choices: [\n { 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.' },\n { id: 'partial-ok', label: 'Partial is fine', means: 'No check is added for this action.' },\n ],\n fact: `${route.handler} writes ${tables.map(t => `\"${t}\"`).join(', ')} in more than one step.`,\n };\n}\n\nfunction outsideQuestion(route: Report['surface']['routes'][number], kinds: string[], names: Names): Question {\n const service = kinds.includes('model') ? 'an AI model' : 'another service on the internet';\n return {\n id: `outside:${route.path}`,\n kind: 'outside',\n subject: route.path,\n ask: `\"${shown(names, route.path)}\" calls ${service}. If that service is down or slow, what should the person using your app see?`,\n why: 'Outside services fail often. Without a plan, a failure can leave a half-finished record or charge for work that never happened.',\n choices: [\n { id: 'fail-clean', label: 'An error, with nothing saved', means: 'Yichus makes the service fail and checks that nothing from this action stays saved.' },\n { 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.' },\n { id: 'no-plan', label: 'No preference', means: 'No check is added for this action.' },\n ],\n fact: `${route.handler} reaches ${kinds.join(' and ')}.`,\n };\n}\n\n// The authorities a signed-in person calls with; a worker route is the\n// app's own server, and an anonymous one needs no sign-in.\nconst PERSON_SIGNS_IN = new Set(['authenticated', 'publishable', 'requires-roles']);\n\nconst signIn: Question = {\n id: 'sign-in',\n kind: 'sign-in',\n subject: null,\n ask: 'How do people sign in to your app?',\n 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.',\n choices: [\n { id: 'new', label: 'They don\\'t yet', means: 'Your agent adds sign-in with a provider that runs it for you, such as Clerk.' },\n { id: 'clerk', label: 'Clerk', means: 'The server checks each person\\'s Clerk session.' },\n { 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.' },\n { id: 'other', label: 'Another sign-in provider', means: 'Auth0, Google, Firebase, Cognito, Microsoft Entra or another provider that publishes its signing keys.' },\n { id: 'keys', label: 'Only programs call it, with keys', means: 'No person signs in: scripts and other servers call the app with API keys.' },\n ],\n fact: 'Some actions are for signed-in people only.',\n};\n\nconst existingData: Question = {\n id: 'data',\n kind: 'data',\n subject: null,\n ask: 'Are there records somewhere today, such as in an app you already run, that this app must start with?',\n 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.',\n choices: [\n { id: 'new', label: 'No, it starts empty', means: 'Nothing is moved.' },\n { 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.' },\n { 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.' },\n ],\n fact: 'The program keeps records.',\n};\n\nexport function questionsFor(report: Report, structure: Structure, names: Names = {}): Question[] {\n const questions: Question[] = [];\n if (report.surface.routes.length) questions.push(topology);\n for (const table of report.dataModel.tables) questions.push(accessQuestion(table, names));\n for (const table of report.dataModel.tables) {\n const both = table.readers.filter(h => table.writers.includes(h));\n if (both.length) questions.push(togetherQuestion(table, both, names));\n }\n for (const route of report.surface.routes) {\n const writes = route.inferredSteps.filter(s => s.resource === 'db' && s.op !== 'read' && s.op !== 'query');\n const tables = [...new Set(writes.flatMap(s => s.tables))];\n if (writes.length >= 2) questions.push(partialQuestion(route, tables, names));\n }\n for (const route of report.surface.routes) {\n const entry = structure.entries.find(e => e.entry === `route:${route.path}`);\n const kinds = (entry?.resources ?? []).filter(r => r === 'model' || r === 'net');\n if (kinds.length) questions.push(outsideQuestion(route, kinds, names));\n }\n // How the app meets the world it replaces: asked last, since nothing in\n // the program waits on them.\n if (report.surface.routes.some(r => r.authority !== undefined && PERSON_SIGNS_IN.has(r.authority))) questions.push(signIn);\n if (report.dataModel.tables.length) questions.push(existingData);\n return questions;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\n\n// What the person decided, in their own words, kept beside the code so a new\n// agent session starts from the same decisions. .yichus/requirements.json is\n// meant to be committed; .yichus/state.json is derived and ignored.\n\nconst Answer = z.object({\n question: z.string().min(1),\n choice: z.string().min(1),\n words: z.string(),\n answeredAt: z.string(),\n});\nexport type Answer = z.infer<typeof Answer>;\n\n/** What the person or their agent says happens when an entry runs. The\n * engine (api_organize lens=structure with requirements) checks each claim\n * against the tree it computes and refuses ids it did not compute; here it\n * is only kept, so saving the file never drops it. */\nexport const Scenario = z.object({\n entry: z.string().min(1),\n title: z.string().optional(),\n names: z.record(z.string(), z.string()).optional(),\n expect: z.array(z.object({ at: z.string(), claim: z.string() }).strict()).optional(),\n}).strict();\nexport type Scenario = z.infer<typeof Scenario>;\n\n/** A rule the person stated about what the app must always or never do, in\n * their words, with the laws (Yichus/Law) that check it. */\nexport const RuleRecord = z.object({ rule: z.string().trim().min(1), laws: z.array(z.string().min(1)).min(1) }).strict();\nexport type RuleRecord = z.infer<typeof RuleRecord>;\n\nconst Requirements = z.object({\n schemaVersion: z.literal('yichus-requirements-1'),\n description: z.string().nullable(),\n answers: z.array(Answer),\n /** Plain names for the program's records and actions, keyed by code name. */\n names: z.record(z.string(), z.string()).optional(),\n scenarios: z.array(Scenario).optional(),\n /** The rules the agent listed; absent until it has looked, empty when the\n * person stated none. */\n rules: z.array(RuleRecord).optional(),\n});\nexport type Requirements = z.infer<typeof Requirements>;\n\nexport const studioDir = (root: string) => path.join(root, '.yichus');\nconst requirementsPath = (root: string) => path.join(studioDir(root), 'requirements.json');\n\nexport function loadRequirements(root: string): Requirements {\n const file = requirementsPath(root);\n if (!fs.existsSync(file)) return { schemaVersion: 'yichus-requirements-1', description: null, answers: [] };\n const parsed = Requirements.safeParse(JSON.parse(fs.readFileSync(file, 'utf8')));\n if (!parsed.success) throw new Error(`${file} is not a yichus-requirements-1 file: ${parsed.error.issues[0]?.message ?? 'invalid'}`);\n return parsed.data;\n}\n\nexport function saveRequirements(root: string, requirements: Requirements): void {\n ensureStudioDir(root);\n fs.writeFileSync(requirementsPath(root), `${JSON.stringify(Requirements.parse(requirements), null, 2)}\\n`);\n}\n\nexport function withNames(requirements: Requirements, names: Record<string, string>): Requirements {\n return { ...requirements, names: { ...requirements.names, ...names } };\n}\n\n/** A scenario replaces any earlier one for the same entry, and a dropped\n * entry loses its scenario. */\nexport function withScenarios(requirements: Requirements, scenarios: Scenario[], drop: string[] = []): Requirements {\n const replaced = new Set([...scenarios.map(s => s.entry), ...drop]);\n return { ...requirements, scenarios: [...(requirements.scenarios ?? []).filter(s => !replaced.has(s.entry)), ...scenarios] };\n}\n\n/** The latest answer to a question replaces any earlier one. */\nexport function withAnswer(requirements: Requirements, answer: Answer): Requirements {\n return { ...requirements, answers: [...requirements.answers.filter(a => a.question !== answer.question), answer] };\n}\n\nexport function ensureStudioDir(root: string): void {\n const dir = studioDir(root);\n fs.mkdirSync(dir, { recursive: true });\n // What the studio derives, what the agent points at while it talks, what\n // the person has in view and where the page runs stay out of the person's\n // commits.\n const ignore = path.join(dir, '.gitignore');\n // The file is the person's too: what is in it stays as it is, and only\n // the missing lines are added at its end.\n const before = fs.existsSync(ignore) ? fs.readFileSync(ignore, 'utf8') : '';\n const kept = new Set(before.split('\\n').map(line => line.trim()));\n const missing = ['state.json', 'marks.json', 'viewing.json', 'pages/'].filter(name => !kept.has(name));\n if (missing.length) fs.appendFileSync(ignore, `${before && !before.endsWith('\\n') ? '\\n' : ''}${missing.map(line => `${line}\\n`).join('')}`);\n}\n","import { z } from 'zod';\nimport { outcomeLabel, stationLabel } from '../../../../web/what-happens-record.js';\n\n// What happens when: each entry's decision tree as the engine computes it,\n// with the scenarios the agent wrote in the person's words checked against\n// it. The record is web/what-happens-record.js's; this module reads it to\n// say what the agent still owes: an entry nobody described, a computed id\n// without the person's words, an outcome no claim covers, a name or claim\n// the engine refused, an expectation that is not a claim, and the claims\n// that fail; and which entries the engine could not follow, so that\n// nothing said about them is checked.\n\nconst Effect = z.looseObject({ op: z.string(), tables: z.array(z.string()).default([]) });\nconst Claim = z.looseObject({ verdict: z.string(), parsed: z.string(), at: z.string(),\n property: z.looseObject({ is: z.string(), subject: z.string().optional() }).optional() });\nconst Leaf = z.looseObject({ kind: z.literal('leaf'), id: z.string(), words: z.string().nullable(), outcome: z.unknown(), claims: z.array(Claim).default([]) });\ntype Node = { kind: 'node'; id: string; test: string; words: string | null; arms: Arm[] };\ntype Arm = { id: string; pattern: string; words: string | null; effects: z.infer<typeof Effect>[]; next: Tree };\ntype Tree = Node | z.infer<typeof Leaf>;\nconst Tree: z.ZodType<Tree> = z.lazy(() => z.union([Leaf, z.looseObject({\n kind: z.literal('node'), id: z.string(), test: z.string(), words: z.string().nullable(),\n arms: z.array(z.looseObject({ id: z.string(), pattern: z.string(), words: z.string().nullable(), effects: z.array(Effect).default([]), next: Tree })),\n})])) as z.ZodType<Tree>;\n// An entry the engine could not follow has no tree, and says why.\nconst Entry = z.looseObject({ entry: z.string(), title: z.string().nullable(), described: z.boolean(), effects: z.array(Effect).default([]), tree: Tree.nullable(),\n unsupported: z.string().nullable() });\nconst Checked = z.looseObject({ entry: z.string(), at: z.string(), claim: z.string(), parsed: z.string(), verdict: z.string() });\nconst Refused = z.looseObject({ entry: z.string(), id: z.string(), words: z.string(), reason: z.string() });\nexport const WhatHappens = z.looseObject({\n entries: z.array(Entry),\n claims: z.array(Checked),\n refused: z.array(Refused),\n /** Expectations that are not claims in the grammar, so nothing checks them. */\n notes: z.array(z.looseObject({ entry: z.string(), at: z.string(), text: z.string() })),\n mismatches: z.array(z.looseObject({ entry: z.string(), reason: z.string() })),\n});\nexport type WhatHappens = z.infer<typeof WhatHappens>;\n\n/** One computed id the person's words are still missing on, with what the\n * engine computed there, for the agent. */\nexport interface Unnamed { id: string; what: string }\n\nexport interface Owed {\n entry: string;\n /** No scenario describes the entry yet. */\n undescribed: boolean;\n unnamed: Unnamed[];\n /** Outcomes no claim says anything about. */\n uncovered: string[];\n}\n\nconst effectsText = (effects: z.infer<typeof Effect>[]) => effects.length ? `; effects: ${effects.map(stationLabel).join(', ')}` : '';\n\nfunction walk(tree: Tree | null, visit: (id: string, what: string, words: string | null, leaf: boolean, claims: number) => void) {\n if (!tree) return;\n if (tree.kind === 'leaf') { visit(tree.id, `outcome: ${outcomeLabel(tree.outcome)}`, tree.words, true, tree.claims.length); return; }\n visit(tree.id, `the program checks ${tree.test}`, tree.words, false, 0);\n for (const arm of tree.arms) {\n // An arm that ends at once shares its id with its outcome.\n if (arm.next.id !== arm.id) visit(arm.id, `when ${arm.pattern}${effectsText(arm.effects)}`, arm.words, false, 0);\n else if (arm.next.kind === 'leaf') {\n const leaf = arm.next;\n visit(leaf.id, `when ${arm.pattern}${effectsText(arm.effects)}, outcome: ${outcomeLabel(leaf.outcome)}`, leaf.words ?? arm.words, true, leaf.claims.length);\n continue;\n }\n walk(arm.next, visit);\n }\n}\n\n/** What the agent still owes for each entry. */\nexport function owed(record: WhatHappens): Owed[] {\n return record.entries.map(e => {\n const unnamed: Unnamed[] = [], uncovered: string[] = [];\n walk(e.tree, (id, what, words, leaf, claims) => {\n if (!words) unnamed.push({ id, what });\n if (leaf && !claims) uncovered.push(id);\n });\n return { entry: e.entry, undescribed: !e.described, unnamed, uncovered };\n }).filter(o => o.undescribed || o.unnamed.length || o.uncovered.length);\n}\n\n/** What the person's claims say actions answer (returns CONSTRUCTOR): the\n * page says each in the person's words, so each wants a name. */\nexport function replies(record: WhatHappens): string[] {\n const found = new Set<string>();\n const visit = (tree: Tree | null) => {\n if (!tree) return;\n if (tree.kind === 'leaf') { for (const c of tree.claims) if (c.property?.is === 'returns' && c.property.subject) found.add(c.property.subject); return; }\n for (const arm of tree.arms) visit(arm.next);\n };\n for (const e of record.entries) visit(e.tree);\n return [...found].sort();\n}\n\n/** The entries the engine could not follow, with why: nothing the person\n * expects of them is checked. */\nexport function unfollowed(record: WhatHappens): Array<{ entry: string; why: string }> {\n return record.entries.filter(e => !e.tree).map(e => ({\n entry: e.entry, why: e.unsupported ?? 'the engine gave no reason' }));\n}\n","// How the studio's words name its tools: as MCP tools for an agent on the\n// MCP connection, or as shell commands for an agent in a terminal. Every\n// step, reply and error goes through one of these, so neither agent reads\n// the other's names.\n\nexport type StudioTool = 'yichus_start' | 'yichus_next' | 'yichus_name' | 'yichus_answer' | 'yichus_rules' | 'yichus_scenario' | 'yichus_point' | 'yichus_page';\n\nexport interface Say {\n surface: 'mcp' | 'cli';\n /** The tool's name where a sentence names it (\"the latest yichus_next\"). */\n name(tool: StudioTool): string;\n /** An instruction to use a studio tool: \"call yichus_next\". */\n use(tool: StudioTool): string;\n /** An instruction to use a studio tool with this input. */\n useWith(tool: StudioTool, input: string): string;\n /** An instruction to read a reference topic. */\n reference(topic: string): string;\n /** An instruction to call an engine tool with these arguments. */\n api(tool: string, args?: Record<string, unknown>): string;\n}\n\nexport const MCP: Say = {\n surface: 'mcp',\n name: tool => tool,\n use: tool => `call ${tool}`,\n useWith: (tool, input) => `call ${tool} with ${input}`,\n reference: topic => `call yichus_reference with topic \"${topic}\"`,\n api: (tool, args) => {\n const given = Object.entries(args ?? {}).map(([key, value]) => `${key} ${JSON.stringify(value)}`);\n return `call ${tool}${given.length ? ` with ${given.join(' and ')}` : ''}`;\n },\n};\n\nconst COMMAND: Record<StudioTool, string> = {\n yichus_start: 'yichus start \"DESCRIPTION\"',\n yichus_next: 'yichus next',\n yichus_name: 'yichus name CODE \"NAME\" [CODE \"NAME\" ...]',\n yichus_answer: 'yichus answer QUESTION CHOICE --words \"THEIR WORDS\"',\n yichus_rules: 'yichus rules FILE.json',\n yichus_scenario: 'yichus scenario FILE.json',\n yichus_point: 'yichus point FILE.json',\n yichus_page: 'yichus page',\n};\n\nexport const CLI: Say = {\n surface: 'cli',\n name: tool => `\\`${COMMAND[tool].split(' ').slice(0, 2).join(' ')}\\``,\n use: tool => `run \\`${COMMAND[tool]}\\``,\n // A command that takes input reads it from the FILE.json it names.\n useWith: (tool, input) => `run \\`${COMMAND[tool]}\\` with FILE.json holding ${input}`,\n reference: topic => `run \\`yichus reference ${topic}\\``,\n api: (tool, args) => {\n // A tool that requires sources reads the project folder, as the studio does.\n // The guide answers {sections: [{title, body}]}; one section is the first.\n const select = tool === 'api_guide' && args?.section !== undefined ? ' --select /sections/0/body' : '';\n if (!args || !Object.keys(args).length) return `run \\`yichus call ${tool}${select}\\``;\n return `run \\`yichus call ${tool} --args ARGS.json${select}\\` with ARGS.json holding ${JSON.stringify(args)}`;\n },\n};\n\n/** The command-line names of the tools reference documents call by their\n * MCP names. */\nexport const CLI_LEGEND = [\n 'On the command line, the tools this document names are commands:',\n ...Object.entries(COMMAND).map(([tool, command]) => ` ${tool}: ${command}`),\n ' yichus_reference: yichus reference TOPIC',\n ' 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',\n].join('\\n');\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema, type CallToolResult, type Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport { type StudioEngine, type StudioState, direct, drawnParts, readState } from './director.js';\nimport { caseSources, projectSources, sourcesHash } from './project.js';\nimport { recordMarks } from './marks.js';\nimport { pageText } from './page-view.js';\nimport { type Locate, REFERENCE, TOPICS, builtCopy, readReference, topicList } from './reference.js';\nimport { RuleRecord, loadRequirements, saveRequirements, withAnswer, withNames, withScenarios } from './requirements.js';\nimport { MCP, type Say } from './surface.js';\nimport { stepText } from './text.js';\n\n// The studio's MCP face. The instructions travel in the MCP handshake, so\n// an agent learns the loop before it reads a single tool description.\nexport const 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.\n\nWhy 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?\".\n\nThe loop:\n1. 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.\n2. 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.\n3. 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.\n4. 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.\n5. 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.\n6. 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.\n7. 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\").\n8. 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.\n9. 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.\n\nEvery 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.`;\n\nconst START = { name: 'yichus_start', description: 'Record what the person wants built, in their own words, and get the studio page link to give them. Call this first.',\n inputSchema: { type: 'object' as const, properties: { description: { type: 'string', description: 'The person\\'s description of the software, unchanged.' } }, required: ['description'] } };\nconst NEXT = { name: 'yichus_next', 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.',\n inputSchema: { type: 'object' as const, properties: {} } };\nconst ANSWER = { name: 'yichus_answer', 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.',\n inputSchema: { type: 'object' as const, properties: {\n question: { type: 'string', description: 'The question id from yichus_next.' },\n choice: { type: 'string', description: 'The id of the choice the person picked.' },\n words: { type: 'string', description: 'What the person said, in their words.' },\n }, required: ['question', 'choice', 'words'] } };\n\nconst NAME = { name: 'yichus_name', 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.',\n inputSchema: { type: 'object' as const, properties: {\n names: { type: 'object', additionalProperties: { type: 'string' },\n 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\".' },\n }, required: ['names'] } };\n\nconst SCENARIO = { name: 'yichus_scenario', 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.',\n inputSchema: { type: 'object' as const, properties: {\n scenarios: { type: 'array', items: { type: 'object', properties: {\n entry: { type: 'string', description: 'The action, as yichus_next listed it (route:/path).' },\n title: { type: 'string', description: 'What the person does, in their words.' },\n names: { type: 'object', additionalProperties: { type: 'string' }, description: 'Each id yichus_next listed under the action, with the person\\'s words for it.' },\n expect: { type: 'array', items: { type: 'object', properties: { at: { type: 'string' }, claim: { type: 'string' } }, required: ['at', 'claim'] },\n description: 'What must and must not happen: [not] reads TABLE, writes TABLE, refused, returns CONSTRUCTOR, reaches model or reaches net, at an id.' },\n }, required: ['entry', 'title', 'names', 'expect'] } },\n drop: { type: 'array', items: { type: 'string' }, description: 'Actions yichus_next reports the app no longer has, whose scenarios to remove.' },\n } } };\n\nconst RULES = { name: 'yichus_rules', 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.',\n inputSchema: { type: 'object' as const, properties: {\n rules: { type: 'array', items: { type: 'object', properties: {\n rule: { type: 'string', description: 'The rule, in the person\\'s words.' },\n 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.' },\n }, required: ['rule', 'laws'] } },\n }, required: ['rules'] } };\n\nconst POINT = { name: 'yichus_point', 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.',\n inputSchema: { type: 'object' as const, properties: {\n marks: { type: 'array', items: { type: 'object', properties: {\n 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.' },\n note: { type: 'string', description: 'What you are saying about it, in the person\\'s words, at most 280 characters.' },\n }, required: ['at', 'note'] } },\n }, required: ['marks'] } };\n\nconst PAGE = { name: 'yichus_page', 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.',\n inputSchema: { type: 'object' as const, properties: {} } };\n\nconst REFERENCE_TOOL = { name: 'yichus_reference', description: `Reference material yichus_next asks for. ${TOPICS.map(t => `${t}: ${REFERENCE[t].about}`).join(' ')}`,\n inputSchema: { type: 'object' as const, properties: { topic: { type: 'string', enum: TOPICS, description: 'The topic yichus_next named.' } }, required: ['topic'] } };\n\nconst StartArgs = z.object({ description: z.string().min(1) }).strict();\nconst AnswerArgs = z.object({ question: z.string().min(1), choice: z.string().min(1), words: z.string() }).strict();\n// What the tool takes: every field of a scenario, unlike the stored file,\n// which keeps whatever an earlier version wrote.\nconst ScenarioInput = z.object({\n entry: z.string().min(1), title: z.string().trim().min(1), names: z.record(z.string().min(1), z.string().trim().min(1)),\n expect: z.array(z.object({ at: z.string().min(1), claim: z.string().trim().min(1) }).strict()),\n}).strict();\nconst ScenarioArgs = z.object({ scenarios: z.array(ScenarioInput).default([]), drop: z.array(z.string().min(1)).default([]) })\n .refine(a => a.scenarios.length + a.drop.length > 0, 'give at least one scenario or one action to drop');\nconst RulesArgs = z.object({ rules: z.array(RuleRecord) }).strict();\nconst NameArgs = z.object({ names: z.record(z.string().min(1), z.string().trim().min(1)).refine(names => Object.keys(names).length > 0) });\n\nexport interface StudioMcpOptions {\n root: string;\n engine: StudioEngine;\n /** The engine's catalog, as tools/list advertises it. */\n catalog: () => Promise<Tool[]>;\n pageUrl: string | null;\n now?: () => Date;\n /** Where the reference files are (default: copied beside the built CLI). */\n locate?: Locate;\n}\n\nconst text = (body: string, structured?: Record<string, unknown>, isError = false): CallToolResult =>\n ({ content: [{ type: 'text', text: body }], ...(structured ? { structuredContent: structured } : {}), isError });\n\n/** A catalog tool as the studio offers it: sources become optional. */\nexport function studioTool(tool: Tool): Tool {\n const schema = tool.inputSchema;\n if (!schema.properties || !('sources' in schema.properties)) return tool;\n return {\n ...tool,\n description: [tool.description, 'In the studio, leave out sources to check every .bosatsu file in the project folder.'].filter(Boolean).join(' '),\n inputSchema: { ...schema, required: (schema.required ?? []).filter(name => name !== 'sources') },\n };\n}\n\n/** The person's description of what to build. */\nexport function recordStart(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = StartArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_start')} needs the person's description, and nothing else. ${z.prettifyError(parsed.error)}` };\n saveRequirements(root, { ...loadRequirements(root), description: parsed.data.description });\n return { ok: true };\n}\n\n/** Answer a question for an agent: validates the ids against the latest state. */\nexport function recordAnswer(root: string, args: unknown, now: Date, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = AnswerArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_answer')} needs question, choice and words, and nothing else. ${z.prettifyError(parsed.error)}` };\n const state = readState(root);\n const property = state?.properties.find(p => p.question.id === parsed.data.question);\n if (!property) return { ok: false, error: `No question ${parsed.data.question} in the latest ${say.name('yichus_next')}; ${say.use('yichus_next')} and use its ids.` };\n if (!property.question.choices.some(c => c.id === parsed.data.choice)) {\n 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(', ')}.` };\n }\n saveRequirements(root, withAnswer(loadRequirements(root), { ...parsed.data, answeredAt: now.toISOString() }));\n return { ok: true };\n}\n\n/** Name parts of the program for the person: each must be one the latest\n * state asks about or draws. */\nexport function recordNames(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = NameArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_name')} needs names: each code name ${say.name('yichus_next')} listed, with its plain name.` };\n const state = readState(root);\n const parts = new Set([...state?.properties.flatMap(p => p.question.subject ?? []) ?? [], ...state ? drawnParts(state).map(p => p.code) : []]);\n const unknown = Object.keys(parsed.data.names).filter(code => !parts.has(code));\n if (unknown.length) {\n const listed = [...parts].slice(0, 20).join(', ') + (parts.size > 20 ? `, and ${parts.size - 20} more` : '');\n // A part the program gained since then is named once the studio has seen it.\n const changed = state && state.sourcesHash !== sourcesHash(projectSources(root)) ? ` The program changed since then: ${say.use('yichus_next')} first.` : '';\n return { ok: false, error: `No part named ${unknown.join(', ')} in the latest ${say.name('yichus_next')}; the parts are ${listed || 'none yet'}.${changed}` };\n }\n saveRequirements(root, withNames(loadRequirements(root), parsed.data.names));\n return { ok: true };\n}\n\n/** Describe actions for the person: each must be one the latest state\n * computed a decision tree for. The engine checks the ids and claims on\n * the next yichus_next. */\nexport function recordScenarios(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = ScenarioArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_scenario')} needs scenarios, each with entry, title, names and expect, or drop. ${z.prettifyError(parsed.error)}` };\n const happens = readState(root)?.whatHappens;\n const entries = new Set(happens?.entries.map(e => e.entry) ?? []);\n const unknown = parsed.data.scenarios.map(s => s.entry).filter(e => !entries.has(e));\n if (unknown.length) return { ok: false, error: `No action ${unknown.join(', ')} in the latest ${say.name('yichus_next')}; the actions are ${[...entries].join(', ') || 'none yet'}.` };\n // Only a scenario whose action is gone can be dropped: a scenario of an\n // action the app still has is replaced, never removed.\n const gone = new Set(happens?.mismatches.map(m => m.entry));\n const kept = parsed.data.drop.filter(e => !gone.has(e));\n if (kept.length) return { ok: false, error: `The latest ${say.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.` };\n saveRequirements(root, withScenarios(loadRequirements(root), parsed.data.scenarios, parsed.data.drop));\n return { ok: true };\n}\n\n/** The rules the person stated, each with the laws that check it: every\n * law must be one the latest state found in the program. */\nexport function recordRules(root: string, args: unknown, say: Say = MCP): { ok: true } | { ok: false; error: string } {\n const parsed = RulesArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `${say.name('yichus_rules')} needs rules: a list of {\"rule\": the person's words, \"laws\": [law names]}, empty if they stated none. ${z.prettifyError(parsed.error)}` };\n const laws = readState(root)?.laws ?? [];\n const known = (ref: string) => laws.some(l => l.binding === ref || l.binding.endsWith(`::${ref}`) || l.name === ref);\n const unknown = [...new Set(parsed.data.rules.flatMap(r => r.laws).filter(ref => !known(ref)))];\n if (unknown.length) {\n const listed = laws.map(l => l.binding.slice(l.binding.lastIndexOf('::') + 2)).join(', ');\n return { ok: false, error: `No law named ${unknown.join(', ')} in the latest ${say.name('yichus_next')}; the laws are ${listed || 'none yet'}. Write the law, ${say.use('yichus_next')}, then record the rules.` };\n }\n saveRequirements(root, { ...loadRequirements(root), rules: parsed.data.rules });\n return { ok: true };\n}\n\n/** What yichus_start says about the studio page: its link when one runs,\n * and that it opens only on the computer it runs on. */\nexport function pageNote(pageUrl: string | null, say: Say): string {\n 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 ${say.name('yichus_page')}.`;\n if (!pageUrl) return [`The studio page is not running yet. Start it in the background in this folder with \\`yichus studio --page\\` and leave it running; ${say.name('yichus_start')}, ${say.name('yichus_next')} and ${say.name('yichus_page')} then give its link. It opens only in a browser on the computer it runs on.`,\n `${elsewhere} Before you give them the link, ${say.reference('guiding')}.`].join('\\n');\n return [`Read the \"guiding\" reference (${say.reference('guiding')}), then give the person this link and ask them to keep it open: ${pageUrl}`,\n `It opens only in a browser on the computer the studio runs on. ${elsewhere}`].join('\\n');\n}\n\nexport interface StudioMcpServer {\n server: Server;\n /** Resolves once every accepted request has been answered. */\n idle(): Promise<void>;\n}\n\nexport function createStudioMcpServer({ root, engine, catalog, pageUrl, now = () => new Date(), locate = builtCopy }: StudioMcpOptions): StudioMcpServer {\n const server = new Server({ name: 'yichus-studio', version: '0.3.3' }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });\n const active = new Set<Promise<unknown>>();\n const track = <T>(task: Promise<T>): Promise<T> => {\n active.add(task);\n void task.finally(() => active.delete(task)).catch(() => {});\n return task;\n };\n let tools: Tool[] | null = null;\n const catalogTools = async () => (tools ??= (await catalog()).map(studioTool));\n let last: StudioState | null = readState(root);\n\n server.setRequestHandler(ListToolsRequestSchema, () => track((async () => ({ tools: [START, NEXT, NAME, ANSWER, RULES, SCENARIO, POINT, PAGE, REFERENCE_TOOL, ...await catalogTools()] }))()));\n\n server.setRequestHandler(CallToolRequestSchema, request => track(callTool(request.params)));\n\n async function callTool(params: { name: string; arguments?: Record<string, unknown> }): Promise<CallToolResult> {\n const { name, arguments: args = {} } = params;\n if (name === 'yichus_start') {\n const result = recordStart(root, args);\n if (!result.ok) return text(result.error, undefined, true);\n return text(`${pageNote(pageUrl, MCP)}\\nIf this replaces an app the person already has, read yichus_reference topic \"porting\" first.\\nNext: call yichus_next.`, { pageUrl });\n }\n if (name === 'yichus_next') {\n last = await direct({ root, engine, requirements: loadRequirements(root), previous: last });\n const { map: _map, layers: _layers, whatHappens: _whatHappens, ...rest } = last;\n return text(stepText(last, pageUrl), rest as unknown as Record<string, unknown>);\n }\n if (name === 'yichus_answer') {\n const result = recordAnswer(root, args, now());\n return result.ok ? text('Recorded. Ask any remaining questions, then call yichus_next.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_name') {\n const result = recordNames(root, args);\n return result.ok ? text('Recorded. Call yichus_next.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_rules') {\n const result = recordRules(root, args);\n return result.ok ? text('Recorded. Call yichus_next: it runs every law and says how each rule stands.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_scenario') {\n const result = recordScenarios(root, args);\n return result.ok ? text('Recorded. Call yichus_next: the engine checks every name and claim.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_point') {\n const result = recordMarks(root, args, now());\n return result.ok ? text('The page shows your notes now. Go on talking with the person.') : text(result.error, undefined, true);\n }\n if (name === 'yichus_page') {\n if (Object.keys(args).length) return text('yichus_page takes no arguments.', undefined, true);\n return text(pageText(root, pageUrl, now(), MCP));\n }\n if (name === 'yichus_reference') {\n const said = readReference(String(args.topic), locate);\n return said ? text(said) : text(`No reference topic ${String(args.topic)}.\\n${topicList(topic => `topic \"${topic}\"`)}`, undefined, true);\n }\n const tool = (await catalogTools()).find(t => t.name === name);\n if (!tool) return text(`Unknown tool ${name}.`, undefined, true);\n const filled: Record<string, unknown> = { ...args };\n const props = tool.inputSchema.properties ?? {};\n if ('sources' in props && filled.sources === undefined) {\n filled.sources = name === 'api_protocol_check' ? [...projectSources(root), ...caseSources(root)] : projectSources(root);\n }\n // The person's answer about servers is the topology every check uses.\n const topology = loadRequirements(root).answers.find(a => a.question === 'topology')?.choice;\n if ('instances' in props && filled.instances === undefined && topology) filled.instances = topology === 'one' ? '1' : 'many';\n const result = await engine.call(name, filled);\n // The whole guide is over 100 KB; in the studio it is read a section at a time.\n if (name === 'api_guide' && filled.section === undefined && Array.isArray(result.sections)) {\n const titles = { ok: true, tool: 'api_guide', titles: (result.sections as Array<{ title: string }>).map(s => s.title),\n note: 'The whole guide is long. Call api_guide with section set to one of these titles, or to part of one.' };\n return text(JSON.stringify(titles), titles);\n }\n return text(JSON.stringify(result), result, result.ok !== true);\n }\n return {\n server,\n async idle() {\n while (active.size) await Promise.allSettled(active);\n // The SDK writes a handler's response a few microtasks after it settles.\n await new Promise(resolve => setImmediate(resolve));\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { readState } from './director.js';\nimport { personDiagrams } from './person.js';\nimport { ensureStudioDir, loadRequirements, studioDir } from './requirements.js';\n\n// What the agent is pointing at on the studio page while it talks with the\n// person: each mark names a part the page draws (a section of the app, an\n// action, or a step inside one) and carries the agent's short note. The\n// page lays the notes over the diagrams as the agent's words, never inside\n// them. Marks are part of the conversation, not of what the person decided,\n// so .yichus/marks.json is not committed; each call replaces the last.\n\nconst Mark = z.object({ at: z.string().min(1), note: z.string().trim().min(1).max(280) }).strict();\nexport type Mark = z.infer<typeof Mark>;\nconst Marks = z.object({ schemaVersion: z.literal('yichus-marks-1'), said: z.string(), marks: z.array(Mark) });\nexport type Marks = z.infer<typeof Marks>;\nconst PointArgs = z.object({ marks: z.array(Mark) }).strict();\n\nconst marksPath = (root: string) => path.join(studioDir(root), 'marks.json');\n\nexport function loadMarks(root: string): Marks | null {\n const file = marksPath(root);\n if (!fs.existsSync(file)) return null;\n const parsed = Marks.safeParse(JSON.parse(fs.readFileSync(file, 'utf8')));\n if (!parsed.success) throw new Error(`${file} is not a yichus-marks-1 file: ${z.prettifyError(parsed.error)}`);\n return parsed.data;\n}\n\n/** Every id a mark may name: exactly the parts the page draws now, the\n * sections it stacks, the described actions, and each step inside one. */\nexport function pointable(root: string): Set<string> {\n const state = readState(root);\n return new Set(state ? personDiagrams(state, loadRequirements(root).names ?? {}).anchors.keys() : []);\n}\n\n/** Point at parts of the page: replaces the marks before, and an empty\n * list clears them. */\nexport function recordMarks(root: string, args: unknown, now: Date): { ok: true } | { ok: false; error: string } {\n const parsed = PointArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `yichus_point needs marks, each with at and a note of at most 280 characters. ${z.prettifyError(parsed.error)}` };\n const known = pointable(root);\n const unknown = parsed.data.marks.map(m => m.at).filter(at => !known.has(at));\n 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.` };\n ensureStudioDir(root);\n fs.writeFileSync(marksPath(root), `${JSON.stringify(Marks.parse({ schemaVersion: 'yichus-marks-1', said: now.toISOString(), marks: parsed.data.marks }), null, 2)}\\n`);\n return { ok: true };\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { usesElsewhere } from '../../../../web/layer-groups.js';\n\n// The two diagrams the studio page draws, made from the engine's records with\n// nothing in them but the person's words: the sections of the app stacked\n// on what they are built from, and what happens in each action. A record\n// built here holds no code name, test, pattern or status code; a part\n// nobody has named yet is drawn as not named, never under its code name.\n// Each part carries an opaque anchor, its place in the picture, so the agent\n// can point at it (marks.ts) without the page learning its code name.\n\ntype Names = Record<string, string>;\nconst named = (names: Names, code: string) => names[code] ?? null;\n\n/** Words the page draws: computed text, and the agent's own words, which\n * the page sets apart as unchecked. */\nexport type Phrase = Array<string | { theirs: string }>;\nconst theirs = (words: string | null, missing: string): Phrase[number] => words === null ? missing : { theirs: words };\n\n// ---------------------------------------------------------------- sections\n\nconst Package = z.looseObject({\n name: z.string(), level: z.number(),\n reads: z.array(z.string()), writes: z.array(z.string()), handedIn: z.array(z.string()),\n});\nconst Layers = z.looseObject({\n layers: z.looseObject({ packages: z.array(Package), packageEdges: z.array(z.looseObject({})), crossEdges: z.array(z.looseObject({})) }),\n});\n\n/** Where each code name is drawn: code name to anchor. */\nexport type Anchors = Map<string, string>;\n\nexport interface Section {\n anchor: string;\n /** The person's name for the section, or null while it has none. */\n name: string | null;\n /** The records it changes, then the ones it only looks at: the person's\n * name for each, or null for a kind of record not named yet. */\n changes: Array<string | null>;\n looks: Array<string | null>;\n /** How much of the rest of the app is built on it. */\n uses: number;\n}\n\n/** The app's sections in layers, the top first: each layer is built only\n * from the layers below it. */\nexport function personSections(layers: unknown, names: Names, anchors: Anchors = new Map()): Section[][] | null {\n const parsed = Layers.safeParse(layers);\n if (!parsed.success) return null;\n const data = parsed.data.layers;\n const uses = usesElsewhere(data);\n const levels = [...new Set(data.packages.map(p => p.level))].sort((a, b) => b - a);\n return levels.map((level, i) => data.packages.filter(p => p.level === level).map(p => {\n // Records a caller hands in are the caller's, so a section counts its own.\n const own = (tables: string[]) => [...new Set(tables.filter(t => !p.handedIn.includes(t)).map(t => named(names, t)))];\n const changes = own(p.writes);\n return { code: p.name, name: named(names, p.name), changes, looks: own(p.reads).filter(t => !changes.includes(t)), uses: uses.get(p.name)! };\n }).sort((a, b) => b.uses - a.uses).map(({ code, ...section }, k) => {\n const anchor = `section-${i}-${k}`;\n anchors.set(code, anchor);\n return { anchor, ...section };\n }));\n}\n\n// ------------------------------------------------------------ what happens\n\n// The engine sends each claim's fields as well as its text, so nothing here\n// parses the text back.\nconst Property = z.object({ negated: z.boolean(), is: z.enum(['reads', 'writes', 'refused', 'returns', 'reaches']), subject: z.string().optional() });\nexport type Property = z.infer<typeof Property>;\nconst Claim = z.looseObject({ property: Property, verdict: z.enum(['holds', 'fails', 'inconclusive']) });\nconst Leaf = z.looseObject({\n kind: z.literal('leaf'), id: z.string(), words: z.string().nullable(), status: z.enum(['grey', 'red', 'green', 'unchecked']),\n outcome: z.looseObject({ kind: z.string() }), claims: z.array(Claim), witnesses: z.array(z.string()),\n});\ntype Node = { kind: 'node'; id: string; words: string | null; arms: Arm[] };\ntype Arm = { id: string; words: string | null; next: Tree };\ntype Tree = Node | z.infer<typeof Leaf>;\nconst Tree: z.ZodType<Tree> = z.lazy(() => z.union([Leaf, z.looseObject({\n kind: z.literal('node'), id: z.string(), words: z.string().nullable(),\n arms: z.array(z.looseObject({ id: z.string(), words: z.string().nullable(), next: Tree })),\n})])) as z.ZodType<Tree>;\nconst Happens = z.looseObject({\n entries: z.array(z.looseObject({ entry: z.string(), title: z.string().nullable(), described: z.boolean(), tree: Tree.nullable() })),\n witnesses: z.array(z.looseObject({ id: z.string(), resource: z.string() })),\n});\n\nexport type Verdict = 'holds' | 'fails' | 'cannot say';\nexport interface Check { says: Phrase; verdict: Verdict }\nexport interface Outcome {\n kind: 'outcome';\n anchor: string;\n /** The person's words for what happens, or null while there are none. */\n words: string | null;\n /** The request is turned away here rather than answered. */\n refused: boolean;\n /** red: something the person expects is false here; unchecked: the engine cannot say. */\n status: 'grey' | 'red' | 'green' | 'unchecked';\n checks: Check[];\n}\nexport interface Choice { kind: 'choice'; anchor: string; words: string | null; ways: Array<{ anchor: string; words: string | null; then: Step }> }\nexport type Step = Outcome | Choice;\nexport interface Action {\n anchor: string;\n /** The person's title for the action, or null while it has none. */\n title: string | null;\n first: Step | null;\n}\nexport interface PersonWhatHappens {\n /** The actions the person has described. */\n actions: Action[];\n /** How many actions nobody has described yet. */\n waiting: number;\n}\n\n/** A checked claim, said the way the person would say it. */\nexport function sayClaim({ negated, is, subject }: Property, names: Names): Phrase {\n const thing = theirs(subject === undefined ? null : named(names, subject), 'something not named yet');\n const said: Phrase = is === 'refused' ? ['turned away']\n : is === 'reaches' ? [subject === 'model' ? 'asks the AI model' : 'reaches the internet']\n : [is === 'reads' ? 'looks at ' : is === 'writes' ? 'changes ' : 'answers ', thing];\n return !negated ? said : is === 'refused' ? ['not turned away'] : ['never ', ...said];\n}\n\n/** What happens in each described action, in the person's words only. */\nexport function personWhatHappens(record: unknown, names: Names, anchors: Anchors = new Map()): PersonWhatHappens | null {\n const parsed = Happens.safeParse(record);\n if (!parsed.success) return null;\n const reach = new Map(parsed.data.witnesses.map(w => [w.id, named(names, w.resource)]));\n const VERDICT = { holds: 'holds', fails: 'fails', inconclusive: 'cannot say' } as const;\n const at = (id: string, anchor: string) => { anchors.set(id, anchor); return anchor; };\n const step = (t: Tree, said: string | null, place: string): Step => {\n if (t.kind === 'leaf') return {\n kind: 'outcome', anchor: at(t.id, place), words: t.words === said ? null : t.words, refused: t.outcome.kind === 'refused', status: t.status,\n checks: [\n ...t.claims.map(c => ({ says: sayClaim(c.property, names), verdict: VERDICT[c.verdict] })),\n ...t.witnesses.map(w => ({ says: ['someone else\\'s ', theirs(reach.get(w) ?? null, 'records'), ' can be reached here'], verdict: 'fails' as const })),\n ],\n };\n // An arm that ends at once shares its id, and its words, with its outcome,\n // so pointing at either points at the outcome.\n return { kind: 'choice', anchor: at(t.id, place), words: t.words, ways: t.arms.map((a, k) => {\n const then = step(a.next, a.next.id === a.id ? a.words : null, `${place}-${k}`);\n return { anchor: a.next.id === a.id ? then.anchor : at(a.id, `${place}-${k}-way`), words: a.words, then };\n }) };\n };\n const described = parsed.data.entries.filter(e => e.described);\n return {\n actions: described.map((e, i) => ({ anchor: at(e.entry, `action-${i}`), title: e.title, first: e.tree && step(e.tree, null, `action-${i}-step`) })),\n waiting: parsed.data.entries.length - described.length,\n };\n}\n\n/** Both diagrams, where each part the agent may point at is drawn, and\n * which drawing that is: an anchor names the same part only while the\n * drawing stays the same. */\nexport function personDiagrams(state: { layers: unknown; whatHappens: unknown }, names: Names) {\n const anchors: Anchors = new Map();\n const sections = personSections(state.layers, names, anchors);\n const whatHappens = state.whatHappens ? personWhatHappens(state.whatHappens, names, anchors) : null;\n const drawing = createHash('sha256').update(JSON.stringify([...anchors])).digest('hex').slice(0, 16);\n return { sections, whatHappens, anchors, drawing };\n}\n","// Groups and weights for the layer diagram, computed from the layers\n// lens output alone. Packages are alike on one chosen dimension: the\n// packages they connect to, the types they share, or the tables they\n// touch. Names are only labels here; a group comes from shared facts.\n\nexport const dimensions = Object.freeze({\n connections: 'packages they connect to',\n types: 'types they share',\n tables: 'tables they touch',\n none: 'no grouping',\n});\n\n// Two groups merge while their members are, on average, at least this\n// alike (Jaccard similarity of the chosen facts).\nconst together = 0.3;\n\n// What a package has on one dimension, as a set of fact keys. A type is\n// shared by the package that defines it and every package importing it.\nfunction facts(data, dimension) {\n const sets = new Map(data.packages.map(p => [p.name, new Set()]));\n for (const p of data.packages) {\n const f = sets.get(p.name);\n if (dimension === 'tables') [...p.reads, ...p.writes].forEach(t => f.add(t));\n if (dimension === 'connections') f.add(p.name);\n }\n for (const e of data.packageEdges) {\n if (dimension === 'connections') { sets.get(e.from).add(e.to); sets.get(e.to).add(e.from); }\n if (dimension === 'types') for (const t of e.typeNames) {\n sets.get(e.from).add(`${e.to}::${t}`);\n sets.get(e.to).add(`${e.to}::${t}`);\n }\n }\n return sets;\n}\n\nconst alike = (a, b) => {\n if (a.size === 0 || b.size === 0) return 0;\n let shared = 0;\n for (const x of a) if (b.has(x)) shared++;\n return shared / (a.size + b.size - shared);\n};\n\n// Whether folding each group into one node leaves a graph with no cycle.\nfunction foldsToLayers(data, groups) {\n const nodeOf = new Map(groups.flatMap((g, i) => g.map(m => [m, i])));\n const out = groups.map(() => new Set());\n for (const e of data.packageEdges) if (nodeOf.get(e.from) !== nodeOf.get(e.to)) out[nodeOf.get(e.from)].add(nodeOf.get(e.to));\n const state = groups.map(() => 0);\n const acyclic = i => {\n if (state[i]) return state[i] === 2;\n state[i] = 1;\n const ok = [...out[i]].every(acyclic);\n state[i] = 2;\n return ok;\n };\n return groups.every((_, i) => acyclic(i));\n}\n\n// Average-linkage clustering. Two groups merge only if folding every group\n// into one box still leaves arrows that all point down. Members keep the order they\n// were merged in, so the most alike packages sit next to each other.\nexport function groupPackages(data, dimension) {\n const sets = facts(data, dimension);\n let groups = data.packages.map(p => [p.name]);\n // A group of more than half the program would say nothing about it.\n const half = Math.max(2, Math.floor(data.packages.length / 2));\n if (dimension === 'none') return groups.map(members => ({ members, shared: [] }));\n const score = (x, y) => x.reduce((s, a) => s + y.reduce((t, b) => t + alike(sets.get(a), sets.get(b)), 0), 0) / (x.length * y.length);\n for (;;) {\n const pairs = [];\n for (let i = 0; i < groups.length; i++)\n for (let j = i + 1; j < groups.length; j++) {\n const s = score(groups[i], groups[j]);\n if (s >= together) pairs.push({ s, i, j });\n }\n const best = pairs.sort((a, b) => b.s - a.s).find(({ i, j }) => groups[i].length + groups[j].length <= half && foldsToLayers(data, groups.map((g, k) => k === i ? [...g, ...groups[j]] : g).filter((_, k) => k !== j)));\n if (!best) break;\n groups[best.i] = [...groups[best.i], ...groups[best.j]];\n groups = groups.filter((_, k) => k !== best.j);\n }\n return groups.map(members => ({ members, shared: members.length > 1 ? sharedFacts(members, sets) : [] }));\n}\n\n// The facts at least half the members have, most common first.\nfunction sharedFacts(members, sets) {\n const count = new Map();\n for (const m of members) for (const x of sets.get(m)) count.set(x, (count.get(x) ?? 0) + 1);\n return [...count].filter(([, n]) => n * 2 >= members.length)\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([x]) => x);\n}\n\n// How much the rest of the program leans on each node (a package, or a\n// folded group): references from definitions outside it to definitions in\n// it, plus each type imported into it from outside.\nexport function usesElsewhere(data, nodeOf = new Map(data.packages.map(p => [p.name, p.name]))) {\n const pkg = id => id.slice(0, id.indexOf('::'));\n const uses = new Map([...new Set(nodeOf.values())].map(n => [n, 0]));\n const add = (from, to, n) => { if (nodeOf.get(from) !== nodeOf.get(to)) uses.set(nodeOf.get(to), uses.get(nodeOf.get(to)) + n); };\n for (const e of data.crossEdges) add(pkg(e.from), pkg(e.to), 1);\n for (const e of data.packageEdges) add(e.from, e.to, e.typeNames.length);\n return uses;\n}\n\n// Each folded group of two or more as one node; every other package stays\n// itself. A fold of groups that folds to layers (see groupPackages) has no\n// cycle whichever groups are folded, so a node's level is one more than\n// the highest level it is built from.\nexport function foldGroups(data, groups, folded = () => true) {\n const nodes = groups.flatMap((g, i) => g.members.length > 1 && folded(i)\n ? [{ name: `group:${i}`, group: g, members: g.members }]\n : g.members.map(m => ({ name: m, members: [m] })));\n const nodeOf = new Map(nodes.flatMap(n => n.members.map(m => [m, n.name])));\n const edges = new Map();\n for (const e of data.packageEdges) {\n const from = nodeOf.get(e.from), to = nodeOf.get(e.to);\n if (from === to) continue;\n const key = `${from}\\n${to}`;\n const sum = edges.get(key) ?? { from, to, refs: 0, types: 0 };\n edges.set(key, { ...sum, refs: sum.refs + e.refs, types: sum.types + e.typeNames.length });\n }\n const below = new Map(nodes.map(n => [n.name, []]));\n for (const e of edges.values()) below.get(e.from).push(e.to);\n const level = new Map();\n const visit = n => {\n if (!level.has(n)) level.set(n, below.get(n).reduce((l, m) => Math.max(l, visit(m) + 1), 0));\n return level.get(n);\n };\n return { nodes: nodes.map(n => ({ ...n, level: visit(n.name) })), edges: [...edges.values()], nodeOf };\n}\n","import type { Status } from './director.js';\nimport type { PageSection } from './viewing.js';\n\n// The studio page: what the person asked for, questions waiting for them,\n// each property they chose with the engine's status, what happens in each\n// action, the sections their app is built from, and the system map of their\n// own program. Everything inside a \"Yichus output\" frame is copied\n// from the engine's results or the studio's pre-written questions; the\n// person's own words are labeled as theirs, and the diagrams that carry the\n// agent's words sit outside those frames, labeled unchecked. What the agent\n// points at while it talks floats in a layer above everything, each note\n// marked as the agent's and not checked. Text goes in through textContent\n// only. The page tells the studio what the person has in view, by id only,\n// so the agent can see it too (yichus_page).\n\n/** Each property status as the page says it, and its tone. yichus_page\n * says the same words. */\nexport const PAGE_STATUS: Record<Status | 'pending', [string, 'quiet' | 'good' | 'warn' | 'bad']> = {\n unanswered: ['waiting for your answer', 'quiet'], decided: ['decided', 'good'], assumed: ['holds, under an assumption', 'warn'],\n proven: ['proven', 'good'], bounded: ['holds in every scenario checked', 'good'], broken: ['broken', 'bad'],\n mismatch: ['the code says otherwise', 'bad'], 'needs-case': ['scenario being written', 'quiet'],\n 'needs-law': ['check being written', 'quiet'], unused: ['checked, but your app does not use it yet', 'bad'],\n inconclusive: ['not decided yet', 'warn'], 'no-check': ['no check needed', 'quiet'], pending: ['answered, waiting for your agent to check', 'quiet'],\n};\n\n/** The page's sections and their headings, which yichus_page says too. */\nexport const PAGE_HEADINGS: Record<PageSection, string> = {\n asked: 'What you asked for',\n now: 'What is happening now',\n questions: 'Questions for you',\n props: 'What your program must do',\n happens: 'What happens when',\n sections: 'How your app is built',\n map: 'The shape of your program',\n};\n\n/** What happens when, for a program with no actions people take. */\nexport const 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.';\n\nexport const STUDIO_PAGE = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Yichus studio</title>\n<link rel=\"stylesheet\" href=\"system-map.css\">\n<style>\n :root { --ink:#0f172a; --muted:#475569; --faint:#94a3b8; --rule:#e2e8f0; --paper:#ffffff; --page:#f6f8fb;\n --good:#047857; --goodSoft:#ecfdf5; --bad:#b91c1c; --badSoft:#fef2f2; --warn:#92400e; --warnSoft:#fffbeb; --accent:#22675e;\n --agent:#4f46e5; --agentSoft:rgba(79,70,229,0.16); }\n * { box-sizing:border-box; }\n body { margin:0; background:var(--page); color:var(--ink); font:16px/1.55 Inter, system-ui, sans-serif; }\n main { max-width:1100px; margin:0 auto; padding:24px 16px 64px; }\n header p { margin:4px 0 0; color:var(--muted); }\n h1 { font-size:1.6rem; margin:0; font-weight:600; }\n h2 { font-size:1.15rem; margin:32px 0 8px; }\n section > p.lede { color:var(--muted); margin:0 0 12px; max-width:70ch; }\n .frame { background:var(--paper); border:1px solid var(--rule); border-radius:10px; padding:16px; position:relative; }\n .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; }\n .yours { border-left:3px solid var(--accent); padding:4px 12px; margin:0; font-style:italic; }\n .label { font-size:0.75rem; color:var(--muted); text-transform:uppercase; letter-spacing:0.06em; margin:0 0 4px; }\n .now { font-weight:600; }\n .question { border-top:1px solid var(--rule); padding:14px 0; }\n .question:first-of-type { border-top:none; padding-top:4px; }\n .question .ask { font-weight:600; margin:0 0 4px; }\n .question .why { color:var(--muted); margin:0 0 8px; font-size:0.94rem; }\n .choice { display:flex; gap:8px; align-items:flex-start; margin:6px 0; }\n .choice span small { display:block; color:var(--muted); }\n textarea { width:100%; min-height:3.2em; font:inherit; border:1px solid var(--rule); border-radius:8px; padding:8px; margin:6px 0; }\n button { font:inherit; font-weight:600; border:none; border-radius:8px; padding:8px 14px; background:var(--accent); color:#fff; cursor:pointer; }\n button:disabled { opacity:0.5; cursor:default; }\n .props { list-style:none; margin:0; padding:0; }\n .props li { border-top:1px solid var(--rule); padding:12px 0; display:grid; grid-template-columns:1fr auto; gap:4px 16px; }\n .props li:first-child { border-top:none; }\n .chip { font-size:0.8rem; font-weight:700; border-radius:999px; padding:2px 10px; white-space:nowrap; align-self:start; justify-self:start; }\n .chip.good { color:var(--good); background:var(--goodSoft); }\n .chip.bad { color:var(--bad); background:var(--badSoft); }\n .chip.warn { color:var(--warn); background:var(--warnSoft); }\n .chip.quiet { color:var(--muted); background:var(--rule); }\n .props .choice-said { color:var(--muted); font-size:0.94rem; grid-column:1 / -1; }\n details { grid-column:1 / -1; font-size:0.88rem; }\n 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; }\n .empty { color:var(--muted); }\n .studio-action { border-top:1px solid var(--rule); padding:12px 0; }\n .studio-action:first-child { border-top:none; padding-top:0; }\n .studio-action h3 { font-size:1rem; margin:0 0 8px; font-weight:600; }\n .studio-ask, .studio-way { margin:0; }\n .studio-ways { list-style:none; margin:4px 0 0 9px; padding:0 0 0 14px; border-left:2px solid var(--rule); }\n .studio-ways > li { position:relative; padding:4px 0; }\n .studio-ways > li::before { content:''; position:absolute; left:-14px; top:15px; width:10px; border-top:2px solid var(--rule); }\n .studio-way, .studio-on { color:var(--muted); }\n .studio-on { margin:4px 0 0; }\n .studio-fold summary { cursor:pointer; color:var(--muted); }\n .studio-folded { margin:4px 0 0; padding-left:10px; border-left:2px dashed var(--rule); }\n .studio-outcome { display:grid; grid-template-columns:20px minmax(0, 1fr); align-items:center; gap:2px 8px; margin:2px 0 0; }\n .studio-said, .studio-ask, .studio-way, .studio-checks li { overflow-wrap:anywhere; }\n .studio-end { font-weight:600; }\n .studio-outcome[data-status=\"red\"] .studio-end { color:var(--bad); }\n .studio-outcome[data-status=\"green\"] .studio-end { color:var(--good); }\n .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); }\n .studio-checks li { min-width:0; }\n .studio-checks [data-verdict=\"fails\"] { color:var(--bad); font-weight:600; }\n .studio-checks [data-verdict=\"cannot say\"] { color:var(--warn); }\n .studio-unnamed, .studio-waiting { color:var(--faint); }\n .studio-stack { display:block; max-width:100%; height:auto; }\n .studio-band { fill:var(--page); }\n .studio-band[data-shade=\"1\"] { fill:#eef2f7; }\n .studio-section rect { fill:var(--paper); stroke:var(--faint); }\n .studio-canvas { fill:var(--paper); }\n .studio-section-name { fill:var(--ink); }\n .studio-section[data-named=\"false\"] .studio-section-name { fill:var(--faint); }\n .studio-section-does { fill:var(--muted); }\n .agent-layer { position:absolute; left:0; top:0; width:0; height:0; z-index:20; pointer-events:none; }\n .agent-ring { position:absolute; border-radius:10px; box-shadow:0 0 0 2px var(--agent), 0 0 0 8px var(--agentSoft); }\n .agent-bubble { position:absolute; pointer-events:auto; background:var(--paper); border:1px solid var(--agent); border-radius:4px 14px 14px 14px;\n padding:8px 30px 10px 12px; box-shadow:0 10px 28px rgba(15,23,42,0.18); font-size:0.94rem; }\n .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); }\n .agent-bubble[data-side=\"right\"] { border-radius:14px 14px 14px 14px; }\n .agent-bubble[data-side=\"right\"] .agent-tail { transform:rotate(-45deg); }\n .agent-who { margin:0 0 2px; font-size:0.72rem; font-weight:700; letter-spacing:0.06em; text-transform:uppercase; color:var(--agent); }\n .agent-who span { color:var(--muted); font-weight:600; }\n .agent-says { margin:0; overflow-wrap:anywhere; }\n .agent-close { position:absolute; top:4px; right:4px; background:none; color:var(--muted); padding:2px 8px; font-size:1rem; line-height:1; }\n .agent-in { animation:agent-in 280ms ease-out both; }\n @keyframes agent-in { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }\n @media (prefers-reduced-motion: reduce) { .agent-in { animation:none; } }\n @media (max-width:640px) { .props li { grid-template-columns:1fr; } }\n</style>\n</head>\n<body>\n<main>\n <header>\n <h1>Yichus studio<span id=\"project\"></span></h1>\n <p id=\"updated\">Waiting for your agent.</p>\n <p>Ask your agent what anything here means.</p>\n </header>\n <section aria-labelledby=\"h-asked\" data-section=\"asked\">\n <h2 id=\"h-asked\">${PAGE_HEADINGS.asked}</h2>\n <p class=\"label\">Your words</p>\n <p class=\"yours\" id=\"description\">Nothing yet. Tell your agent what you want to build.</p>\n </section>\n <section aria-labelledby=\"h-now\" data-section=\"now\">\n <h2 id=\"h-now\">${PAGE_HEADINGS.now}</h2>\n <div class=\"frame\"><span class=\"tag\">Yichus output</span>\n <p class=\"now\" id=\"summary\">No checks have run yet.</p>\n </div>\n </section>\n <section aria-labelledby=\"h-questions\" id=\"questions-section\" data-section=\"questions\" hidden>\n <h2 id=\"h-questions\">${PAGE_HEADINGS.questions}</h2>\n <p class=\"lede\">Your agent will ask you these too. Answer here or in the chat, whichever is easier.</p>\n <div class=\"frame\"><span class=\"tag\">Yichus output</span><div id=\"questions\"></div></div>\n </section>\n <section aria-labelledby=\"h-props\" data-section=\"props\">\n <h2 id=\"h-props\">${PAGE_HEADINGS.props}</h2>\n <div class=\"frame\"><span class=\"tag\">Yichus output</span><ul class=\"props\" id=\"props\"><li class=\"empty\">No properties chosen yet.</li></ul></div>\n </section>\n <section aria-labelledby=\"h-happens\" data-section=\"happens\">\n <h2 id=\"h-happens\">${PAGE_HEADINGS.happens}</h2>\n <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>\n <p class=\"label\">Drawn by Yichus. Words in italics are your agent's, not checked</p>\n <div class=\"frame\"><div id=\"happens\"><p class=\"empty\">This appears once the program compiles.</p></div></div>\n </section>\n <section aria-labelledby=\"h-sections\" data-section=\"sections\">\n <h2 id=\"h-sections\">${PAGE_HEADINGS.sections}</h2>\n <p class=\"lede\">The parts of your app, stacked: each layer is built only from the layers below it.</p>\n <p class=\"label\">Drawn by Yichus. Words in italics are your agent's, not checked</p>\n <div class=\"frame\"><div id=\"sections\"><p class=\"empty\">This appears once the program compiles.</p></div></div>\n </section>\n <section aria-labelledby=\"h-map\" data-section=\"map\">\n <h2 id=\"h-map\">${PAGE_HEADINGS.map}</h2>\n <div class=\"frame\"><div class=\"system-map\" id=\"map\"><p class=\"empty\">The map appears once the program compiles.</p></div></div>\n </section>\n</main>\n<script type=\"module\">\nimport { mount } from './system-map.js';\nimport { mountSections, mountWhatHappens, reportViewing, showMarks } from './studio-views.js';\n\nconst STATUS = ${JSON.stringify(PAGE_STATUS)};\nconst NO_ACTIONS = ${JSON.stringify(NO_ACTIONS)};\nconst el = (tag, props = {}, ...kids) => { const n = Object.assign(document.createElement(tag), props); n.append(...kids); return n; };\nlet mapHash = null, drawn = '';\n\nfunction questionCard(q, saved) {\n const card = el('div', { className: 'question' });\n card.dataset.question = q.id;\n card.append(el('p', { className: 'ask', textContent: q.ask }), el('p', { className: 'why', textContent: q.why }));\n const name = 'q-' + q.id;\n for (const c of q.choices) {\n const input = el('input', { type: 'radio', name, value: c.id, checked: saved?.choice === c.id });\n card.append(el('label', { className: 'choice' }, input, el('span', {}, c.label, el('small', { textContent: c.means }))));\n }\n const words = el('textarea', { placeholder: 'In your own words (optional)', value: saved?.words ?? '' });\n const status = el('span', { className: 'empty', textContent: saved ? ' Saved. Your agent will check it next.' : '' });\n const save = el('button', { type: 'button', textContent: 'Save answer' });\n save.addEventListener('click', async () => {\n const picked = card.querySelector('input[name=\"' + CSS.escape(name) + '\"]:checked');\n if (!picked) { status.textContent = ' Pick one of the choices first.'; return; }\n save.disabled = true;\n const label = q.choices.find(c => c.id === picked.value).label;\n const response = await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ question: q.id, choice: picked.value, words: words.value.trim() || label }) });\n const result = await response.json();\n status.textContent = result.ok ? ' Saved. Your agent will check it next.' : ' ' + result.error;\n save.disabled = false;\n });\n card.append(el('p', { className: 'label', textContent: 'Your words' }), words, save, status);\n return card;\n}\n\nfunction ruleRow(r) {\n const [words, tone] = STATUS[r.status];\n const li = el('li', {}, el('span', { textContent: 'A rule you gave: ' }, el('em', { textContent: r.rule })), el('span', { className: 'chip ' + tone, textContent: words }));\n li.append(el('span', { className: 'choice-said', textContent: 'Checked with ' + (r.laws === 1 ? '1 law' : r.laws + ' laws') + ' your agent wrote.' }));\n return li;\n}\n\nfunction propertyRow(p, saved) {\n const stale = saved && (!p.answer || p.answer.answeredAt !== saved.answeredAt);\n const [words, tone] = STATUS[stale ? 'pending' : p.status];\n const answer = stale ? saved : p.answer;\n const label = p.question.choices.find(c => c.id === answer.choice)?.label ?? answer.choice;\n const li = el('li', {}, el('span', { textContent: p.question.ask }), el('span', { className: 'chip ' + tone, textContent: words }));\n li.dataset.property = p.question.id;\n li.append(el('span', { className: 'choice-said', textContent: 'You chose: ' + label + (answer.words && answer.words !== label ? ' (\"' + answer.words + '\")' : '') }));\n return li;\n}\n\nasync function refresh() {\n const { state, requirements } = await (await fetch('/state')).json();\n const savedOf = id => requirements.answers.find(a => a.question === id);\n if (requirements.description) document.getElementById('description').textContent = requirements.description;\n // Before the first check there is nothing drawn, but the person may already be looking.\n if (!state) { viewing(null); return; }\n document.getElementById('project').textContent = ': ' + state.project;\n document.getElementById('updated').textContent = 'Last checked ' + new Date(state.updatedAt).toLocaleTimeString() + '.';\n document.getElementById('summary').textContent = state.summary;\n const open = state.properties.filter(p => p.status === 'unanswered' && !savedOf(p.question.id));\n document.getElementById('questions-section').hidden = !open.length;\n // Keep a half-written answer: only rebuild cards when the questions change.\n const qs = document.getElementById('questions');\n const ids = open.map(p => p.question.id).join(' ');\n if (qs.dataset.ids !== ids) { qs.dataset.ids = ids; qs.replaceChildren(...open.map(p => questionCard(p.question, savedOf(p.question.id)))); }\n const chosen = state.properties.filter(p => p.answer || savedOf(p.question.id));\n const rows = [...state.rules.map(ruleRow), ...chosen.map(p => propertyRow(p, savedOf(p.question.id)))];\n document.getElementById('props').replaceChildren(...(rows.length ? rows : [el('li', { className: 'empty', textContent: 'No properties chosen yet.' })]));\n // Redrawn only when the words or the program change.\n const views = JSON.stringify([state.hasActions, state.whatHappens, state.sections]);\n if (views !== drawn) {\n drawn = views;\n const happens = document.getElementById('happens');\n if (state.hasActions === false) happens.replaceChildren(el('p', { className: 'empty', textContent: NO_ACTIONS }));\n else if (state.whatHappens) mountWhatHappens(happens, state.whatHappens);\n else happens.replaceChildren(el('p', { className: 'empty', textContent: 'This appears once the program compiles.' }));\n if (state.sections) mountSections(document.getElementById('sections'), state.sections);\n }\n const map = document.getElementById('map');\n if (state.map && state.sourcesHash !== mapHash) { mapHash = state.sourcesHash; mount(map, state.map); }\n else if (!state.map && state.mapError) map.replaceChildren(el('p', { className: 'empty', textContent: 'The map could not be drawn: ' + state.mapError }));\n // Last, so each note is placed over the pictures as they are now drawn.\n showMarks(state.marks);\n viewing(state.drawing);\n}\n\n// What the person has in view goes to the studio, so their agent can follow\n// along when they say \"this one\".\nconst viewing = reportViewing(body => fetch('/viewing', { method: 'POST', headers: { 'content-type': 'application/json' }, body }));\n\nnew EventSource('/events').addEventListener('change', () => refresh());\nrefresh();\n</script>\n</body>\n</html>\n`;\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { ensureStudioDir, studioDir } from './requirements.js';\n\n// What the person has in view on the studio page, as the page last said:\n// the page's sections on screen, the drawn parts on screen, the questions\n// shown, the folds open, and the last thing the person clicked. The page\n// sends ids only, never words; page-view.ts says the words from the records\n// the page drew them from. Like the marks, this is the conversation's and\n// not the person's decisions, so .yichus/viewing.json is not committed. The\n// page server does not watch it, so a report never makes the page redraw.\n\n/** The page's sections, in the order the page shows them. */\nexport const PAGE_SECTIONS = ['asked', 'now', 'questions', 'props', 'happens', 'sections', 'map'] as const;\nexport type PageSection = (typeof PAGE_SECTIONS)[number];\n\nconst Id = z.string().min(1).max(200);\nconst Ids = z.array(Id).max(1000);\nconst Section = z.enum(PAGE_SECTIONS);\nconst Touched = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('section'), id: Section }).strict(),\n z.object({ kind: z.enum(['part', 'question', 'property']), id: Id }).strict(),\n]);\nconst Report = z.object({\n /** The page's tab is the one in front. */\n shown: z.boolean(),\n sections: z.array(Section).max(PAGE_SECTIONS.length),\n /** Anchors of the drawn parts on screen (person.ts). */\n parts: Ids,\n questions: Ids,\n /** Question ids of the properties shown. */\n properties: Ids,\n /** Anchors of the folds the person opened. */\n open: Ids,\n touched: Touched.nullable(),\n /** The drawing the anchors belong to (person.ts), or null before one is drawn. */\n drawing: z.string().max(64).nullable(),\n}).strict();\nexport type ViewingReport = z.infer<typeof Report>;\nconst Viewing = Report.extend({\n schemaVersion: z.literal('yichus-viewing-1'),\n at: z.string(),\n /** The page server the report came through: only it can tell that its page went. */\n server: z.string().optional(),\n /** When the last copy of the page open on that server went away, until a page connects again. */\n closed: z.string().optional(),\n}).strict();\nexport type Viewing = z.infer<typeof Viewing>;\n\nconst viewingPath = (root: string) => path.join(studioDir(root), 'viewing.json');\n\nexport function loadViewing(root: string): Viewing | null {\n const file = viewingPath(root);\n if (!fs.existsSync(file)) return null;\n const parsed = Viewing.safeParse(JSON.parse(fs.readFileSync(file, 'utf8')));\n if (!parsed.success) throw new Error(`${file} is not a yichus-viewing-1 file: ${z.prettifyError(parsed.error)}`);\n return parsed.data;\n}\n\nfunction writeViewing(root: string, viewing: Viewing) {\n ensureStudioDir(root);\n // Written beside it and renamed over it, so a reader never sees half a report.\n const file = viewingPath(root), written = `${file}.${process.pid}.tmp`;\n fs.writeFileSync(written, `${JSON.stringify(Viewing.parse(viewing), null, 2)}\\n`);\n fs.renameSync(written, file);\n}\n\n/** The page server saw its last open page go: what the page last said\n * through it stays, marked closed. A report through another server is that\n * server's page, which may still be open. */\nexport function recordClosed(root: string, server: string, now: Date): void {\n const last = loadViewing(root);\n if (last?.server === server) writeViewing(root, { ...last, closed: now.toISOString() });\n}\n\n/** A page connected to the server again, as one does by itself after the\n * server restarts or the computer wakes: it is open, and what it last said\n * still holds, since it reports again only when that changes. */\nexport function recordOpened(root: string, server: string): void {\n const last = loadViewing(root);\n if (last?.server === server && last.closed) {\n const { closed: _, ...open } = last;\n writeViewing(root, open);\n }\n}\n\n/** The page's latest report replaces the one before. */\nexport function recordViewing(root: string, server: string, report: unknown, now: Date): { ok: true } | { ok: false; error: string } {\n const parsed = Report.safeParse(report);\n if (!parsed.success) return { ok: false, error: `The page's report is not one this studio reads. ${z.prettifyError(parsed.error)}` };\n writeViewing(root, { schemaVersion: 'yichus-viewing-1', at: now.toISOString(), server, ...parsed.data });\n return { ok: true };\n}\n","import { ownPackages, readState } from './director.js';\nimport { loadMarks } from './marks.js';\nimport { NO_ACTIONS, PAGE_HEADINGS, PAGE_STATUS } from './page.js';\nimport { type Phrase, type Section, type Step, personDiagrams } from './person.js';\nimport { loadRequirements } from './requirements.js';\nimport { type Viewing, loadViewing } from './viewing.js';\nimport type { Say } from './surface.js';\nimport { nameableParts } from '../../../../web/system-map-names.js';\n\n// The studio page in words, for the agent driving the conversation: what the\n// page shows the person now, from the same records the page draws, and what\n// the person has in view. Everything here is computed; words in quotes are\n// the ones the agent or the person gave. Each part the agent can point at\n// carries, in brackets, the id yichus_point takes.\n\nconst quoted = (words: string | null, missing: string) => words === null ? missing : `\"${words}\"`;\nconst say = (phrase: Phrase) => phrase.map(p => typeof p === 'string' ? p : `\"${p.theirs}\"`).join('');\nconst TICK = { holds: '✓', fails: '✗', 'cannot say': '?' } as const;\nconst ENDING = {\n grey: 'no expectation is false here', red: 'something expected is false here', green: 'an ending that was broken is fixed', unchecked: 'the check cannot say',\n} as const;\n\n/** Seconds, minutes or hours, said plainly. */\nfunction ago(from: string, now: Date): string {\n const seconds = Math.max(0, Math.round((now.getTime() - Date.parse(from)) / 1000));\n const [n, unit] = seconds < 120 ? [seconds, 'second'] : seconds < 7200 ? [Math.round(seconds / 60), 'minute'] : [Math.round(seconds / 3600), 'hour'];\n return `${n} ${unit}${n === 1 ? '' : 's'} ago`;\n}\n\nexport function pageText(root: string, pageUrl: string | null, now: Date, surface: Say): string {\n const state = readState(root);\n const { description, answers, names = {} } = loadRequirements(root);\n const marks = loadMarks(root);\n const { sections, whatHappens, anchors, drawing } = state ? personDiagrams(state, names) : { sections: null, whatHappens: null, anchors: new Map<string, string>(), drawing: null };\n const codeAt = new Map([...anchors].map(([code, anchor]) => [anchor, code]));\n // What each part the agent can point at says, for the lines about what is in view.\n const said = new Map<string, string>();\n const part = (anchor: string, words: string) => { said.set(codeAt.get(anchor)!, words); return `[${codeAt.get(anchor)}]`; };\n\n const out: string[] = [`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.`];\n const heading = (key: keyof typeof PAGE_HEADINGS) => out.push('', `## ${PAGE_HEADINGS[key]}`);\n // Filled in last, once every part has its words.\n out.push('', '## What the person has in view');\n const inView = out.length;\n\n heading('asked');\n out.push(description ? `\"${description}\"` : 'Nothing yet.');\n heading('now');\n out.push(state ? state.step.summary : 'No checks have run yet.');\n\n const savedOf = (id: string) => answers.find(a => a.question === id);\n const open = (state?.properties ?? []).filter(p => p.status === 'unanswered' && !savedOf(p.question.id));\n if (open.length) {\n heading('questions');\n for (const { question: q } of open) out.push(`question ${q.id}: ${q.ask}`, ...q.choices.map(c => ` - ${c.label}: ${c.means}`));\n }\n heading('props');\n const chosen = (state?.properties ?? []).filter(p => p.answer || savedOf(p.question.id));\n const rules = state?.rules ?? [];\n if (!chosen.length && !rules.length) out.push('No properties chosen yet.');\n 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.`);\n for (const p of chosen) {\n const saved = savedOf(p.question.id);\n const stale = saved && (!p.answer || p.answer.answeredAt !== saved.answeredAt);\n const answer = stale ? saved : p.answer!;\n const label = p.question.choices.find(c => c.id === answer.choice)?.label ?? answer.choice;\n out.push(`question ${p.question.id}: ${p.question.ask} Status: ${PAGE_STATUS[stale ? 'pending' : p.status][0]}. They chose ${label}${answer.words && answer.words !== label ? ` (\"${answer.words}\")` : ''}.`);\n }\n\n heading('happens');\n const step = (s: Step, pad: string): string[] => {\n if (s.kind === 'outcome') {\n const end = `${s.refused ? 'turned away' : 'answered'}${s.words ? ` \"${s.words}\"` : ''}`;\n return [`${pad}${part(s.anchor, end)} ${end}: ${ENDING[s.status]}`, ...s.checks.map(c => `${pad} ${TICK[c.verdict]} ${say(c.says)}`)];\n }\n const asks = quoted(s.words, 'a check not described yet');\n return [`${pad}${part(s.anchor, asks)} checks ${asks}`, ...s.ways.flatMap(w => {\n const words = quoted(w.words, 'a way not described yet');\n return [`${pad} way ${words}${w.anchor === w.then.anchor ? '' : ` ${part(w.anchor, words)}`}:`, ...step(w.then, `${pad} `)];\n })];\n };\n if (state?.hasActions === false) out.push(NO_ACTIONS);\n else if (!whatHappens) out.push(state?.whatHappensError ? `It could not be drawn: ${state.whatHappensError}` : 'This appears once the program compiles.');\n else {\n if (!whatHappens.actions.length && !whatHappens.waiting) out.push('The app has no actions yet.');\n for (const a of whatHappens.actions) {\n const title = quoted(a.title, 'an action not described yet');\n out.push(`${part(a.anchor, title)} ${title}`, ...(a.first ? step(a.first, ' ') : [' This action could not be followed.']));\n }\n if (whatHappens.waiting) out.push(`${whatHappens.waiting} more ${whatHappens.waiting === 1 ? 'action is' : 'actions are'} not described yet.`);\n }\n\n heading('sections');\n const records = (verb: string, names: Array<string | null>) => names.length ? [`${verb} ${names.map(n => quoted(n, 'a kind of record not named yet')).join(', ')}`] : [];\n const does = (s: Section) => [...records('changes', s.changes), ...records('looks at', s.looks)].join(' · ') || 'keeps no records itself';\n if (!sections) out.push('This appears once the program compiles.');\n else sections.forEach((layer, i) => {\n out.push(`layer ${i + 1} of ${sections.length}${i === 0 ? ', the top' : ''}:`);\n for (const s of layer) {\n const name = quoted(s.name, 'a part not named yet');\n out.push(` ${part(s.anchor, name)} ${name}: ${does(s)}`);\n }\n });\n\n heading('map');\n if (state?.map) {\n const parts = nameableParts(state.map, ownPackages(state.layers));\n const unnamed = parts.filter(p => !(p.code in names)).length;\n 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.`);\n } else out.push(state?.mapError ? `The map could not be drawn: ${state.mapError}` : 'The map appears once the program compiles.');\n\n out.push('', '## Your notes on the page');\n // A report about another drawing says nothing about which part is which.\n const report = loadViewing(root);\n const viewing = report && { ...report, current: report.drawing === drawing };\n const visible = new Set(!viewing?.current ? [] : viewing.parts.flatMap(a => codeAt.has(a) ? [codeAt.get(a)!] : []));\n const notes = marks?.marks.filter(m => anchors.has(m.at)) ?? [];\n if (!notes.length) out.push(`None. ${surface.name('yichus_point')} puts a note over a part of the page.`);\n else out.push(`Said ${ago(marks!.said, now)}:`, ...notes.map(m => ` [${m.at}] \"${m.note}\"${visible.has(m.at) ? ' (on screen)' : ''}`));\n\n out.splice(inView, 0, ...inViewLines(viewing, codeAt, said, now, pageUrl));\n return `${out.join('\\n')}\\n`;\n}\n\nfunction inViewLines(viewing: (Viewing & { current: boolean }) | null, codeAt: Map<string, string>, said: Map<string, string>, now: Date, pageUrl: string | null): string[] {\n const link = 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.';\n if (!viewing) return [`The page has not said what is on screen: it may not be open. ${link}`];\n if (viewing.closed) return [`The person closed the page ${ago(viewing.closed, now)}, so it is not open now. ${pageUrl ? `If you want them to look at it, give them its link again: ${pageUrl}` : link}`];\n if (!pageUrl) return [`The page is not open: its server stopped after it last said what was on screen. ${link}`];\n const parts = (anchors: string[]) => !viewing.current ? [] : anchors.flatMap(a => codeAt.has(a) ? [`[${codeAt.get(a)}] ${said.get(codeAt.get(a)!)}`] : []);\n const list = (what: string, items: string[]) => items.length ? [`${what}:`, ...items.map(i => ` ${i}`)] : [];\n const { touched } = viewing;\n const clicked = !touched ? [] : touched.kind === 'section' ? [`Last clicked: in ${PAGE_HEADINGS[touched.id]}.`]\n : touched.kind === 'question' ? [`Last clicked: question ${touched.id}.`] : touched.kind === 'property' ? [`Last clicked: the property of question ${touched.id}.`]\n : parts([touched.id]).map(p => `Last clicked: ${p}`);\n return [\n `The page said this ${ago(viewing.at, now)}. ${viewing.shown ? 'Its tab is in front.' : 'Its tab is behind another one.'}`,\n `On screen: ${viewing.sections.map(s => PAGE_HEADINGS[s]).join(', ') || 'nothing of the page'}.`,\n ...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.'],\n ...list('Parts on screen', parts(viewing.parts)),\n ...list('Questions on screen', viewing.questions.map(q => `question ${q}`)),\n ...list('Properties on screen', viewing.properties.map(q => `question ${q}`)),\n ...list('Folds the person opened', parts(viewing.open)),\n ...clicked,\n ];\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport REFERENCE from './reference.json' with { type: 'json' };\n\n// Reference material the agent needs and cannot be expected to fetch: how\n// to guide the person, porting, deploying, laws, step programs and protocol\n// cases, each with worked files. The build copies each file next to the CLI\n// (scripts/copy-studio-assets.mjs) from the repository path reference.json\n// names. A file that names sections is given from those sections only: the\n// rest of it is about the Yichus repository, which the agent does not have.\nexport { REFERENCE };\nexport type Topic = keyof typeof REFERENCE;\nexport const TOPICS = Object.keys(REFERENCE) as Topic[];\ninterface File { name: string; from: string; sections?: string[] }\n\nexport const BUILT_REFERENCE = fileURLToPath(new URL('./studio-reference/', import.meta.url));\nexport const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url));\n\n/** Where a reference file is: the built copy, or the repository source. */\nexport type Locate = (file: { name: string; from: string }) => string;\nexport const builtCopy: Locate = file => path.join(BUILT_REFERENCE, file.name);\nexport const repoSource: Locate = file => path.join(REPO_ROOT, file.from);\n\n/** The parts of a Markdown file under the named headings, each up to the\n * next heading of the same or a higher level; the file's title gives the\n * text before its first section. */\nexport function sectionsOf(text: string, titles: string[]): string {\n const lines = text.split('\\n');\n // A line in a fenced code block is never a heading, whatever it starts with.\n let fenced = false;\n const headings = lines.map(line => {\n if (line.startsWith('```')) fenced = !fenced;\n const match = fenced ? null : /^(#+) (.*)$/.exec(line);\n return match ? { level: match[1]!.length, title: match[2]! } : null;\n });\n const parts = titles.map(title => {\n const start = headings.findIndex(h => h?.title === title);\n if (start < 0) throw new Error(`No section \"${title}\" in the reference file`);\n const level = Math.max(headings[start]!.level, 2);\n const end = headings.findIndex((h, i) => i > start && h !== null && h.level <= level);\n return lines.slice(start, end < 0 ? undefined : end).join('\\n').trim();\n });\n return `${parts.join('\\n\\n')}\\n`;\n}\n\n/** Every topic with what it is about, for an agent that has not picked one. */\nexport const topicList = (ask: (topic: string) => string) =>\n ['Reference topics:', ...TOPICS.map(topic => ` ${topic}: ${REFERENCE[topic].about} (${ask(topic)})`)].join('\\n');\n\nexport function readReference(topic: string, locate: Locate): string | null {\n if (!(TOPICS as string[]).includes(topic)) return null;\n return (REFERENCE[topic as Topic].files as File[]).map(file => {\n const text = fs.readFileSync(locate(file), 'utf8');\n return `===== ${file.name} =====\\n${file.sections ? sectionsOf(text, file.sections) : text}`;\n }).join('\\n\\n');\n}\n","{\n \"guiding\": {\n \"about\": \"How to guide the person through the studio page: what each part shows and when to bring it up.\",\n \"files\": [\n { \"name\": \"the-page.md\", \"from\": \"docs/studio/the-page.md\" }\n ]\n },\n \"porting\": {\n \"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.\",\n \"files\": [\n { \"name\": \"porting.md\", \"from\": \"docs/studio/porting.md\" },\n { \"name\": \"worker-authority.md\", \"from\": \"docs/runtime/worker-authority.md\", \"sections\": [\"Worker authority in generated APIs\", \"Secret bootstrap\"] }\n ]\n },\n \"deploy\": {\n \"about\": \"What to build for each place the app can run, with a working server, store and Render Blueprint to start from.\",\n \"files\": [\n { \"name\": \"deploy-platforms.md\", \"from\": \"docs/studio/deploy-platforms.md\" },\n { \"name\": \"server.mjs\", \"from\": \"docs/studio/deploy-example/server.mjs\" },\n { \"name\": \"store.mjs\", \"from\": \"docs/studio/deploy-example/store.mjs\" },\n { \"name\": \"render.yaml\", \"from\": \"docs/studio/deploy-example/render.yaml\" }\n ]\n },\n \"laws\": {\n \"about\": \"Writing a rule the person stated as a law the studio checks, and the standard functions the language has.\",\n \"files\": [\n { \"name\": \"laws.md\", \"from\": \"docs/studio/laws.md\" },\n { \"name\": \"consent.bosatsu\", \"from\": \"docs/studio/laws-example/consent.bosatsu\" },\n { \"name\": \"consent-laws.bosatsu\", \"from\": \"docs/studio/laws-example/consent-laws.bosatsu\" },\n { \"name\": \"balance.bosatsu\", \"from\": \"docs/studio/laws-example/limits/balance.bosatsu\" },\n { \"name\": \"balance-listed-laws.bosatsu\", \"from\": \"docs/studio/laws-example/limits/balance-listed-laws.bosatsu\" }\n ]\n },\n \"portable-programs\": {\n \"about\": \"Work that takes several steps or waits on an outside service, written as one pure step program a rule-free engine drives.\",\n \"files\": [\n { \"name\": \"portable-programs.md\", \"from\": \"docs/studio/portable-programs.md\" },\n { \"name\": \"refund-policy.bosatsu\", \"from\": \"demos/portable/refund-policy.bosatsu\" },\n { \"name\": \"refund-desk.bosatsu\", \"from\": \"demos/portable/refund-desk.bosatsu\" },\n { \"name\": \"refund-test.bosatsu\", \"from\": \"demos/portable/refund-test.bosatsu\" },\n { \"name\": \"refund-desk-one-round.bosatsu\", \"from\": \"demos/portable/limits/refund-desk-one-round.bosatsu\" }\n ]\n },\n \"protocol-case\": {\n \"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.\",\n \"files\": [\n { \"name\": \"protocol-cases.md\", \"from\": \"docs/studio/protocol-cases.md\" },\n { \"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\"] },\n { \"name\": \"withdrawal-case.json\", \"from\": \"eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/case.json\" },\n { \"name\": \"withdrawal.bosatsu\", \"from\": \"eval/corpus/webmcp-traps/iteration-003/programs/Q15/twin/ledger.bosatsu\" }\n ]\n },\n \"calculator\": {\n \"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.\",\n \"files\": [\n { \"name\": \"calculator.md\", \"from\": \"docs/studio/calculator.md\" }\n ]\n }\n}\n","import type { Status, StudioState } from './director.js';\n\n// The director's step in words, for an agent reading a tool result or a\n// terminal. The same state drives the page.\n\nexport const STATUS_WORDS: Record<Status, string> = {\n unanswered: 'not answered yet',\n decided: 'decided',\n assumed: 'holds under an assumption',\n proven: 'proven',\n bounded: 'holds in every scenario checked',\n broken: 'broken',\n mismatch: 'declared differently from the answer',\n 'needs-case': 'needs a failure scenario',\n 'needs-law': 'needs a law that checks it',\n unused: 'checked, but no action of the app uses what the law checks',\n inconclusive: 'not decided by the check',\n 'no-check': 'no check needed',\n};\n\nexport function stepText(state: StudioState, pageUrl: string | null): string {\n const { step } = state;\n const lines = [`Stage: ${step.stage}. ${step.summary}`, '', 'Do this:', ...step.instructions.map((s, i) => `${i + 1}. ${s}`)];\n if (step.items) lines.push('', `${step.items.heading}:`, ...step.items.lines.map(l => ` ${l}`));\n for (const q of step.ask ?? []) {\n lines.push('', `Question ${q.id}: ${q.ask}`, ` Why it matters: ${q.why}`);\n for (const c of q.choices) lines.push(` - ${c.id}: ${c.label}. ${c.means}`);\n }\n if (step.evidence?.length) lines.push('', 'Evidence (engine output):', ...step.evidence.map(e => ` ${e}`));\n const answered = state.properties.filter(p => p.status !== 'unanswered');\n if (answered.length) {\n lines.push('', 'Properties:');\n for (const p of answered) {\n const choice = p.question.choices.find(c => c.id === p.answer?.choice)?.label ?? p.answer?.choice;\n lines.push(` ${p.question.id} (${choice}): ${STATUS_WORDS[p.status]}`);\n }\n }\n if (state.rules.length) {\n lines.push('', 'Rules the person stated:');\n for (const r of state.rules) lines.push(` \"${r.rule}\" (${r.laws.join(', ')}): ${STATUS_WORDS[r.status]}`);\n }\n if (pageUrl) lines.push('', `Studio page: ${pageUrl}`);\n return `${lines.join('\\n')}\\n`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { ensureStudioDir, studioDir } from './requirements.js';\n\n// Where the running studio pages are, so the terminal commands can hand the\n// person a link. Each page server writes its own file in .yichus/pages/\n// when it starts and removes only that file when it stops, so a second page\n// for the folder stopping never hides one still running. A file whose server\n// died without removing it names a process that no longer runs: it is never\n// read as a link, and the next command to look removes it. A server that\n// starts also removes any other file for its own port, since it holds that\n// port now, so a dead server's file is gone even when its process id has\n// been reused.\n\nconst PageLink = z.object({ schemaVersion: z.literal('yichus-page-2'), url: z.string().url(), pid: z.number().int().positive(),\n startedAt: z.number().int().nonnegative() }).strict();\ntype PageLink = z.infer<typeof PageLink>;\n\nconst pagesDir = (root: string) => path.join(studioDir(root), 'pages');\n// One server per process and port: two servers never listen on one port.\nconst linkPath = (root: string, url: string, pid: number) => path.join(pagesDir(root), `${pid}-${new URL(url).port}.json`);\n\nexport function writePageLink(root: string, url: string, pid: number = process.pid, startedAt: number = Date.now()): void {\n ensureStudioDir(root);\n fs.mkdirSync(pagesDir(root), { recursive: true });\n // The one link file studios before .yichus/pages/ kept.\n fs.rmSync(path.join(studioDir(root), 'page.json'), { force: true });\n const port = new URL(url).port;\n for (const { file, link } of liveLinks(root)) if (new URL(link.url).port === port) fs.rmSync(file, { force: true });\n const file = linkPath(root, url, pid), written = `${file}.tmp`;\n fs.writeFileSync(written, `${JSON.stringify(PageLink.parse({ schemaVersion: 'yichus-page-2', url, pid, startedAt }), null, 2)}\\n`);\n fs.renameSync(written, file);\n}\n\n/** Remove the link of the page this process serves at `url`; every other page's stays. */\nexport function clearPageLink(root: string, url: string, pid: number = process.pid): void {\n fs.rmSync(linkPath(root, url, pid), { force: true });\n}\n\nconst running = (pid: number): boolean => {\n try { process.kill(pid, 0); return true; } catch (error) {\n // EPERM: the process runs, under another user.\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n};\n\n/** The links whose server still runs; the files of the others are removed. */\nfunction liveLinks(root: string): Array<{ file: string; link: PageLink }> {\n const dir = pagesDir(root);\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir).filter(name => name.endsWith('.json')).flatMap(name => {\n const file = path.join(dir, name);\n // A file cut short or edited by hand names no page; it never stops a command.\n let raw: unknown;\n try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { raw = null; }\n const parsed = PageLink.safeParse(raw);\n if (parsed.success && running(parsed.data.pid)) return [{ file, link: parsed.data }];\n fs.rmSync(file, { force: true });\n return [];\n });\n}\n\n/** The link of the studio page serving this folder now, the newest when several do. */\nexport function runningPageUrl(root: string): string | null {\n const live = liveLinks(root).map(({ link }) => link);\n return live.length ? live.reduce((a, b) => b.startedAt > a.startedAt ? b : a).url : null;\n}\n","import { once } from 'node:events';\nimport type { Readable, Writable } from 'node:stream';\nimport { fileURLToPath } from 'node:url';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { type ApiEngine, EngineWorkerClient, catalogTools } from '@yichus/api-mcp';\nimport type { StudioEngine } from './director.js';\nimport { createStudioMcpServer } from './mcp.js';\nimport { clearPageLink, writePageLink } from './page-link.js';\nimport { startPageServer } from './page-server.js';\n\nconst objectResult = (raw: string, tool: string): Record<string, unknown> => {\n const value: unknown = JSON.parse(raw);\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${tool} returned no JSON object`);\n return value as Record<string, unknown>;\n};\n\n/** The in-process engine, for one-shot commands. */\nexport const inProcessEngine = (engine: ApiEngine): StudioEngine => ({\n async call(tool, args) { return objectResult(engine.callTool(tool, JSON.stringify(args)), tool); },\n});\n\n/** The engine in a worker process: a long check never stalls the page or\n * the MCP stream, and a timed-out check is killed rather than left running.\n * A large program's report can take minutes, so the deadline is generous. */\nexport function workerEngine(bundle: string): StudioEngine & { catalog(): Promise<Tool[]>; close(): Promise<void> } {\n const worker = new EngineWorkerClient(bundle, 900_000);\n let id = 0;\n return {\n async call(tool, args) { return objectResult(await worker.callTool(tool, JSON.stringify(args), `studio-${++id}`), tool); },\n async catalog() { return catalogTools(await worker.listTools(`studio-${++id}`)); },\n close: () => worker.close(),\n };\n}\n\n// The page assets are copied next to the built CLI (scripts/copy-studio-assets.mjs).\nexport const BUILT_ASSETS = fileURLToPath(new URL('./studio-page/', import.meta.url));\n\nexport interface ServeOptions {\n root: string;\n /** null: the first free studio port. */\n port: number | null;\n pageOnly: boolean;\n bundle: string;\n stderr(text: string): void;\n assetsDir?: string;\n stdin?: Readable;\n stdout?: Writable;\n /** Page-only mode runs until this settles (default: Ctrl-C or a stop signal). */\n stopped?: Promise<unknown>;\n}\n\nexport async function serveStudio(options: ServeOptions): Promise<void> {\n const started = await startPageServer(options.root, options.assetsDir ?? BUILT_ASSETS, options.port);\n // The terminal commands read the link from the project folder.\n writePageLink(options.root, started.url);\n const page = { url: started.url, async close() { clearPageLink(options.root, started.url); await started.close(); } };\n options.stderr(`Yichus studio page: ${page.url}\\n`);\n if (options.pageOnly) {\n await (options.stopped ?? Promise.race([once(process, 'SIGINT'), once(process, 'SIGTERM')]));\n await page.close();\n return;\n }\n const engine = workerEngine(options.bundle);\n const { server, idle } = createStudioMcpServer({ root: options.root, engine, pageUrl: page.url, catalog: engine.catalog });\n const stdin = options.stdin ?? process.stdin;\n const closed = once(stdin, 'end');\n try {\n await server.connect(new StdioServerTransport(stdin, options.stdout ?? process.stdout));\n await closed;\n await idle();\n } finally {\n await server.close();\n await engine.close();\n await page.close();\n }\n}\n","import fs from 'node:fs';\nimport http from 'node:http';\nimport path from 'node:path';\nimport type { AddressInfo } from 'node:net';\nimport { type StudioState, readState } from './director.js';\nimport { recordAnswer } from './mcp.js';\nimport { STUDIO_PAGE } from './page.js';\nimport { relabelSystemMap } from '../../../../web/system-map-names.js';\nimport ASSETS from './page-assets.json' with { type: 'json' };\nimport { type Marks, loadMarks } from './marks.js';\nimport { personDiagrams } from './person.js';\nimport { ensureStudioDir, loadRequirements, studioDir } from './requirements.js';\nimport { recordClosed, recordOpened, recordViewing } from './viewing.js';\n\n// The page the person keeps open. It serves the latest .yichus/state.json,\n// requirements.json and marks.json, pushes a change event whenever one changes\n// (whoever ran the director: the MCP studio or `yichus next`), and takes the\n// person's answers and what they have in view (viewing.ts). It listens on loopback only and refuses requests from\n// any other origin or host name.\n\n/** The site's modules the page draws with; the build copies them next to the CLI. */\nexport const PAGE_ASSETS: readonly string[] = ASSETS;\n\n/** What the page may show: the person's own words, the questions, statuses\n * the map under the person's names, and the sections and what happens in\n * each action in the person's words only. Evidence, check names, file names\n * and the agent's instructions stay with the agent. What the agent points\n * at comes as anchors into those diagrams, each with the agent's note. */\nexport function personView(state: StudioState | null, names: Record<string, string>, marks: Marks | null = null) {\n if (!state) return null;\n const { sections, whatHappens, anchors, drawing } = personDiagrams(state, names);\n return {\n project: state.project,\n updatedAt: state.updatedAt,\n sourcesHash: state.sourcesHash,\n summary: state.step.summary,\n properties: state.properties.map(p => ({\n question: { id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices },\n answer: p.answer,\n status: p.status,\n })),\n // A state written before rules were kept has none.\n rules: (state.rules ?? []).map(r => ({ rule: r.rule, status: r.status, laws: r.laws.length })),\n map: state.map ? relabelSystemMap(state.map, names) : null,\n mapError: state.mapError,\n sections,\n // A state written before this field says nothing either way.\n hasActions: state.hasActions ?? null,\n whatHappens,\n // Sent back with what the person has in view, so a report about an\n // older drawing is not read against this one.\n drawing,\n // A mark on a part the page no longer draws is left out.\n marks: marks && { said: marks.said, marks: marks.marks.flatMap(m => anchors.has(m.at) ? [{ anchor: anchors.get(m.at)!, note: m.note }] : []) },\n };\n}\n\n// The names come from requirements.json, so a name shows as soon as the\n// agent records it.\nfunction stateBody(root: string) {\n const { description, answers, names } = loadRequirements(root);\n return { state: personView(readState(root), names ?? {}, loadMarks(root)), requirements: { description, answers } };\n}\n\nexport interface PageServer { url: string; close(): Promise<void> }\n\n/** Ports tried in order when none is asked for, so the page keeps its address\n * when the agent restarts the studio. A random port is the last resort. */\nexport const STUDIO_PORTS = [4317, 4318, 4319, 4320, 4321, 0];\n\nexport async function startPageServer(root: string, assetsDir: string, port: number | null = null, now = () => new Date()): Promise<PageServer> {\n ensureStudioDir(root);\n const clients = new Set<http.ServerResponse>();\n // Polled rather than fs.watch: macOS FSEvents can miss a write made just\n // after the watch starts, and polling also works on network folders.\n const watched = ['state.json', 'requirements.json', 'marks.json'].map(name => path.join(studioDir(root), name));\n const changed = (now: fs.Stats, before: fs.Stats) => {\n if (now.mtimeMs !== before.mtimeMs || now.size !== before.size) for (const res of clients) res.write('event: change\\ndata: {}\\n\\n');\n };\n for (const file of watched) fs.watchFile(file, { interval: 250 }, changed);\n const hosts = new Set<string>();\n // This server's own address, once it listens; and whether it is closing,\n // when the pages it drops are still open in the person's browser.\n let self = '', closing = false;\n const takes = new Map<string, (args: unknown) => { ok: boolean }>([\n ['/answer', args => recordAnswer(root, args, now())],\n ['/viewing', args => recordViewing(root, self, args, now())],\n ]);\n const server = http.createServer((req, res) => {\n const send = (status: number, type: string, body: string) => {\n res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });\n res.end(body);\n };\n // A page on another site, or a host name rebound to 127.0.0.1, is refused.\n const host = req.headers.host ?? '';\n if (!hosts.has(host) || (req.headers.origin && req.headers.origin !== `http://${host}`)) {\n send(403, 'text/plain', 'This studio only answers its own page.');\n return;\n }\n const url = new URL(req.url ?? '/', `http://${host}`);\n if (req.method === 'GET' && url.pathname === '/') return send(200, 'text/html; charset=utf-8', STUDIO_PAGE);\n if (req.method === 'GET' && url.pathname === '/state') {\n return send(200, 'application/json', JSON.stringify(stateBody(root)));\n }\n if (req.method === 'GET' && url.pathname === '/events') {\n res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });\n res.write(': connected\\n\\n');\n clients.add(res);\n recordOpened(root, self);\n // The last open page going, while this server runs, is the person\n // closing it: say so, or the agent goes on describing a page nobody has open.\n req.on('close', () => { clients.delete(res); if (!clients.size && !closing) recordClosed(root, self, now()); });\n return;\n }\n const asset = PAGE_ASSETS.find(a => url.pathname === `/${a}`);\n if (req.method === 'GET' && asset) {\n return send(200, asset.endsWith('.css') ? 'text/css' : 'text/javascript', fs.readFileSync(path.join(assetsDir, asset), 'utf8'));\n }\n // The person's answer, and what they have in view, as JSON.\n const take = req.method === 'POST' ? takes.get(url.pathname) : undefined;\n if (take) {\n if (req.headers['content-type'] !== 'application/json') return send(415, 'text/plain', 'Send JSON.');\n let body = '';\n req.setEncoding('utf8');\n req.on('data', chunk => { body += chunk; if (body.length > 65536) req.destroy(); });\n req.on('end', () => {\n let args: unknown;\n try { args = JSON.parse(body); } catch { return send(400, 'application/json', JSON.stringify({ ok: false, error: 'The request is not JSON.' })); }\n const result = take(args);\n send(result.ok ? 200 : 400, 'application/json', JSON.stringify(result));\n });\n return;\n }\n send(404, 'text/plain', 'Not found.');\n });\n for (const candidate of port === null ? STUDIO_PORTS : [port]) {\n const error = await new Promise<NodeJS.ErrnoException | null>(resolve => {\n server.once('error', resolve);\n server.listen(candidate, '127.0.0.1', () => { server.off('error', resolve); resolve(null); });\n });\n if (!error) break;\n if (error.code !== 'EADDRINUSE' || candidate === port) throw error;\n }\n const bound = (server.address() as AddressInfo).port;\n hosts.add(`127.0.0.1:${bound}`).add(`localhost:${bound}`);\n self = `http://127.0.0.1:${bound}/`;\n return {\n url: self,\n async close() {\n closing = true;\n for (const file of watched) fs.unwatchFile(file, changed);\n // Stop taking connections, then drop every open one: an open page\n // reconnects over its keep-alive socket, which would hold close() open.\n const closed = new Promise<void>(resolve => server.close(() => resolve()));\n server.closeAllConnections();\n await closed;\n },\n };\n}\n","[\"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\"]\n"],"mappings":";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAS,sBAAsB,kBAAkB,qBAAqB;;;ACDtE,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,mBAAmB,aAAAC,kBAAiB;AAE7C,SAAS,KAAAC,WAAS;;;ACJlB,SAAS,SAAS;AAKX,IAAM,iBAAiB,EAAE,KAAK,CAAC,UAAU,WAAW,YAAY,SAAS,CAAC;AAGjF,IAAM,WAAW,EAAE,YAAY;AAAA,EAC7B,IAAI,EAAE,OAAO;AAAA,EACb,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,EAC3B,QAAQ;AAAA,EACR,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA;AAAA,EAE3B,UAAU,EAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AAGM,IAAM,eAAe,EAAE,YAAY;AAAA,EACxC,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9B,SAAS,EAAE,YAAY;AAAA,IACrB,YAAY,EAAE,MAAM,QAAQ;AAAA,IAC5B,QAAQ,EAAE,MAAM,EAAE,OAA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O,MAAM;AACnB,UAAM,KAAK,MAAM;AAAA,EACnB;AACF;;;A3BrEA,IAAM,gBAAgB,CAAC,WAA4B;AACjD,QAAM,WAAW,UAAU,iBAAiB;AAC5C,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,2EAA2E;AAC1G,SAAO;AACT;AAEA,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,QAAQ,WAAW,gBAAgB,IAAI,KAAK,CAAC,KAAK,EAAE,IAChD,MAAM,iBAAiB,MAAM;AAAA,EAC7B,QAAQ,YAAY,gBAAgB,MAAM,cAAc,cAAc,CAAC,CAAC;AAAA,EACxE,OAAO,aAAW,YAAY,EAAE,GAAG,SAAS,QAAQ,cAAc,GAAG,QAAQ,CAACC,UAAS,QAAQ,OAAO,MAAMA,KAAI,EAAE,CAAC;AAAA,EACnH,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EAC3C,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EAC3C,KAAK,MAAM,oBAAI,KAAK;AAAA,EACpB,QAAQ;AACV,CAAC,IACC,MAAM,OAAO,MAAM;AAAA,EACnB,MAAM,WAAW,QAAQ;AACvB,WAAO,cAAc,cAAc,MAAM,CAAC;AAAA,EAC5C;AAAA,EACA,MAAM,cAAc,QAAQ,MAAM,SAAS,WAAW;AACpD,WAAO,qBAAqB,cAAc,MAAM,GAAG,MAAM,SAAS,SAAS;AAAA,EAC7E;AAAA;AAAA;AAAA,EAGA,WAAW,MAAMA,MAAK,QAAQ,KAAK;AAAA,EACnC,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EAC3C,QAAQ,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAC7C,CAAC;","names":["text","fs","path","parseArgs","z","text","said","reason","errors","lines","topology","shown","z","indent","EngineError","checker","plural","said","fs","path","fs","path","z","walk","theirs","text","VOCABULARY","bare","path","bare","leaves","VOCABULARY","bare","bare","walk","z","fs","path","z","z","z","Entry","walk","z","path","fs","reach","said","plural","say","title","z","fs","path","z","createHash","z","z","Property","Claim","Leaf","Tree","said","createHash","z","path","fs","fs","path","z","z","Report","path","fs","said","label","title","names","fs","path","path","text","title","fs","z","say","catalogTools","result","said","topology","fs","path","z","z","path","fs","file","argv","path","fs","said","label","z","argv","parseArgs","named","path","fs","said","text","fileURLToPath","fs","path","path","now","fs","fileURLToPath","text"]}