yichus 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +45 -16
  2. package/dist/cli.js +17 -2123
  3. package/dist/cli.js.map +1 -1
  4. package/dist/main.js +3762 -0
  5. package/dist/main.js.map +1 -0
  6. package/dist/studio-page/dom.js +22 -0
  7. package/dist/studio-page/label-fit.js +7 -0
  8. package/dist/studio-page/layer-diagram.js +458 -0
  9. package/dist/studio-page/layer-groups.js +129 -0
  10. package/dist/studio-page/source-link.js +17 -0
  11. package/dist/studio-page/studio-views.js +256 -0
  12. package/dist/studio-page/system-map-record.js +124 -10
  13. package/dist/studio-page/system-map.js +476 -87
  14. package/dist/studio-page/what-happens-record.js +224 -0
  15. package/dist/studio-page/what-happens.js +771 -0
  16. package/dist/studio-reference/balance-listed-laws.bosatsu +29 -0
  17. package/dist/studio-reference/balance.bosatsu +7 -0
  18. package/dist/studio-reference/calculator.md +20 -0
  19. package/dist/studio-reference/consent-laws.bosatsu +37 -0
  20. package/dist/studio-reference/consent.bosatsu +15 -0
  21. package/dist/studio-reference/deploy-platforms.md +79 -0
  22. package/dist/studio-reference/laws.md +62 -0
  23. package/dist/studio-reference/portable-programs.md +58 -0
  24. package/dist/studio-reference/porting.md +34 -0
  25. package/dist/studio-reference/protocol-cases.md +11 -0
  26. package/dist/studio-reference/{protocol-specification.txt → protocol-specification.md} +16 -18
  27. package/dist/studio-reference/refund-desk-one-round.bosatsu +196 -0
  28. package/dist/studio-reference/refund-desk.bosatsu +194 -0
  29. package/dist/studio-reference/refund-policy.bosatsu +97 -0
  30. package/dist/studio-reference/refund-test.bosatsu +75 -0
  31. package/dist/studio-reference/render.yaml +42 -0
  32. package/dist/studio-reference/server.mjs +33 -0
  33. package/dist/studio-reference/store.mjs +16 -0
  34. package/dist/studio-reference/the-page.md +130 -0
  35. package/dist/studio-reference/worker-authority.md +159 -0
  36. 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","../src/studio/project.ts","../src/studio/questions.ts","../src/studio/requirements.ts","../src/studio/mcp.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.ts"],"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 path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { type StudioEngine, direct, readState } from './director.js';\nimport { recordAnswer, recordNames } from './mcp.js';\nimport { type Locate, readReference } from './reference.js';\nimport { loadRequirements, saveRequirements } 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 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', '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 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 saveRequirements(root, { ...loadRequirements(root), description: rest[0]! });\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 === '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 { type SourceFile, caseSources, projectSources, sourcesHash } from './project.js';\nimport { ACCESS_POLICY, type Question, Report, Structure, questionsFor } from './questions.js';\nimport { type Answer, type Requirements, ensureStudioDir, studioDir } from './requirements.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' | '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}\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 '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 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\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 if (!state.files.length) return {\n stage: 'write',\n summary: 'No program yet.',\n instructions: [\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 '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 {\n stage: 'ask',\n summary: `${unanswered.length} question${unanswered.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: unanswered.map(p => ({ id: p.question.id, ask: p.question.ask, why: p.question.why, choices: p.question.choices })),\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 if (broken.length || state.other.length) return {\n stage: 'fix',\n summary: `${broken.length + state.other.length} propert${broken.length + state.other.length === 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 'Never weaken a rule, delete a check, or declare one server to make a check pass: change the code. Then call yichus_next.',\n ],\n evidence: [...broken.flatMap(p => p.evidence), ...state.other.flatMap(o => o.details)],\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 ],\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 };\n let compileErrors: string[] | null = null;\n if (requirements.description && sources.length) {\n const verify = Verify.parse(await call(engine, 'api_verify', { sources, ...(instances ? { instances } : {}) }));\n base.topology = verify.topology ?? null;\n base.proven = verify.verdict.proven;\n const compiles = verify.verdict.properties.find(p => p.id === 'compiles');\n if (compiles && compiles.status !== 'proven') compileErrors = compiles.details;\n else {\n const report = Report.parse(await call(engine, 'api_report', { sources }));\n const structureRaw = await call(engine, 'api_organize', { sources, lens: 'structure' });\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 if (withMap) {\n if (previous?.sourcesHash === hash && previous.map) base.map = previous.map;\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 } 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-2), 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// 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-2';\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 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; the count under the model says how many entries do <- entries[].model',\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: 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 a count: 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 <- 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 },\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))); };\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 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 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\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', '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","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 = '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\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. */\nconst 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/** 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 const ignore = path.join(dir, '.gitignore');\n if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, 'state.json\\n');\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 { type Locate, TOPICS, builtCopy, readReference } from './reference.js';\nimport { loadRequirements, saveRequirements, withAnswer, withNames } 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.\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 and whether each property they chose holds.\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, use the words they would use.\n\nEvery api_* tool is available too. Leave out sources and the studio supplies the project's files.`;\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 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) });\nconst AnswerArgs = z.object({ question: z.string().min(1), choice: z.string().min(1), words: z.string() });\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/** 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.' };\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\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.2.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, 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 parsed = StartArgs.safeParse(args);\n if (!parsed.success) return text('yichus_start needs the person\\'s description.', undefined, true);\n saveRequirements(root, { ...loadRequirements(root), description: parsed.data.description });\n const page = pageUrl ? `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, ...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_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 { 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}\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 { ensureStudioDir, loadRequirements, studioDir } from './requirements.js';\n\n// The page the person keeps open. It serves the latest .yichus/state.json and\n// requirements.json, pushes a change event whenever either file changes\n// (whoever ran the director: the MCP studio or `yichus next`), and takes the\n// person's answers. It listens on loopback only and refuses requests from\n// any other origin or host name.\n\nexport const PAGE_ASSETS = ['system-map.js', 'label-fit.js', 'system-map-record.js', 'system-map.css'] as const;\n\n/** What the page may show: the person's own words, the questions, statuses\n * and the map under the person's names. Evidence, check names, file names\n * and the agent's instructions stay with the agent. */\nexport function personView(state: StudioState | null, names: Record<string, string>) {\n if (!state) return null;\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 };\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 ?? {}), 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'].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 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 if (req.method === 'POST' && url.pathname === '/answer') {\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 answer is not JSON.' })); }\n const result = recordAnswer(root, args, now());\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","// The studio page: what the person asked for, questions waiting for them,\n// each property they chose with the engine's status, and the system map of\n// their 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. Text goes in through\n// textContent only.\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 * { 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 a.guide { color:var(--accent); font-weight:600; }\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 @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><a class=\"guide\" href=\"https://yich.us/start/studio.html#page\" target=\"_blank\" rel=\"noopener\">How to read this page</a> (opens in a new tab)</p>\n </header>\n <section aria-labelledby=\"h-asked\">\n <h2 id=\"h-asked\">What you asked for</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\">\n <h2 id=\"h-now\">What is happening 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\" hidden>\n <h2 id=\"h-questions\">Questions for you</h2>\n <p class=\"lede\">Your agent will ask you these too. Answer here or in the chat, whichever is easier. <a class=\"guide\" href=\"https://yich.us/start/studio.html#questions\" target=\"_blank\" rel=\"noopener\">About these questions</a></p>\n <div class=\"frame\"><span class=\"tag\">Yichus output</span><div id=\"questions\"></div></div>\n </section>\n <section aria-labelledby=\"h-props\">\n <h2 id=\"h-props\">What your program must do</h2>\n <p class=\"lede\"><a class=\"guide\" href=\"https://yich.us/start/studio.html#statuses\" target=\"_blank\" rel=\"noopener\">What each status means</a></p>\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-map\">\n <h2 id=\"h-map\">The shape of your program</h2>\n <p class=\"lede\"><a class=\"guide\" href=\"https://yich.us/start/studio.html#shape\" target=\"_blank\" rel=\"noopener\">How to read the picture</a></p>\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';\n\nconst STATUS = {\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};\nconst el = (tag, props = {}, ...kids) => { const n = Object.assign(document.createElement(tag), props); n.append(...kids); return n; };\nlet mapHash = null;\n\nfunction questionCard(q, saved) {\n const card = el('div', { className: 'question' });\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.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 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}\n\nnew EventSource('/events').addEventListener('change', () => refresh());\nrefresh();\n</script>\n</body>\n</html>\n`;\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,UAAS;;;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,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ines","topology","shown","z","indent","EngineError","checker","plural","path","fs","path","z","text","z","fs","path","z","z","path","fs","title","z","fs","path","path","fs","z","catalogTools","result","topology","argv","path","label","z","argv","parseArgs","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.1\",\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":[]}