[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D4CREC5JCN7WANEQY3400S":3,"skill-same:01M7D4CREC5JCN7WANEQY3400S":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":33,"updatedAt":34,"install":35,"resources":48},"01M7D4CREC5JCN7WANEQY3400S","dynamic-workflows",null,"Use when writing, debugging, or resubmitting a dynamic-workflow script for the CreateWorkflow tool: choosing subagent topology, typing subagent results, fanning out over files or git, gating loops on world.run commands, testing pieces with EvalWorkflowSnippet, planner-reviewer loops, confirming findings before reporting them, report() salvage, the report shape a run returns, publishing artifacts the user opens, leaving typed holes to fill mid-run, and handling a backgrounded run.","zai-org\u002FZCode","zai-org","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F223098841?v=4","01M7D3Y10287Y0CNVHSNZ4GD03","Z.ai","01M7D3Y10SKN81G21P442YTCYP",8689,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fapps\u002Fzcode-cli\u002Fpackages\u002Fbundled-skills\u002Fskills\u002Fdynamic-workflows\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: dynamic-workflows\ndescription: \"Use when writing, debugging, or resubmitting a dynamic-workflow script for the CreateWorkflow tool: choosing subagent topology, typing subagent results, fanning out over files or git, gating loops on world.run commands, testing pieces with EvalWorkflowSnippet, planner-reviewer loops, confirming findings before reporting them, report() salvage, the report shape a run returns, publishing artifacts the user opens, leaving typed holes to fill mid-run, and handling a backgrounded run.\"\nwhen_to_use: \"Only for CreateWorkflow scripts. A single delegation or a few independent lookups belong to the Agent tool instead.\"\n---\n\n# Writing dynamic workflows\n\nThis skill is the whole authoring contract for `CreateWorkflow`. The tool descriptions are\nshort on purpose; the facade the compiler checks against, the rules a script must satisfy and\nthe fields each tool takes are in §16, and `CreateWorkflow`, `AmendWorkflow`, `FillWorkflowHole`,\n`SaveWorkflow` and `EvalWorkflowSnippet` refuse to run until this skill has been loaded. The\nrest is the judgment layer: how many subagents a request deserves, which of them should share\na context, what each one should hand back, and how to keep the run's work from dying with the\nrun.\n\nTwo names collide in this codebase. `CreateWorkflow` is the dynamic-workflow tool and the\nonly one this skill is about. The legacy `Workflow` tool and `\u002Fexpert` are a different,\nolder feature that happens to share the word.\n\n## The bar: first-class, expert-level work\n\nA workflow exists to produce first-class, expert-level work — the deliverable a senior\npractitioner would hand over after doing the job properly, not a faster draft of what one\nreply could have said. A user who asks for a workflow is paying for that depth, and every\nchoice in this skill serves it: enough subagents to actually cover the ground, fresh eyes\non every plan and every draft (§3), an independent confirmation of every finding,\ndeterministic checks wherever a command can decide, and a report that says what was\nverified, what was not, and what it all means.\nDepth is measured by what is at stake, not by how many subagents re-read the same work:\nverification goes where a wrong claim would cost the user something, and each piece of work\ngets the one check that decides it. When a shortcut and the expert's way disagree, take the\nexpert's way; trim the work only when the task is small, and trim the checking when a wrong\nclaim costs little or a command has already decided it.\n\n## 1. Is this the right tool, and how big should it be?\n\n| The request | The tool |\n| --- | --- |\n| One thing delegated to one agent | `Agent` |\n| A few independent lookups, nobody reading anybody's answer | `Agent`, in parallel |\n| Anything else the user did not name a workflow for, however many steps it needs | `Agent`, or do it yourself |\n| The user said \"use a workflow\" \u002F \"使用 workflow\" \u002F \"用工作流\" — any phrasing naming workflow as the means | `CreateWorkflow`, mandatory, even if `Agent` would have done or one reply could answer |\n\n**Only an explicit request starts a workflow.** A workflow begins with `\u002Fworkflow` or with\nthe user naming workflow\u002F工作流 as the means, never with your own judgement that a task\nlooks orchestration-shaped. Results feeding later steps, a bounded loop, a branch on a typed\nresult — those are shapes the script is good at once one has been requested, not reasons\nthere should be one. Delegate with `Agent` or do the work yourself.\n\n**An explicit request is binding.** Once the user names workflow\u002F工作流 as the means, the\nrouting question is closed — not `Agent`, not inline, not \"too small for a workflow\"; what\nremains is only how big the script should be, and the smallest task gets a small workflow.\n\nAn explicit workflow request is a request for depth, and the bar above is the measure.\nDefault to the thorough shape — a fresh subagent per unit of work, a deterministic gate\nwherever a command can decide, an independent confirmation of every finding the user will\nact on as fact (§10) — sized to the stakes: a bug the user will fix on your word gets a\nconfirmer; a poem or a survey gets a reader at most. Every task is a full model session, so\nput sessions where they raise confidence, not where they repeat each other: \"review the\nchanged files\" wants a reviewer per file plus a confirmer per finding; \"write me twenty\npoems\" wants twenty poets and no confirmers.\n\n**Write only as much of that shape as you know for sure.** Where a later stage depends on\nwhat an earlier one finds, write up to that point, end in a hole (§15), and let the findings\nwrite the rest. Guessing a topology is not depth.\n\n## 2. Subagent topology\n\nThis is the decision that separates a good script from a bad one. It is made twice: now,\nfor what the request already tells you, and at a hole (§15), for what only the run can tell\nyou. This section is about the first, in four parts.\n\n**Fresh subagent per item, or one shared subagent?** Every `agent()` call creates a new context.\nSharing a context means sharing the *variable*:\n\n```ts\n\u002F\u002F Independent: each judge sees only its own item. Runs concurrently.\nitems.map((i) => agent(`judge-${i.id}`).ask\u003CVerdict>(`Judge ${i.id}`));\n\n\u002F\u002F Calibrated: one context sees every item in sequence, so its later verdicts are\n\u002F\u002F consistent with its earlier ones. Asks on one subagent queue FIFO — this serializes.\nconst judge = agent(\"judge\", \"You rank consistently across a whole batch.\");\nitems.map((i) => judge.ask\u003CVerdict>(`Judge ${i.id}`));\n```\n\nIndependent is right for unrelated items; shared is right when the answers must be\nconsistent with each other, at the price of serialization. Hoisting the `agent()` call out\nof a loop for tidiness turns a fan-out into a queue, and nothing rejects that script.\n\n**A name is an identity, and it has to be unique.** No two subagents in one run may share a\nnon-empty name — a duplicate fails the run. One fixed name inside a fan-out is a duplicate\nper item, so write `` agent(`judge-${i.id}`) ``; the compiler catches the literal form, a\nname built at run time costs you the run. Anonymous is always safe.\n\nNames are worth giving anyway: a **revised** re-run finds its cache by them (§13),\nimporting every ask whose instructions did not change at zero tokens. Anonymous subagents\nstart empty.\n\n**Persona, frozen at creation.** A persona stacks on the harness's own subagent contract —\nciting `path:line`, never reporting a check it did not run, saying what it could not do,\nescalating instead of faking — so write the role and the standard of judgement and leave\nthose rules out. Every subagent has the same tools; what it may do with them is said in the\nask: a reviewer that must not touch the code is told \"do not edit any file\".\n\n**Per-subagent model**, only when the user asked for one, with the name they used:\n`agent(\"judge\", { model: \"GLM-5.3-Flash\" })`, ids from `ListModels`. A literal or a `model()`\nModelRef; to route, map the router's typed key to a `model()` table (`patterns.md` #13).\nNEVER move a subagent to a model under another provider on your own — not for a judge, not\nbecause it looks cheaper; another provider is another bill. When a lighter model would\nclearly fit (one-turn judges, routers) and the user has not said, ask them first, before\nthe call: name the model and the provider, say what it would save, and go with their answer.\nTheir yes is the request; write it as the full `providerId\u002FmodelId` (a bare name never\ncrosses providers).\n\n**Search budget.** By default each ask may make 128 `WebSearch` calls; past that, `WebSearch`\nrefuses and the subagent finishes from what it has. When you anticipate an ask needing more\nsearches, which should be rare, set a larger number: `agent(\"scout\", { budget: { webSearch: 512 } })`\n(an integer literal, at most 1024). A result that says its search was cut short means the\nbudget was hit: tell the user, and amend with a larger budget if they want more.\n\n**Where each item goes next.** A run with more than one stage is a pipeline: an item leaves\nits stage as soon as it is done, and the next stage takes it while the rest are still being\nworked on. Decide this at every hand-off when you lay out the topology, and let a stage wait\nfor all of its items only where the next step needs every one. §7 says how to write each case.\n\n**Loops.** Bound every loop with a round cap, and carry the feedback forward:\n\n```ts\nlet feedback = \"none\";\nfor (let round = 0; round \u003C 5; round++) {\n  const plan = await planner.ask\u003CPlan>(`Plan the fix. Previous critique: ${feedback}`);\n  const review = await reviewer.ask\u003CReview>(`Critique this plan: ${JSON.stringify(plan)}`);\n  if (review.approved) return plan;\n  feedback = review.feedback;\n}\n```\n\nReuse the same two subagents across rounds: a subagent asked again keeps its context, so\nround five is cheap. Reuse costs freshness — by round three the reviewer is anchored on its\nown critique — so add an independent one at the end (§3).\n\n**No nesting.** Subagents cannot call `CreateWorkflow`; model a big sub-task as more subagents\nhere.\n\n## 3. Fresh eyes\n\nThe author of a plan or a draft cannot see its gaps, because they filled them while\nwriting. A reader with a separate context has no such fill, so the gaps show. That is the\nwhole method, and it applies at every stage *inside* the workflow where something is\ndrafted — a plan, a fix, a finding, the final report. It pays most on plans, which are\ncheap to critique and expensive to execute wrongly.\n\nFour rules make the eyes actually fresh:\n\n- **Separate context, not a second opinion from the same head.** An independent reader is a new\n  `agent()` that has seen nothing but the draft. Every planner–reviewer loop keeps a\n  persistent reviewer for continuity (§2), and then puts the final draft in front of a\n  reviewer that has never seen an earlier round.\n- **Ask for failures, not approval.** \"Is this good?\" gets a yes. \"What would break this?\n  What is missing? Restate the plan in your own words\" gets findings. Write the ask so\n  that approving takes evidence and objecting is the easy move.\n- **Give the eyes the same evidence.** A reviewer judging a plan about code from its text\n  alone can only judge coherence: tell plan reviewers to read the files the plan touches,\n  and not to edit them.\n- **Give a prose deliverable an independent read.** When the deliverable is text nothing else\n  checked — a guide, an analysis — hand it, before the script returns, to a reader-proxy\n  subagent asked what is unclear, what the text fails to support, and what the user will ask\n  next; then fix those. Say it judges from the text alone — checking claims is a confirmer's\n  job. A report whose\n  findings were each confirmed (§10) has had its eyes; add no reader on top.\n\nThree cautions. Correlated reviewers add little — same model, same prompt, same blind spots\n— so give each a distinct lens. Bound it: one deliverable gets one mechanism — a plan a\nreviewer who reads the code, findings a confirmer, prose a reader; two is the ceiling, with\na reason you can say. And these rules are about the subagents *inside* the script, not a gate\non submitting it: read your own script once against the request, and at every `Promise.all`\nask whether the next step needs every item; where it does not, pipeline it (§7). The\nconfirmation window then puts the plan in front of the user.\n\n## 4. Typed results\n\nPass a type argument to `ask` whenever your control flow will branch on the answer; leave it\noff when you just want prose back. The type must be an interface or type alias you write in\nthe script.\n\n**JSDoc on a property becomes the field description the subagent actually reads.** This is the\ncheapest quality lever in the whole surface and the easiest to skip:\n\n```ts\ninterface Finding {\n  \u002F** Workspace-relative path the problem is in. *\u002F\n  path: string;\n  \u002F** One sentence: what is wrong, not how to fix it. *\u002F\n  problem: string;\n  \u002F** How much it matters. Reserve \"high\" for data loss or a crash. *\u002F\n  severity: \"low\" | \"medium\" | \"high\";\n}\n```\n\nWithout the comments you get whatever the subagent guessed `severity` meant.\n\nKeep results narrow: a result crosses a schema boundary and gets interpolated into the next\nprompt, so a wide one costs tokens twice. **Pass paths, not file contents** — a subagent has\nits own file tools; a stringified 4000-line file spends tokens on what it could have read.\n\n## 5. Getting the world in\n\n`files.glob` and `git.changedFiles` are how a script learns what to fan out over; both are\nexecuted by the harness, recorded, and replayed on resume.\n\nCaps **reject rather than truncate** (§16.2), so narrow the pattern instead of fanning out\nover a silently partial view. Reads are catchable, so a coarser fallback is a `catch` —\nwhich `git` needs, since every `git` call rejects outside a repository:\n\n```ts\nlet paths: string[];\ntry {\n  paths = await git.changedFiles(\"origin\u002Fmain\");\n} catch {\n  paths = await files.glob(\"src\u002F**\u002F*.ts\");\n}\n```\n\nReach for `files.read` or `files.grep` only when the *script itself* must shard or branch on\ncontent; reading files is subagent work.\n\n**`world.run` is the deterministic gate.** When a check is fixed and machine-checkable — the\nbuild passes, the proof checks, the tests are green — run it as code and branch on the exit\ncode, instead of asking a subagent to run it and trusting the claim:\n\n```ts\nconst check = await world.run(\"lake\", [\"build\"], { timeoutMs: 1_800_000 });\nif (check.exitCode !== 0) feedback = check.stderr;\n```\n\nA nonzero exit code is a **value**, not an exception: read `exitCode` and carry `stderr`\nforward as the next round's feedback, with no `catch`; rejections are for the world failing\nto answer (spawn failure, timeout, output over the cap). A test suite can print more than the\n16 MiB cap: a gate that reads only `exitCode` passes `{ output: \"discard\" }`, and a gate that\nhands the failure on passes `{ output: { tail: 16_384 } }`. The command name must be a\ncompile-time string literal, because the user approves the script's command set at\nconfirmation: interpolate paths, flags and round numbers into the **args array**, never into\nthe command. Open-ended editing belongs to a subagent; `world.run` is for checks your\ncontrol flow branches on.\n\n**Choose the gate before you write it.** A gate decides exactly as much as the check it\nruns. Before the first `world.run`, find out what checks the repository has — `package.json`\nscripts, `Makefile` targets, the CI config, the README's \"run this to verify\" line — and\nrank them by how much they decide: a unit suite decides less than an end-to-end suite, which decides less than\nthe acceptance command the README names, and none decides a performance request the way\nthe bench does. Then build the gate in two tiers: the fast tier may drive a loop's rounds;\nthe **strongest** tier the request implies decides the exit and runs for real at least once\nbefore the final `return`, even when the fast tier said yes. Give a slow tier the\n`timeoutMs` it needs; a faster substitute is a different check.\n\n```ts\nphase(\"Fix until the unit tests pass\");\nfor (let round = 1; round \u003C= 5; round++) {\n  const unit = await world.run(\"npm\", [\"test\"]);\n  if (unit.exitCode === 0) break;\n  await fixer.ask(`The unit tests failed:\\n${unit.stderr}\\nFix them.`);\n}\n\nphase(\"Run the end-to-end suite once before handing over\");\nconst e2e = await world.run(\"npm\", [\"run\", \"e2e\"], { timeoutMs: 1_800_000 });\nconst verified = e2e.exitCode === 0;\n```\n\nA check that exists in the repository and did not run is not \"not covered\"; it is\nunverified work (§10).\n\n## 6. Test the pieces before you commit\n\nA workflow script is final at submit. The fixed logic inside it does not have to be: run it\nthrough the `EvalWorkflowSnippet` tool first (§16.6), synchronously and without persisting\nanything. What passed there pastes into the workflow verbatim. Send the snippet\nas `code`, or as `path` to a file holding it — the second try then costs an `Edit`.\n\nSnippet work is the non-subagent part: what a glob really returns, whether a grep pattern\noverruns its cap, how `world.run(\"lean\", ...)`'s stderr parses, whether a gate predicate does\nwhat you meant. A snippet has `files.*`, `git.*`, `world.run` and `log`, but no `agent()`.\nOnce you know which check decides the result (§5), run it once here too: that shows its\noutput, whether it exits nonzero as you assumed, and how long it takes — the `timeoutMs` you\nwrite, not a guess.\n\n## 7. Pipeline by default; join only where the next step needs every item\n\nA workflow with more than one stage should run like a pipeline: every stage works at the\nsame time, and each item moves on the moment it is ready. A reviewed file goes to its\nconfirmer while the other files are still being reviewed; a fact goes to its checker while\nthe researchers are still reading. Write it this way wherever the next step can take items\none at a time, which is nearly every hand-off. Let a stage wait for all of its items only\nwhere the next step needs every one: a deduplication across files, a ranking on one scale, a\nsynthesis. Those are the barriers, and a script has few of them.\n\n`Promise.all` is a join, and a join is a barrier: nothing after it starts until the slowest\nitem before it has landed. Parallelism comes from *not awaiting yet*:\n\n```ts\n\u002F\u002F Concurrent: nothing is awaited until the join.\nconst all = await Promise.all(\n  paths.map((p) => agent(`reviewer-${p}`).ask\u003CReview>(`Review ${p}`)),\n);\n\n\u002F\u002F Serial: each await blocks the next call. Only write this when you mean it.\nfor (const p of paths) results.push(await agent(`reviewer-${p}`).ask\u003CReview>(`Review ${p}`));\n```\n\n**Decide, at every hand-off, how an item leaves its stage:**\n\n| The next step takes | The stages | Write |\n| --- | --- | --- |\n| one item at a time | one to one: a reviewer per file, a confirmer per finding, a migrator per file and a checker per file | the stages chained per item inside one fan-out, one join at the end |\n| one item at a time | a pool of shared workers serves a stage; items are still being found while the next stage works; a later stage sends work back; the stages read better as separate blocks | a `channel` between the stages, a `future` per stage |\n| every item at once | deduplication, a ranking on one scale, a synthesis, the final report | a join, with a comment saying what needs every item |\n\n**Chaining.** When two stages map one to one, a barrier between them makes every worker of\nthe second stage wait for the slowest worker of the first while the run's concurrency slots\nsit idle. Chain the stages per item inside the fan-out instead, and join once at the end:\n\n```ts\n\u002F\u002F One join: each file's findings go to their confirmers the moment its review lands\n\u002F\u002F (two Promise.all — review every file, then confirm every finding — is the barrier).\nconst confirmed = (\n  await Promise.all(\n    paths.map(async (p) => {\n      const review = await agent(`reviewer-${p}`).ask\u003CReview>(`Review ${p}`);\n      return Promise.all(\n        review.findings.map((f, i) => agent(`confirmer-${p}-${i}`).ask\u003CConfirmation>(`Reproduce: ${JSON.stringify(f)}`)),\n      );\n    }),\n  )\n).flat();\n```\n\nA shared, calibrated subagent is not a barrier: asks on it queue first in, first out, so feed\nit each item as it lands and it stays consistent while the pipeline keeps moving (§11).\n\nOne rejection inside `Promise.all` rejects the whole join and the sibling results with it.\nWhen one bad item should cost one item, catch inside the callback (examples #3) or use\n`Promise.allSettled` and read each outcome.\n\n**Channels.** Chaining covers stages that map one to one. It cannot write a stage served by a\npool of shared workers, a producer still finding items while consumers work, stages laid out\nas separate blocks, or a feedback loop to an earlier stage. For those, a `channel\u003CT>()`\ncarries items between two stages and each stage is a `future(async () => { … })`. An item\nsent into the channel is taken by the next stage at once, by a worker that is waiting for it\nor by a new one started for it:\n\n```ts\nconst facts = channel\u003CFact>(\"facts\");\nconst verified: Fact[] = [];\n\nconst research = future(async () => {\n  phase(\"Research the topic from each angle\");\n  try {\n    await Promise.all(\n      angles.map(async (angle) => {\n        const found = await agent(`researcher-${angle}`).ask\u003CResearch>(`Research ${angle}.`);\n        for (const fact of found.facts) facts.send(fact);\n      }),\n    );\n  } finally {\n    facts.close(); \u002F\u002F the producer side owns the close; a failed researcher still ends the stream\n  }\n});\n\nconst verify = future(async () => {\n  phase(\"Check each fact as it arrives\");\n  await Promise.all(\n    [1, 2, 3].map(async (k) => {\n      const verifier = agent(`verifier-${k}`);\n      for await (const fact of facts) {\n        const verdict = await verifier.ask\u003CVerdict>(`Does this hold? ${JSON.stringify(fact)}`);\n        if (verdict.holds) verified.push(fact);\n      }\n    }),\n  );\n});\n\nawait Promise.all([research, verify]); \u002F\u002F start every stage, then join once\n```\n\nThe rules, in the order the code reads:\n\n- **A stage is a future.** Its marker first, then the workers (a `Promise.all` over K\n  `for await` loops on the input channel), then the output's `close()` in a `finally`. Start\n  every stage, then join all of them once with `Promise.all`, with no `await` between: while\n  you await one stage, a failure in another has no listener and surfaces as an unhandled\n  rejection instead of failing the run with its error.\n- **A channel where the next stage should start before the previous one ends; a join where it\n  needs every item.** Never a channel between two stages that need a barrier.\n- **A new subagent per item inside a consumer is a `future` inside the `for await`**, pushed\n  into an array and joined before the stage ends (examples #6); without that join the stage\n  ends when the channel closes with checks still running, and nothing reports it.\n- **A cycle is counted.** A feedback channel (a verifier sends a doubtful fact back for more\n  research) has no single producer who knows when it is done, so keep one count of open work\n  items: increment *before* finishing the item that produced the new work, close the feedback\n  channel when the count hits zero, bound the loop with a depth field on the item\n  (`patterns.md` #12).\n- **Pools trade cache reuse for consistency.** A pool of shared workers (`verifier-1…3`\n  above) judges on one scale, but which item lands on which worker depends on timing, so an\n  amendment that changes one upstream item misses the cache for the whole pool; a fresh\n  `verifier-${fact.id}` per item misses only itself. `send` never waits (the buffer is\n  unbounded); a channel nobody can send to any more fails the run as `ChannelDeadlock`.\n\n**Keep the data flow visible.** The harness recovers the dependency graph by reading your\ncode before it runs: plain variables, template interpolation, destructuring and small local\nhelpers are traced exactly; a result stashed in a container or behind an indirection earns a\ndiagnostic.\n\n## 8. Group the run into named phases\n\nPhases are required. The user experiences a workflow through its phase graph: the\nconfirmation dialog is drawn one node per phase, and thirty step cards is a dialog nobody\nreads. Cover the whole script — every stage gets a `phase(\"...\")` marker at its head; the\narrows between phases are inferred:\n\n\u003C!-- compile -->\n```ts\ninterface Attempt {\n  \u002F** One sentence: the optimization this round is trying. *\u002F\n  approach: string;\n}\n\n\u002F** Total nanoseconds the bench reports, or Infinity when it printed none. *\u002F\nfunction benchNanos(output: string): number {\n  const match = \u002Ftime:\\s*([\\d.]+) ns\u002F.exec(output);\n  return match?.[1] === undefined ? Number.POSITIVE_INFINITY : Number(match[1]);\n}\n\nphase(\"Measure today's baseline\");\nconst baseline = await world.run(\"cargo\", [\"bench\"], { timeoutMs: 1_800_000 });\nconst target = benchNanos(baseline.stdout);\nconst optimizer = agent(\"optimizer\");\n\nlet winner = \"none\";\nfor (let round = 1; round \u003C= 3; round++) {\n  phase(\"Make one improvement\");\n  const plan = await optimizer.ask\u003CAttempt>(\n    `Round ${round}. Baseline timings:\\n${baseline.stdout}\\nMake one improvement.`,\n  );\n\n  phase(\"Check that the tests still pass\");\n  const check = await world.run(\"cargo\", [\"test\"]);\n  if (check.exitCode !== 0) continue;\n\n  phase(\"Measure whether it is actually faster\");\n  const bench = await world.run(\"cargo\", [\"bench\"], { timeoutMs: 1_800_000 });\n  if (bench.exitCode === 0 && benchNanos(bench.stdout) \u003C target) {\n    winner = plan.approach;\n    break;\n  }\n}\n\nphase(\"Collect the final numbers\");\nconst head = await world.run(\"git\", [\"rev-parse\", \"HEAD\"]);\nreturn { approach: winner, commit: head.stdout.trim() };\n```\n\nFive nodes, with an arrow back from the bench to \"Make one improvement\" — and still five\nwhen the real script grows to thirty steps: the user sees the story instead of a wall of\ncards.\n\nThe unit tests are the fast tier that drives the rounds; the bench is the check the request\nwas about, and it decides every round that survives them, not once at the start (§5).\n\n**Write the names for the user, not for the graph.** A phase name is a short natural\nphrase saying what this stage accomplishes for the user, written in the language the\nuser is speaking in this session — \"Research each changed file in parallel\",\n\"汇总并产出最终报告\" (§9). Names are compile-time string literals, so you cannot number\nrounds by interpolation, and should not want to: two markers with the same name are one\nnode, so a loop body stays one box across its rounds.\n\n**Put the marker where the steps are.** A marker claims the rest of the block it sits in,\nnested blocks and inlined helper calls included, so mark the block where the `ask` and\n`world.run` calls actually live.\n\n**Not inside a concurrent fan-out callback.** Twenty `map(async …)` callbacks re-entering\n`phase(\"Review\")` out of order would count every re-entry as a round. A per-item pipeline\n(§7) is one phase named for what it does to each item, with the markers at the top level\naround it.\n\n**One marker at the head of each stage's future.** Concurrent stages written as futures (§7)\neach open their body with their own `phase(\"...\")`. Stamping is lexical — a step gets the\nphase the analyzer places it in, not the marker the engine passed last — so two stages\nrunning at once keep their own steps; still no marker in the per-item callback or the\n`for await` body.\n\n**Every phase must contain at least one `ask` or one `world.run`.** Plain script logic —\nreading `args`, shaping a prompt, building the `return` — shows no progress, so it is not a\nstage: fold it into the phase before or after it, and open none for the setup at the top,\nthe `return` at the bottom, or a branch that only narrates with `report` and `log`.\n\n## 9. Write for the user\n\nSix things you write are read by the user, not by the script: phase names, subagent names,\n`log` lines, artifact titles and the markdown you publish, the four report fields, and any\nquestion a subagent escalates. Write each one as you would tell a colleague across the desk\nwhat is happening: what the work is, in the user's words and language. The machinery —\nfan-out, gate, node, stage, pipeline — is yours, not theirs, and so is the numbering.\n\n| Read by the user | Write | Not |\n| --- | --- | --- |\n| Phase name | Review each changed file \u002F 逐个检查改动的文件 | Fan-out review stage \u002F 文件评审阶段 |\n| Phase name | Check that the tests still pass \u002F 确认测试仍然通过 | Gate: test verification \u002F 执行测试验证任务 |\n| Subagent name | Code reviewer \u002F 代码评审员 | reviewer_2 \u002F 节点3 |\n| Subagent name | Benchmark runner \u002F 跑基准测试的人 | runner \u002F 子代理A |\n| Phase name | Independent review of the final plan \u002F 请没看过方案的人再审一遍 | Cold read of the plan \u002F 冷读方案 |\n| Subagent name | Independent reviewer \u002F 独立评审员 | cold-reviewer \u002F 冷眼评审 |\n| `log` line | Reviewing 12 changed files \u002F 正在检查 12 个改动的文件 | Fan-out sized: n=12 \u002F 扇出阶段初始化完成 |\n| Report conclusion | Two of the twelve files have real bugs, both in the parser. \u002F 12 个文件里有 2 个有真问题，都在解析器里。 | The workflow executed successfully and produced findings. \u002F 工作流已成功执行并生成结果。 |\n| Artifact title | Review report \u002F 评审报告 | report-artifact-v1 \u002F 产物输出 |\n| Escalation question | Should the threshold be 94 rather than 96? \u002F 阈值应该是 94 而不是 96 吗？ | Requesting clarification regarding gate configuration parameters \u002F 请求对门控配置参数进行澄清 |\n\nThe method names in this skill — fresh eyes, independent read — are idioms for you, not\nwords for the user: in Chinese that is 独立复核 or 换人复审, never 冷读 or 冷眼.\nThe language travels through your asks: findings and summaries are written by subagents\nanswering the ask you wrote, so write asks in the user's language, or say which language to\nanswer in; otherwise a Chinese report arrives wrapping English findings.\n\n## 10. Verify, report, deliver\n\n`log(...)` is narration for the human watching the run: after a fan-out is sized, at the top\nof each loop round.\n\n**Verify before you report, in proportion to what a wrong claim costs.** Verification\nexists to buy down the cost of the user acting on something false, so it goes where that cost\nis real: a bug they will fix, a security claim, a number they will quote, a fact a decision\nrests on. Each finding of that kind is confirmed independently before it reaches the user: a\nsecond subagent that reproduces the finding from its evidence alone — reading the code,\nrunning a check when one decides it, never editing — or a `world.run` command when one can\ndecide. The reviewer that found it does not confirm it. A finding that fails confirmation\nis **kept and labelled** `unconfirmed`, never silently dropped — a real issue the confirmer\ncould not reproduce is still worth a human's eyes, and the label tells the user \"seen\" from\n\"suspected\".\n\nThree things that look like verification and are waste. A confirmer on a finding a\n`world.run` already decided: the exit code is the confirmation; record the command in\n`verified`. A confirmer on work nobody will act on as fact — poems, brainstormed options, a\nfirst-draft survey — which gets at most one independent read (§3). A suite run three times\nbecause the hunter, the confirmer and the gate each ran it: a gate runs once, by the script,\nand the asks say so (\"the script runs the full suite after you; do not run it yourself\").\n\n**Gate at the task's scale.** `verified` names the commands that actually decided the\nresult, and the reader holds them against what they asked for. A unit suite in `verified`\nand the end-to-end suite in `notCovered` is an unverified deliverable with a disclosure\nattached. `notCovered` is for what *could not* be checked — no test exists, the environment\nlacks the tool, the check needs something only the user has — never for a check that exists\nand was skipped because it is slow. If the strongest check the request implies exists and\ndid not run, the run is not done: run it, or say in `conclusion` that the work is unverified\nand why (§5).\n\n**Salvage by report.** `report(...)` is not `log`: reported items are delivered with the\ncompletion notification **even when the run fails**, which is how a run that dies on its\ntwelfth task keeps eleven tasks' worth of work. Report each finding the moment it lands —\nafter its confirmation, with its status — rather than accumulating an array to return at the\nend: the array is what you lose. Items are recorded, so a resumed run never shows one twice.\n\n**Stamp what outlives the run with `run.id`.** A ledger line, a file the script writes for a\nlater run, a report item someone will trace back: put `run.id` in it, so the record names the\nrun that produced it (`run.resumedFrom` names the run an amendment revised). Keep both out of\nask text, personas and `files`\u002F`world` arguments. Those are cache keys, and an amendment mints\na new id, so an ask that quotes it misses the cache and runs again.\n\n**Deliver a report.** The script's final `return` is the handoff the main agent presents,\nin the order below; what the user themselves keep is the artifact of the next section.\nReturn this shape (copy the interfaces; they compile as-is) rather than a bare array:\n\n\u003C!-- compile -->\n```ts\ninterface Finding {\n  \u002F** Workspace-relative path, with a line when it applies: \"src\u002Fa.ts:42\". *\u002F\n  where: string;\n  \u002F** One sentence: what is wrong, or what was found. *\u002F\n  what: string;\n  \u002F** What showed it: the lines read, or the command and the output that proved it. *\u002F\n  evidence: string;\n  \u002F** \"verified\" when an independent subagent or a deterministic check confirmed it; \"unconfirmed\" when confirmation failed or was not attempted. *\u002F\n  status: \"verified\" | \"unconfirmed\";\n  \u002F** How much it matters. Reserve \"high\" for data loss, a crash, or a wrong result. *\u002F\n  severity: \"low\" | \"medium\" | \"high\";\n}\ninterface WorkflowReport {\n  \u002F** Two or three sentences answering what the user asked for. *\u002F\n  conclusion: string;\n  findings: Finding[];\n  \u002F** What the run checked and how: the commands it ran, the files it covered. *\u002F\n  verified: string[];\n  \u002F** What the run did not look at or could not check, and why. *\u002F\n  notCovered: string[];\n}\n\nconst result: WorkflowReport = {\n  conclusion: \"Nothing was reviewed: this snippet only shows the shape.\",\n  findings: [],\n  verified: [],\n  notCovered: [\"everything — no subagent ran\"],\n};\nreturn result;\n```\n\nEach field has a reader. `conclusion` is the answer to what the user asked. `findings` carry\ntheir evidence and their status, so the user can tell what was seen from what was suspected.\n`verified` says what this run actually checked and how — the commands it ran, the files it\ncovered. `notCovered` says what it did not look at and why, which is the difference between\n\"we found nothing\" and \"we looked nowhere\". Write all four in the language the user is\nspeaking in this session.\n\n**Deliver artifacts.** The `return` is read by the main agent, which retells it. `artifact.*`\nis the other channel: things the *user* opens, shown as cards beside the run while it is\nstill going and kept after it ends. Two habits:\n\n- **Every run publishes its deliverable.** When the user asked for a thing — a webpage, a PDF\n  — a subagent writes it into the workspace and returns the path (\"write it to `out\u002F…` and\n  return the path\" belongs in the ask), and the script publishes it with `artifact.file`;\n  until it does, nothing the run left in the workspace exists for the user. When the user\n  asked for an answer — findings, a review — the `return` is the compact handoff and the\n  deliverable is the long form of the same facts: markdown built from the values the return\n  is built from, published once, at the end. The exception is a run whose whole answer is a\n  line. With more than one artifact, mark the deliverable `{ primary: true }`: the completion\n  card, the run pane and the notification lead with it. One primary per run.\n- **A dashboard is for the person watching the run.** Declare one when the run has state worth\n  watching while it runs — the key number after each round, which items are done or failed:\n  metrics or a chart for a number, a table or board for items with a status. Declare it once\n  at the top, then tag the items you already report: `report(item, \"perf\")`. It is a\n  projection of that stream, so it grows live and survives a resume. A run that is over\n  before anyone would look needs none.\n\n**Show what matters.** Two tests decide what earns a card: would the user open it on its\nown (else it is a section of the deliverable), and does it repeat another artifact (a CSV and\na table of its rows, a report and a copy of it — one of each pair is noise). The common run\npublishes one deliverable, one dashboard when there is something to watch, and further files\nonly when a subagent produced something else a person opens.\n\nIds and the report tag are compile-time string literals: what a run can publish is fixed\nwhen the user approves the script, and an id assembled at runtime is a compile diagnostic.\nPublishing an id a second time mints the next version and keeps the old one.\n\n**A rejected publish is a repair opportunity, not an error to swallow.** Content publishes\nreject catchably — the file is missing, the path escaped the workspace, the bytes are over the\ncap — and the honest response is to hand the gap back to a subagent and publish again, rather\nthan let a run end with nothing the user can open:\n\n\u003C!-- compile -->\n```ts\ninterface RoundOutcome {\n  \u002F** 1-based round number. *\u002F\n  round: number;\n  \u002F** Query latency in milliseconds, measured after this round's change. *\u002F\n  queryMs: number;\n  \u002F** One sentence: what this round changed. *\u002F\n  change: string;\n}\n\nconst TARGET_MS = 20;\nartifact.chart(\"perf\", {\n  title: \"Query latency by round\",\n  x: { field: \"round\", label: \"Round\" },\n  y: { field: \"queryMs\", label: \"ms\" },\n  baseline: { field: \"target\" },\n});\n\nphase(\"Optimize until the bench meets its target\");\nconst optimizer = agent(\"optimizer\", {\n  system:\n    \"You speed up a JSONL query engine: change one thing, measure it, and write the profile \" +\n    \"of the query path to out\u002Fprofile.html.\",\n});\nconst rounds: RoundOutcome[] = [];\nfor (let round = 1; round \u003C= 3; round += 1) {\n  const outcome = await optimizer.ask\u003CRoundOutcome>(\n    `Round ${round}: make the query faster, then measure it.`,\n  );\n  rounds.push(outcome);\n  report({ ...outcome, target: TARGET_MS }, \"perf\");\n  if (outcome.queryMs \u003C= TARGET_MS) break;\n}\n\nphase(\"Hand the user the profile and the write-up\");\ntry {\n  await artifact.file(\"profile\", \"out\u002Fprofile.html\", { title: \"Query profile after the last round\" });\n} catch {\n  const profiler = agent(\"profiler\");\n  await profiler.ask(\"out\u002Fprofile.html is missing. Profile the query path as it stands and write the profile there.\");\n  await artifact.file(\"profile\", \"out\u002Fprofile.html\", { title: \"Query profile after the last round\" });\n}\nconst latest = rounds[rounds.length - 1]?.queryMs ?? 0;\nawait artifact.markdown(\n  \"report\",\n  [\n    `# Query latency: ${latest}ms against a ${TARGET_MS}ms target`,\n    \"\",\n    ...rounds.map((r) => `- Round ${r.round}: ${r.queryMs}ms — ${r.change}`),\n  ].join(\"\\n\"),\n  {\n    title: \"Optimization report\",\n    description: `What each of the ${rounds.length} rounds changed and what it bought.`,\n    primary: true,\n  },\n);\n\nreturn {\n  conclusion: `Latency landed at ${latest}ms against a ${TARGET_MS}ms target.`,\n  verified: [\"each round's latency was measured by the subagent that made the change\"],\n  notCovered: [\"memory use; only query latency was measured\"],\n};\n```\n\nOne `report` call feeds both surfaces: the tagged item lands on the chart *and* in the run's\nresults. Three cards, none repeating another: the chart is what the user watched, the profile\nis what a person opens, the report is what they keep; the CSV the bench wrote stays in the\nworkspace, since its rows are the chart's points.\n\n## 11. A complete example\n\nThe complete review workflow that used to sit here — a reviewer per changed file, triage\nthrough one shared subagent that is fed as reviews land, a confirmer per kept finding chained\ninside the same callback, one join for the cross-file deduplication — is\n`${ZCODE_SKILL_DIR}\u002Fexamples.md` §5; §7 and §10 carry its rules. The open-ended form — a\nseed that surveys and ends in a tail hole, grown fill by fill — is `examples.md` #7 (§15).\n\n## 12. Anti-patterns\n\n| What you wrote | What it costs you |\n| --- | --- |\n| One subagent hoisted out of a fan-out for tidiness | The fan-out became a FIFO queue (§2) |\n| One fixed name for every subagent in a fan-out | A literal duplicate fails compile, a computed one kills the run; name per item or stay anonymous (§2) |\n| A fresh subagent each loop round | Round five re-learns what round four knew, at full price (§2) |\n| An unbounded `while` | The run dies on a cap instead of finishing (§2) |\n| Findings accumulated in an array, returned at the end | A failure on the last task loses them all; `report` as you go (§10) |\n| A whole file interpolated into a prompt | Tokens spent on what the subagent's own tools read; pass the path (§4) |\n| A wide `files.grep` with no glob | The call rejects; there is no partial result (§5) |\n| A subagent asked to run the tests and say if they passed | A session paid for what `world.run` decides as code, and a claim it can fake (§5) |\n| A `world.run` command name built at run time | Compile fails: the command is a literal; runtime values go in the args array (§5) |\n| The gate written from habit, or only the unit tests gated | The project named a stronger check; survey its checks, and run the strongest one before `return` (§5) |\n| A workflow submitted to see whether a parse function works | A full run for what `EvalWorkflowSnippet` answers now (§6) |\n| An unguarded `.find()` \u002F `.match()` result or optional property | Compile fails under `strict`; plain `items[i]` needs no guard (§16.3) |\n| `Date.now()` \u002F `Math.random()` \u002F `fetch` \u002F `fs` | Compile fails: a replayable run cannot contain them |\n| An `await` per item in a loop with no ordering need | Serial wall-clock for concurrent work (§7) |\n| A stage that waits for the whole previous stage though it handles items one at a time | Every worker of the second stage waits for the slowest of the first while slots idle; chain per item, or use a channel (§7) |\n| A join with no comment saying what needs every item | On the next revision nobody can tell the barrier from a habit; say why, or pipeline it (§7) |\n| A channel nobody closes | `ChannelDeadlock`; the producing stage closes it in a `finally` (§7) |\n| An `await` between starting the stage futures and joining them | A stage failing while you await another has no listener: an unhandled rejection, not a failed run; start all, then join once (§7) |\n| A shared pool where per-item names were wanted | One changed upstream item misses the cache for the whole pool (§7) |\n| Phases or subagents named after the machinery (\"fan-out\", \"文件评审阶段\", \"节点3\"), or no markers | A graph that says nothing about the work, or thirty cards (§8, §9) |\n| A reviewer asked \"is this good?\" | It approves; ask what would break it (§3) |\n| A reviewer loop, a final reviewer, a confirmer and a reader on one deliverable | Four sessions re-reading one piece of work; one mechanism, two with a reason (§3) |\n| Findings reported unconfirmed, or a slow existing check put in `notCovered` | The user cannot tell \"seen\" from \"suspected\", or verified from skipped (§10) |\n| A confirmer on a finding `world.run` already decided, or the suite run by hunter, confirmer and gate | One check paid three times; the exit code is the confirmation (§10) |\n| A bare array returned, or nothing published | The main agent improvises the handoff and the user keeps nothing; return the report shape and publish the deliverable (§10) |\n| A CSV and a table of its rows, or a dashboard nobody watches | Cards that are noise (§10) |\n| A persona that says only \"make the check pass\" | Faking is the obedient reading of an impossible gate; tell it to escalate (§14) |\n| A tunable constant interpolated into an ask | Amending it rewrites every such prompt and re-pays everything downstream (§13) |\n| A wrong run left to finish, or stopped and left | `AmendWorkflow` it now, while it runs (§13) |\n| A revised script pasted inline after a diagnostic | Twenty thousand tokens re-streamed to change one line; `Edit` the named file and pass `path` (§13) |\n| A hole for what an `if` or a subagent could decide, or one in a fan-out callback | A run parked on you for nothing; the fan-out case does not compile (§15) |\n\n## 13. After you submit\n\nCompilation happens first. **Diagnostics mean nothing ran**, and they name the file your\nscript is in: an inline `script` is written under `.zcode\u002Fworkflow-drafts\u002F` before it is\ncompiled and the response hands you the path; a `path` submission is that file already. Each\ndiagnostic reads `{path}:L{line}:C{column} {message}`, counted in the file.\n**Edit that file and resubmit with `path`. Do not paste the script inline again**: the\n`Edit` costs a few lines; the re-stream costs twenty thousand tokens and may stall the\nprovider. (If the response names no file, resubmit inline.)\n\nOn a clean compile the run starts in the background and you get a run ID. **Do not poll it.**\nThe completion notification arrives on its own with the final return value and every\nreported item. Do other work, unless the user asked you to wait.\n\nWhen you genuinely need to look at a run:\n\n- `TaskOutput` blocks until a run *this session started* finishes: the waiting tool.\n- `GetWorkflowRun` is an instant snapshot; use it when you must not block, or for a run\n  another session owns, which `TaskOutput` cannot see.\n- `ListWorkflowRuns` enumerates the project's runs, including other sessions'.\n\nRead the terminal state precisely. A run ends in exactly one of three states:\n\n- **completed** — the script returned.\n- **errored** — the script itself failed (an uncaught throw, a cap it overran, an artifact\n  whose source file was missing). Replaying it would fail the same way, so\n  `ResumeWorkflowRun` refuses it; edit the run's script file, which the notification names,\n  and resubmit it with `AmendWorkflow` and `path`.\n- **stopped** — resumable as-is with `ResumeWorkflowRun`. The `\u003Cstop-reason>` says why:\n  `user` (leave it alone unless they ask), `model` (you stopped it), `interrupted` (the\n  owning process exited; resume it), or `provider` (a deterministic model-side error —\n  sign-in expired, quota cap; the `\u003Cerror>` block names the fix — resolve it with the user,\n  then resume). A fifth state, `superseded`, is a run you amended away: not resumable, no\n  notification.\n\nReported items come back on errored and stopped runs too. A run with a \"waiting for\nprovider\" badge is retrying a provider error (§16.3), not broken; after twenty minutes you\nget one stall notification, and it still needs nothing from you.\n\n**When the script itself was wrong, do not start over.** Any run — errored, stopped,\ncompleted, or still running — can be superseded: edit the run's script file and call\n`AmendWorkflow` with `run_id` and that `path`. The new run imports the old one's finished\nwork, matched per named subagent along its sequence of asks, so every step you did not touch\nsettles from cache and only the changed part runs (the boundary is in §16.4). This is the\nmove after a `ScriptError`, a bad prompt, or a completed analysis that needs one more stage.\nTwo things make the cache hit: names that stay the same, and asks whose instructions stay\nbyte-identical (an upstream change cascades downstream).\n\n**Every run remembers its script file, so a revision is an `Edit`.** The terminal\nnotification names that path and `GetWorkflowRun` reports it as `scriptPath`, so the script\nnever has to live in your context: compaction may have dropped the text you sent, the file\non disk has not moved. Edit it in place and pass `path`; pass `script` only for something\ngenuinely new. A `path` whose bytes still equal what the run ran is refused as\n`script_unchanged` — your `Edit` did not land — with nothing stopped and nothing created.\n\n**Editing a draft asks nothing.** `.zcode\u002Fworkflow-drafts\u002F` is machine-owned and\ngit-ignored, so an `Edit` under it opens no confirmation window; the window still stands\nbetween the file and the run, so fix the file freely and let the submission be what the\nuser answers.\n\n**Repair a run while it is still going.** The same call works before the run ends, and the\nearlier the cheaper. When a run is heading the wrong way, do not wait for it and do not stop\nit first: call `AmendWorkflow` on it. The tool stops the predecessor, waits for it to settle,\nimports everything that settled before the stop at zero cost, and starts the revision — one\ncall, no `TaskStop`, no polling. The old run shows as \"superseded\" and sends no notification;\nthe result you get back names both runs.\n\nThe cascade rule has a converse that decides whether revisions are cheap or ruinous.\nInterpolating an upstream **result** into a prompt is safe: on resume it replays\nbyte-identical, so the prompt does too. Interpolating a script **constant** is the opposite\nbet — constants are what an amendment tunes, and every ask whose text mentions one forfeits\nits cache when you tune it, plus everything downstream:\n\n```ts\n\u002F\u002F ✗ Amending PASS_THRESHOLD (say 96 → 94) rewrites this text, so the resumed run\n\u002F\u002F   misses cache at the first revision and re-pays every ask after it.\ndraft = await writer.ask\u003CDraft>(\n  `Scored ${review.score}; passing needs ${PASS_THRESHOLD}. Revise: ${JSON.stringify(review.comments)}`,\n);\n\n\u002F\u002F ✓ Only replayed upstream values and the fact that the branch was taken; amending\n\u002F\u002F   the threshold now moves only where the loop exits, and earlier rounds settle from cache.\ndraft = await writer.ask\u003CDraft>(\n  `The review did not pass. Address each comment: ${JSON.stringify(review.comments)}`,\n);\n```\n\nKeep the tunable knobs — thresholds, round caps — in the script's control flow, where\namending them is free, and out of ask text, where it is a cache purge. A subagent rarely\nneeds the number; it needs the verdict and the feedback.\n\n## 14. When a subagent escalates\n\nEvery subagent can escalate a blocking question to you while the run is going; nothing in\nthe script switches this on. It exists for the one thing a script cannot design around: a\nsubagent walled in by something not its fault — a gate it cannot pass (capped at 95 against\na threshold of 96), two instructions no single output satisfies, a fact only whoever started\nthe run knows. With no way to ask, it has two moves left, both bad: grind until the round\ncap, or fake its way past.\n\n**What reaches you.** A notification arrives mid-run carrying the run, the subagent, the\nquestion with whatever evidence the subagent attached, and a globally unique question id shaped\nlike `dwfq-...`. Only the subagent that asked is parked, and only on that one call: its\nsiblings, the script's control flow and the run's status all carry on unchanged. Nothing\ntimes out on its behalf either — it waits until you answer or until the run is cancelled. So\nyou need not drop what you are doing, but you cannot leave it unanswered.\n\n**Then decide which of two things is true.**\n\n- The question **has an answer** — a clarification, one missing fact, a tradeoff only you can\n  call. Answer it with `ResolveWorkflowQuestion` and that `question_id`. Your text becomes\n  the result of the subagent's own call, verbatim, and it continues its turn from there. Not\n  sure? Read the run with `GetWorkflowRun`, or put the question to the user with\n  `AskUserQuestion` — then come back and answer, because nothing answers in your place.\n- The **script** is what is broken — a gate no output can pass, control flow routing work to\n  the wrong subagent. No sentence fixes that. Edit the run's script file and call\n  `AmendWorkflow` on it with that `path` (§13); it stops the run for you. The escalation is\n  what makes that amendment cheap: the ask that escalated never settled, so it sits exactly\n  past the cache boundary — everything before it imports from the old run at no token cost,\n  and it re-runs against the fixed script.\n\n**If the notification never arrives**, `GetWorkflowRun` lists what a run still owes you:\nthe questions under `pendingQuestions`, ids included, and the holes it is waiting at (§15).\nThat snapshot is the way to check on a run you suspect is waiting on you.\n\n**Write personas that make honesty the cheap move.** A persona that says \"make the check\npass\" and stops there leaves faking a pass as the obedient reading. One sentence closes that\noff: *\"If a check is impossible to pass, or your instructions contradict each other, escalate\nand say so plainly rather than working around it.\"*\n\nOne ask gets three escalations; the fourth comes back as an ordinary result telling the\nsubagent to proceed on its own best judgement — a guard against chatter.\n\n## 15. Holes: growing the workflow as the run learns\n\n`hole\u003CT>()` is the other mid-run request — §14 is the subagent's, this one is yours. A\nscript is what you know for sure; a hole is where knowing stops. Any phase whose subagents,\nasks or gate you would have to guess is a hole: write the part before the guess, end it in\n`hole\u003CT>()`, and the run's findings write the rest. A workflow whose shape the request fixes\nhas no holes, and that is fine too.\n\nA subagent returns a **value**; a hole returns **code**. Ask a subagent when the script\nalready knows what to do with the answer and only the data is missing. Leave a hole when\nwhat is missing is the rest of the workflow — which phases come next, which subagents exist,\nwhat each is told, what gate runs. *If you could write the code now and only the data is\nmissing, it is not a hole.*\n\n| The unknown is… | Use |\n| --- | --- |\n| an answer the script knows how to consume | a subagent ask; fresh eyes if it is a judgment (§3) |\n| a branch among outcomes you can enumerate now | a typed result and an `if` or a loop, in the script |\n| what the remaining workflow should be, knowable only from findings | a hole |\n| a question a subagent hits mid-task that only the run's owner can answer | escalation (§14) |\n\nSubagents run without you, in parallel; a hole parks one branch until you take a turn. Spend\nholes on shape, never on answers.\n\nThree forms; `T` is always written out:\n\n```ts\nconst plan = await hole\u003CPlan>(\"决定分组\", `最慢的模块是 ${survey.slowest}`); \u002F\u002F decide, then continue\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：${JSON.stringify(survey)}`); \u002F\u002F tail: the rest is not written yet\nconst plan = await hole\u003CPlan>(\"决定分组\", `…`, async () => { \u002F* filled: the body stands in for the hole *\u002F });\n```\n\n- **The name is a phase name.** A literal, unique among the script's holes and phase markers\n  (nested fills included), in the user's language: it labels the station, the notification and\n  the fill file. `T` is the contract the body is checked against.\n- **The prompt is the one channel for values.** Interpolate what the decision needs; the\n  fill reads values there and types from the code.\n- **The body sees every binding declared before the hole, none after**, and may leave holes\n  of its own.\n- **Filled once, run per reach.** A hole in a loop or a helper is filled once and its body\n  runs each iteration with that iteration's bindings. Never inside a fan-out callback (`.map`\n  or another array-method body): the fill would be owed while the items already run.\n\n### Grow by tail holes — the default for a task whose shape is not known upfront\n\nWhen the request does not tell you the workflow — a repository to understand before the\nwork can be planned, a bug whose next step depends on what the last one found — do not\nguess the topology. Write the part you know and end the script with a tail hole. The script\nthen grows by **nesting**: each fill is the statements of the innermost body, does one step,\nand ends in the next tail hole, until one returns instead.\n\n```ts\n\u002F\u002F 0. The seed you submit: what is known, then a typed gap.\nphase(\"盘点仓库顶层目录\");\nconst survey = await agent(\"勘察员\").ask\u003CSurvey>(\"列出顶层目录，各用一句话说明作用。\");\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：${JSON.stringify(survey.dirs)}`);\n```\n\n```ts\n\u002F\u002F 1. After the first fill: the hole has a body — one step, then the next hole.\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：…`, async () => {\n  phase(\"分章并行撰写初稿\");\n  const drafts = await Promise.all(\n    survey.dirs.map((d) => agent(`写手·${d.path}`).ask\u003CChapter>(`写「${d.path}」一章：${d.purpose}`)),\n  );\n  return await hole\u003CGuide>(\"第2步：审读与交付\", `${drafts.length} 章初稿已就绪`);\n});\n```\n\n```ts\n\u002F\u002F 2. After the second fill: the chain closes with a value, which is the run's result.\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：…`, async () => {\n  \u002F* step 1 as above; `survey` and `drafts` are in scope below *\u002F\n  return await hole\u003CGuide>(\"第2步：审读与交付\", `…`, async () => {\n    phase(\"独立审读并修订\");\n    const critique = await agent(\"审读员\").ask\u003Cstring>(`只凭文本挑毛病：${JSON.stringify(drafts)}`);\n    const chapters = await agent(\"修订编辑\").ask\u003CChapter[]>(`按意见修订：${critique}`);\n    return { title: \"仓库导览\", chapters, notCovered: [] };\n  });\n});\n```\n\nYou send only the innermost statements; the tool splices them in and rewrites the draft\nwith the effective script, so the draft you read before the next fill is the script that is\nrunning. The chain's rules: a fresh name per step (`第N步：\u003Cwhat it does>`; a repeated name\nis a 9012); the prompt is the progress ledger; results stay in bindings (`survey`, `drafts`),\nbecause every inner body sees the ones around it; a step may add phases, subagents and\nholes of its own. The timeline grows to the right, one head per step. This is the normal\nway to run a task whose shape only appears as the work proceeds, not a fallback.\n\n### A stage shaped by discovery\n\nThe survey's *value* goes to the script as data; the fill writes the *topology* of the next\nstage, which the survey decided: three reviewers or one, fanned out or sequential, which\ncheck gates them.\n\n```ts\nconst hot = await agent(\"剖析员\").ask\u003CHotspots>(\"找出最慢的三个模块，说明各自的耦合。\");\nconst reviews = await hole\u003CReview[]>(\"怎么审查这些热点\", `热点：${JSON.stringify(hot.modules)}`);\n```\n\nA fill for two independent modules and one shared one: two reviewers in a `Promise.all`,\na calibrated reviewer over the shared module, then a bounded fix-and-recheck loop — none of\nit writable before `hot` was known.\n\n### A procedure decided at first sight, run every round\n\n```ts\nfor (const failure of failures) {\n  const triage = await hole\u003CTriage>(\"每个失败怎么分诊\", `第一个失败：${failure.name}\\n${failure.output}`);\n  report(triage);\n}\n```\n\nFilled at the first failure, the body runs for every one after with that round's `failure`.\nThe fill is a *procedure* — which subagent to send, what to ask, when to mark `unconfirmed`\n— not an answer about one failure; that would be a subagent ask inside the loop.\n\n### A remedy the plan could not enumerate\n\n```ts\nconst gate = await world.run(\"pnpm\", [\"test\"]);\nif (gate.exitCode !== 0) {\n  await hole\u003Cvoid>(\"测试没过怎么办\", `退出码 ${gate.exitCode}：\\n${gate.stderr.slice(0, 2000)}`);\n}\n```\n\nIf the remedies were known, the script would hold a `Remedy` value and an `if`. The hole is\nfor when the fix may need phases and subagents nobody planned — a bisect, a second opinion,\na rollback — decided with the failure in hand.\n\n### Propose, judge, then build\n\n```ts\nconst proposals = await Promise.all([1, 2, 3].map((k) => agent(`方案${k}`).ask\u003CProposal>(\"提一个方案。\")));\nconst pick = await agent(\"评委\").ask\u003CPick>(`选最好的一个：${JSON.stringify(proposals)}`);\nreturn await hole\u003COutcome>(\"按选定方案施工\", `选中：${JSON.stringify(proposals[pick.index])}`);\n```\n\nThe judge is a subagent, because choosing is a value; the hole writes the stage that builds\nthe winner, whose shape depends on what won.\n\n**Not a hole:** a verdict, a summary, a choice among options, an answer per item — those are\nsubagent asks — and any branch an `if` over a typed result can express.\n\n**Filling one.** The notification carries the run, the hole's site id (`hole#21b40fca`), its name\nand type, the prompt with its values in, the draft's path and the hole's line, and the phases\nbefore and after. Then:\n\n1. Read the draft around the line: the body is compiled where the hole stands and sees what\n   is declared above it.\n2. Write only the statements — no `hole(...)` call, no arrow — returning a value of `T`, or\n   ending in a new tail hole when the next step is not known yet; rehearse fixed logic in\n   `EvalWorkflowSnippet` first (§6).\n3. Call `FillWorkflowHole` with `run_id`, `hole_id` and `script` (or `path`, §16.7). The run\n   grows by the body and goes on; the response names the phases added and the draft, now\n   holding the effective script, for any later `AmendWorkflow`.\n4. Diagnostics mean nothing was spliced and the hole still waits: edit the fill file the\n   response names and resubmit with `path`, never paste it again (§13). A line in the\n   draft's file is the run's recorded script: `AmendWorkflow`, not a draft edit.\n\nA fill that throws at run time rejects at the site and ends the run errored unless caught;\namend the draft as usual. Full scripts: `patterns.md` #14–#16, `examples.md` #7.\n\n## Going deeper\n\n- `${ZCODE_SKILL_DIR}\u002Fpatterns.md` — the topology catalogue. Its index puts the pipeline\n  shapes first: per-item chaining, streaming through channels, a feedback loop with a counted\n  close. Then fan-out\u002Ffan-in, review sweeps, planner-reviewer loops, judge panels, staged\n  handoffs, bounded discovery, `world.run`-gated verifier loops, model routing, and the hole\n  shapes (growth by tail holes, a stage shaped by discovery, a remedy hole). Read it when you\n  know the shape you want and want it written correctly.\n- `${ZCODE_SKILL_DIR}\u002Fexamples.md` — complete worked scripts, including a two-subagent\n  adversarial prove\u002Fdisprove loop and a repository guide grown step by step through tail\n  holes. Read one when you want to see a whole script's arc.\n\n## 16. Tool reference\n\nThe five authoring tools — `CreateWorkflow`, `AmendWorkflow`, `FillWorkflowHole`,\n`SaveWorkflow` and `EvalWorkflowSnippet` — carry short descriptions on purpose, and each refuses\nto run until this skill has been loaded in the session. This section is the part of their\ncontract that the descriptions do not carry: the facade the compiler checks against, the\nrules a script must satisfy, and the fields each tool takes. Read it before writing or\nrevising a script; the compiler holds you to it.\n\n### 16.1 `CreateWorkflow`\n\nTypechecks the script; on a clean compile asks the user to confirm and starts the run in the\nbackground; you are notified with the script's final `return` value when the run settles.\nCompilation errors come back as diagnostics, counted in the script's file (§13).\n\n**Three sources; pass exactly one.**\n\n- `script`: a one-off workflow written inline. It is saved to a file under\n  `.zcode\u002Fworkflow-drafts\u002F` and the result names that file, compiled or not; revise it by\n  editing the file and resubmitting with `path` (§13).\n- `saved`: a workflow saved in this project or globally, by name —\n  `saved: { name: \"pr-review\", args: { pr: \"123\" } }`; arguments are validated against its\n  declaration before anything runs. Check `ListSavedWorkflows` before writing one from\n  scratch: a saved workflow the user kept beats a rebuilt one. Running a saved workflow\n  is the one call that does not need this skill loaded.\n- `path`: a script file on disk, relative to the working directory or absolute — normally\n  the file a previous result named. Pass `args` alongside it when the file declares\n  arguments in its `\u002F* zcode-workflow` block.\n\nEither way the user confirms the run, and the confirmation shows the actual script.\n\n**Fields.**\n\n- `name`: a short label for the run in the user's language (\"PR review\", \"代码评审\").\n  Always pass it for an inline script; it labels the run everywhere and names its draft\n  file. It defaults to the saved workflow's name.\n- `max_concurrency`: an upper bound on how many subagents work at once. Set it only when\n  the user asks to limit parallelism — never as a reaction to provider rate limits or\n  errors, which the runtime already adapts to.\n- `subagent_model`: the model the subagents run on, as `providerId\u002FmodelId` or a bare model\n  id (optionally `$reasoningLevel`). Set it only when the user asks for a specific model;\n  pass the name they used, and if the tool cannot resolve it, pick from the ids it lists or\n  `ListModels`. NEVER set a model under another provider the user did not ask for: a bare\n  name resolves only within the session's provider, and crossing to another one is written\n  as the full `providerId\u002FmodelId`, which you write only when the user named that model.\n  If you think a cheaper or faster model elsewhere would serve the run, ask the user before\n  calling — model, provider, what it saves — and treat their yes as the request. You stay\n  on the session model either way.\n\nThis tool starts a new run. To change a run that exists — errored, completed, stopped or\nstill running — call `AmendWorkflow` (§13, §16.4), never `CreateWorkflow` again.\n\n### 16.2 The facade\n\nEvery script and snippet is checked against these declarations. They are the same constant\nthe compiler is fed, so what you read here is what typechecks. The block uses `declare`\nbecause it is the host's ambient API description — do not imitate it; your script defines\nplain interfaces and never uses `declare`.\n\n\u003C!-- facade-dts:start -->\n```ts\n\u002F** The pending result of one ask. Await it, or pass it to Promise.all with others. *\u002F\ndeclare interface Node\u003CT> extends PromiseLike\u003CT> {}\n\n\u002F** A model declared with model(). *\u002F\ndeclare class ModelRef { private constructor(); private readonly modelRef: never }\n\n\u002F**\n * Declare a model subagents may run on: \"modelId\" or \"providerId\u002FmodelId\", optional \"$level\".\n * String literal only (checked at launch); choose among ModelRefs at run time.\n *\u002F\ndeclare function model(id: string): ModelRef;\n\n\u002F** Persona of a subagent, fixed when agent() creates it. Every subagent has the same working tools. *\u002F\ndeclare interface AgentPersona {\n  \u002F** System prompt describing the actor's role. *\u002F\n  system?: string;\n  \u002F** Model id literal or ModelRef; omitted = the run's subagent model. *\u002F\n  model?: ModelRef | string;\n  \u002F** WebSearch calls per ask (integer literal, at most 1024); omitted = 128. *\u002F\n  budget?: { webSearch?: number };\n}\n\n\u002F**\n * A subagent: one conversation that keeps its context across asks. Asks issued while it is\n * busy wait their turn, first in, first out.\n *\u002F\ndeclare interface Agent {\n  \u002F**\n   * Give the subagent one task. With a type argument, the answer is a value of type T,\n   * validated against a schema built from it: T is an interface you define in this script\n   * with a plain \"interface\" declaration (no \"declare\" modifier). Without one, the answer is\n   * the subagent's final reply text.\n   *\u002F\n  ask\u003CT = string>(instructions: string): Node\u003CT>;\n}\n\n\u002F**\n * Create a subagent. Every call starts a new, empty conversation; to share one, share the\n * returned value. A non-empty name is an identity: unique within the run (a literal duplicate\n * is a compile error, a computed one fails the run) and the key AmendWorkflow matches cached\n * work by. Unnamed subagents are allowed and never reuse cached work.\n *\u002F\ndeclare function agent(name?: string, persona?: string | AgentPersona): Agent;\n\n\u002F**\n * The run's arguments. For a saved workflow they are validated against its declared\n * arguments, with defaults filled in, before the run starts; an inline script or a snippet\n * gets {}. Always defined; the values are unknown, so narrow them (String(args.target), a\n * typeof guard).\n *\u002F\ndeclare const args: Readonly\u003CRecord\u003Cstring, unknown>>;\n\n\u002F**\n * This run's id, and the run it amends. ResumeWorkflowRun keeps both; AmendWorkflow mints a\n * new id. Keep them out of ask text, personas and world arguments: those are cache keys.\n *\u002F\ndeclare const run: { readonly id: string; readonly resumedFrom?: string };\n\n\u002F** Emit a progress message to the user. *\u002F\ndeclare function log(message: string): void;\n\n\u002F**\n * Publish one intermediate result while the run is going; returns nothing. Items are\n * recorded: a resumed run never shows one twice, and they reach the completion notification\n * even when the run fails. The item must be JSON-serializable (plain objects, arrays, strings,\n * numbers, booleans, null); functions, class instances, Date and promises are compile\n * errors. Caps fail the whole run, not the call: 65,536 items per run, 1 MiB per serialized\n * item, 1 GiB per run.\n *\n * artifactId routes the item to a dashboard: a compile-time literal naming a preset\n * (artifact.chart \u002F table \u002F metrics \u002F board) whose declaration has executed by then. The\n * item becomes one point, row, tile value or card there and still lands in the run's\n * Results. A tag naming nothing, or a file\u002Fmarkdown artifact, fails the run.\n *\u002F\ndeclare function report(item: unknown, artifactId?: string): void;\n\n\u002F** A published artifact version: the id it was published under, and which version this call minted. *\u002F\ndeclare interface ArtifactRef { id: string; version: number }\n\u002F** Card metadata every artifact kind accepts. *\u002F\ndeclare interface ArtifactOptions {\n  \u002F** Shown as the card title; defaults to the id. In the user's language. *\u002F\n  title?: string;\n  \u002F** A sentence or two, shown beside the title when this artifact is the run's primary. *\u002F\n  description?: string;\n  \u002F** The run's deliverable: the card and the run pane lead with it. At most one id per run; once set it stays set for later versions. *\u002F\n  primary?: boolean;\n}\ndeclare interface ArtifactFileOptions extends ArtifactOptions {\n  \u002F** Overrides the type sniffed from the extension (\"application\u002Fpdf\", \"text\u002Fhtml\", …). *\u002F\n  contentType?: string;\n}\n\u002F** One value taken from a reported item: a dot path into the item (\"timing.after\"). *\u002F\ndeclare interface ArtifactField { field: string; label?: string; unit?: string }\ndeclare interface ChartSpec extends ArtifactOptions {\n  type?: \"line\" | \"bar\" | \"scatter\";        \u002F\u002F default \"line\"\n  x: ArtifactField;\n  y: ArtifactField | ArtifactField[];        \u002F\u002F several = several series\n  scale?: \"linear\" | \"log\";                  \u002F\u002F y axis, default \"linear\"\n  \u002F** A reference value drawn as a horizontal rule, taken from the first item that has the field. *\u002F\n  baseline?: ArtifactField;\n}\ndeclare interface TableSpec extends ArtifactOptions {\n  columns: ArtifactField[];\n  \u002F** Field that identifies a row; a later item with the same key replaces the row. Absent = append-only. *\u002F\n  key?: string;\n}\ndeclare interface MetricsSpec extends ArtifactOptions {\n  \u002F** Each tile shows the value from the latest item that has the field. *\u002F\n  metrics: ArtifactField[];\n}\ndeclare interface BoardSpec extends ArtifactOptions {\n  \u002F** Field identifying a card; a later item with the same key moves\u002Fupdates the card. *\u002F\n  key: string;\n  \u002F** Field holding the card's column. *\u002F\n  status: string;\n  \u002F** Column order. Items whose status is not listed land in a trailing \"other\" column. *\u002F\n  columns: string[];\n  \u002F** Field for the card title (default: the key) and extra fields shown on the card. *\u002F\n  cardTitle?: string;\n  detail?: ArtifactField[];\n}\n\u002F**\n * Publish what the user keeps: cards beside the run, kept after it ends. Every id is a\n * compile-time string literal (non-empty, at most 64 characters of [A-Za-z0-9_.-]) and is\n * used with one member only.\n * - CONTENT (file, markdown) are effects: async, resolve to an ArtifactRef, and reject\n *   catchably (missing file, not a file, outside the workspace, over the cap, or no artifact\n *   store in this host).\n *   Bytes are copied at publish time; republishing an id mints the next version and keeps\n *   the old ones.\n * - PRESET (chart, table, metrics, board) are declarations: synchronous and void, drawn from\n *   the items tagged report(item, \"\u003Cid>\"). Declare each once, at the top level; an identical\n *   re-declaration is a no-op, a different or malformed spec fails the whole run.\n * Caps: 32 ids per run, 16 versions per id, 20 MiB per file, 256 KB per markdown, 120\n * characters of title and 500 of description.\n *\u002F\ndeclare const artifact: {\n  \u002F** Publish a workspace file, path resolved as in files.read(). The type comes from the extension unless opts.contentType sets it. *\u002F\n  file(id: string, path: string, opts?: ArtifactFileOptions): Promise\u003CArtifactRef>;\n  \u002F** Publish markdown text the script composed. *\u002F\n  markdown(id: string, content: string, opts?: ArtifactOptions): Promise\u003CArtifactRef>;\n  \u002F** Declare a chart fed by report(item, id): each tagged item is one point. *\u002F\n  chart(id: string, spec: ChartSpec): void;\n  \u002F** Declare a table fed by report(item, id): each tagged item is one row. *\u002F\n  table(id: string, spec: TableSpec): void;\n  \u002F** Declare a metric tile row fed by report(item, id): each tile shows the newest value it has. *\u002F\n  metrics(id: string, spec: MetricsSpec): void;\n  \u002F** Declare a board fed by report(item, id): each tagged item is a card, placed by its status field. *\u002F\n  board(id: string, spec: BoardSpec): void;\n};\n\n\u002F**\n * Mark the start of a phase: a named group of the steps that follow, drawn as one node on\n * the graph the user approves. Presentation only: it starts, waits for and returns nothing.\n * Required. The name is a non-empty compile-time literal and the call a standalone\n * statement. A marker covers every step from it to the end of the block it stands in\n * (nested blocks and inlined helpers included); two markers with the same name are one\n * phase. Every phase contains at least one ask or world.run.\n *\u002F\ndeclare function phase(name: string): void;\n\n\u002F**\n * A typed gap: code you write later, once an earlier step's findings are in. When the run\n * reaches an unfilled hole, that branch waits while you write the body (FillWorkflowHole);\n * the rest of the run keeps going. prompt is the message you will receive, so interpolate\n * the values the decision needs. The body runs in the hole's place, sees the bindings\n * declared before it, and returns the hole's value. The filled form passes the body last.\n *\u002F\ndeclare function hole\u003CT>(name: string, prompt?: string): Promise\u003CT>;\ndeclare function hole\u003CT>(name: string, body: () => Promise\u003CT>): Promise\u003CT>;\ndeclare function hole\u003CT>(name: string, prompt: string, body: () => Promise\u003CT>): Promise\u003CT>;\n\n\u002F** One matching line found by files.grep. *\u002F\ndeclare interface GrepMatch {\n  \u002F** Workspace-relative path of the file the match was found in. *\u002F\n  path: string;\n  \u002F** One-based line number of the match. *\u002F\n  line: number;\n  \u002F** The full text of the matching line. *\u002F\n  text: string;\n}\n\n\u002F**\n * Read-only views of the workspace. Each result is recorded, so a resumed run gets the same\n * answer back instead of reading again. There is no write: writing is a subagent's task.\n *\u002F\ndeclare const files: {\n  \u002F** Workspace-relative paths matching a glob, sorted. Over 2000 files the call rejects. *\u002F\n  glob(pattern: string): Promise\u003Cstring[]>;\n  \u002F** Read one workspace file as UTF-8 text. Size-capped. *\u002F\n  read(path: string): Promise\u003Cstring>;\n  \u002F**\n   * Search contents with a ripgrep-compatible regex, optionally narrowed by a glob over\n   * paths (\"*.ts\", \"src\u002F**\"); one entry per matching line. Over 2000 matches or 256KB of\n   * results the call rejects.\n   *\u002F\n  grep(pattern: string, glob?: string): Promise\u003CGrepMatch[]>;\n};\n\n\u002F** The working tree's status, as reported by git.status(). *\u002F\ndeclare interface GitStatus {\n  \u002F** Current branch name; absent when HEAD is detached. *\u002F\n  branch?: string;\n  \u002F** True when nothing is staged, modified, or untracked. *\u002F\n  clean: boolean;\n  \u002F** Workspace-relative paths staged for the next commit. *\u002F\n  staged: string[];\n  \u002F** Workspace-relative paths modified in the working tree but not staged. *\u002F\n  unstaged: string[];\n  \u002F** Workspace-relative paths git does not track (honouring .gitignore). *\u002F\n  untracked: string[];\n}\n\n\u002F** One commit, as reported by git.log(). *\u002F\ndeclare interface GitCommit {\n  \u002F** Full commit hash. *\u002F\n  hash: string;\n  \u002F** First line of the commit message. *\u002F\n  subject: string;\n  \u002F** Author name. *\u002F\n  author: string;\n  \u002F** Author date, ISO 8601. *\u002F\n  date: string;\n}\n\n\u002F**\n * Read-only git views, recorded like files.* so a resumed run gets the same answer back; no\n * call can write. A base names a single ref (no \"..\" ranges). Paths are workspace-relative, and\n * changes outside the workspace are not reported; git.log alone is repository-wide. Caps\n * reject rather than truncate: diff at 512KB, log at 100 commits. Outside a git repository,\n * or without git, every call rejects catchably.\n *\u002F\ndeclare const git: {\n  \u002F**\n   * Workspace-relative paths that changed. With no base: files modified against HEAD, plus\n   * untracked files. With a base ref: tracked files whose current state differs from that\n   * ref, uncommitted edits included, untracked files not.\n   *\u002F\n  changedFiles(base?: string): Promise\u003Cstring[]>;\n  \u002F**\n   * Unified diff against base (default HEAD). Covers the whole workspace unless you\n   * narrow it to one workspace-relative path.\n   *\u002F\n  diff(base?: string, path?: string): Promise\u003Cstring>;\n  \u002F** The current working-tree status, for the workspace. *\u002F\n  status(): Promise\u003CGitStatus>;\n  \u002F** The most recent commits, newest first. Default 20, maximum 100. *\u002F\n  log(count?: number): Promise\u003CGitCommit[]>;\n};\n\n\u002F** The outcome of one world.run command, including nonzero exits. *\u002F\ndeclare interface WorldRunResult {\n  \u002F** The process exit code. Nonzero is a normal, returned outcome — branch on it. *\u002F\n  exitCode: number;\n  \u002F** Captured output (UTF-8), shaped by opts.output. *\u002F\n  stdout: string;\n  stderr: string;\n}\n\n\u002F**\n * Run a command. Each call runs once and its result is recorded: a resumed run reuses the\n * recorded result instead of running the command again. A completed process RESOLVES,\n * nonzero exit included; the promise rejects (catchably) only on spawn failure or timeout\n * (default 300000ms, timeoutMs overrides, no upper cap). cmd is a compile-time string\n * literal, shown to the user at confirmation. Fixed argv, never a shell: no pipes,\n * redirection or expansion. cwd is the workspace. Node builtins are reachable as\n * world.run(\"node\", [\"-e\", code]).\n * opts.output (both streams): \"full\" (default) rejects over 16 MiB; \"discard\" is \"\";\n * { tail: n } keeps the last n bytes, n \u003C= 16777216 (16 MiB). Neither bounds what the process prints.\n *\u002F\ndeclare const world: {\n  run(cmd: string, args?: string[], opts?: { timeoutMs?: number; output?: \"full\" | \"discard\" | { tail: number } }): Promise\u003CWorldRunResult>;\n};\n\n\u002F**\n * A stream of typed items between two stages: one stage send()s, another drains it with\n * for await. Unbounded, first-in-first-out, each item to exactly one receiver.\n *\u002F\ndeclare interface Channel\u003CT> extends AsyncIterable\u003CT> {\n  \u002F** Enqueue one item; synchronous, never waits. Throws ChannelClosed after close(). *\u002F\n  send(item: T): void;\n  \u002F**\n   * End the stream: receivers get the remaining items, then their loops exit. Idempotent.\n   * A channel nobody closes fails the run as ChannelDeadlock, naming it, once nothing in\n   * flight could send to it again.\n   *\u002F\n  close(): void;\n}\n\n\u002F**\n * Create a channel. The name labels the deadlock message; it is not an identity. A receiver\n * on an empty, open channel waits until a send or the close.\n *\u002F\ndeclare function channel\u003CT>(name?: string): Channel\u003CT>;\n\n\u002F**\n * Run an async block as a concurrent stage. It starts immediately, not when awaited, and\n * returns its promise.\n *\u002F\ndeclare function future\u003CT>(body: () => Promise\u003CT>): Promise\u003CT>;\n```\n\u003C!-- facade-dts:end -->\n\n### 16.3 Rules the compiler and the analyzer enforce\n\n- Plain TypeScript. Define result types with a plain `interface Foo { ... }` or\n  `type Foo = ...` and pass them as `ask\u003CT>` type arguments.\n- Compiled under `strict` with `noUncheckedIndexedAccess` off: indexing an array or record\n  (`items[i]`) needs no guard. `.find()`, `.match()`, `Map.get()` and optional properties\n  still yield `T | undefined` \u002F `null` and must be guarded before use.\n- Never use the `declare` modifier: the script is compiled inside a function body, where\n  ambient declarations are illegal. No `export` statements — the workflow's output is its\n  final `return`. No `import` statements.\n- Top-level `await` and a final `return \u003Cvalue>` are allowed; the returned value is exactly\n  what the completion notification carries.\n- No Node or web APIs: `process`, `fetch`, `fs` do not exist and fail typechecking.\n- `world.run` executes a real command. Its first argument must be a compile-time string\n  literal — the script's command set is shown to the user at confirmation — so interpolate\n  runtime values into the args array, never into the command name. A nonzero exit code\n  comes back as a value, not an exception (§5).\n- `hole\u003CT>()` (§15): explicit type argument; a literal name of at most 128 characters,\n  unique among the script's holes and phase markers; the call awaited and written inline;\n  outside every array-method fan-out callback (a `for...of` body is fine); the body reads no\n  binding declared after the hole. All of these are diagnostic 9012.\n- Phases are required (§8): cover the whole script with `phase(\"...\")` markers, one at the\n  head of each stage. The name is a compile-time string literal and the call is a standalone\n  statement; the marker claims the rest of its enclosing block, nested blocks and inlined\n  helper calls included, so a marker inside an `if` covers that branch only. Two markers\n  with the same name are one phase, which is how a retry loop stays two nodes instead of\n  per-round sprawl. Every phase contains at least one subagent `ask` or one `world.run`;\n  plain script logic between two asks is not a stage, so do not open a phase for the setup\n  at the top or the `return` at the bottom.\n- Subagent names: the name you pass to `agent(\"...\")` is the card the user sees, so write\n  it for the user in the session's language (§9). It is also an identity: unique within the\n  run, and the key an amended run matches its cached results by. Keep names stable across\n  revisions, and give duplicates in a loop their own computed names.\n- Artifact ids and the `report` tag are compile-time literals; one id belongs to one\n  artifact kind; at most one artifact carries `primary: true`; a preset artifact is declared\n  at the top level, not inside a loop, callback or branch (§10), and a fill's body is where\n  its hole stands. Publishing rejects catchably when the file is missing or too large.\n- Model-side errors never reach the script. Rate limits, overload, network errors and\n  timeouts are retried by the runtime without limit while it adapts the fan-out; a\n  deterministic one (expired sign-in, model not in the plan, quota cap) stops the run as\n  `stopped` for the user to fix and resume. Write no retry loops or `try`\u002F`catch` for\n  provider errors; reserve them for logic failures — a result that failed validation, a gate\n  that did not pass, a world read over its cap, a missing artifact source, or a\n  `ContextLimit` (the ask outgrew the model's context even after compaction: split it).\n- `channel`, `future`, `Channel.send` and `Channel.close` are facade callables: call them\n  directly (9001 applies to a stored or aliased call); a channel value itself may be stored\n  or passed freely. `send` after `close()` throws\n  `ChannelClosed`, catchable. Stalls fail the run, never time out: `ChannelDeadlock` when\n  receivers wait on channels nothing can send to any more (naming each), `ScriptStalled` when\n  some other promise can never settle.\n- The final `return` is the model-facing result; artifacts are the user-facing deliverable.\n  Never put the same content in both.\n- On diagnostics, edit the file the result names and call the tool again with `path`; never\n  paste the script a second time.\n\n### 16.4 `AmendWorkflow`\n\nRevises an existing run: it starts a new run that supersedes the old one and imports its\nfinished work as a cache, so only what you changed is paid for again. §13 has the cache\nrules and the repair-while-running move. It works on any run of this project — completed,\nerrored, stopped or still running; a running predecessor is stopped and superseded in the\nsame call, so never `TaskStop` it first and never rewrite it from scratch with\n`CreateWorkflow`. To continue a stopped run unchanged, use `ResumeWorkflowRun` instead.\n\n**Fields — every field you omit keeps the predecessor's value.**\n\n- `run_id` (required): from a `CreateWorkflow` or `AmendWorkflow` result, a notification,\n  `GetWorkflowRun` or `ListWorkflowRuns`.\n- `path` or `script`, never both. `path` is the usual form: the errored notification and\n  `GetWorkflowRun` name the run's script file — edit it in place and pass the same path\n  back, so a revision costs one `Edit` instead of a second copy of the whole script. A file\n  whose bytes you did not change is refused (`script_unchanged`) unless the call also\n  changes `max_concurrency` or `subagent_model`; nothing is stopped and nothing is created.\n  `script` carries a whole revised script inline, written against the same facade and rules;\n  it is saved to a draft file the result names, so the next revision can go back to `path`.\n  Omit both to keep the predecessor's script byte for byte and change only the settings\n  below; its finished work still replays from the cache.\n- `name`: a new display label; defaults to the predecessor's.\n- `max_concurrency`: omit to keep the predecessor's limit, pass `null` to remove it, pass a\n  number to change it (only when the user asks). A call carrying nothing but `run_id` and\n  `max_concurrency`, against a run that is still going, retunes that run in place instead of\n  starting a new one: same run, nothing stopped, nothing re-run.\n- `subagent_model`: omit to keep the predecessor's choice, pass `null` to put the subagents\n  back on the session model, pass a model id to change it (only when the user asks; never\n  a model under another provider the user did not name — ask them first if you think one\n  would help). `ListModels` lists the ids.\n\nChanging only a setting on a running run still stops it; what it had in flight runs again in\nthe new run, except that a named subagent whose unfinished ask you did not change picks that\nask up where it left off instead of starting it over.\n\n**How the cache works.** Named subagents are matched by name across the two scripts; each\none's asks are matched in order by byte-identical instructions. A match settles from the\nrecorded result at zero tokens; a changed or added ask runs live. The cache stays open until a\nlive subagent makes its first write to the workspace (or a live `world.run` executes): from\nthat moment, cached world reads and cached asks whose subagent had read or run something\nwould describe a workspace that no longer exists, so they run live too. Asks that only\nanswered keep settling from the cache. Editing an ask's text is how you force it to run\nagain; keep names stable and keep tunable constants out of ask text (§13).\n\nOn diagnostics nothing was stopped and nothing was started; fix the file the result names\nand call again with `path`.\n\n**Confirmation.** A run this session started (through `CreateWorkflow`, a previous\n`AmendWorkflow` or the workflows hub) is amended without a confirmation window, even while\nit is running. A run the user stopped, or a run another session started, asks the user\nfirst, and so does an amendment that would put subagents on a provider neither the session\nnor the run used (a model you name under another provider, in `subagent_model` or in the\nscript): that choice is the user's, and the window is where they make it. Another session's run that is still running cannot be amended or filled from here: the call is refused, and only that session can act on it. The result names the run that was superseded (if one was stopped) and the new run's\nid. The superseded run sends no notification of its own; the new run notifies when it\nsettles. Do not wait for it or poll it with `TaskOutput`.\n\n### 16.5 `SaveWorkflow`\n\nSaves a script with its metadata so it can be run again by name — through `CreateWorkflow`'s\n`saved` source, discovered with `ListSavedWorkflows`. Project definitions go in\n`.zcode\u002Fworkflows\u002F\u003Cname>.dwf.ts`, committed with the repository; global definitions go in\n`~\u002F.zcode\u002Fworkflows\u002F\u003Cname>.dwf.ts` and are available from every project on this machine.\n\n**When to call it.**\n\n- Never unsolicited. Saving writes a file into the user's repository; that is their\n  decision, not yours.\n- When a workflow you just built looks reusable — it would plausibly run again with\n  different inputs — suggest saving it in prose, one sentence naming what you would save and\n  why, then stop and wait. Call `SaveWorkflow` only after the user agrees, or when the user\n  asks directly (\"save this workflow\", \"保存这个工作流\"). A one-off script tailored to a\n  single question is not worth suggesting.\n\n**Fields.**\n\n- `name`: a file-safe identifier (letters, digits, dot, dash and underscore). Saving over an\n  existing name replaces that workflow, and the confirmation says whether the file is new or\n  an overwrite: reuse a name to update, pick a new one for a variant.\n- `description` (required) and `whenToUse`: written for a reader who has not seen this\n  conversation. `description` shows up wherever the workflow is listed.\n- `scope` (required, no default): `project` when the script references this repository's\n  files, commands, conventions or layout; `global` when it depends on nothing in the\n  project.\n- `script` or `script_path`, never both. `script_path` saves a draft a `CreateWorkflow` or\n  `AmendWorkflow` result named without re-emitting it; a `\u002F* zcode-workflow` block in that\n  file is dropped, because the metadata comes from this call's fields. `script` is the body\n  only — no metadata block.\n- `args`: name exactly the values that would change between runs — a PR number, a\n  directory, a depth. Each declaration gives a `type` (`string`, `number`,\n  `boolean`, or `json` for anything else), and optionally a `description`, `required: true`\n  and a `default`; every future call is validated against them.\n\nThe saved file is valid TypeScript: a `\u002F* zcode-workflow` block of YAML metadata, then the\nscript verbatim. The script is typechecked by the same compiler as `CreateWorkflow`, before\nthe user is asked; diagnostics mean nothing was written. The rules in §16.3 apply, phases\nincluded — future callers did not see this conversation, so the phase names are all they\nget.\n\n### 16.6 `EvalWorkflowSnippet`\n\nCompiles and runs a small snippet synchronously against the same compiler, sandbox and\nworld-read execution path a real run uses, and returns the result in the tool call. Nothing\npersists: no journal rows, no background task, no run. It is the test bench of §6, for the\nfixed logic of a script or of a hole's body; it is not for orchestration.\n\n- `code` or `path`, never both: the snippet inline, or a file holding it, read whole with no\n  metadata handling.\n- `timeoutMs`: the wall clock for the whole snippet in milliseconds; default 60000, at most\n  600000.\n- The snippet facade is the `args`, `run`, `log`, `files`\u002F`git`, `world.run`, `channel` and\n  `future` parts of the block in §16.2 (a snippet's `run.id` is a throwaway `dwfeval-…` id); `agent()`, `report()`, `artifact.*`, `hole()` and the `phase`\n  marker are the only absentees — they do not exist here and\n  fail typechecking. The language rules are a script's: plain interfaces, top-level `await`, a\n  final `return \u003Cvalue>`. The returned value is serialized into the result, so return a\n  summary, not a dump; over 256KB fails the call. `log(...)` lines come back in order. A\n  snippet that contains `world.run` asks the user for confirmation before running. On\n  diagnostics nothing ran: fix the snippet and call again.\n\n### 16.7 `FillWorkflowHole`\n\nWrites the body of a hole a run is waiting at (§15). It starts nothing: the run keeps its id,\njournal and subagents, and the effective script — the run's script with the body spliced in —\nis what a resume replays, an amend revises and `SaveWorkflow` keeps.\n\n- `run_id` and `hole_id` (required): from the notification or `GetWorkflowRun`; the hole id\n  is the site id (`hole#21b40fca`), not the name.\n- `script` or `path`, never both: the body's statements only. An inline `script` is written to\n  a fill file under `.zcode\u002Fworkflow-drafts\u002F` before it is compiled and the result names it;\n  `path` is usually that file after an `Edit`, and bytes equal to the last rejected attempt\n  are refused as `fill_unchanged`.\n\nThe body is compiled where the hole stands, against the whole script; a diagnostic is anchored\nto the file it falls in — the fill file inside the body, the run's draft outside it — and on\ndiagnostics nothing is spliced. A body may name only the models the run was launched with; any\nother model is diagnostic 9011 — to add one, amend the run.\n`hole_not_waiting` means the run is not in flight or not\nwaiting at that hole (filled, not yet reached, unknown id); resume a stopped run first and the\nhole asks again. A body may end in a new tail hole instead of returning (§15). On success the\nresponse names the phases added and the run's draft, rewritten in place with the effective\nscript. Confirmation follows the amend rule (§16.4): this session's run fills without a\nwindow; otherwise the window shows the new stations and the `world.run` commands the body\nadds.\n","# Writing dynamic workflows\n\nThis skill is the whole authoring contract for `CreateWorkflow`. The tool descriptions are\nshort on purpose; the facade the compiler checks against, the rules a script must satisfy and\nthe fields each tool takes are in §16, and `CreateWorkflow`, `AmendWorkflow`, `FillWorkflowHole`,\n`SaveWorkflow` and `EvalWorkflowSnippet` refuse to run until this skill has been loaded. The\nrest is the judgment layer: how many subagents a request deserves, which of them should share\na context, what each one should hand back, and how to keep the run's work from dying with the\nrun.\n\nTwo names collide in this codebase. `CreateWorkflow` is the dynamic-workflow tool and the\nonly one this skill is about. The legacy `Workflow` tool and `\u002Fexpert` are a different,\nolder feature that happens to share the word.\n\n## The bar: first-class, expert-level work\n\nA workflow exists to produce first-class, expert-level work — the deliverable a senior\npractitioner would hand over after doing the job properly, not a faster draft of what one\nreply could have said. A user who asks for a workflow is paying for that depth, and every\nchoice in this skill serves it: enough subagents to actually cover the ground, fresh eyes\non every plan and every draft (§3), an independent confirmation of every finding,\ndeterministic checks wherever a command can decide, and a report that says what was\nverified, what was not, and what it all means.\nDepth is measured by what is at stake, not by how many subagents re-read the same work:\nverification goes where a wrong claim would cost the user something, and each piece of work\ngets the one check that decides it. When a shortcut and the expert's way disagree, take the\nexpert's way; trim the work only when the task is small, and trim the checking when a wrong\nclaim costs little or a command has already decided it.\n\n## 1. Is this the right tool, and how big should it be?\n\n| The request | The tool |\n| --- | --- |\n| One thing delegated to one agent | `Agent` |\n| A few independent lookups, nobody reading anybody's answer | `Agent`, in parallel |\n| Anything else the user did not name a workflow for, however many steps it needs | `Agent`, or do it yourself |\n| The user said \"use a workflow\" \u002F \"使用 workflow\" \u002F \"用工作流\" — any phrasing naming workflow as the means | `CreateWorkflow`, mandatory, even if `Agent` would have done or one reply could answer |\n\n**Only an explicit request starts a workflow.** A workflow begins with `\u002Fworkflow` or with\nthe user naming workflow\u002F工作流 as the means, never with your own judgement that a task\nlooks orchestration-shaped. Results feeding later steps, a bounded loop, a branch on a typed\nresult — those are shapes the script is good at once one has been requested, not reasons\nthere should be one. Delegate with `Agent` or do the work yourself.\n\n**An explicit request is binding.** Once the user names workflow\u002F工作流 as the means, the\nrouting question is closed — not `Agent`, not inline, not \"too small for a workflow\"; what\nremains is only how big the script should be, and the smallest task gets a small workflow.\n\nAn explicit workflow request is a request for depth, and the bar above is the measure.\nDefault to the thorough shape — a fresh subagent per unit of work, a deterministic gate\nwherever a command can decide, an independent confirmation of every finding the user will\nact on as fact (§10) — sized to the stakes: a bug the user will fix on your word gets a\nconfirmer; a poem or a survey gets a reader at most. Every task is a full model session, so\nput sessions where they raise confidence, not where they repeat each other: \"review the\nchanged files\" wants a reviewer per file plus a confirmer per finding; \"write me twenty\npoems\" wants twenty poets and no confirmers.\n\n**Write only as much of that shape as you know for sure.** Where a later stage depends on\nwhat an earlier one finds, write up to that point, end in a hole (§15), and let the findings\nwrite the rest. Guessing a topology is not depth.\n\n## 2. Subagent topology\n\nThis is the decision that separates a good script from a bad one. It is made twice: now,\nfor what the request already tells you, and at a hole (§15), for what only the run can tell\nyou. This section is about the first, in four parts.\n\n**Fresh subagent per item, or one shared subagent?** Every `agent()` call creates a new context.\nSharing a context means sharing the *variable*:\n\n```ts\n\u002F\u002F Independent: each judge sees only its own item. Runs concurrently.\nitems.map((i) => agent(`judge-${i.id}`).ask\u003CVerdict>(`Judge ${i.id}`));\n\n\u002F\u002F Calibrated: one context sees every item in sequence, so its later verdicts are\n\u002F\u002F consistent with its earlier ones. Asks on one subagent queue FIFO — this serializes.\nconst judge = agent(\"judge\", \"You rank consistently across a whole batch.\");\nitems.map((i) => judge.ask\u003CVerdict>(`Judge ${i.id}`));\n```\n\nIndependent is right for unrelated items; shared is right when the answers must be\nconsistent with each other, at the price of serialization. Hoisting the `agent()` call out\nof a loop for tidiness turns a fan-out into a queue, and nothing rejects that script.\n\n**A name is an identity, and it has to be unique.** No two subagents in one run may share a\nnon-empty name — a duplicate fails the run. One fixed name inside a fan-out is a duplicate\nper item, so write `` agent(`judge-${i.id}`) ``; the compiler catches the literal form, a\nname built at run time costs you the run. Anonymous is always safe.\n\nNames are worth giving anyway: a **revised** re-run finds its cache by them (§13),\nimporting every ask whose instructions did not change at zero tokens. Anonymous subagents\nstart empty.\n\n**Persona, frozen at creation.** A persona stacks on the harness's own subagent contract —\nciting `path:line`, never reporting a check it did not run, saying what it could not do,\nescalating instead of faking — so write the role and the standard of judgement and leave\nthose rules out. Every subagent has the same tools; what it may do with them is said in the\nask: a reviewer that must not touch the code is told \"do not edit any file\".\n\n**Per-subagent model**, only when the user asked for one, with the name they used:\n`agent(\"judge\", { model: \"GLM-5.3-Flash\" })`, ids from `ListModels`. A literal or a `model()`\nModelRef; to route, map the router's typed key to a `model()` table (`patterns.md` #13).\nNEVER move a subagent to a model under another provider on your own — not for a judge, not\nbecause it looks cheaper; another provider is another bill. When a lighter model would\nclearly fit (one-turn judges, routers) and the user has not said, ask them first, before\nthe call: name the model and the provider, say what it would save, and go with their answer.\nTheir yes is the request; write it as the full `providerId\u002FmodelId` (a bare name never\ncrosses providers).\n\n**Search budget.** By default each ask may make 128 `WebSearch` calls; past that, `WebSearch`\nrefuses and the subagent finishes from what it has. When you anticipate an ask needing more\nsearches, which should be rare, set a larger number: `agent(\"scout\", { budget: { webSearch: 512 } })`\n(an integer literal, at most 1024). A result that says its search was cut short means the\nbudget was hit: tell the user, and amend with a larger budget if they want more.\n\n**Where each item goes next.** A run with more than one stage is a pipeline: an item leaves\nits stage as soon as it is done, and the next stage takes it while the rest are still being\nworked on. Decide this at every hand-off when you lay out the topology, and let a stage wait\nfor all of its items only where the next step needs every one. §7 says how to write each case.\n\n**Loops.** Bound every loop with a round cap, and carry the feedback forward:\n\n```ts\nlet feedback = \"none\";\nfor (let round = 0; round \u003C 5; round++) {\n  const plan = await planner.ask\u003CPlan>(`Plan the fix. Previous critique: ${feedback}`);\n  const review = await reviewer.ask\u003CReview>(`Critique this plan: ${JSON.stringify(plan)}`);\n  if (review.approved) return plan;\n  feedback = review.feedback;\n}\n```\n\nReuse the same two subagents across rounds: a subagent asked again keeps its context, so\nround five is cheap. Reuse costs freshness — by round three the reviewer is anchored on its\nown critique — so add an independent one at the end (§3).\n\n**No nesting.** Subagents cannot call `CreateWorkflow`; model a big sub-task as more subagents\nhere.\n\n## 3. Fresh eyes\n\nThe author of a plan or a draft cannot see its gaps, because they filled them while\nwriting. A reader with a separate context has no such fill, so the gaps show. That is the\nwhole method, and it applies at every stage *inside* the workflow where something is\ndrafted — a plan, a fix, a finding, the final report. It pays most on plans, which are\ncheap to critique and expensive to execute wrongly.\n\nFour rules make the eyes actually fresh:\n\n- **Separate context, not a second opinion from the same head.** An independent reader is a new\n  `agent()` that has seen nothing but the draft. Every planner–reviewer loop keeps a\n  persistent reviewer for continuity (§2), and then puts the final draft in front of a\n  reviewer that has never seen an earlier round.\n- **Ask for failures, not approval.** \"Is this good?\" gets a yes. \"What would break this?\n  What is missing? Restate the plan in your own words\" gets findings. Write the ask so\n  that approving takes evidence and objecting is the easy move.\n- **Give the eyes the same evidence.** A reviewer judging a plan about code from its text\n  alone can only judge coherence: tell plan reviewers to read the files the plan touches,\n  and not to edit them.\n- **Give a prose deliverable an independent read.** When the deliverable is text nothing else\n  checked — a guide, an analysis — hand it, before the script returns, to a reader-proxy\n  subagent asked what is unclear, what the text fails to support, and what the user will ask\n  next; then fix those. Say it judges from the text alone — checking claims is a confirmer's\n  job. A report whose\n  findings were each confirmed (§10) has had its eyes; add no reader on top.\n\nThree cautions. Correlated reviewers add little — same model, same prompt, same blind spots\n— so give each a distinct lens. Bound it: one deliverable gets one mechanism — a plan a\nreviewer who reads the code, findings a confirmer, prose a reader; two is the ceiling, with\na reason you can say. And these rules are about the subagents *inside* the script, not a gate\non submitting it: read your own script once against the request, and at every `Promise.all`\nask whether the next step needs every item; where it does not, pipeline it (§7). The\nconfirmation window then puts the plan in front of the user.\n\n## 4. Typed results\n\nPass a type argument to `ask` whenever your control flow will branch on the answer; leave it\noff when you just want prose back. The type must be an interface or type alias you write in\nthe script.\n\n**JSDoc on a property becomes the field description the subagent actually reads.** This is the\ncheapest quality lever in the whole surface and the easiest to skip:\n\n```ts\ninterface Finding {\n  \u002F** Workspace-relative path the problem is in. *\u002F\n  path: string;\n  \u002F** One sentence: what is wrong, not how to fix it. *\u002F\n  problem: string;\n  \u002F** How much it matters. Reserve \"high\" for data loss or a crash. *\u002F\n  severity: \"low\" | \"medium\" | \"high\";\n}\n```\n\nWithout the comments you get whatever the subagent guessed `severity` meant.\n\nKeep results narrow: a result crosses a schema boundary and gets interpolated into the next\nprompt, so a wide one costs tokens twice. **Pass paths, not file contents** — a subagent has\nits own file tools; a stringified 4000-line file spends tokens on what it could have read.\n\n## 5. Getting the world in\n\n`files.glob` and `git.changedFiles` are how a script learns what to fan out over; both are\nexecuted by the harness, recorded, and replayed on resume.\n\nCaps **reject rather than truncate** (§16.2), so narrow the pattern instead of fanning out\nover a silently partial view. Reads are catchable, so a coarser fallback is a `catch` —\nwhich `git` needs, since every `git` call rejects outside a repository:\n\n```ts\nlet paths: string[];\ntry {\n  paths = await git.changedFiles(\"origin\u002Fmain\");\n} catch {\n  paths = await files.glob(\"src\u002F**\u002F*.ts\");\n}\n```\n\nReach for `files.read` or `files.grep` only when the *script itself* must shard or branch on\ncontent; reading files is subagent work.\n\n**`world.run` is the deterministic gate.** When a check is fixed and machine-checkable — the\nbuild passes, the proof checks, the tests are green — run it as code and branch on the exit\ncode, instead of asking a subagent to run it and trusting the claim:\n\n```ts\nconst check = await world.run(\"lake\", [\"build\"], { timeoutMs: 1_800_000 });\nif (check.exitCode !== 0) feedback = check.stderr;\n```\n\nA nonzero exit code is a **value**, not an exception: read `exitCode` and carry `stderr`\nforward as the next round's feedback, with no `catch`; rejections are for the world failing\nto answer (spawn failure, timeout, output over the cap). A test suite can print more than the\n16 MiB cap: a gate that reads only `exitCode` passes `{ output: \"discard\" }`, and a gate that\nhands the failure on passes `{ output: { tail: 16_384 } }`. The command name must be a\ncompile-time string literal, because the user approves the script's command set at\nconfirmation: interpolate paths, flags and round numbers into the **args array**, never into\nthe command. Open-ended editing belongs to a subagent; `world.run` is for checks your\ncontrol flow branches on.\n\n**Choose the gate before you write it.** A gate decides exactly as much as the check it\nruns. Before the first `world.run`, find out what checks the repository has — `package.json`\nscripts, `Makefile` targets, the CI config, the README's \"run this to verify\" line — and\nrank them by how much they decide: a unit suite decides less than an end-to-end suite, which decides less than\nthe acceptance command the README names, and none decides a performance request the way\nthe bench does. Then build the gate in two tiers: the fast tier may drive a loop's rounds;\nthe **strongest** tier the request implies decides the exit and runs for real at least once\nbefore the final `return`, even when the fast tier said yes. Give a slow tier the\n`timeoutMs` it needs; a faster substitute is a different check.\n\n```ts\nphase(\"Fix until the unit tests pass\");\nfor (let round = 1; round \u003C= 5; round++) {\n  const unit = await world.run(\"npm\", [\"test\"]);\n  if (unit.exitCode === 0) break;\n  await fixer.ask(`The unit tests failed:\\n${unit.stderr}\\nFix them.`);\n}\n\nphase(\"Run the end-to-end suite once before handing over\");\nconst e2e = await world.run(\"npm\", [\"run\", \"e2e\"], { timeoutMs: 1_800_000 });\nconst verified = e2e.exitCode === 0;\n```\n\nA check that exists in the repository and did not run is not \"not covered\"; it is\nunverified work (§10).\n\n## 6. Test the pieces before you commit\n\nA workflow script is final at submit. The fixed logic inside it does not have to be: run it\nthrough the `EvalWorkflowSnippet` tool first (§16.6), synchronously and without persisting\nanything. What passed there pastes into the workflow verbatim. Send the snippet\nas `code`, or as `path` to a file holding it — the second try then costs an `Edit`.\n\nSnippet work is the non-subagent part: what a glob really returns, whether a grep pattern\noverruns its cap, how `world.run(\"lean\", ...)`'s stderr parses, whether a gate predicate does\nwhat you meant. A snippet has `files.*`, `git.*`, `world.run` and `log`, but no `agent()`.\nOnce you know which check decides the result (§5), run it once here too: that shows its\noutput, whether it exits nonzero as you assumed, and how long it takes — the `timeoutMs` you\nwrite, not a guess.\n\n## 7. Pipeline by default; join only where the next step needs every item\n\nA workflow with more than one stage should run like a pipeline: every stage works at the\nsame time, and each item moves on the moment it is ready. A reviewed file goes to its\nconfirmer while the other files are still being reviewed; a fact goes to its checker while\nthe researchers are still reading. Write it this way wherever the next step can take items\none at a time, which is nearly every hand-off. Let a stage wait for all of its items only\nwhere the next step needs every one: a deduplication across files, a ranking on one scale, a\nsynthesis. Those are the barriers, and a script has few of them.\n\n`Promise.all` is a join, and a join is a barrier: nothing after it starts until the slowest\nitem before it has landed. Parallelism comes from *not awaiting yet*:\n\n```ts\n\u002F\u002F Concurrent: nothing is awaited until the join.\nconst all = await Promise.all(\n  paths.map((p) => agent(`reviewer-${p}`).ask\u003CReview>(`Review ${p}`)),\n);\n\n\u002F\u002F Serial: each await blocks the next call. Only write this when you mean it.\nfor (const p of paths) results.push(await agent(`reviewer-${p}`).ask\u003CReview>(`Review ${p}`));\n```\n\n**Decide, at every hand-off, how an item leaves its stage:**\n\n| The next step takes | The stages | Write |\n| --- | --- | --- |\n| one item at a time | one to one: a reviewer per file, a confirmer per finding, a migrator per file and a checker per file | the stages chained per item inside one fan-out, one join at the end |\n| one item at a time | a pool of shared workers serves a stage; items are still being found while the next stage works; a later stage sends work back; the stages read better as separate blocks | a `channel` between the stages, a `future` per stage |\n| every item at once | deduplication, a ranking on one scale, a synthesis, the final report | a join, with a comment saying what needs every item |\n\n**Chaining.** When two stages map one to one, a barrier between them makes every worker of\nthe second stage wait for the slowest worker of the first while the run's concurrency slots\nsit idle. Chain the stages per item inside the fan-out instead, and join once at the end:\n\n```ts\n\u002F\u002F One join: each file's findings go to their confirmers the moment its review lands\n\u002F\u002F (two Promise.all — review every file, then confirm every finding — is the barrier).\nconst confirmed = (\n  await Promise.all(\n    paths.map(async (p) => {\n      const review = await agent(`reviewer-${p}`).ask\u003CReview>(`Review ${p}`);\n      return Promise.all(\n        review.findings.map((f, i) => agent(`confirmer-${p}-${i}`).ask\u003CConfirmation>(`Reproduce: ${JSON.stringify(f)}`)),\n      );\n    }),\n  )\n).flat();\n```\n\nA shared, calibrated subagent is not a barrier: asks on it queue first in, first out, so feed\nit each item as it lands and it stays consistent while the pipeline keeps moving (§11).\n\nOne rejection inside `Promise.all` rejects the whole join and the sibling results with it.\nWhen one bad item should cost one item, catch inside the callback (examples #3) or use\n`Promise.allSettled` and read each outcome.\n\n**Channels.** Chaining covers stages that map one to one. It cannot write a stage served by a\npool of shared workers, a producer still finding items while consumers work, stages laid out\nas separate blocks, or a feedback loop to an earlier stage. For those, a `channel\u003CT>()`\ncarries items between two stages and each stage is a `future(async () => { … })`. An item\nsent into the channel is taken by the next stage at once, by a worker that is waiting for it\nor by a new one started for it:\n\n```ts\nconst facts = channel\u003CFact>(\"facts\");\nconst verified: Fact[] = [];\n\nconst research = future(async () => {\n  phase(\"Research the topic from each angle\");\n  try {\n    await Promise.all(\n      angles.map(async (angle) => {\n        const found = await agent(`researcher-${angle}`).ask\u003CResearch>(`Research ${angle}.`);\n        for (const fact of found.facts) facts.send(fact);\n      }),\n    );\n  } finally {\n    facts.close(); \u002F\u002F the producer side owns the close; a failed researcher still ends the stream\n  }\n});\n\nconst verify = future(async () => {\n  phase(\"Check each fact as it arrives\");\n  await Promise.all(\n    [1, 2, 3].map(async (k) => {\n      const verifier = agent(`verifier-${k}`);\n      for await (const fact of facts) {\n        const verdict = await verifier.ask\u003CVerdict>(`Does this hold? ${JSON.stringify(fact)}`);\n        if (verdict.holds) verified.push(fact);\n      }\n    }),\n  );\n});\n\nawait Promise.all([research, verify]); \u002F\u002F start every stage, then join once\n```\n\nThe rules, in the order the code reads:\n\n- **A stage is a future.** Its marker first, then the workers (a `Promise.all` over K\n  `for await` loops on the input channel), then the output's `close()` in a `finally`. Start\n  every stage, then join all of them once with `Promise.all`, with no `await` between: while\n  you await one stage, a failure in another has no listener and surfaces as an unhandled\n  rejection instead of failing the run with its error.\n- **A channel where the next stage should start before the previous one ends; a join where it\n  needs every item.** Never a channel between two stages that need a barrier.\n- **A new subagent per item inside a consumer is a `future` inside the `for await`**, pushed\n  into an array and joined before the stage ends (examples #6); without that join the stage\n  ends when the channel closes with checks still running, and nothing reports it.\n- **A cycle is counted.** A feedback channel (a verifier sends a doubtful fact back for more\n  research) has no single producer who knows when it is done, so keep one count of open work\n  items: increment *before* finishing the item that produced the new work, close the feedback\n  channel when the count hits zero, bound the loop with a depth field on the item\n  (`patterns.md` #12).\n- **Pools trade cache reuse for consistency.** A pool of shared workers (`verifier-1…3`\n  above) judges on one scale, but which item lands on which worker depends on timing, so an\n  amendment that changes one upstream item misses the cache for the whole pool; a fresh\n  `verifier-${fact.id}` per item misses only itself. `send` never waits (the buffer is\n  unbounded); a channel nobody can send to any more fails the run as `ChannelDeadlock`.\n\n**Keep the data flow visible.** The harness recovers the dependency graph by reading your\ncode before it runs: plain variables, template interpolation, destructuring and small local\nhelpers are traced exactly; a result stashed in a container or behind an indirection earns a\ndiagnostic.\n\n## 8. Group the run into named phases\n\nPhases are required. The user experiences a workflow through its phase graph: the\nconfirmation dialog is drawn one node per phase, and thirty step cards is a dialog nobody\nreads. Cover the whole script — every stage gets a `phase(\"...\")` marker at its head; the\narrows between phases are inferred:\n\n\u003C!-- compile -->\n```ts\ninterface Attempt {\n  \u002F** One sentence: the optimization this round is trying. *\u002F\n  approach: string;\n}\n\n\u002F** Total nanoseconds the bench reports, or Infinity when it printed none. *\u002F\nfunction benchNanos(output: string): number {\n  const match = \u002Ftime:\\s*([\\d.]+) ns\u002F.exec(output);\n  return match?.[1] === undefined ? Number.POSITIVE_INFINITY : Number(match[1]);\n}\n\nphase(\"Measure today's baseline\");\nconst baseline = await world.run(\"cargo\", [\"bench\"], { timeoutMs: 1_800_000 });\nconst target = benchNanos(baseline.stdout);\nconst optimizer = agent(\"optimizer\");\n\nlet winner = \"none\";\nfor (let round = 1; round \u003C= 3; round++) {\n  phase(\"Make one improvement\");\n  const plan = await optimizer.ask\u003CAttempt>(\n    `Round ${round}. Baseline timings:\\n${baseline.stdout}\\nMake one improvement.`,\n  );\n\n  phase(\"Check that the tests still pass\");\n  const check = await world.run(\"cargo\", [\"test\"]);\n  if (check.exitCode !== 0) continue;\n\n  phase(\"Measure whether it is actually faster\");\n  const bench = await world.run(\"cargo\", [\"bench\"], { timeoutMs: 1_800_000 });\n  if (bench.exitCode === 0 && benchNanos(bench.stdout) \u003C target) {\n    winner = plan.approach;\n    break;\n  }\n}\n\nphase(\"Collect the final numbers\");\nconst head = await world.run(\"git\", [\"rev-parse\", \"HEAD\"]);\nreturn { approach: winner, commit: head.stdout.trim() };\n```\n\nFive nodes, with an arrow back from the bench to \"Make one improvement\" — and still five\nwhen the real script grows to thirty steps: the user sees the story instead of a wall of\ncards.\n\nThe unit tests are the fast tier that drives the rounds; the bench is the check the request\nwas about, and it decides every round that survives them, not once at the start (§5).\n\n**Write the names for the user, not for the graph.** A phase name is a short natural\nphrase saying what this stage accomplishes for the user, written in the language the\nuser is speaking in this session — \"Research each changed file in parallel\",\n\"汇总并产出最终报告\" (§9). Names are compile-time string literals, so you cannot number\nrounds by interpolation, and should not want to: two markers with the same name are one\nnode, so a loop body stays one box across its rounds.\n\n**Put the marker where the steps are.** A marker claims the rest of the block it sits in,\nnested blocks and inlined helper calls included, so mark the block where the `ask` and\n`world.run` calls actually live.\n\n**Not inside a concurrent fan-out callback.** Twenty `map(async …)` callbacks re-entering\n`phase(\"Review\")` out of order would count every re-entry as a round. A per-item pipeline\n(§7) is one phase named for what it does to each item, with the markers at the top level\naround it.\n\n**One marker at the head of each stage's future.** Concurrent stages written as futures (§7)\neach open their body with their own `phase(\"...\")`. Stamping is lexical — a step gets the\nphase the analyzer places it in, not the marker the engine passed last — so two stages\nrunning at once keep their own steps; still no marker in the per-item callback or the\n`for await` body.\n\n**Every phase must contain at least one `ask` or one `world.run`.** Plain script logic —\nreading `args`, shaping a prompt, building the `return` — shows no progress, so it is not a\nstage: fold it into the phase before or after it, and open none for the setup at the top,\nthe `return` at the bottom, or a branch that only narrates with `report` and `log`.\n\n## 9. Write for the user\n\nSix things you write are read by the user, not by the script: phase names, subagent names,\n`log` lines, artifact titles and the markdown you publish, the four report fields, and any\nquestion a subagent escalates. Write each one as you would tell a colleague across the desk\nwhat is happening: what the work is, in the user's words and language. The machinery —\nfan-out, gate, node, stage, pipeline — is yours, not theirs, and so is the numbering.\n\n| Read by the user | Write | Not |\n| --- | --- | --- |\n| Phase name | Review each changed file \u002F 逐个检查改动的文件 | Fan-out review stage \u002F 文件评审阶段 |\n| Phase name | Check that the tests still pass \u002F 确认测试仍然通过 | Gate: test verification \u002F 执行测试验证任务 |\n| Subagent name | Code reviewer \u002F 代码评审员 | reviewer_2 \u002F 节点3 |\n| Subagent name | Benchmark runner \u002F 跑基准测试的人 | runner \u002F 子代理A |\n| Phase name | Independent review of the final plan \u002F 请没看过方案的人再审一遍 | Cold read of the plan \u002F 冷读方案 |\n| Subagent name | Independent reviewer \u002F 独立评审员 | cold-reviewer \u002F 冷眼评审 |\n| `log` line | Reviewing 12 changed files \u002F 正在检查 12 个改动的文件 | Fan-out sized: n=12 \u002F 扇出阶段初始化完成 |\n| Report conclusion | Two of the twelve files have real bugs, both in the parser. \u002F 12 个文件里有 2 个有真问题，都在解析器里。 | The workflow executed successfully and produced findings. \u002F 工作流已成功执行并生成结果。 |\n| Artifact title | Review report \u002F 评审报告 | report-artifact-v1 \u002F 产物输出 |\n| Escalation question | Should the threshold be 94 rather than 96? \u002F 阈值应该是 94 而不是 96 吗？ | Requesting clarification regarding gate configuration parameters \u002F 请求对门控配置参数进行澄清 |\n\nThe method names in this skill — fresh eyes, independent read — are idioms for you, not\nwords for the user: in Chinese that is 独立复核 or 换人复审, never 冷读 or 冷眼.\nThe language travels through your asks: findings and summaries are written by subagents\nanswering the ask you wrote, so write asks in the user's language, or say which language to\nanswer in; otherwise a Chinese report arrives wrapping English findings.\n\n## 10. Verify, report, deliver\n\n`log(...)` is narration for the human watching the run: after a fan-out is sized, at the top\nof each loop round.\n\n**Verify before you report, in proportion to what a wrong claim costs.** Verification\nexists to buy down the cost of the user acting on something false, so it goes where that cost\nis real: a bug they will fix, a security claim, a number they will quote, a fact a decision\nrests on. Each finding of that kind is confirmed independently before it reaches the user: a\nsecond subagent that reproduces the finding from its evidence alone — reading the code,\nrunning a check when one decides it, never editing — or a `world.run` command when one can\ndecide. The reviewer that found it does not confirm it. A finding that fails confirmation\nis **kept and labelled** `unconfirmed`, never silently dropped — a real issue the confirmer\ncould not reproduce is still worth a human's eyes, and the label tells the user \"seen\" from\n\"suspected\".\n\nThree things that look like verification and are waste. A confirmer on a finding a\n`world.run` already decided: the exit code is the confirmation; record the command in\n`verified`. A confirmer on work nobody will act on as fact — poems, brainstormed options, a\nfirst-draft survey — which gets at most one independent read (§3). A suite run three times\nbecause the hunter, the confirmer and the gate each ran it: a gate runs once, by the script,\nand the asks say so (\"the script runs the full suite after you; do not run it yourself\").\n\n**Gate at the task's scale.** `verified` names the commands that actually decided the\nresult, and the reader holds them against what they asked for. A unit suite in `verified`\nand the end-to-end suite in `notCovered` is an unverified deliverable with a disclosure\nattached. `notCovered` is for what *could not* be checked — no test exists, the environment\nlacks the tool, the check needs something only the user has — never for a check that exists\nand was skipped because it is slow. If the strongest check the request implies exists and\ndid not run, the run is not done: run it, or say in `conclusion` that the work is unverified\nand why (§5).\n\n**Salvage by report.** `report(...)` is not `log`: reported items are delivered with the\ncompletion notification **even when the run fails**, which is how a run that dies on its\ntwelfth task keeps eleven tasks' worth of work. Report each finding the moment it lands —\nafter its confirmation, with its status — rather than accumulating an array to return at the\nend: the array is what you lose. Items are recorded, so a resumed run never shows one twice.\n\n**Stamp what outlives the run with `run.id`.** A ledger line, a file the script writes for a\nlater run, a report item someone will trace back: put `run.id` in it, so the record names the\nrun that produced it (`run.resumedFrom` names the run an amendment revised). Keep both out of\nask text, personas and `files`\u002F`world` arguments. Those are cache keys, and an amendment mints\na new id, so an ask that quotes it misses the cache and runs again.\n\n**Deliver a report.** The script's final `return` is the handoff the main agent presents,\nin the order below; what the user themselves keep is the artifact of the next section.\nReturn this shape (copy the interfaces; they compile as-is) rather than a bare array:\n\n\u003C!-- compile -->\n```ts\ninterface Finding {\n  \u002F** Workspace-relative path, with a line when it applies: \"src\u002Fa.ts:42\". *\u002F\n  where: string;\n  \u002F** One sentence: what is wrong, or what was found. *\u002F\n  what: string;\n  \u002F** What showed it: the lines read, or the command and the output that proved it. *\u002F\n  evidence: string;\n  \u002F** \"verified\" when an independent subagent or a deterministic check confirmed it; \"unconfirmed\" when confirmation failed or was not attempted. *\u002F\n  status: \"verified\" | \"unconfirmed\";\n  \u002F** How much it matters. Reserve \"high\" for data loss, a crash, or a wrong result. *\u002F\n  severity: \"low\" | \"medium\" | \"high\";\n}\ninterface WorkflowReport {\n  \u002F** Two or three sentences answering what the user asked for. *\u002F\n  conclusion: string;\n  findings: Finding[];\n  \u002F** What the run checked and how: the commands it ran, the files it covered. *\u002F\n  verified: string[];\n  \u002F** What the run did not look at or could not check, and why. *\u002F\n  notCovered: string[];\n}\n\nconst result: WorkflowReport = {\n  conclusion: \"Nothing was reviewed: this snippet only shows the shape.\",\n  findings: [],\n  verified: [],\n  notCovered: [\"everything — no subagent ran\"],\n};\nreturn result;\n```\n\nEach field has a reader. `conclusion` is the answer to what the user asked. `findings` carry\ntheir evidence and their status, so the user can tell what was seen from what was suspected.\n`verified` says what this run actually checked and how — the commands it ran, the files it\ncovered. `notCovered` says what it did not look at and why, which is the difference between\n\"we found nothing\" and \"we looked nowhere\". Write all four in the language the user is\nspeaking in this session.\n\n**Deliver artifacts.** The `return` is read by the main agent, which retells it. `artifact.*`\nis the other channel: things the *user* opens, shown as cards beside the run while it is\nstill going and kept after it ends. Two habits:\n\n- **Every run publishes its deliverable.** When the user asked for a thing — a webpage, a PDF\n  — a subagent writes it into the workspace and returns the path (\"write it to `out\u002F…` and\n  return the path\" belongs in the ask), and the script publishes it with `artifact.file`;\n  until it does, nothing the run left in the workspace exists for the user. When the user\n  asked for an answer — findings, a review — the `return` is the compact handoff and the\n  deliverable is the long form of the same facts: markdown built from the values the return\n  is built from, published once, at the end. The exception is a run whose whole answer is a\n  line. With more than one artifact, mark the deliverable `{ primary: true }`: the completion\n  card, the run pane and the notification lead with it. One primary per run.\n- **A dashboard is for the person watching the run.** Declare one when the run has state worth\n  watching while it runs — the key number after each round, which items are done or failed:\n  metrics or a chart for a number, a table or board for items with a status. Declare it once\n  at the top, then tag the items you already report: `report(item, \"perf\")`. It is a\n  projection of that stream, so it grows live and survives a resume. A run that is over\n  before anyone would look needs none.\n\n**Show what matters.** Two tests decide what earns a card: would the user open it on its\nown (else it is a section of the deliverable), and does it repeat another artifact (a CSV and\na table of its rows, a report and a copy of it — one of each pair is noise). The common run\npublishes one deliverable, one dashboard when there is something to watch, and further files\nonly when a subagent produced something else a person opens.\n\nIds and the report tag are compile-time string literals: what a run can publish is fixed\nwhen the user approves the script, and an id assembled at runtime is a compile diagnostic.\nPublishing an id a second time mints the next version and keeps the old one.\n\n**A rejected publish is a repair opportunity, not an error to swallow.** Content publishes\nreject catchably — the file is missing, the path escaped the workspace, the bytes are over the\ncap — and the honest response is to hand the gap back to a subagent and publish again, rather\nthan let a run end with nothing the user can open:\n\n\u003C!-- compile -->\n```ts\ninterface RoundOutcome {\n  \u002F** 1-based round number. *\u002F\n  round: number;\n  \u002F** Query latency in milliseconds, measured after this round's change. *\u002F\n  queryMs: number;\n  \u002F** One sentence: what this round changed. *\u002F\n  change: string;\n}\n\nconst TARGET_MS = 20;\nartifact.chart(\"perf\", {\n  title: \"Query latency by round\",\n  x: { field: \"round\", label: \"Round\" },\n  y: { field: \"queryMs\", label: \"ms\" },\n  baseline: { field: \"target\" },\n});\n\nphase(\"Optimize until the bench meets its target\");\nconst optimizer = agent(\"optimizer\", {\n  system:\n    \"You speed up a JSONL query engine: change one thing, measure it, and write the profile \" +\n    \"of the query path to out\u002Fprofile.html.\",\n});\nconst rounds: RoundOutcome[] = [];\nfor (let round = 1; round \u003C= 3; round += 1) {\n  const outcome = await optimizer.ask\u003CRoundOutcome>(\n    `Round ${round}: make the query faster, then measure it.`,\n  );\n  rounds.push(outcome);\n  report({ ...outcome, target: TARGET_MS }, \"perf\");\n  if (outcome.queryMs \u003C= TARGET_MS) break;\n}\n\nphase(\"Hand the user the profile and the write-up\");\ntry {\n  await artifact.file(\"profile\", \"out\u002Fprofile.html\", { title: \"Query profile after the last round\" });\n} catch {\n  const profiler = agent(\"profiler\");\n  await profiler.ask(\"out\u002Fprofile.html is missing. Profile the query path as it stands and write the profile there.\");\n  await artifact.file(\"profile\", \"out\u002Fprofile.html\", { title: \"Query profile after the last round\" });\n}\nconst latest = rounds[rounds.length - 1]?.queryMs ?? 0;\nawait artifact.markdown(\n  \"report\",\n  [\n    `# Query latency: ${latest}ms against a ${TARGET_MS}ms target`,\n    \"\",\n    ...rounds.map((r) => `- Round ${r.round}: ${r.queryMs}ms — ${r.change}`),\n  ].join(\"\\n\"),\n  {\n    title: \"Optimization report\",\n    description: `What each of the ${rounds.length} rounds changed and what it bought.`,\n    primary: true,\n  },\n);\n\nreturn {\n  conclusion: `Latency landed at ${latest}ms against a ${TARGET_MS}ms target.`,\n  verified: [\"each round's latency was measured by the subagent that made the change\"],\n  notCovered: [\"memory use; only query latency was measured\"],\n};\n```\n\nOne `report` call feeds both surfaces: the tagged item lands on the chart *and* in the run's\nresults. Three cards, none repeating another: the chart is what the user watched, the profile\nis what a person opens, the report is what they keep; the CSV the bench wrote stays in the\nworkspace, since its rows are the chart's points.\n\n## 11. A complete example\n\nThe complete review workflow that used to sit here — a reviewer per changed file, triage\nthrough one shared subagent that is fed as reviews land, a confirmer per kept finding chained\ninside the same callback, one join for the cross-file deduplication — is\n`${ZCODE_SKILL_DIR}\u002Fexamples.md` §5; §7 and §10 carry its rules. The open-ended form — a\nseed that surveys and ends in a tail hole, grown fill by fill — is `examples.md` #7 (§15).\n\n## 12. Anti-patterns\n\n| What you wrote | What it costs you |\n| --- | --- |\n| One subagent hoisted out of a fan-out for tidiness | The fan-out became a FIFO queue (§2) |\n| One fixed name for every subagent in a fan-out | A literal duplicate fails compile, a computed one kills the run; name per item or stay anonymous (§2) |\n| A fresh subagent each loop round | Round five re-learns what round four knew, at full price (§2) |\n| An unbounded `while` | The run dies on a cap instead of finishing (§2) |\n| Findings accumulated in an array, returned at the end | A failure on the last task loses them all; `report` as you go (§10) |\n| A whole file interpolated into a prompt | Tokens spent on what the subagent's own tools read; pass the path (§4) |\n| A wide `files.grep` with no glob | The call rejects; there is no partial result (§5) |\n| A subagent asked to run the tests and say if they passed | A session paid for what `world.run` decides as code, and a claim it can fake (§5) |\n| A `world.run` command name built at run time | Compile fails: the command is a literal; runtime values go in the args array (§5) |\n| The gate written from habit, or only the unit tests gated | The project named a stronger check; survey its checks, and run the strongest one before `return` (§5) |\n| A workflow submitted to see whether a parse function works | A full run for what `EvalWorkflowSnippet` answers now (§6) |\n| An unguarded `.find()` \u002F `.match()` result or optional property | Compile fails under `strict`; plain `items[i]` needs no guard (§16.3) |\n| `Date.now()` \u002F `Math.random()` \u002F `fetch` \u002F `fs` | Compile fails: a replayable run cannot contain them |\n| An `await` per item in a loop with no ordering need | Serial wall-clock for concurrent work (§7) |\n| A stage that waits for the whole previous stage though it handles items one at a time | Every worker of the second stage waits for the slowest of the first while slots idle; chain per item, or use a channel (§7) |\n| A join with no comment saying what needs every item | On the next revision nobody can tell the barrier from a habit; say why, or pipeline it (§7) |\n| A channel nobody closes | `ChannelDeadlock`; the producing stage closes it in a `finally` (§7) |\n| An `await` between starting the stage futures and joining them | A stage failing while you await another has no listener: an unhandled rejection, not a failed run; start all, then join once (§7) |\n| A shared pool where per-item names were wanted | One changed upstream item misses the cache for the whole pool (§7) |\n| Phases or subagents named after the machinery (\"fan-out\", \"文件评审阶段\", \"节点3\"), or no markers | A graph that says nothing about the work, or thirty cards (§8, §9) |\n| A reviewer asked \"is this good?\" | It approves; ask what would break it (§3) |\n| A reviewer loop, a final reviewer, a confirmer and a reader on one deliverable | Four sessions re-reading one piece of work; one mechanism, two with a reason (§3) |\n| Findings reported unconfirmed, or a slow existing check put in `notCovered` | The user cannot tell \"seen\" from \"suspected\", or verified from skipped (§10) |\n| A confirmer on a finding `world.run` already decided, or the suite run by hunter, confirmer and gate | One check paid three times; the exit code is the confirmation (§10) |\n| A bare array returned, or nothing published | The main agent improvises the handoff and the user keeps nothing; return the report shape and publish the deliverable (§10) |\n| A CSV and a table of its rows, or a dashboard nobody watches | Cards that are noise (§10) |\n| A persona that says only \"make the check pass\" | Faking is the obedient reading of an impossible gate; tell it to escalate (§14) |\n| A tunable constant interpolated into an ask | Amending it rewrites every such prompt and re-pays everything downstream (§13) |\n| A wrong run left to finish, or stopped and left | `AmendWorkflow` it now, while it runs (§13) |\n| A revised script pasted inline after a diagnostic | Twenty thousand tokens re-streamed to change one line; `Edit` the named file and pass `path` (§13) |\n| A hole for what an `if` or a subagent could decide, or one in a fan-out callback | A run parked on you for nothing; the fan-out case does not compile (§15) |\n\n## 13. After you submit\n\nCompilation happens first. **Diagnostics mean nothing ran**, and they name the file your\nscript is in: an inline `script` is written under `.zcode\u002Fworkflow-drafts\u002F` before it is\ncompiled and the response hands you the path; a `path` submission is that file already. Each\ndiagnostic reads `{path}:L{line}:C{column} {message}`, counted in the file.\n**Edit that file and resubmit with `path`. Do not paste the script inline again**: the\n`Edit` costs a few lines; the re-stream costs twenty thousand tokens and may stall the\nprovider. (If the response names no file, resubmit inline.)\n\nOn a clean compile the run starts in the background and you get a run ID. **Do not poll it.**\nThe completion notification arrives on its own with the final return value and every\nreported item. Do other work, unless the user asked you to wait.\n\nWhen you genuinely need to look at a run:\n\n- `TaskOutput` blocks until a run *this session started* finishes: the waiting tool.\n- `GetWorkflowRun` is an instant snapshot; use it when you must not block, or for a run\n  another session owns, which `TaskOutput` cannot see.\n- `ListWorkflowRuns` enumerates the project's runs, including other sessions'.\n\nRead the terminal state precisely. A run ends in exactly one of three states:\n\n- **completed** — the script returned.\n- **errored** — the script itself failed (an uncaught throw, a cap it overran, an artifact\n  whose source file was missing). Replaying it would fail the same way, so\n  `ResumeWorkflowRun` refuses it; edit the run's script file, which the notification names,\n  and resubmit it with `AmendWorkflow` and `path`.\n- **stopped** — resumable as-is with `ResumeWorkflowRun`. The `\u003Cstop-reason>` says why:\n  `user` (leave it alone unless they ask), `model` (you stopped it), `interrupted` (the\n  owning process exited; resume it), or `provider` (a deterministic model-side error —\n  sign-in expired, quota cap; the `\u003Cerror>` block names the fix — resolve it with the user,\n  then resume). A fifth state, `superseded`, is a run you amended away: not resumable, no\n  notification.\n\nReported items come back on errored and stopped runs too. A run with a \"waiting for\nprovider\" badge is retrying a provider error (§16.3), not broken; after twenty minutes you\nget one stall notification, and it still needs nothing from you.\n\n**When the script itself was wrong, do not start over.** Any run — errored, stopped,\ncompleted, or still running — can be superseded: edit the run's script file and call\n`AmendWorkflow` with `run_id` and that `path`. The new run imports the old one's finished\nwork, matched per named subagent along its sequence of asks, so every step you did not touch\nsettles from cache and only the changed part runs (the boundary is in §16.4). This is the\nmove after a `ScriptError`, a bad prompt, or a completed analysis that needs one more stage.\nTwo things make the cache hit: names that stay the same, and asks whose instructions stay\nbyte-identical (an upstream change cascades downstream).\n\n**Every run remembers its script file, so a revision is an `Edit`.** The terminal\nnotification names that path and `GetWorkflowRun` reports it as `scriptPath`, so the script\nnever has to live in your context: compaction may have dropped the text you sent, the file\non disk has not moved. Edit it in place and pass `path`; pass `script` only for something\ngenuinely new. A `path` whose bytes still equal what the run ran is refused as\n`script_unchanged` — your `Edit` did not land — with nothing stopped and nothing created.\n\n**Editing a draft asks nothing.** `.zcode\u002Fworkflow-drafts\u002F` is machine-owned and\ngit-ignored, so an `Edit` under it opens no confirmation window; the window still stands\nbetween the file and the run, so fix the file freely and let the submission be what the\nuser answers.\n\n**Repair a run while it is still going.** The same call works before the run ends, and the\nearlier the cheaper. When a run is heading the wrong way, do not wait for it and do not stop\nit first: call `AmendWorkflow` on it. The tool stops the predecessor, waits for it to settle,\nimports everything that settled before the stop at zero cost, and starts the revision — one\ncall, no `TaskStop`, no polling. The old run shows as \"superseded\" and sends no notification;\nthe result you get back names both runs.\n\nThe cascade rule has a converse that decides whether revisions are cheap or ruinous.\nInterpolating an upstream **result** into a prompt is safe: on resume it replays\nbyte-identical, so the prompt does too. Interpolating a script **constant** is the opposite\nbet — constants are what an amendment tunes, and every ask whose text mentions one forfeits\nits cache when you tune it, plus everything downstream:\n\n```ts\n\u002F\u002F ✗ Amending PASS_THRESHOLD (say 96 → 94) rewrites this text, so the resumed run\n\u002F\u002F   misses cache at the first revision and re-pays every ask after it.\ndraft = await writer.ask\u003CDraft>(\n  `Scored ${review.score}; passing needs ${PASS_THRESHOLD}. Revise: ${JSON.stringify(review.comments)}`,\n);\n\n\u002F\u002F ✓ Only replayed upstream values and the fact that the branch was taken; amending\n\u002F\u002F   the threshold now moves only where the loop exits, and earlier rounds settle from cache.\ndraft = await writer.ask\u003CDraft>(\n  `The review did not pass. Address each comment: ${JSON.stringify(review.comments)}`,\n);\n```\n\nKeep the tunable knobs — thresholds, round caps — in the script's control flow, where\namending them is free, and out of ask text, where it is a cache purge. A subagent rarely\nneeds the number; it needs the verdict and the feedback.\n\n## 14. When a subagent escalates\n\nEvery subagent can escalate a blocking question to you while the run is going; nothing in\nthe script switches this on. It exists for the one thing a script cannot design around: a\nsubagent walled in by something not its fault — a gate it cannot pass (capped at 95 against\na threshold of 96), two instructions no single output satisfies, a fact only whoever started\nthe run knows. With no way to ask, it has two moves left, both bad: grind until the round\ncap, or fake its way past.\n\n**What reaches you.** A notification arrives mid-run carrying the run, the subagent, the\nquestion with whatever evidence the subagent attached, and a globally unique question id shaped\nlike `dwfq-...`. Only the subagent that asked is parked, and only on that one call: its\nsiblings, the script's control flow and the run's status all carry on unchanged. Nothing\ntimes out on its behalf either — it waits until you answer or until the run is cancelled. So\nyou need not drop what you are doing, but you cannot leave it unanswered.\n\n**Then decide which of two things is true.**\n\n- The question **has an answer** — a clarification, one missing fact, a tradeoff only you can\n  call. Answer it with `ResolveWorkflowQuestion` and that `question_id`. Your text becomes\n  the result of the subagent's own call, verbatim, and it continues its turn from there. Not\n  sure? Read the run with `GetWorkflowRun`, or put the question to the user with\n  `AskUserQuestion` — then come back and answer, because nothing answers in your place.\n- The **script** is what is broken — a gate no output can pass, control flow routing work to\n  the wrong subagent. No sentence fixes that. Edit the run's script file and call\n  `AmendWorkflow` on it with that `path` (§13); it stops the run for you. The escalation is\n  what makes that amendment cheap: the ask that escalated never settled, so it sits exactly\n  past the cache boundary — everything before it imports from the old run at no token cost,\n  and it re-runs against the fixed script.\n\n**If the notification never arrives**, `GetWorkflowRun` lists what a run still owes you:\nthe questions under `pendingQuestions`, ids included, and the holes it is waiting at (§15).\nThat snapshot is the way to check on a run you suspect is waiting on you.\n\n**Write personas that make honesty the cheap move.** A persona that says \"make the check\npass\" and stops there leaves faking a pass as the obedient reading. One sentence closes that\noff: *\"If a check is impossible to pass, or your instructions contradict each other, escalate\nand say so plainly rather than working around it.\"*\n\nOne ask gets three escalations; the fourth comes back as an ordinary result telling the\nsubagent to proceed on its own best judgement — a guard against chatter.\n\n## 15. Holes: growing the workflow as the run learns\n\n`hole\u003CT>()` is the other mid-run request — §14 is the subagent's, this one is yours. A\nscript is what you know for sure; a hole is where knowing stops. Any phase whose subagents,\nasks or gate you would have to guess is a hole: write the part before the guess, end it in\n`hole\u003CT>()`, and the run's findings write the rest. A workflow whose shape the request fixes\nhas no holes, and that is fine too.\n\nA subagent returns a **value**; a hole returns **code**. Ask a subagent when the script\nalready knows what to do with the answer and only the data is missing. Leave a hole when\nwhat is missing is the rest of the workflow — which phases come next, which subagents exist,\nwhat each is told, what gate runs. *If you could write the code now and only the data is\nmissing, it is not a hole.*\n\n| The unknown is… | Use |\n| --- | --- |\n| an answer the script knows how to consume | a subagent ask; fresh eyes if it is a judgment (§3) |\n| a branch among outcomes you can enumerate now | a typed result and an `if` or a loop, in the script |\n| what the remaining workflow should be, knowable only from findings | a hole |\n| a question a subagent hits mid-task that only the run's owner can answer | escalation (§14) |\n\nSubagents run without you, in parallel; a hole parks one branch until you take a turn. Spend\nholes on shape, never on answers.\n\nThree forms; `T` is always written out:\n\n```ts\nconst plan = await hole\u003CPlan>(\"决定分组\", `最慢的模块是 ${survey.slowest}`); \u002F\u002F decide, then continue\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：${JSON.stringify(survey)}`); \u002F\u002F tail: the rest is not written yet\nconst plan = await hole\u003CPlan>(\"决定分组\", `…`, async () => { \u002F* filled: the body stands in for the hole *\u002F });\n```\n\n- **The name is a phase name.** A literal, unique among the script's holes and phase markers\n  (nested fills included), in the user's language: it labels the station, the notification and\n  the fill file. `T` is the contract the body is checked against.\n- **The prompt is the one channel for values.** Interpolate what the decision needs; the\n  fill reads values there and types from the code.\n- **The body sees every binding declared before the hole, none after**, and may leave holes\n  of its own.\n- **Filled once, run per reach.** A hole in a loop or a helper is filled once and its body\n  runs each iteration with that iteration's bindings. Never inside a fan-out callback (`.map`\n  or another array-method body): the fill would be owed while the items already run.\n\n### Grow by tail holes — the default for a task whose shape is not known upfront\n\nWhen the request does not tell you the workflow — a repository to understand before the\nwork can be planned, a bug whose next step depends on what the last one found — do not\nguess the topology. Write the part you know and end the script with a tail hole. The script\nthen grows by **nesting**: each fill is the statements of the innermost body, does one step,\nand ends in the next tail hole, until one returns instead.\n\n```ts\n\u002F\u002F 0. The seed you submit: what is known, then a typed gap.\nphase(\"盘点仓库顶层目录\");\nconst survey = await agent(\"勘察员\").ask\u003CSurvey>(\"列出顶层目录，各用一句话说明作用。\");\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：${JSON.stringify(survey.dirs)}`);\n```\n\n```ts\n\u002F\u002F 1. After the first fill: the hole has a body — one step, then the next hole.\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：…`, async () => {\n  phase(\"分章并行撰写初稿\");\n  const drafts = await Promise.all(\n    survey.dirs.map((d) => agent(`写手·${d.path}`).ask\u003CChapter>(`写「${d.path}」一章：${d.purpose}`)),\n  );\n  return await hole\u003CGuide>(\"第2步：审读与交付\", `${drafts.length} 章初稿已就绪`);\n});\n```\n\n```ts\n\u002F\u002F 2. After the second fill: the chain closes with a value, which is the run's result.\nreturn await hole\u003CGuide>(\"第1步：决定导览结构\", `盘点：…`, async () => {\n  \u002F* step 1 as above; `survey` and `drafts` are in scope below *\u002F\n  return await hole\u003CGuide>(\"第2步：审读与交付\", `…`, async () => {\n    phase(\"独立审读并修订\");\n    const critique = await agent(\"审读员\").ask\u003Cstring>(`只凭文本挑毛病：${JSON.stringify(drafts)}`);\n    const chapters = await agent(\"修订编辑\").ask\u003CChapter[]>(`按意见修订：${critique}`);\n    return { title: \"仓库导览\", chapters, notCovered: [] };\n  });\n});\n```\n\nYou send only the innermost statements; the tool splices them in and rewrites the draft\nwith the effective script, so the draft you read before the next fill is the script that is\nrunning. The chain's rules: a fresh name per step (`第N步：\u003Cwhat it does>`; a repeated name\nis a 9012); the prompt is the progress ledger; results stay in bindings (`survey`, `drafts`),\nbecause every inner body sees the ones around it; a step may add phases, subagents and\nholes of its own. The timeline grows to the right, one head per step. This is the normal\nway to run a task whose shape only appears as the work proceeds, not a fallback.\n\n### A stage shaped by discovery\n\nThe survey's *value* goes to the script as data; the fill writes the *topology* of the next\nstage, which the survey decided: three reviewers or one, fanned out or sequential, which\ncheck gates them.\n\n```ts\nconst hot = await agent(\"剖析员\").ask\u003CHotspots>(\"找出最慢的三个模块，说明各自的耦合。\");\nconst reviews = await hole\u003CReview[]>(\"怎么审查这些热点\", `热点：${JSON.stringify(hot.modules)}`);\n```\n\nA fill for two independent modules and one shared one: two reviewers in a `Promise.all`,\na calibrated reviewer over the shared module, then a bounded fix-and-recheck loop — none of\nit writable before `hot` was known.\n\n### A procedure decided at first sight, run every round\n\n```ts\nfor (const failure of failures) {\n  const triage = await hole\u003CTriage>(\"每个失败怎么分诊\", `第一个失败：${failure.name}\\n${failure.output}`);\n  report(triage);\n}\n```\n\nFilled at the first failure, the body runs for every one after with that round's `failure`.\nThe fill is a *procedure* — which subagent to send, what to ask, when to mark `unconfirmed`\n— not an answer about one failure; that would be a subagent ask inside the loop.\n\n### A remedy the plan could not enumerate\n\n```ts\nconst gate = await world.run(\"pnpm\", [\"test\"]);\nif (gate.exitCode !== 0) {\n  await hole\u003Cvoid>(\"测试没过怎么办\", `退出码 ${gate.exitCode}：\\n${gate.stderr.slice(0, 2000)}`);\n}\n```\n\nIf the remedies were known, the script would hold a `Remedy` value and an `if`. The hole is\nfor when the fix may need phases and subagents nobody planned — a bisect, a second opinion,\na rollback — decided with the failure in hand.\n\n### Propose, judge, then build\n\n```ts\nconst proposals = await Promise.all([1, 2, 3].map((k) => agent(`方案${k}`).ask\u003CProposal>(\"提一个方案。\")));\nconst pick = await agent(\"评委\").ask\u003CPick>(`选最好的一个：${JSON.stringify(proposals)}`);\nreturn await hole\u003COutcome>(\"按选定方案施工\", `选中：${JSON.stringify(proposals[pick.index])}`);\n```\n\nThe judge is a subagent, because choosing is a value; the hole writes the stage that builds\nthe winner, whose shape depends on what won.\n\n**Not a hole:** a verdict, a summary, a choice among options, an answer per item — those are\nsubagent asks — and any branch an `if` over a typed result can express.\n\n**Filling one.** The notification carries the run, the hole's site id (`hole#21b40fca`), its name\nand type, the prompt with its values in, the draft's path and the hole's line, and the phases\nbefore and after. Then:\n\n1. Read the draft around the line: the body is compiled where the hole stands and sees what\n   is declared above it.\n2. Write only the statements — no `hole(...)` call, no arrow — returning a value of `T`, or\n   ending in a new tail hole when the next step is not known yet; rehearse fixed logic in\n   `EvalWorkflowSnippet` first (§6).\n3. Call `FillWorkflowHole` with `run_id`, `hole_id` and `script` (or `path`, §16.7). The run\n   grows by the body and goes on; the response names the phases added and the draft, now\n   holding the effective script, for any later `AmendWorkflow`.\n4. Diagnostics mean nothing was spliced and the hole still waits: edit the fill file the\n   response names and resubmit with `path`, never paste it again (§13). A line in the\n   draft's file is the run's recorded script: `AmendWorkflow`, not a draft edit.\n\nA fill that throws at run time rejects at the site and ends the run errored unless caught;\namend the draft as usual. Full scripts: `patterns.md` #14–#16, `examples.md` #7.\n\n## Going deeper\n\n- `${ZCODE_SKILL_DIR}\u002Fpatterns.md` — the topology catalogue. Its index puts the pipeline\n  shapes first: per-item chaining, streaming through channels, a feedback loop with a counted\n  close. Then fan-out\u002Ffan-in, review sweeps, planner-reviewer loops, judge panels, staged\n  handoffs, bounded discovery, `world.run`-gated verifier loops, model routing, and the hole\n  shapes (growth by tail holes, a stage shaped by discovery, a remedy hole). Read it when you\n  know the shape you want and want it written correctly.\n- `${ZCODE_SKILL_DIR}\u002Fexamples.md` — complete worked scripts, including a two-subagent\n  adversarial prove\u002Fdisprove loop and a repository guide grown step by step through tail\n  holes. Read one when you want to see a whole script's arc.\n\n## 16. Tool reference\n\nThe five authoring tools — `CreateWorkflow`, `AmendWorkflow`, `FillWorkflowHole`,\n`SaveWorkflow` and `EvalWorkflowSnippet` — carry short descriptions on purpose, and each refuses\nto run until this skill has been loaded in the session. This section is the part of their\ncontract that the descriptions do not carry: the facade the compiler checks against, the\nrules a script must satisfy, and the fields each tool takes. Read it before writing or\nrevising a script; the compiler holds you to it.\n\n### 16.1 `CreateWorkflow`\n\nTypechecks the script; on a clean compile asks the user to confirm and starts the run in the\nbackground; you are notified with the script's final `return` value when the run settles.\nCompilation errors come back as diagnostics, counted in the script's file (§13).\n\n**Three sources; pass exactly one.**\n\n- `script`: a one-off workflow written inline. It is saved to a file under\n  `.zcode\u002Fworkflow-drafts\u002F` and the result names that file, compiled or not; revise it by\n  editing the file and resubmitting with `path` (§13).\n- `saved`: a workflow saved in this project or globally, by name —\n  `saved: { name: \"pr-review\", args: { pr: \"123\" } }`; arguments are validated against its\n  declaration before anything runs. Check `ListSavedWorkflows` before writing one from\n  scratch: a saved workflow the user kept beats a rebuilt one. Running a saved workflow\n  is the one call that does not need this skill loaded.\n- `path`: a script file on disk, relative to the working directory or absolute — normally\n  the file a previous result named. Pass `args` alongside it when the file declares\n  arguments in its `\u002F* zcode-workflow` block.\n\nEither way the user confirms the run, and the confirmation shows the actual script.\n\n**Fields.**\n\n- `name`: a short label for the run in the user's language (\"PR review\", \"代码评审\").\n  Always pass it for an inline script; it labels the run everywhere and names its draft\n  file. It defaults to the saved workflow's name.\n- `max_concurrency`: an upper bound on how many subagents work at once. Set it only when\n  the user asks to limit parallelism — never as a reaction to provider rate limits or\n  errors, which the runtime already adapts to.\n- `subagent_model`: the model the subagents run on, as `providerId\u002FmodelId` or a bare model\n  id (optionally `$reasoningLevel`). Set it only when the user asks for a specific model;\n  pass the name they used, and if the tool cannot resolve it, pick from the ids it lists or\n  `ListModels`. NEVER set a model under another provider the user did not ask for: a bare\n  name resolves only within the session's provider, and crossing to another one is written\n  as the full `providerId\u002FmodelId`, which you write only when the user named that model.\n  If you think a cheaper or faster model elsewhere would serve the run, ask the user before\n  calling — model, provider, what it saves — and treat their yes as the request. You stay\n  on the session model either way.\n\nThis tool starts a new run. To change a run that exists — errored, completed, stopped or\nstill running — call `AmendWorkflow` (§13, §16.4), never `CreateWorkflow` again.\n\n### 16.2 The facade\n\nEvery script and snippet is checked against these declarations. They are the same constant\nthe compiler is fed, so what you read here is what typechecks. The block uses `declare`\nbecause it is the host's ambient API description — do not imitate it; your script defines\nplain interfaces and never uses `declare`.\n\n\u003C!-- facade-dts:start -->\n```ts\n\u002F** The pending result of one ask. Await it, or pass it to Promise.all with others. *\u002F\ndeclare interface Node\u003CT> extends PromiseLike\u003CT> {}\n\n\u002F** A model declared with model(). *\u002F\ndeclare class ModelRef { private constructor(); private readonly modelRef: never }\n\n\u002F**\n * Declare a model subagents may run on: \"modelId\" or \"providerId\u002FmodelId\", optional \"$level\".\n * String literal only (checked at launch); choose among ModelRefs at run time.\n *\u002F\ndeclare function model(id: string): ModelRef;\n\n\u002F** Persona of a subagent, fixed when agent() creates it. Every subagent has the same working tools. *\u002F\ndeclare interface AgentPersona {\n  \u002F** System prompt describing the actor's role. *\u002F\n  system?: string;\n  \u002F** Model id literal or ModelRef; omitted = the run's subagent model. *\u002F\n  model?: ModelRef | string;\n  \u002F** WebSearch calls per ask (integer literal, at most 1024); omitted = 128. *\u002F\n  budget?: { webSearch?: number };\n}\n\n\u002F**\n * A subagent: one conversation that keeps its context across asks. Asks issued while it is\n * busy wait their turn, first in, first out.\n *\u002F\ndeclare interface Agent {\n  \u002F**\n   * Give the subagent one task. With a type argument, the answer is a value of type T,\n   * validated against a schema built from it: T is an interface you define in this script\n   * with a plain \"interface\" declaration (no \"declare\" modifier). Without one, the answer is\n   * the subagent's final reply text.\n   *\u002F\n  ask\u003CT = string>(instructions: string): Node\u003CT>;\n}\n\n\u002F**\n * Create a subagent. Every call starts a new, empty conversation; to share one, share the\n * returned value. A non-empty name is an identity: unique within the run (a literal duplicate\n * is a compile error, a computed one fails the run) and the key AmendWorkflow matches cached\n * work by. Unnamed subagents are allowed and never reuse cached work.\n *\u002F\ndeclare function agent(name?: string, persona?: string | AgentPersona): Agent;\n\n\u002F**\n * The run's arguments. For a saved workflow they are validated against its declared\n * arguments, with defaults filled in, before the run starts; an inline script or a snippet\n * gets {}. Always defined; the values are unknown, so narrow them (String(args.target), a\n * typeof guard).\n *\u002F\ndeclare const args: Readonly\u003CRecord\u003Cstring, unknown>>;\n\n\u002F**\n * This run's id, and the run it amends. ResumeWorkflowRun keeps both; AmendWorkflow mints a\n * new id. Keep them out of ask text, personas and world arguments: those are cache keys.\n *\u002F\ndeclare const run: { readonly id: string; readonly resumedFrom?: string };\n\n\u002F** Emit a progress message to the user. *\u002F\ndeclare function log(message: string): void;\n\n\u002F**\n * Publish one intermediate result while the run is going; returns nothing. Items are\n * recorded: a resumed run never shows one twice, and they reach the completion notification\n * even when the run fails. The item must be JSON-serializable (plain objects, arrays, strings,\n * numbers, booleans, null); functions, class instances, Date and promises are compile\n * errors. Caps fail the whole run, not the call: 65,536 items per run, 1 MiB per serialized\n * item, 1 GiB per run.\n *\n * artifactId routes the item to a dashboard: a compile-time literal naming a preset\n * (artifact.chart \u002F table \u002F metrics \u002F board) whose declaration has executed by then. The\n * item becomes one point, row, tile value or card there and still lands in the run's\n * Results. A tag naming nothing, or a file\u002Fmarkdown artifact, fails the run.\n *\u002F\ndeclare function report(item: unknown, artifactId?: string): void;\n\n\u002F** A published artifact version: the id it was published under, and which version this call minted. *\u002F\ndeclare interface ArtifactRef { id: string; version: number }\n\u002F** Card metadata every artifact kind accepts. *\u002F\ndeclare interface ArtifactOptions {\n  \u002F** Shown as the card title; defaults to the id. In the user's language. *\u002F\n  title?: string;\n  \u002F** A sentence or two, shown beside the title when this artifact is the run's primary. *\u002F\n  description?: string;\n  \u002F** The run's deliverable: the card and the run pane lead with it. At most one id per run; once set it stays set for later versions. *\u002F\n  primary?: boolean;\n}\ndeclare interface ArtifactFileOptions extends ArtifactOptions {\n  \u002F** Overrides the type sniffed from the extension (\"application\u002Fpdf\", \"text\u002Fhtml\", …). *\u002F\n  contentType?: string;\n}\n\u002F** One value taken from a reported item: a dot path into the item (\"timing.after\"). *\u002F\ndeclare interface ArtifactField { field: string; label?: string; unit?: string }\ndeclare interface ChartSpec extends ArtifactOptions {\n  type?: \"line\" | \"bar\" | \"scatter\";        \u002F\u002F default \"line\"\n  x: ArtifactField;\n  y: ArtifactField | ArtifactField[];        \u002F\u002F several = several series\n  scale?: \"linear\" | \"log\";                  \u002F\u002F y axis, default \"linear\"\n  \u002F** A reference value drawn as a horizontal rule, taken from the first item that has the field. *\u002F\n  baseline?: ArtifactField;\n}\ndeclare interface TableSpec extends ArtifactOptions {\n  columns: ArtifactField[];\n  \u002F** Field that identifies a row; a later item with the same key replaces the row. Absent = append-only. *\u002F\n  key?: string;\n}\ndeclare interface MetricsSpec extends ArtifactOptions {\n  \u002F** Each tile shows the value from the latest item that has the field. *\u002F\n  metrics: ArtifactField[];\n}\ndeclare interface BoardSpec extends ArtifactOptions {\n  \u002F** Field identifying a card; a later item with the same key moves\u002Fupdates the card. *\u002F\n  key: string;\n  \u002F** Field holding the card's column. *\u002F\n  status: string;\n  \u002F** Column order. Items whose status is not listed land in a trailing \"other\" column. *\u002F\n  columns: string[];\n  \u002F** Field for the card title (default: the key) and extra fields shown on the card. *\u002F\n  cardTitle?: string;\n  detail?: ArtifactField[];\n}\n\u002F**\n * Publish what the user keeps: cards beside the run, kept after it ends. Every id is a\n * compile-time string literal (non-empty, at most 64 characters of [A-Za-z0-9_.-]) and is\n * used with one member only.\n * - CONTENT (file, markdown) are effects: async, resolve to an ArtifactRef, and reject\n *   catchably (missing file, not a file, outside the workspace, over the cap, or no artifact\n *   store in this host).\n *   Bytes are copied at publish time; republishing an id mints the next version and keeps\n *   the old ones.\n * - PRESET (chart, table, metrics, board) are declarations: synchronous and void, drawn from\n *   the items tagged report(item, \"\u003Cid>\"). Declare each once, at the top level; an identical\n *   re-declaration is a no-op, a different or malformed spec fails the whole run.\n * Caps: 32 ids per run, 16 versions per id, 20 MiB per file, 256 KB per markdown, 120\n * characters of title and 500 of description.\n *\u002F\ndeclare const artifact: {\n  \u002F** Publish a workspace file, path resolved as in files.read(). The type comes from the extension unless opts.contentType sets it. *\u002F\n  file(id: string, path: string, opts?: ArtifactFileOptions): Promise\u003CArtifactRef>;\n  \u002F** Publish markdown text the script composed. *\u002F\n  markdown(id: string, content: string, opts?: ArtifactOptions): Promise\u003CArtifactRef>;\n  \u002F** Declare a chart fed by report(item, id): each tagged item is one point. *\u002F\n  chart(id: string, spec: ChartSpec): void;\n  \u002F** Declare a table fed by report(item, id): each tagged item is one row. *\u002F\n  table(id: string, spec: TableSpec): void;\n  \u002F** Declare a metric tile row fed by report(item, id): each tile shows the newest value it has. *\u002F\n  metrics(id: string, spec: MetricsSpec): void;\n  \u002F** Declare a board fed by report(item, id): each tagged item is a card, placed by its status field. *\u002F\n  board(id: string, spec: BoardSpec): void;\n};\n\n\u002F**\n * Mark the start of a phase: a named group of the steps that follow, drawn as one node on\n * the graph the user approves. Presentation only: it starts, waits for and returns nothing.\n * Required. The name is a non-empty compile-time literal and the call a standalone\n * statement. A marker covers every step from it to the end of the block it stands in\n * (nested blocks and inlined helpers included); two markers with the same name are one\n * phase. Every phase contains at least one ask or world.run.\n *\u002F\ndeclare function phase(name: string): void;\n\n\u002F**\n * A typed gap: code you write later, once an earlier step's findings are in. When the run\n * reaches an unfilled hole, that branch waits while you write the body (FillWorkflowHole);\n * the rest of the run keeps going. prompt is the message you will receive, so interpolate\n * the values the decision needs. The body runs in the hole's place, sees the bindings\n * declared before it, and returns the hole's value. The filled form passes the body last.\n *\u002F\ndeclare function hole\u003CT>(name: string, prompt?: string): Promise\u003CT>;\ndeclare function hole\u003CT>(name: string, body: () => Promise\u003CT>): Promise\u003CT>;\ndeclare function hole\u003CT>(name: string, prompt: string, body: () => Promise\u003CT>): Promise\u003CT>;\n\n\u002F** One matching line found by files.grep. *\u002F\ndeclare interface GrepMatch {\n  \u002F** Workspace-relative path of the file the match was found in. *\u002F\n  path: string;\n  \u002F** One-based line number of the match. *\u002F\n  line: number;\n  \u002F** The full text of the matching line. *\u002F\n  text: string;\n}\n\n\u002F**\n * Read-only views of the workspace. Each result is recorded, so a resumed run gets the same\n * answer back instead of reading again. There is no write: writing is a subagent's task.\n *\u002F\ndeclare const files: {\n  \u002F** Workspace-relative paths matching a glob, sorted. Over 2000 files the call rejects. *\u002F\n  glob(pattern: string): Promise\u003Cstring[]>;\n  \u002F** Read one workspace file as UTF-8 text. Size-capped. *\u002F\n  read(path: string): Promise\u003Cstring>;\n  \u002F**\n   * Search contents with a ripgrep-compatible regex, optionally narrowed by a glob over\n   * paths (\"*.ts\", \"src\u002F**\"); one entry per matching line. Over 2000 matches or 256KB of\n   * results the call rejects.\n   *\u002F\n  grep(pattern: string, glob?: string): Promise\u003CGrepMatch[]>;\n};\n\n\u002F** The working tree's status, as reported by git.status(). *\u002F\ndeclare interface GitStatus {\n  \u002F** Current branch name; absent when HEAD is detached. *\u002F\n  branch?: string;\n  \u002F** True when nothing is staged, modified, or untracked. *\u002F\n  clean: boolean;\n  \u002F** Workspace-relative paths staged for the next commit. *\u002F\n  staged: string[];\n  \u002F** Workspace-relative paths modified in the working tree but not staged. *\u002F\n  unstaged: string[];\n  \u002F** Workspace-relative paths git does not track (honouring .gitignore). *\u002F\n  untracked: string[];\n}\n\n\u002F** One commit, as reported by git.log(). *\u002F\ndeclare interface GitCommit {\n  \u002F** Full commit hash. *\u002F\n  hash: string;\n  \u002F** First line of the commit message. *\u002F\n  subject: string;\n  \u002F** Author name. *\u002F\n  author: string;\n  \u002F** Author date, ISO 8601. *\u002F\n  date: string;\n}\n\n\u002F**\n * Read-only git views, recorded like files.* so a resumed run gets the same answer back; no\n * call can write. A base names a single ref (no \"..\" ranges). Paths are workspace-relative, and\n * changes outside the workspace are not reported; git.log alone is repository-wide. Caps\n * reject rather than truncate: diff at 512KB, log at 100 commits. Outside a git repository,\n * or without git, every call rejects catchably.\n *\u002F\ndeclare const git: {\n  \u002F**\n   * Workspace-relative paths that changed. With no base: files modified against HEAD, plus\n   * untracked files. With a base ref: tracked files whose current state differs from that\n   * ref, uncommitted edits included, untracked files not.\n   *\u002F\n  changedFiles(base?: string): Promise\u003Cstring[]>;\n  \u002F**\n   * Unified diff against base (default HEAD). Covers the whole workspace unless you\n   * narrow it to one workspace-relative path.\n   *\u002F\n  diff(base?: string, path?: string): Promise\u003Cstring>;\n  \u002F** The current working-tree status, for the workspace. *\u002F\n  status(): Promise\u003CGitStatus>;\n  \u002F** The most recent commits, newest first. Default 20, maximum 100. *\u002F\n  log(count?: number): Promise\u003CGitCommit[]>;\n};\n\n\u002F** The outcome of one world.run command, including nonzero exits. *\u002F\ndeclare interface WorldRunResult {\n  \u002F** The process exit code. Nonzero is a normal, returned outcome — branch on it. *\u002F\n  exitCode: number;\n  \u002F** Captured output (UTF-8), shaped by opts.output. *\u002F\n  stdout: string;\n  stderr: string;\n}\n\n\u002F**\n * Run a command. Each call runs once and its result is recorded: a resumed run reuses the\n * recorded result instead of running the command again. A completed process RESOLVES,\n * nonzero exit included; the promise rejects (catchably) only on spawn failure or timeout\n * (default 300000ms, timeoutMs overrides, no upper cap). cmd is a compile-time string\n * literal, shown to the user at confirmation. Fixed argv, never a shell: no pipes,\n * redirection or expansion. cwd is the workspace. Node builtins are reachable as\n * world.run(\"node\", [\"-e\", code]).\n * opts.output (both streams): \"full\" (default) rejects over 16 MiB; \"discard\" is \"\";\n * { tail: n } keeps the last n bytes, n \u003C= 16777216 (16 MiB). Neither bounds what the process prints.\n *\u002F\ndeclare const world: {\n  run(cmd: string, args?: string[], opts?: { timeoutMs?: number; output?: \"full\" | \"discard\" | { tail: number } }): Promise\u003CWorldRunResult>;\n};\n\n\u002F**\n * A stream of typed items between two stages: one stage send()s, another drains it with\n * for await. Unbounded, first-in-first-out, each item to exactly one receiver.\n *\u002F\ndeclare interface Channel\u003CT> extends AsyncIterable\u003CT> {\n  \u002F** Enqueue one item; synchronous, never waits. Throws ChannelClosed after close(). *\u002F\n  send(item: T): void;\n  \u002F**\n   * End the stream: receivers get the remaining items, then their loops exit. Idempotent.\n   * A channel nobody closes fails the run as ChannelDeadlock, naming it, once nothing in\n   * flight could send to it again.\n   *\u002F\n  close(): void;\n}\n\n\u002F**\n * Create a channel. The name labels the deadlock message; it is not an identity. A receiver\n * on an empty, open channel waits until a send or the close.\n *\u002F\ndeclare function channel\u003CT>(name?: string): Channel\u003CT>;\n\n\u002F**\n * Run an async block as a concurrent stage. It starts immediately, not when awaited, and\n * returns its promise.\n *\u002F\ndeclare function future\u003CT>(body: () => Promise\u003CT>): Promise\u003CT>;\n```\n\u003C!-- facade-dts:end -->\n\n### 16.3 Rules the compiler and the analyzer enforce\n\n- Plain TypeScript. Define result types with a plain `interface Foo { ... }` or\n  `type Foo = ...` and pass them as `ask\u003CT>` type arguments.\n- Compiled under `strict` with `noUncheckedIndexedAccess` off: indexing an array or record\n  (`items[i]`) needs no guard. `.find()`, `.match()`, `Map.get()` and optional properties\n  still yield `T | undefined` \u002F `null` and must be guarded before use.\n- Never use the `declare` modifier: the script is compiled inside a function body, where\n  ambient declarations are illegal. No `export` statements — the workflow's output is its\n  final `return`. No `import` statements.\n- Top-level `await` and a final `return \u003Cvalue>` are allowed; the returned value is exactly\n  what the completion notification carries.\n- No Node or web APIs: `process`, `fetch`, `fs` do not exist and fail typechecking.\n- `world.run` executes a real command. Its first argument must be a compile-time string\n  literal — the script's command set is shown to the user at confirmation — so interpolate\n  runtime values into the args array, never into the command name. A nonzero exit code\n  comes back as a value, not an exception (§5).\n- `hole\u003CT>()` (§15): explicit type argument; a literal name of at most 128 characters,\n  unique among the script's holes and phase markers; the call awaited and written inline;\n  outside every array-method fan-out callback (a `for...of` body is fine); the body reads no\n  binding declared after the hole. All of these are diagnostic 9012.\n- Phases are required (§8): cover the whole script with `phase(\"...\")` markers, one at the\n  head of each stage. The name is a compile-time string literal and the call is a standalone\n  statement; the marker claims the rest of its enclosing block, nested blocks and inlined\n  helper calls included, so a marker inside an `if` covers that branch only. Two markers\n  with the same name are one phase, which is how a retry loop stays two nodes instead of\n  per-round sprawl. Every phase contains at least one subagent `ask` or one `world.run`;\n  plain script logic between two asks is not a stage, so do not open a phase for the setup\n  at the top or the `return` at the bottom.\n- Subagent names: the name you pass to `agent(\"...\")` is the card the user sees, so write\n  it for the user in the session's language (§9). It is also an identity: unique within the\n  run, and the key an amended run matches its cached results by. Keep names stable across\n  revisions, and give duplicates in a loop their own computed names.\n- Artifact ids and the `report` tag are compile-time literals; one id belongs to one\n  artifact kind; at most one artifact carries `primary: true`; a preset artifact is declared\n  at the top level, not inside a loop, callback or branch (§10), and a fill's body is where\n  its hole stands. Publishing rejects catchably when the file is missing or too large.\n- Model-side errors never reach the script. Rate limits, overload, network errors and\n  timeouts are retried by the runtime without limit while it adapts the fan-out; a\n  deterministic one (expired sign-in, model not in the plan, quota cap) stops the run as\n  `stopped` for the user to fix and resume. Write no retry loops or `try`\u002F`catch` for\n  provider errors; reserve them for logic failures — a result that failed validation, a gate\n  that did not pass, a world read over its cap, a missing artifact source, or a\n  `ContextLimit` (the ask outgrew the model's context even after compaction: split it).\n- `channel`, `future`, `Channel.send` and `Channel.close` are facade callables: call them\n  directly (9001 applies to a stored or aliased call); a channel value itself may be stored\n  or passed freely. `send` after `close()` throws\n  `ChannelClosed`, catchable. Stalls fail the run, never time out: `ChannelDeadlock` when\n  receivers wait on channels nothing can send to any more (naming each), `ScriptStalled` when\n  some other promise can never settle.\n- The final `return` is the model-facing result; artifacts are the user-facing deliverable.\n  Never put the same content in both.\n- On diagnostics, edit the file the result names and call the tool again with `path`; never\n  paste the script a second time.\n\n### 16.4 `AmendWorkflow`\n\nRevises an existing run: it starts a new run that supersedes the old one and imports its\nfinished work as a cache, so only what you changed is paid for again. §13 has the cache\nrules and the repair-while-running move. It works on any run of this project — completed,\nerrored, stopped or still running; a running predecessor is stopped and superseded in the\nsame call, so never `TaskStop` it first and never rewrite it from scratch with\n`CreateWorkflow`. To continue a stopped run unchanged, use `ResumeWorkflowRun` instead.\n\n**Fields — every field you omit keeps the predecessor's value.**\n\n- `run_id` (required): from a `CreateWorkflow` or `AmendWorkflow` result, a notification,\n  `GetWorkflowRun` or `ListWorkflowRuns`.\n- `path` or `script`, never both. `path` is the usual form: the errored notification and\n  `GetWorkflowRun` name the run's script file — edit it in place and pass the same path\n  back, so a revision costs one `Edit` instead of a second copy of the whole script. A file\n  whose bytes you did not change is refused (`script_unchanged`) unless the call also\n  changes `max_concurrency` or `subagent_model`; nothing is stopped and nothing is created.\n  `script` carries a whole revised script inline, written against the same facade and rules;\n  it is saved to a draft file the result names, so the next revision can go back to `path`.\n  Omit both to keep the predecessor's script byte for byte and change only the settings\n  below; its finished work still replays from the cache.\n- `name`: a new display label; defaults to the predecessor's.\n- `max_concurrency`: omit to keep the predecessor's limit, pass `null` to remove it, pass a\n  number to change it (only when the user asks). A call carrying nothing but `run_id` and\n  `max_concurrency`, against a run that is still going, retunes that run in place instead of\n  starting a new one: same run, nothing stopped, nothing re-run.\n- `subagent_model`: omit to keep the predecessor's choice, pass `null` to put the subagents\n  back on the session model, pass a model id to change it (only when the user asks; never\n  a model under another provider the user did not name — ask them first if you think one\n  would help). `ListModels` lists the ids.\n\nChanging only a setting on a running run still stops it; what it had in flight runs again in\nthe new run, except that a named subagent whose unfinished ask you did not change picks that\nask up where it left off instead of starting it over.\n\n**How the cache works.** Named subagents are matched by name across the two scripts; each\none's asks are matched in order by byte-identical instructions. A match settles from the\nrecorded result at zero tokens; a changed or added ask runs live. The cache stays open until a\nlive subagent makes its first write to the workspace (or a live `world.run` executes): from\nthat moment, cached world reads and cached asks whose subagent had read or run something\nwould describe a workspace that no longer exists, so they run live too. Asks that only\nanswered keep settling from the cache. Editing an ask's text is how you force it to run\nagain; keep names stable and keep tunable constants out of ask text (§13).\n\nOn diagnostics nothing was stopped and nothing was started; fix the file the result names\nand call again with `path`.\n\n**Confirmation.** A run this session started (through `CreateWorkflow`, a previous\n`AmendWorkflow` or the workflows hub) is amended without a confirmation window, even while\nit is running. A run the user stopped, or a run another session started, asks the user\nfirst, and so does an amendment that would put subagents on a provider neither the session\nnor the run used (a model you name under another provider, in `subagent_model` or in the\nscript): that choice is the user's, and the window is where they make it. Another session's run that is still running cannot be amended or filled from here: the call is refused, and only that session can act on it. The result names the run that was superseded (if one was stopped) and the new run's\nid. The superseded run sends no notification of its own; the new run notifies when it\nsettles. Do not wait for it or poll it with `TaskOutput`.\n\n### 16.5 `SaveWorkflow`\n\nSaves a script with its metadata so it can be run again by name — through `CreateWorkflow`'s\n`saved` source, discovered with `ListSavedWorkflows`. Project definitions go in\n`.zcode\u002Fworkflows\u002F\u003Cname>.dwf.ts`, committed with the repository; global definitions go in\n`~\u002F.zcode\u002Fworkflows\u002F\u003Cname>.dwf.ts` and are available from every project on this machine.\n\n**When to call it.**\n\n- Never unsolicited. Saving writes a file into the user's repository; that is their\n  decision, not yours.\n- When a workflow you just built looks reusable — it would plausibly run again with\n  different inputs — suggest saving it in prose, one sentence naming what you would save and\n  why, then stop and wait. Call `SaveWorkflow` only after the user agrees, or when the user\n  asks directly (\"save this workflow\", \"保存这个工作流\"). A one-off script tailored to a\n  single question is not worth suggesting.\n\n**Fields.**\n\n- `name`: a file-safe identifier (letters, digits, dot, dash and underscore). Saving over an\n  existing name replaces that workflow, and the confirmation says whether the file is new or\n  an overwrite: reuse a name to update, pick a new one for a variant.\n- `description` (required) and `whenToUse`: written for a reader who has not seen this\n  conversation. `description` shows up wherever the workflow is listed.\n- `scope` (required, no default): `project` when the script references this repository's\n  files, commands, conventions or layout; `global` when it depends on nothing in the\n  project.\n- `script` or `script_path`, never both. `script_path` saves a draft a `CreateWorkflow` or\n  `AmendWorkflow` result named without re-emitting it; a `\u002F* zcode-workflow` block in that\n  file is dropped, because the metadata comes from this call's fields. `script` is the body\n  only — no metadata block.\n- `args`: name exactly the values that would change between runs — a PR number, a\n  directory, a depth. Each declaration gives a `type` (`string`, `number`,\n  `boolean`, or `json` for anything else), and optionally a `description`, `required: true`\n  and a `default`; every future call is validated against them.\n\nThe saved file is valid TypeScript: a `\u002F* zcode-workflow` block of YAML metadata, then the\nscript verbatim. The script is typechecked by the same compiler as `CreateWorkflow`, before\nthe user is asked; diagnostics mean nothing was written. The rules in §16.3 apply, phases\nincluded — future callers did not see this conversation, so the phase names are all they\nget.\n\n### 16.6 `EvalWorkflowSnippet`\n\nCompiles and runs a small snippet synchronously against the same compiler, sandbox and\nworld-read execution path a real run uses, and returns the result in the tool call. Nothing\npersists: no journal rows, no background task, no run. It is the test bench of §6, for the\nfixed logic of a script or of a hole's body; it is not for orchestration.\n\n- `code` or `path`, never both: the snippet inline, or a file holding it, read whole with no\n  metadata handling.\n- `timeoutMs`: the wall clock for the whole snippet in milliseconds; default 60000, at most\n  600000.\n- The snippet facade is the `args`, `run`, `log`, `files`\u002F`git`, `world.run`, `channel` and\n  `future` parts of the block in §16.2 (a snippet's `run.id` is a throwaway `dwfeval-…` id); `agent()`, `report()`, `artifact.*`, `hole()` and the `phase`\n  marker are the only absentees — they do not exist here and\n  fail typechecking. The language rules are a script's: plain interfaces, top-level `await`, a\n  final `return \u003Cvalue>`. The returned value is serialized into the result, so return a\n  summary, not a dump; over 256KB fails the call. `log(...)` lines come back in order. A\n  snippet that contains `world.run` asks the user for confirmation before running. On\n  diagnostics nothing ran: fix the snippet and call again.\n\n### 16.7 `FillWorkflowHole`\n\nWrites the body of a hole a run is waiting at (§15). It starts nothing: the run keeps its id,\njournal and subagents, and the effective script — the run's script with the body spliced in —\nis what a resume replays, an amend revises and `SaveWorkflow` keeps.\n\n- `run_id` and `hole_id` (required): from the notification or `GetWorkflowRun`; the hole id\n  is the site id (`hole#21b40fca`), not the name.\n- `script` or `path`, never both: the body's statements only. An inline `script` is written to\n  a fill file under `.zcode\u002Fworkflow-drafts\u002F` before it is compiled and the result names it;\n  `path` is usually that file after an `Edit`, and bytes equal to the last rejected attempt\n  are refused as `fill_unchanged`.\n\nThe body is compiled where the hole stands, against the whole script; a diagnostic is anchored\nto the file it falls in — the fill file inside the body, the run's draft outside it — and on\ndiagnostics nothing is spliced. A body may name only the models the run was launched with; any\nother model is diagnostic 9011 — to add one, amend the run.\n`hole_not_waiting` means the run is not in flight or not\nwaiting at that hole (filled, not yet reached, unknown id); resume a stopped run first and the\nhole asks again. A body may end in a new tail hole instead of returning (§15). On success the\nresponse names the phases added and the run's draft, rewritten in place with the effective\nscript. Confirmation follows the amend rule (§16.4): this session's run fills without a\nwindow; otherwise the window shows the new stations and the `world.run` commands the body\nadds.\n",{"name":5,"description":7,"when_to_use":24},"Only for CreateWorkflow scripts. A single delegation or a few independent lookups belong to the Agent tool instead.","main","fec975905a2abd4c07e35c40d51fa097a2258ec9","apps\u002Fzcode-cli\u002Fpackages\u002Fbundled-skills\u002Fskills\u002Fdynamic-workflows",2710,"https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode","https:\u002F\u002Fzcode.z.ai\u002F","https:\u002F\u002Fgithub.com\u002Fzai-org","https:\u002F\u002Fwww.zhipuai.cn\u002Fen","ChatGLM, GLM-4.5, CogVLM, CodeGeeX, CogView, CogVideoX | CogDL, AMiner | Zhipu.ai (Z.ai)","2026-11-13 16:21:40",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add zai-org\u002FZCode --skill dynamic-workflows",{"tool":41,"command":42},"bunx","bunx skills add zai-org\u002FZCode --skill dynamic-workflows",{"tool":44,"command":45},"pnpm","pnpm dlx skills add zai-org\u002FZCode --skill dynamic-workflows","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fapps\u002Fzcode-cli\u002Fpackages\u002Fbundled-skills\u002Fskills\u002Fdynamic-workflows\u002FSKILL.md",true,[49,55],{"path":50,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":53,"sourceHtmlUrl":54},"examples.md","REFERENCE","参考文档",47899,"https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fapps\u002Fzcode-cli\u002Fpackages\u002Fbundled-skills\u002Fskills\u002Fdynamic-workflows\u002Fexamples.md",{"path":56,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":57,"sourceHtmlUrl":58},"patterns.md",34448,"https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fapps\u002Fzcode-cli\u002Fpackages\u002Fbundled-skills\u002Fskills\u002Fdynamic-workflows\u002Fpatterns.md",[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7D57RTFKZH4SFFWF6NXSQ62","plugin-mcp-ping","E2E workspace Plugin skill marker","https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fpackages\u002Fdesktop\u002Ftest\u002Fe2e\u002Ffixtures\u002Fplugin-mcp-skill\u002Fe2e-plugin-mcp-ping\u002Fskills\u002Fplugin-mcp-ping\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M7D57NRW93T0ETX2QPQY3JCP","e2e-ext-compat-plain","PLM-EXT-STORE fixture skill for e2e-ext-compat-plain.","https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fpackages\u002Fdesktop\u002Ftest\u002Fe2e\u002Ffixtures\u002Ffs\u002Fplugins\u002Fplugin-store-extension-compat\u002Fstore-market\u002Fplugins\u002Fe2e-ext-compat-plain\u002Fskills\u002Fe2e-ext-compat-plain\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7D57JYKJK5A4VW7Y5MYEA7R","e2e-ext-compat-ok","PLM-EXT-STORE fixture skill for e2e-ext-compat-ok.","https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fpackages\u002Fdesktop\u002Ftest\u002Fe2e\u002Ffixtures\u002Ffs\u002Fplugins\u002Fplugin-store-extension-compat\u002Fstore-market\u002Fplugins\u002Fe2e-ext-compat-ok\u002Fskills\u002Fe2e-ext-compat-ok\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7D57FZQKN28QJJ0HVG93ACN","e2e-ext-compat-installed","PLM-EXT-STORE fixture skill for e2e-ext-compat-installed.","https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fpackages\u002Fdesktop\u002Ftest\u002Fe2e\u002Ffixtures\u002Ffs\u002Fplugins\u002Fplugin-store-extension-compat\u002Fstore-market\u002Fplugins\u002Fe2e-ext-compat-installed\u002Fskills\u002Fe2e-ext-compat-installed\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7D57C9W30WJ3NJDAYX2MN0J","e2e-ext-compat-future","PLM-EXT-STORE fixture skill for e2e-ext-compat-future.","https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fpackages\u002Fdesktop\u002Ftest\u002Fe2e\u002Ffixtures\u002Ffs\u002Fplugins\u002Fplugin-store-extension-compat\u002Fstore-market\u002Fplugins\u002Fe2e-ext-compat-future\u002Fskills\u002Fe2e-ext-compat-future\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7D579KKRR6D2GPVW4J4QWVT","e2e-store-skill-b","E2E store fixture skill b","https:\u002F\u002Fgithub.com\u002Fzai-org\u002FZCode\u002Fblob\u002Fmain\u002Fpackages\u002Fdesktop\u002Ftest\u002Fe2e\u002Ffixtures\u002Ffs\u002Fplugins\u002Fplugin-extension-reads\u002Fstore-market\u002Fplugins\u002Fe2e-ext-store-b\u002Fskills\u002Fe2e-store-skill-b\u002FSKILL.md",[],[]]