yichus 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +17 -3192
- package/dist/cli.js.map +1 -1
- package/dist/main.js +3762 -0
- package/dist/main.js.map +1 -0
- package/dist/studio-page/system-map-record.js +3 -3
- package/dist/studio-page/system-map.js +41 -9
- package/dist/studio-page/what-happens-record.js +11 -4
- package/dist/studio-page/what-happens.js +48 -29
- package/dist/studio-reference/balance-listed-laws.bosatsu +29 -0
- package/dist/studio-reference/balance.bosatsu +7 -0
- package/dist/studio-reference/calculator.md +20 -0
- package/dist/studio-reference/consent-laws.bosatsu +37 -0
- package/dist/studio-reference/consent.bosatsu +15 -0
- package/dist/studio-reference/deploy-platforms.md +6 -6
- package/dist/studio-reference/laws.md +62 -0
- package/dist/studio-reference/porting.md +3 -1
- package/dist/studio-reference/protocol-cases.md +11 -0
- package/dist/studio-reference/{protocol-specification.txt → protocol-specification.md} +16 -18
- package/dist/studio-reference/refund-desk-one-round.bosatsu +21 -18
- package/dist/studio-reference/refund-desk.bosatsu +21 -18
- package/dist/studio-reference/render.yaml +42 -0
- package/dist/studio-reference/server.mjs +33 -0
- package/dist/studio-reference/store.mjs +16 -0
- package/dist/studio-reference/the-page.md +34 -11
- package/dist/studio-reference/withdrawal.bosatsu +11 -15
- package/package.json +2 -2
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.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/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/serve.ts","../src/studio/page-server.ts","../src/studio/page-assets.json"],"sourcesContent":["#!/usr/bin/env node\nimport { 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';\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 ...]\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 --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 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 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.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\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 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 { recordAnswer, recordNames, recordScenarios, recordStart } from './mcp.js';\nimport { type Locate, readReference } from './reference.js';\nimport { recordMarks } from './marks.js';\nimport { pageText } from './page-view.js';\nimport { loadRequirements } from './requirements.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 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\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', 'scenario', 'point', 'page', 'reference', 'studio']);\n\nexport const STUDIO_HELP = `\nStudio (guided building; all take --project DIR, default the current folder):\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 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\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]! });\n if (!result.ok) throw new Error(result.error);\n io.stderr('Recorded the description. Next: 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 });\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());\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 === 'scenario') {\n expect(1, 'yichus scenario FILE.json');\n const result = recordScenarios(root, JSON.parse(fs.readFileSync(path.resolve(rest[0]!), 'utf8')));\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, null, io.now()));\n return 0;\n }\n if (command === 'reference') {\n expect(1, 'yichus reference TOPIC');\n const said = readReference(rest[0]!, io.locate);\n if (!said) throw new Error(`No reference topic ${rest[0]!}`);\n io.stdout(`${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) });\n io.stdout(values.json ? `${JSON.stringify(state, null, 2)}\\n` : stepText(state, null));\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_POLICY, PLATFORM_SECTION, type Question, Report, Structure, platform, questionsFor } from './questions.js';\nimport { type Answer, type Requirements, ensureStudioDir, studioDir } from './requirements.js';\nimport { WhatHappens, owed, unfollowed } from './scenarios.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' | '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\nexport type Stage = 'describe' | 'write' | 'fix-compile' | 'name' | 'ask' | 'scenarios' | 'declare' | 'fix' | '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 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\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 step: Step;\n map: unknown;\n mapError: string | null;\n /** api_organize lens=layers, for the layer stack. */\n layers: unknown;\n /** Each entry'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;\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, answer: Answer | null,\n report: Report, verify: VerifyProperty[]): Promise<Property> {\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 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 want = ACCESS_POLICY[answer.choice];\n const declared = table?.policy ?? null;\n if (!want || !declared || !declared.startsWith(want)) {\n return { ...base, status: 'mismatch', check: 'api_report dataModel.tables[].policy',\n evidence: [`\"${question.subject}\" is declared ${declared ?? 'with no rule'}; the person chose ${want ?? answer.choice}.`] };\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 const props = verify.filter(p => p.id === 'rmw-transactions' || p.id === 'integrity');\n const bad = worst(props);\n const mentions = (p: VerifyProperty) => p.details.filter(d => d.includes(`\"${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 QUESTION_PROPERTIES = (id: string) => id.startsWith('access:') || id === 'access-coverage' || id === 'rmw-transactions' || id === 'integrity';\n\nconst GUIDE: Record<Question['kind'], string> = {\n platform: 'Deploy',\n topology: 'Multi-instance data integrity',\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\nconst askStep = (open: Property[]): Step => ({\n stage: 'ask',\n summary: `${open.length} question${open.length === 1 ? '' : 's'} 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 with yichus_answer (the question id, the choice id, and their own words), then call 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\nexport function nextStep(state: Omit<StudioState, 'step'>, compileErrors: string[] | null): Step {\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. Call yichus_start with their description, unchanged.'],\n };\n // Where the app runs decides what to build, so it is asked first; every\n // later step follows that platform's section of the deploy reference.\n const where = state.properties.find(p => p.question.kind === 'platform')!;\n if (!where.answer) return askStep([where]);\n const deploySection = PLATFORM_SECTION[where.answer.choice]!;\n if (!state.files.length) return {\n stage: 'write',\n summary: 'No program yet.',\n instructions: [\n `Call yichus_reference with topic \"deploy\" and build what its \"${deploySection}\" section says: which pieces run where, the database, and how background work starts.`,\n 'Call api_guide with section \"Required workflow\", then write the program as .bosatsu files in this project folder.',\n 'For an app that stores records, call api_scaffold first and save its module as a file here. You never need to pass sources: the studio reads every .bosatsu file in the folder.',\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: call yichus_reference with topic \"portable-programs\" before writing it.',\n 'Then call yichus_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, then call yichus_next.'],\n evidence: compileErrors,\n };\n // Questions name their subjects, and the picture draws every part.\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 state.map ? nameableParts(state.map) : []) {\n if (!(code in state.names) && !unnamed.has(code)) unnamed.set(code, [`${what[0]!.toUpperCase()}${what.slice(1)}.`]);\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 these parts of the program in questions and in the picture of the program. Give each a short name in the person\\'s own vocabulary, never a code name, path or table name (for example \"family lists\" or \"starting a new list\"). Name a kind of value plainly too (\"text\", \"a number\"):',\n ...[...unnamed].map(([subject, facts]) => `${subject}: ${facts.join(' ')}`),\n 'Call yichus_name with all of them at once, then call yichus_next.',\n ],\n };\n const unanswered = state.properties.filter(p => p.status === 'unanswered');\n if (unanswered.length) return askStep(unanswered);\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 below, as the person would say it, and call 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 ...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 'Then call yichus_next.',\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 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 => `Make the AccessSpec rule for \"${p.question.subject}\" ${ACCESS_POLICY[p.answer!.choice]} (api_add_rule gives the snippet; api_guide section \"${p.answer!.choice === 'owner' ? 'Owner-scoped data' : p.answer!.choice === 'shared' ? 'Guarded data' : 'Public data'}\" explains it).`),\n 'Then call yichus_next.',\n ],\n evidence: mismatched.flatMap(p => p.evidence),\n };\n const broken = state.properties.filter(p => p.status === 'broken' || p.status === 'inconclusive');\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 unchecked = (state.whatHappensError ? 1 : 0) + unfollowedEntries.length;\n const open = broken.length + state.other.length + claims.length + unchecked;\n if (open) return {\n stage: 'fix',\n summary: `${open} propert${open === 1 ? 'y is' : 'ies 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 ...broken.map(p => `\"${p.question.ask}\" The person chose \"${p.question.choices.find(c => c.id === p.answer?.choice)?.label}\". Read api_guide section \"${GUIDE[p.question.kind]}\".`),\n ...state.other.map(o => `${o.title} (${o.id}) is ${o.status}.`),\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. Then call yichus_next.',\n ],\n evidence: [...broken.flatMap(p => p.evidence), ...state.other.flatMap(o => o.details),\n ...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 'Call yichus_reference with topic \"protocol-case\": it returns 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. Then call yichus_next.',\n ],\n };\n const assumed = state.properties.filter(p => p.status === 'assumed');\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 'When they describe a new feature, change the code and call yichus_next again: new facts can raise new questions.',\n `When they want the app online, follow the \"${deploySection}\" section of yichus_reference topic \"deploy\"; api_deploy generates the server.`,\n ],\n };\n}\n\nexport interface RunOptions { root: string; engine: StudioEngine; requirements: Requirements; withMap?: boolean; previous?: StudioState | null }\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 }: 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 map: null as unknown,\n mapError: null as string | null,\n layers: null as unknown,\n whatHappens: null as WhatHappens | null,\n whatHappensError: null as string | null,\n };\n let compileErrors: string[] | null = null;\n // Where the app runs is asked before there is code, so no engine fact backs it.\n if (requirements.description) base.properties.push(await judge(root, engine, sources, platform, answerOf(requirements, platform.id), Report.parse({}), []));\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 for (const question of questionsFor(report, structure, base.names)) {\n base.properties.push(await judge(root, engine, sources, question, answerOf(requirements, question.id), report, verify.verdict.properties));\n }\n base.other = verify.verdict.properties\n .filter(p => !QUESTION_PROPERTIES(p.id) && p.status !== 'proven' && !isAccepted(p))\n .map(({ id, title, status, details }) => ({ id, title, status, details }));\n try {\n const access = await call(engine, 'api_access_check', { sources });\n base.whatHappens = WhatHappens.parse(buildWhatHappens({ structure: structureRaw, access }, { program: base.project }));\n } catch (error) {\n base.whatHappensError = error instanceof Error ? error.message : String(error);\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) };\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 the hull band 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 <- 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 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 role a person can hold', 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\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. */\nexport function nameableParts(map) {\n const found = new Map();\n const add = (code, what) => { if (code && !found.has(code)) found.set(code, what); };\n const idParts = id => { const i = id.lastIndexOf('::'); 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(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, \"no base compared\" when no earlier version was compared) <- 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\", struck <- 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, one row per arm that skips the handler, read as a side stub (the arm, its struck writes, what the request gets, ticks), then \"continue\" (a transaction: \"runs\"), and its effects; 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}\nexport function outcomeLabel(o) {\n if (o.status && !o.constructors.length) return o.shown;\n const head = o.constructors.length ? o.constructors.join(' | ') : (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' | '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() });\nconst Route = z.looseObject({ path: z.string(), handler: z.string(), inferredSteps: z.array(Step).default([]) });\nconst Table = z.looseObject({\n name: z.string(),\n policy: z.string().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\nexport const ACCESS_POLICY: Record<string, string> = {\n owner: 'OwnerScoped',\n shared: 'Guarded',\n 'everyone-reads': 'PublicReadRoleWrite',\n public: 'Public',\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\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.' },\n { id: 'shared', label: 'The creator and people they share it with', means: 'Every read goes through a sharing rule, and the check proves nothing skips it.' },\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: string, handlers: string[], names: Names): Question {\n return {\n id: `together:${table}`,\n kind: 'together',\n subject: table,\n ask: `Two requests change the same record in \"${shown(names, table)}\" at the same moment (two people, or one person on two devices). What should happen?`,\n why: 'When a request reads a record and then writes it back, a second request in between can be silently lost. People rarely notice until data goes missing.',\n choices: [\n { id: 'keep-both', label: 'Both changes are kept', means: 'Each change happens as one indivisible step, so neither can overwrite the other unseen; the check proves no change is lost.' },\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}\" 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\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.name, 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 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\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});\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, and\n // what the person has in view stay out of the person's 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'].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() });\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/** 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","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, readState } from './director.js';\nimport { caseSources, projectSources } from './project.js';\nimport { recordMarks } from './marks.js';\nimport { pageText } from './page-view.js';\nimport { type Locate, TOPICS, builtCopy, readReference } from './reference.js';\nimport { loadRequirements, saveRequirements, withAnswer, withNames, withScenarios } from './requirements.js';\nimport { stepText } from './text.js';\nimport { nameableParts } from '../../../../web/system-map-names.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 proves the properties the person chooses.\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 declare a single server to make a check pass. Change the code.\n5. Give the person the studio page link from yichus_start. 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 the programming language, code names, file names, tool names or question ids; when yichus_next asks you to name parts of the program or describe what happens, use the words they would use.\n7. Build for the place the person chose to run the app (yichus_reference topic \"deploy\"). 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 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, such as the protocol case specification with a complete worked case.',\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 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): { ok: true } | { ok: false; error: string } {\n const parsed = StartArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `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): { ok: true } | { ok: false; error: string } {\n const parsed = AnswerArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `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 yichus_next; call 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): { ok: true } | { ok: false; error: string } {\n const parsed = NameArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: 'yichus_name needs names: each code 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?.map ? nameableParts(state.map).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 return { ok: false, error: `No part named ${unknown.join(', ')} in the latest yichus_next; the parts are ${listed || 'none yet'}.` };\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): { ok: true } | { ok: false; error: string } {\n const parsed = ScenarioArgs.safeParse(args);\n if (!parsed.success) return { ok: false, error: `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 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 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\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.0' }, { 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, 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 const page = pageUrl ? `Read yichus_reference topic \"guiding\", then give the person this link and ask them to keep it open: ${pageUrl}` : 'No studio page is running.';\n return text(`${page}\\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_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()));\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)}; the topics are ${TOPICS.join(', ')}.`, 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 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\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 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 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 document.getElementById('props').replaceChildren(...(chosen.length ? chosen.map(p => propertyRow(p, savedOf(p.question.id)))\n : [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.whatHappens, state.sections]);\n if (views !== drawn) {\n drawn = views;\n if (state.whatHappens) mountWhatHappens(document.getElementById('happens'), state.whatHappens);\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 { readState } from './director.js';\nimport { loadMarks } from './marks.js';\nimport { 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 { 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): 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 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 if (!chosen.length) out.push('No properties chosen yet.');\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 (!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);\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. 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));\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): string[] {\n if (!viewing) return ['The page has not said what is on screen: it may not be open. Give the person the link yichus_start returned.'];\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: the\n// protocol case specification and a complete worked case. The build copies\n// each file next to the CLI (scripts/copy-studio-assets.mjs) from the\n// repository path reference.json names.\nexport { REFERENCE };\nexport type Topic = keyof typeof REFERENCE;\nexport const TOPICS = Object.keys(REFERENCE) as Topic[];\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\nexport function readReference(topic: string, locate: Locate): string | null {\n if (!(TOPICS as string[]).includes(topic)) return null;\n return REFERENCE[topic as Topic].map(file => `===== ${file.name} =====\\n${fs.readFileSync(locate(file), 'utf8')}`).join('\\n\\n');\n}\n","{\n \"protocol-case\": [\n { \"name\": \"protocol-specification.txt\", \"from\": \"docs/protocol-verification.md\" },\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 \"portable-programs\": [\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 \"deploy\": [\n { \"name\": \"deploy-platforms.md\", \"from\": \"docs/studio/deploy-platforms.md\" }\n ],\n \"guiding\": [\n { \"name\": \"the-page.md\", \"from\": \"docs/studio/the-page.md\" }\n ],\n \"porting\": [\n { \"name\": \"porting.md\", \"from\": \"docs/studio/porting.md\" },\n { \"name\": \"worker-authority.md\", \"from\": \"docs/runtime/worker-authority.md\" }\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 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 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 (pageUrl) lines.push('', `Studio page: ${pageUrl}`);\n return `${lines.join('\\n')}\\n`;\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 { 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). */\n stopped?: Promise<unknown>;\n}\n\nexport async function serveStudio(options: ServeOptions): Promise<void> {\n const page = await startPageServer(options.root, options.assetsDir ?? BUILT_ASSETS, options.port);\n options.stderr(`Yichus studio page: ${page.url}\\n`);\n if (options.pageOnly) {\n await (options.stopped ?? once(process, 'SIGINT'));\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 map: state.map ? relabelSystemMap(state.map, names) : null,\n mapError: state.mapError,\n sections,\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\", \"dom.js\", \"layer-groups.js\", \"layer-diagram.js\", \"source-link.js\", \"what-happens.js\", \"what-happens-record.js\", \"studio-views.js\"]\n"],"mappings":";;;AACA,SAAS,QAAAA,aAAY;AACrB,SAAS,sBAAsB,kBAAkB,qBAAqB;;;ACFtE,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,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA;AAAA;AAAA,IAGtC,iBAAiB,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAChD,CAAC;AACH,CAAC;AAGM,IAAM,gBAAgB,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;AAGrF,IAAM,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EA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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","errors","lines","topology","shown","z","indent","EngineError","checker","plural","fs","path","fs","path","z","walk","text","VOCABULARY","bare","path","bare","leaves","VOCABULARY","bare","walk","z","fs","path","z","z","z","Entry","walk","z","path","fs","title","z","fs","path","z","createHash","z","z","Property","Claim","Leaf","Tree","createHash","z","path","fs","fs","path","z","z","Report","path","fs","label","title","names","fs","path","path","fs","z","catalogTools","result","topology","argv","path","fs","label","z","argv","parseArgs","named","path","fs","text","fileURLToPath","fs","path","path","now","fs","fileURLToPath","text"]}
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/node-version.ts","../src/cli.ts"],"sourcesContent":["{\n \"name\": \"yichus\",\n \"version\": \"0.3.2\",\n \"description\": \"Local Bosatsu compilation, Yichus analysis, and generated apps using the WebMCP engine\",\n \"license\": \"MIT\",\n \"homepage\": \"https://yich.us\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/snoble/yichus.git\",\n \"directory\": \"packages/yichus-cli\"\n },\n \"type\": \"module\",\n \"bin\": {\n \"yichus\": \"./dist/cli.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup && node ./scripts/copy-studio-assets.mjs\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run --coverage\",\n \"prepack\": \"npm run build\"\n },\n \"dependencies\": {\n \"@yichus/api-mcp\": \"workspace:*\",\n \"zod\": \"^4.3.6\",\n \"@modelcontextprotocol/sdk\": \"^1.26.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^22.0.0\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.6.0\",\n \"vitest\": \"^2.1.0\",\n \"@vitest/coverage-v8\": \"2.1.9\"\n },\n \"engines\": {\n \"node\": \">=20\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","/**\n * The sentence that stops the command on a Node older than the package's\n * `engines.node` floor, or undefined when the running Node meets it.\n */\nexport function nodeVersionProblem(running: string, required: string): string | undefined {\n const floor = /^>=(\\d+)$/.exec(required);\n if (!floor) throw new Error(`engines.node must read >=N, not ${required}`);\n const needed = Number(floor[1]);\n if (Number(running.split('.')[0]) >= needed) return undefined;\n return `yichus needs Node ${needed} or newer; this is Node ${running}. Install Node ${needed} or newer and run the command again.`;\n}\n","#!/usr/bin/env node\n// The Node check runs before the rest of the command loads, so an older\n// Node gets a sentence naming what to install rather than an error from\n// inside the engine.\nimport { engines } from '../package.json';\nimport { nodeVersionProblem } from './node-version.js';\n\nconst problem = nodeVersionProblem(process.versions.node, engines.node);\nif (problem) {\n process.stderr.write(`${problem}\\n`);\n process.exitCode = 1;\n} else {\n await import('./main.js');\n}\n"],"mappings":";;;AAqCE,cAAW;AAAA,EACT,MAAQ;AACV;;;ACnCK,SAAS,mBAAmB,SAAiB,UAAsC;AACxF,QAAM,QAAQ,YAAY,KAAK,QAAQ;AACvC,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,mCAAmC,QAAQ,EAAE;AACzE,QAAM,SAAS,OAAO,MAAM,CAAC,CAAC;AAC9B,MAAI,OAAO,QAAQ,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,OAAQ,QAAO;AACpD,SAAO,qBAAqB,MAAM,2BAA2B,OAAO,kBAAkB,MAAM;AAC9F;;;ACHA,IAAM,UAAU,mBAAmB,QAAQ,SAAS,MAAM,QAAQ,IAAI;AACtE,IAAI,SAAS;AACX,UAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,CAAI;AACnC,UAAQ,WAAW;AACrB,OAAO;AACL,QAAM,OAAO,WAAW;AAC1B;","names":[]}
|