# Jig ### A two origin, agent native design workbench built on WebMCP, where a person and an agent edit the same live document through the same unbypassable gate. **What it is.** Jig grades knitting patterns. Grading is the job of resizing one garment across a whole run of sizes while every number stays locked to every other one: cast on counts, row counts, yoke increases, finished measurements, and how much yarn it takes. Get a single number wrong and the pattern reads perfectly and cannot be knitted. **Why I built it.** My family's business is yarn, and I grew up around patterns covered in red pen. The knitter finds the mistake after buying the wool and knitting half a sleeve. Designers do this work in spreadsheets today, and a spreadsheet cannot refuse a number. So I built the thing that can, for myself first, and I have been grading real patterns in it since. **This is the future of the open web in one page: humans and agents interacting, collaborating, and creating together on a shared artifact, with neither one privileged and neither one locked out.** Ask the agent for a cast on of 87 stitches. The document refuses, names the rule that was broken, and hands back the two numbers that actually fit. The agent reads the refusal, corrects itself, and the change lands in front of you in the size table. No server round trip, no hidden state, no session to hand over. **A complete, deployed, self verifying product.** | | | |---|---| | **Demo video** | **[youtu.be/jNH0qcJe-DQ](https://youtu.be/jNH0qcJe-DQ)** | | **Live workbench** | **[jig-workbench.pages.dev](https://jig-workbench.pages.dev)** | | **Live partner origin** | **[jig-yarn-service.pages.dev](https://jig-yarn-service.pages.dev)** | | **Works in** | ChatGPT's in-app browser, and Chrome 149+ with WebMCP enabled, and **ordinary Chrome with no flag at all** | | **Setup required** | None. No install, no API key, no signup | | **WebMCP tools** | **14 descriptors across 2 real origins** | | **Registration paths used** | All of them: hook, raw with `AbortSignal`, raw with `exposedTo`, and declarative HTML | | **Test suite** | **1,641 tests across 108 files**, all green | | **Formal correctness properties** | **16**, machine audited against the design document | | **Agent evaluation score** | **4 of 4** with `gpt-4o-mini`, on Chrome's own WebMCP host and on ours | | **Browser proof, no model needed** | `npm run verify:browser`, **11 of 11 checks** | | **License** | **MIT**, see [LICENSE](./LICENSE) | --- ## Try it in 60 seconds **Watch the demo: [youtu.be/jNH0qcJe-DQ](https://youtu.be/jNH0qcJe-DQ)** Or open **[jig-workbench.pages.dev](https://jig-workbench.pages.dev)** directly in ChatGPT's in-app browser, or in Chrome with `chrome://flags/#enable-webmcp-testing` enabled, or in plain Chrome with nothing enabled. All three work. 1. Top left, in **Ask the agent**, press **The cast on that cannot exist**. 2. Watch four real tool calls fire. The second is **refused**. The refusal names **86 and 98** as the only counts that fit a twelve stitch cable repeat plus two edge stitches. 3. The agent reads that refusal, sends **86**, and the cast on cell changes in front of you. 4. Open the **transcript** from the masthead switch. Every call, every refusal, every reason, and who authored it, in plain English. Then type your own sentence. Try `set the cast on for size M to 87 stitches`, get refused, then follow up with `now use the nearest count below that fits`. Conversation state travels with the request, so the second instruction resolves against the first. **Nothing to configure and no key to paste.** The deployment carries its own model server side in [`apps/jig/functions/api/model.ts`](./apps/jig/functions/api/model.ts), a Cloudflare Pages Function holding the key as an encrypted secret so it never reaches the bundle. **Why it works with no flag.** [`packages/webmcp/src/polyfill.ts`](./packages/webmcp/src/polyfill.ts) installs a stand in host that reproduces Chrome's measured WebMCP behaviour exactly, refusals included, so every visitor gets a working agent surface. Enable the flag and the identical application code drives the browser's real surface instead. The capability panel and the ask panel both tell you which host answered, and the tool count rises from nine to ten, because the tenth is `setup_project`, which **the browser itself derives from annotated HTML** rather than from any registration call. --- ## The four questions, answered up front ### 1. Why this use case is a strong fit for WebMCP Pattern grading is resizing one garment across up to thirteen sizes while every number stays mutually constrained. The arithmetic is simple to state and completely unforgiving: - Cast on is bust width times stitch gauge, **rounded to a multiple of the stitch repeat**. - A raglan yoke can only reach a target stitch count in **whole increase rounds of eight**. - Shaping has to land on **whole rows**. - Armhole depth, cross back and neck drop **have to grow as sizes grow**. Break one and you get a pattern that reads perfectly and cannot be knitted. Language is fluent about this and the arithmetic is merciless, and that gap is exactly where WebMCP belongs, for three reasons. **The rules can refuse.** A tool call is a proposal, not a command. A wrong number comes back with the rule it broke and the nearest values that satisfy it, so a caller never has to derive the lattice. It reads one sentence and tries again. That loop is only cheap when the constraint lives next to the caller, in the page, rather than behind a server the human is not editing. **The rules cannot be bypassed.** Both authors write through one gate. The committed document type carries a private `unique symbol` brand, so constructing one outside the engine **is a compile error**. **The document is shared, not handed over.** The designer keeps editing while a grading run is in flight, and the run picks up the edit for every size it has not computed yet. There is no session to own and nothing to merge afterwards. ### 2. How it creates a better user experience **A refusal beats a rejection.** When a write breaks a rule, the result names the rule in knitter language, gives the offending value, and gives the nearest valid values on either side. On the human path those become one click corrections in the size table. On the agent path they are text in the tool result. **Same sentence, both audiences.** **A long run shows its work and can be stopped.** `grade_sizes` commits one size at a time through the gate, so the table fills column by column and cancelling leaves every finished size in place with nothing to roll back. A cancellation reports as a **success**, listing what completed and what did not. **The negotiation is readable by the person, not just the model.** Every invocation, refusal, correction and human edit becomes a plain English sentence in the transcript, with corrections linked to the refusal they answer. No schema fragments, no stack traces. **The workbench audits itself.** The tech editor pass reads Jig's own tool list through its own `getTools` and calls its own read only verbs through its own `executeTool`, then checks every rule across every size. Export stays unregistered until it comes back clean. **And it degrades with dignity.** With no agent surface at all, the whole workbench is still reachable, the engine and audit and export are unchanged, and the page says plainly which browsers add the agent features. ### 3. What people and agents can do together that was difficult before **A spreadsheet cannot refuse.** Grading in spreadsheets is [taught practice](https://www.sistermountain.com/blog/grade-knitting-patterns-spreadsheet), and a formula produces a number: an off repeat cast on is a number like any other. An agent driving a spreadsheet inherits exactly that blindness. Four things need the constraint and the conversation in the same place. **Correcting a refused instruction without ever being told the rule.** The designer asks for 87 and says nothing else. The document refuses with the rule, the offending value, and 86 and 98. A correct second call **can only have come from reading that refusal**, because the prompt never mentioned the repeat. That loop is measured against a real browser, not asserted. **Editing a number while a grading run is in flight.** `gradeSizes` takes a read thunk rather than a snapshot, so every size not yet computed picks up the human's edit mid run. Asserted in [`grade.test.ts`](./apps/jig/src/state/grade.test.ts) by running a grade with somebody typing into it against the same grade with nobody. **A yarn swap that crosses an origin and returns a whole skein answer.** Change yarn and gauge changes, so yards per square inch changes, while the new skein has its own yardage. Two variables, [a known trap](https://yarnsub.com/articles/gauge-and-yardage/). `substitute_yarn` is one verb to the agent. Underneath it resolves partner tools by origin, invokes them, quarantines every string that crosses the boundary, revalidates through the same gate, and reports the difference **in whole skeins per size**. The seeded case returns `M 7 to 10, 3 more skeins`. **Watching the whole negotiation in plain English.** Every invocation, refusal, correction and human edit becomes a sentence in the transcript with its author, and a correction is linked to the refusal it answers. No schema fragments and no stack traces, so the person is never guessing what the agent just did or why it was told no. That readable record is what makes the other three reviewable rather than merely fast. ### 4. How WebMCP was implemented Every tool is a plain data descriptor in [`packages/tools/src/catalogue.ts`](./packages/tools/src/catalogue.ts), so **the exact strings an agent reads are the strings the build validator measures.** Registration goes through one wrapper in [`packages/webmcp/src/register.ts`](./packages/webmcp/src/register.ts): ```js document.modelContext.registerTool({ name: 'edit_number', description: 'Sets one number on one size, such as a cast on count, a row count or a finished ' + 'measurement. The value is checked against the panel repeat, the raglan increase ' + 'arithmetic and the size run before it is accepted, and a value that does not fit ' + 'comes back with the rule it breaks and the nearest values that work.', inputSchema: { type: 'object', required: ['size', 'field', 'value'], properties: { size: { type: 'string', description: 'Size label such as M or 2X.' }, field: { type: 'string', enum: ['yokeCastOn', 'bodyStitches', 'armholeDepthIn', /* ... */] }, value: { type: 'number', description: 'New value. Counts are whole numbers, measurements are inches.' }, }, }, annotations: { readOnlyHint: false, untrustedContentHint: false }, execute: async (input) => broker.edit_number(input), }, { signal: controller.signal }); ``` Two details in that call are load bearing and both came from measuring a real browser. The `field` parameter is a **closed enum** rather than a free string, because a model asked to change a cast on reaches first for `castOnCount`, which does not exist. And the `AbortSignal` is passed as the **second argument**, which is the only position that actually withdraws a tool. More on both below. --- ## WebMCP Leverage **Fourteen tools, two origins, and every registration path the specification offers.** Not one pattern repeated fourteen times. | WebMCP surface | Where Jig uses it | Why that path and no other | |---|---|---| | **Hook registration** | The 8 broker verbs: `read_pattern`, `read_chart`, `set_gauge`, `grade_sizes`, `edit_number`, `substitute_yarn`, `audit_pattern`, `export_pattern` | Lifecycle follows the component, withdrawal on unmount | | **Raw registration + `AbortSignal`** | `check_panel_fit`, `set_chart_cell` | Withdrawal by aborting the signal given at registration is unreachable through a hook | | **Raw registration + `exposedTo`** | `fit_published_pattern` | Names a consuming origin, which a hook cannot carry | | **`getTools({ fromOrigins })` + `executeTool`** | The `substitute_yarn` fan out to origin B | Cross origin tool resolution and invocation | | **`allow="tools"` + `exposedTo`** | The partner iframe and all 3 `yarns_` tools | Two halves of one contract, neither sufficient alone | | **Declarative HTML form** | `setup_project` | `toolname`, `tooldescription`, `toolparamdescription`, `SubmitEvent.respondWith`, `agentInvoked` | | **`toolchange` event** | Partner availability tracking | Re-reads the list, announces only when the reading moves | | **`requestUserInteraction`** | Human confirmation, with an in page route either way | Never assumes the method exists | | **Annotations** | `readOnlyHint`, `untrustedContentHint` | Both **derived**, never hand written. See Trust below | | **Conditional registration** | `export_pattern` | Registered only while the self audit comes back clean | ### Engineering discipline a scan can verify **One module may touch `document.modelContext`.** Feature detection lives in [`platform/capabilities.ts`](./apps/jig/src/platform/capabilities.ts) and a **custom ESLint rule, `jig/model-context-gate`**, fails the build if anything else reaches for it. **The engine cannot be corrupted.** `packages/engine` is forbidden from importing React, the DOM, `webmcp-types` or either app, enforced by a second custom rule, `jig/engine-purity`. That is what makes the correctness properties testable against pure functions rather than a rendered page. **The gate cannot be bypassed, as a compile error.** Human keystrokes, agent tool calls, declarative form submissions and the self audit all enter the same `propose` function in [`packages/engine/src/apply.ts`](./packages/engine/src/apply.ts). **Tool contracts are gated at build time.** [`packages/tools/src/validate.ts`](./packages/tools/src/validate.ts) enforces name length, description length, parameter description length, name uniqueness, both annotation derivations, and raw registration wherever `exposedTo` appears. It runs three ways: as a Vitest test, as a Vite `buildStart` plugin in both apps, and as a standalone script. **A budget violation exits the build non zero.** **Every descriptor speaks the caller's units, and conversion happens once.** Chart columns are one based in the tool contract, because that is how a knitter counts stitches, while the engine keeps the zero based array index it actually needs. The broker verb converts at exactly one place, with a round trip test, so an agent that trusts its own descriptor and the engine that stores the cell can never disagree about which stitch is column one. **The page is its own agent host.** The tech editor pass in [`agent/techEditor.ts`](./apps/jig/src/agent/techEditor.ts) calls Jig's own `getTools` and `executeTool` with no external agent in the loop. ### Four platform behaviours found by measuring, and absorbed into one resolver Driven headless against the deployed site on **Chrome Canary 154.0.8032.0**. Each was a live behaviour that **no unit test could have caught**, because a test only knows what its fake host was told to do. 1. **`AbortSignal` withdraws a tool only as the second argument**, `registerTool(descriptor, { signal })`. As a descriptor field it is accepted and silently ignored. Fixing this is what makes chart tool withdrawal real. 2. **`executeTool` will not accept a tool name.** It wants the tool **object** from `getTools`. A string rejects with `TypeError`. 3. **Arguments must be a JSON string.** An object rejects with `UnknownError: Failed to parse input arguments`. A resolved call answers with a JSON string too, so callers must handle both. 4. **A refusal's first text part must stand alone.** Some hosts collapse a structured result to `content[0].text`. Ours now states one whole violation with its repairs in that first part. All four live in one resolver, [`packages/webmcp/src/invoke.ts`](./packages/webmcp/src/invoke.ts), and the fake host in [`packages/webmcp/src/fakehost.ts`](./packages/webmcp/src/fakehost.ts) now reproduces Chrome's behaviour precisely, refusals included. **Reverting the resolver fails 64 tests across 7 files.** That is what keeps a platform finding from quietly regressing. --- ## Execution **A coherent product, deployed, that a stranger uses with zero setup.** - **Two origins live on HTTPS**, deployed and serving, with the cross origin tool contract wired end to end. Both are **Cloudflare Pages** projects, `jig-workbench` and `jig-yarn-service`, deployed from this repo with `npm run deploy:jig` and `npm run deploy:yarns`. The workbench also runs one **Cloudflare Pages Function**, [`functions/api/model.ts`](./apps/jig/functions/api/model.ts), which holds the model key as an encrypted environment secret so the browser never sees it. Two separate Pages projects rather than one, because `allow="tools"`, `exposedTo` and `getTools({ fromOrigins })` need two genuinely different origins. - **A full designer interface**, not a tool console: editable size table, live SVG schematic, stitch chart with repeat boundaries drawn as geometry, 3D garment view, yarn substitution row, gated export, and a transcript drawer that takes a grid column so opening it shrinks the working columns instead of covering them. - **Agent activity is visible to the human.** A 240ms accent wash marks any cell an agent changed, a refused cell keeps its outline until repaired, and `:tool-form-active` styling shows an agent filling the setup form in real time. - **Agent discovery built in** on both origins: `llms.txt`, `robots.txt`, `.well-known/mcp.json`, `sitemap.xml`, JSON-LD, and full `