zcode-app-cli 3.14.1-27 → 3.14.3-27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,10 +6,13 @@ when_to_use: "Only for CreateWorkflow scripts. A single delegation or a few inde
6
6
 
7
7
  # Writing dynamic workflows
8
8
 
9
- The `CreateWorkflow` tool's own description already carries the complete API surface and
10
- the hard authoring rules. **Read them there, not here** — this skill is the judgment layer:
11
- how many subagents a request deserves, which of them should share a context, what each one
12
- should hand back, and how to keep the run's work from dying with the run.
9
+ This skill is the whole authoring contract for `CreateWorkflow`. The tool descriptions are
10
+ short on purpose; the facade the compiler checks against, the rules a script must satisfy and
11
+ the fields each tool takes are in §16, and `CreateWorkflow`, `AmendWorkflow`, `SaveWorkflow`
12
+ and `EvalWorkflowSnippet` refuse to run until this skill has been loaded in the session. The
13
+ rest is the judgment layer: how many subagents a request deserves, which of them should share
14
+ a context, what each one should hand back, and how to keep the run's work from dying with the
15
+ run.
13
16
 
14
17
  Two names collide in this codebase. `CreateWorkflow` is the dynamic-workflow tool and the
15
18
  only one this skill is about. The legacy `Workflow` tool and `/expert` are a different,
@@ -689,142 +692,11 @@ chart's points, so a card for it would say nothing new.
689
692
 
690
693
  ## 11. A complete example
691
694
 
692
- Review every changed file, triage its findings on one scale, confirm each kept finding
693
- independently, and hand back a report. Everything a file needs happens as soon as its own
694
- review lands; the only join is the cross-file deduplication that needs every finding.
695
-
696
- <!-- compile -->
697
- ```ts
698
- interface Finding {
699
- /** Workspace-relative path, with a line when it applies: "src/a.ts:42". */
700
- where: string;
701
- /** One sentence: what is wrong. */
702
- what: string;
703
- /** What showed it: the lines read, or the command and the output that proved it. */
704
- evidence: string;
705
- /** How much it matters. Reserve "high" for data loss, a crash, or a wrong result. */
706
- severity: "low" | "medium" | "high";
707
- }
708
- interface Review {
709
- findings: Finding[];
710
- }
711
- interface Keep {
712
- /** True when this finding is worth putting in front of a human. */
713
- keep: boolean;
714
- }
715
- interface Confirmation {
716
- /** True only when you reproduced the problem yourself from the evidence. */
717
- reproduced: boolean;
718
- /** What you did to check, one sentence. */
719
- note: string;
720
- }
721
- interface ReportedFinding extends Finding {
722
- /** "verified" when the confirmer reproduced it; "unconfirmed" when it could not. */
723
- status: "verified" | "unconfirmed";
724
- }
725
- interface Digest {
726
- /** The confirmed findings with duplicates across files merged, one line each. */
727
- lines: string[];
728
- /** Two or three sentences a reader can act on. */
729
- summary: string;
730
- }
731
- interface WorkflowReport {
732
- /** Two or three sentences answering what the user asked for. */
733
- conclusion: string;
734
- findings: ReportedFinding[];
735
- /** What the run checked and how. */
736
- verified: string[];
737
- /** What the run did not look at or could not check, and why. */
738
- notCovered: string[];
739
- }
740
-
741
- phase("Review each changed file and confirm its findings as they land");
742
- let paths: string[];
743
- try {
744
- paths = await git.changedFiles("origin/main");
745
- } catch {
746
- paths = await files.glob("src/**/*.ts");
747
- }
748
- log(`reviewing ${paths.length} changed files`);
749
-
750
- // One triage subagent for all findings: severity only means anything if it is judged on a
751
- // consistent scale. It is a queue, not a barrier — asks on it run FIFO, so a finding reaches
752
- // it the moment its file's review lands, whichever file that is.
753
- const triage = agent("triage", "You decide which review findings deserve a human's attention. Be strict.");
754
-
755
- // One reviewer per file, fresh each: the files are unrelated, so nothing is gained by
756
- // sharing a context and everything is gained by running them at once. Triage and
757
- // confirmation live inside the same callback, so no file waits for the slowest review
758
- // before its findings move on; the outer `Promise.all` is the only join the report waits on.
759
- const perFile = await Promise.all(
760
- paths.map(async (p) => {
761
- const review = await agent(`reviewer-${p}`).ask<Review>(`Review ${p} for correctness bugs.`);
762
-
763
- const kept: Finding[] = [];
764
- for (const finding of review.findings) {
765
- const verdict = await triage.ask<Keep>(`Worth reporting? ${JSON.stringify(finding)}`);
766
- if (verdict.keep) kept.push(finding);
767
- }
768
-
769
- // A separate confirmer per kept finding, blind to the reviewer that raised it: it reads
770
- // the code, runs a check if one decides it, and is told not to fix anything. The name
771
- // carries the path and the index, because every subagent name in a run must be unique.
772
- return Promise.all(
773
- kept.map(async (finding, index) => {
774
- const check = await agent(`confirmer-${p}-${index}`).ask<Confirmation>(
775
- `Reproduce this finding from its evidence alone: read the code, run a check if one exists. Do not edit any file.\n${JSON.stringify(finding)}`,
776
- );
777
- const reported: ReportedFinding = {
778
- ...finding,
779
- status: check.reproduced ? "verified" : "unconfirmed",
780
- };
781
- report(reported); // published now, with its status, so it survives a later failure
782
- return reported;
783
- }),
784
- );
785
- }),
786
- );
787
- const confirmed = perFile.flat();
788
- log(`${confirmed.length} findings confirmed or labelled`);
789
-
790
- // The one stage that genuinely needs every finding: two reviewers can flag the same root
791
- // cause from two files, and only a reader of the whole list can merge them.
792
- phase("Merge duplicate findings across files and write them up");
793
- const digest = await agent("editor", "You merge review findings that share a root cause and write them up for the engineer who fixes them.")
794
- .ask<Digest>(`Merge duplicates and write these up:\n${JSON.stringify(confirmed)}`);
795
-
796
- const verifiedCount = confirmed.filter((f) => f.status === "verified").length;
797
- await artifact.markdown(
798
- "report",
799
- [
800
- `# Review of ${paths.length} changed files: ${confirmed.length} findings, ${verifiedCount} reproduced`,
801
- "",
802
- digest.summary,
803
- "",
804
- ...digest.lines.map((line) => `- ${line}`),
805
- "",
806
- "## Every finding",
807
- ...confirmed.map((f) => `- **${f.where}** (${f.severity}, ${f.status}): ${f.what}\n ${f.evidence}`),
808
- ].join("\n"),
809
- { title: "Review report" },
810
- );
811
- const result: WorkflowReport = {
812
- conclusion: digest.summary,
813
- findings: confirmed,
814
- verified: paths.map((p) => `reviewed ${p}; every kept finding re-checked by a separate subagent`),
815
- notCovered: ["files outside the change set", "runtime behaviour no existing test exercises"],
816
- };
817
- return result;
818
- ```
819
-
820
- Three shapes in one script, each chosen for a reason. The reviewers are fresh and parallel
821
- because the files are unrelated. The triage subagent is shared because severity must mean the
822
- same thing twice — and sharing costs nothing here, because its FIFO queue is fed as reviews
823
- land rather than after all of them. The confirmers are fresh, per finding and blind to the
824
- reviewer, and they start the moment their file's triage is done: with twelve files and one
825
- slow reviewer, eleven files' findings are confirmed and reported while it is still reading.
826
- Nothing gets a second reader on top: each finding was confirmed, and the editor's job is
827
- merging and writing up, not re-checking.
695
+ The complete review workflow that used to sit here — a reviewer per changed file, triage
696
+ through one shared subagent that is fed as reviews land, a confirmer per kept finding chained
697
+ inside the same callback, one join for the cross-file deduplication — is
698
+ `${ZCODE_SKILL_DIR}/examples.md` §5. Read it when you want to see a whole script's arc; §7
699
+ and §10 already carry its rules.
828
700
 
829
701
  ## 12. Anti-patterns
830
702
 
@@ -915,13 +787,14 @@ completed, or still running — can be superseded: edit the run's script file an
915
787
  `AmendWorkflow` with `run_id: "<runId>"` and that `path`. That starts a new run which
916
788
  imports the old one's finished work, matched per named subagent along its sequence of asks,
917
789
  so every step you did not touch settles from cache at no token cost and only the changed
918
- part actually runs — with one
919
- deliberate limit: the moment any subagent runs live, the workspace may no longer be the one
920
- the old results were computed against, so from that point every `world.run`, every world
921
- read and every ask to any subagent runs live even if its text is unchanged. A gate command
922
- therefore always tests the code the amended run actually
923
- produced; the price is that steps after the first re-run doer are re-paid. The old
924
- run is left exactly as it was. This is the move after a `ScriptError`, after a bad prompt
790
+ part actually runs — with one deliberate limit: the moment a live subagent writes to the
791
+ workspace (or a live `world.run` executes), the workspace may no longer be the one the old
792
+ results were computed against, so from that point every cached `world.run`, every cached
793
+ world read and every cached ask whose subagent had read or run something runs live even if
794
+ its text is unchanged; asks whose subagent only answered keep settling from the cache. A gate
795
+ command therefore always tests the code the amended run actually produced; the price is
796
+ that doing steps after the first live write are re-paid. The old run is left exactly as it
797
+ was. This is the move after a `ScriptError`, after a bad prompt
925
798
  produced a useless result, and when a completed analysis needs one more stage — rewriting
926
799
  the workflow from scratch throws away work that was already paid for. Two things make the
927
800
  cache hit: names that stay the same across the revision, and asks whose instructions stay
@@ -1040,3 +913,608 @@ chatter, not an allowance to spend.
1040
913
  when you know the shape you want and want it written correctly.
1041
914
  - `${ZCODE_SKILL_DIR}/examples.md` — complete worked scripts, including a two-subagent
1042
915
  adversarial prove/disprove loop. Read one when you want to see a whole script's arc.
916
+
917
+ ## 16. Tool reference
918
+
919
+ The four authoring tools — `CreateWorkflow`, `AmendWorkflow`, `SaveWorkflow` and
920
+ `EvalWorkflowSnippet` — carry one-paragraph descriptions on purpose, and each of them refuses
921
+ to run until this skill has been loaded in the session. This section is the part of their
922
+ contract that the descriptions do not carry: the facade the compiler checks against, the
923
+ rules a script must satisfy, and the fields each tool takes. Read it before writing or
924
+ revising a script; the compiler holds you to it.
925
+
926
+ ### 16.1 `CreateWorkflow`
927
+
928
+ Typechecks the script; on a clean compile asks the user to confirm and starts the run in the
929
+ background; you are notified with the script's final `return` value when the run settles.
930
+ Compilation errors come back as diagnostics, counted in the script's file (§13).
931
+
932
+ **Three sources; pass exactly one.**
933
+
934
+ - `script`: a one-off workflow written inline. It is saved to a file under
935
+ `.zcode/workflow-drafts/` and the result names that file, whether the script compiled or
936
+ not; revise it by editing the file and resubmitting with `path`, never by pasting the
937
+ script again.
938
+ - `saved`: a workflow saved in this project or globally, by name —
939
+ `saved: { name: "pr-review", args: { pr: "123" } }`. Its arguments are validated against
940
+ its declaration (unknown keys, missing required values and wrong types are rejected)
941
+ before anything runs. Before writing a workflow from scratch, check `ListSavedWorkflows`:
942
+ a saved workflow the user reviewed and kept beats a rebuilt one. Running a saved workflow
943
+ is the one call that does not need this skill loaded.
944
+ - `path`: a script file on disk, relative to the working directory or absolute — normally
945
+ the file a previous result named. Pass `args` alongside it when the file declares
946
+ arguments in its `/* zcode-workflow` block.
947
+
948
+ Either way the user confirms the run, and the confirmation shows the actual script.
949
+
950
+ **Fields.**
951
+
952
+ - `name`: a short label for the run in the user's language ("PR review", "代码评审").
953
+ Always pass it for an inline script; it labels the run everywhere and names its draft
954
+ file. It defaults to the saved workflow's name.
955
+ - `max_concurrency`: an upper bound on how many subagents work at once. Set it only when
956
+ the user asks to limit parallelism — never on your own initiative and never as a
957
+ reaction to provider rate limits or errors, which the runtime already adapts to. A value
958
+ above the machine's ceiling is lowered to it. Otherwise how many subagents run at once is
959
+ the runtime's decision, not the script's.
960
+ - `subagent_model`: the model the subagents run on, as `providerId/modelId` or a bare
961
+ model id (optionally `$reasoningLevel`). Set it only when the user asks for a specific
962
+ model; pass the name the user used, and if the tool cannot resolve it, pick from the ids
963
+ it lists or call `ListModels`. You stay on the session model either way.
964
+
965
+ This tool starts a new run. To change a run that exists — errored, completed, stopped or
966
+ still running — call `AmendWorkflow` (§13, §16.4), never `CreateWorkflow` again.
967
+
968
+ ### 16.2 The facade
969
+
970
+ Every script and snippet is checked against these declarations. They are the same constant
971
+ the compiler is fed, so what you read here is what typechecks. The block uses `declare`
972
+ because it is the host's ambient API description — do not imitate it; your script defines
973
+ plain interfaces and never uses `declare`.
974
+
975
+ <!-- facade-dts:start -->
976
+ ```ts
977
+ /**
978
+ * A node: one task assigned to an actor, producing a typed result.
979
+ * Thenable — await it, or combine with Promise.all for joins.
980
+ */
981
+ declare interface Node<T> extends PromiseLike<T> {}
982
+
983
+ /**
984
+ * Persona of an actor: identity, fixed at creation (frozen for the actor's lifetime). Every
985
+ * actor has the regular working tools (reading, searching, editing, running commands); what
986
+ * it may do with them is said in the ask.
987
+ */
988
+ declare interface AgentPersona {
989
+ /** System prompt describing the actor's role. */
990
+ system?: string;
991
+ }
992
+
993
+ /**
994
+ * An actor: a persistent conversational context that executes tasks serially.
995
+ * Context accumulates across asks; concurrent asks on one actor queue FIFO.
996
+ */
997
+ declare interface Agent {
998
+ /**
999
+ * Assign one task. T is the task's output value: an interface you define in
1000
+ * this script with a plain "interface" declaration (no "declare" modifier; the
1001
+ * harness synthesizes its runtime schema from the type), or the final response
1002
+ * text when the type argument is omitted.
1003
+ */
1004
+ ask<T = string>(instructions: string): Node<T>;
1005
+ }
1006
+
1007
+ /**
1008
+ * Create a fresh actor. Every call creates a new context; sharing context means
1009
+ * sharing this reference.
1010
+ *
1011
+ * The name is optional, but a non-empty one is an identity, not a label. It must be
1012
+ * unique within the run: two actors under the same name fail the whole run. It is
1013
+ * also the key a revised re-run matches its cache on (AmendWorkflow imports the
1014
+ * finished work of each named actor), so stable, meaningful
1015
+ * names carry work across script revisions. Anonymous actors are legal and never
1016
+ * reuse imported work.
1017
+ *
1018
+ * In a fan-out or a loop each iteration is a separate actor, so a single static name
1019
+ * there is the duplicate case: give each one its own name (agent("reviewer-" + file))
1020
+ * or leave them all anonymous. A literal name in a loop is reported when the script
1021
+ * is compiled; a computed one fails at run time.
1022
+ */
1023
+ declare function agent(name?: string, persona?: string | AgentPersona): Agent;
1024
+
1025
+ /**
1026
+ * The run's arguments: the values supplied when this workflow was started.
1027
+ *
1028
+ * A workflow saved into the project declares its arguments (name, type, whether they
1029
+ * are required, defaults); the host validates the caller's values against that
1030
+ * declaration and fills in defaults before the run starts, so what lands here is
1031
+ * always a complete, checked bag. For an inline script — and inside a snippet — it is
1032
+ * simply empty.
1033
+ *
1034
+ * Always defined, so reading args.target is a plain property read rather than a crash.
1035
+ * The values are typed unknown on purpose: the compiler surface must not change from
1036
+ * one workflow to the next, so narrow them in the script -- String(args.target), or a
1037
+ * typeof guard -- exactly as you would any other external input.
1038
+ */
1039
+ declare const args: Readonly<Record<string, unknown>>;
1040
+
1041
+ /** Emit a progress message to the user. */
1042
+ declare function log(message: string): void;
1043
+
1044
+ /**
1045
+ * Publish one intermediate result while the run is still going. Like log() it
1046
+ * returns nothing and there is nothing to await — a finding has no reply.
1047
+ *
1048
+ * Unlike log() it is journaled: a resumed run never shows the same item twice, and
1049
+ * the items are delivered with the completion notification even when the run ends in
1050
+ * failure. That is the point of it — a run that dies on its twelfth of forty tasks
1051
+ * still did eleven tasks' worth of work, and reported items are how that work
1052
+ * survives.
1053
+ *
1054
+ * Two caps, and both fail the whole run rather than the call (there is no rejection
1055
+ * channel in a void return): at most 256 items per run, and at most 32KB per
1056
+ * serialized item. They are generous on purpose — report findings, not chatter.
1057
+ *
1058
+ * The item must be JSON-serializable: plain objects, arrays, strings, numbers,
1059
+ * booleans, null. Functions, class instances, Date and promises are rejected when
1060
+ * the script is compiled.
1061
+ *
1062
+ * The optional second argument routes the item to a dashboard artifact: pass the id
1063
+ * of a preset declared with artifact.chart / table / metrics / board, and this item
1064
+ * becomes one more point, row, tile value or card on it — the dashboard is nothing
1065
+ * but the items tagged with its id. The tag must be a compile-time string literal
1066
+ * naming a preset the script declares (anywhere in the text, but the declaration must
1067
+ * have executed by the time this call runs); a tag that names nothing, or names a
1068
+ * file/markdown artifact, fails the run. An untagged report is unchanged: it goes to
1069
+ * the run's Results, and a tagged one goes to both.
1070
+ */
1071
+ declare function report(item: unknown, artifactId?: string): void;
1072
+
1073
+ /** A published artifact version: the id it was published under, and which version this call minted. */
1074
+ declare interface ArtifactRef { id: string; version: number }
1075
+ /** Card metadata every artifact kind accepts. */
1076
+ declare interface ArtifactOptions {
1077
+ /** Shown as the card title; defaults to the id. In the user's language. */
1078
+ title?: string;
1079
+ /** A sentence or two, shown beside the title when this artifact leads the card. */
1080
+ description?: string;
1081
+ /** 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. */
1082
+ primary?: boolean;
1083
+ }
1084
+ declare interface ArtifactFileOptions extends ArtifactOptions {
1085
+ /** Overrides the type sniffed from the extension ("application/pdf", "text/html", …). */
1086
+ contentType?: string;
1087
+ }
1088
+ /** One value taken from a reported item: a dot path into the item ("timing.after"). */
1089
+ declare interface ArtifactField { field: string; label?: string; unit?: string }
1090
+ declare interface ChartSpec extends ArtifactOptions {
1091
+ type?: "line" | "bar" | "scatter"; // default "line"
1092
+ x: ArtifactField;
1093
+ y: ArtifactField | ArtifactField[]; // several = several series
1094
+ scale?: "linear" | "log"; // y axis, default "linear"
1095
+ /** A reference value drawn as a horizontal rule, taken from the first item that has the field. */
1096
+ baseline?: ArtifactField;
1097
+ }
1098
+ declare interface TableSpec extends ArtifactOptions {
1099
+ columns: ArtifactField[];
1100
+ /** Field that identifies a row; a later item with the same key replaces the row. Absent = append-only. */
1101
+ key?: string;
1102
+ }
1103
+ declare interface MetricsSpec extends ArtifactOptions {
1104
+ /** Each tile shows the value from the latest item that has the field. */
1105
+ metrics: ArtifactField[];
1106
+ }
1107
+ declare interface BoardSpec extends ArtifactOptions {
1108
+ /** Field identifying a card; a later item with the same key moves/updates the card. */
1109
+ key: string;
1110
+ /** Field holding the card's column. */
1111
+ status: string;
1112
+ /** Column order. Items whose status is not listed land in a trailing "other" column. */
1113
+ columns: string[];
1114
+ /** Field for the card title (default: the key) and extra fields shown on the card. */
1115
+ cardTitle?: string;
1116
+ detail?: ArtifactField[];
1117
+ }
1118
+ /**
1119
+ * Publish what the user should see: the run's own deliverable surface, kept after it ends.
1120
+ * Two habits. (1) EVERY RUN PUBLISHES ITS DELIVERABLE, whatever the user asked for: a webpage
1121
+ * or PDF a subagent wrote goes out via file(); an answer (findings, a review) goes out as the
1122
+ * long form of the facts the return summarises, usually via markdown(). Once, at the end;
1123
+ * skip it only when the whole answer is one line. When the run publishes more than one
1124
+ * artifact, mark the deliverable { primary: true }. (2) A DASHBOARD IS FOR THE PERSON WATCHING
1125
+ * THE RUN: declare one when there is state worth watching mid-run (the key number per round,
1126
+ * which items are done) and none when the run is over before anyone looks. Two tests keep it
1127
+ * to what matters: would the user open it on its own? does it repeat another artifact? A CSV
1128
+ * and a table of its rows: one of them is noise.
1129
+ *
1130
+ * Every id is a compile-time string literal (non-empty, at most 64 characters of
1131
+ * [A-Za-z0-9_.-]); the set a run can publish is fixed at submit time, so the compiler
1132
+ * rejects a computed one. Within one run an id belongs to exactly one member.
1133
+ * The two families are deliberately asymmetric, and the asymmetry is the whole design:
1134
+ * - CONTENT (file, markdown) are EFFECTS: async, resolve to an ArtifactRef, and REJECT
1135
+ * catchably — missing file, not a file, path outside the workspace, over the size cap, no
1136
+ * store. try { await artifact.file("book", "out/book.pdf") } catch { …ask a subagent to
1137
+ * write it… } is the intended idiom. Bytes are copied at publish time, so later workspace
1138
+ * edits never rewrite a version; republishing an id mints the NEXT version and keeps the
1139
+ * old ones (at most 16 per id).
1140
+ * - PRESET (chart, table, metrics, board) are DECLARATIONS: synchronous, return nothing,
1141
+ * never touch a file; they say how items tagged with their id are drawn. Declare each ONCE,
1142
+ * at the top, then feed it with report(item, "<id>"). The same id with an identical spec is
1143
+ * a no-op; a DIFFERENT or malformed spec fails the whole run — a void return has no
1144
+ * rejection channel, exactly as with report().
1145
+ * Caps: 32 ids per run, 16 versions per id, 20 MiB per file, 256 KB per markdown, 120
1146
+ * characters of title and 500 of description.
1147
+ */
1148
+ declare const artifact: {
1149
+ /**
1150
+ * Publish a file from the workspace. path is workspace-relative, resolved by the same
1151
+ * resolver files.read() uses; the bytes are copied at publish time. The content type is
1152
+ * read off the extension unless opts.contentType overrides it. Rejects (catchably)
1153
+ * rather than publishing something empty.
1154
+ */
1155
+ file(id: string, path: string, opts?: ArtifactFileOptions): Promise<ArtifactRef>;
1156
+ /** Publish markdown text the script composed: the usual shape of a report deliverable, the long form of what the return summarises. */
1157
+ markdown(id: string, content: string, opts?: ArtifactOptions): Promise<ArtifactRef>;
1158
+ /** Declare a chart fed by report(item, id): each tagged item is one point. */
1159
+ chart(id: string, spec: ChartSpec): void;
1160
+ /** Declare a table fed by report(item, id): each tagged item is one row. */
1161
+ table(id: string, spec: TableSpec): void;
1162
+ /** Declare a metric tile row fed by report(item, id): each tile shows the newest value it has. */
1163
+ metrics(id: string, spec: MetricsSpec): void;
1164
+ /** Declare a board fed by report(item, id): each tagged item is a card, placed by its status field. */
1165
+ board(id: string, spec: BoardSpec): void;
1166
+ };
1167
+
1168
+ /**
1169
+ * Mark the start of a phase: a short, human-readable name for the group of steps that
1170
+ * follow, shown as one node on the workflow graph the user reads and approves.
1171
+ * Presentation only — it starts nothing, waits for nothing, returns nothing.
1172
+ *
1173
+ * Required in every script you submit, not optional: the phase graph is how the user
1174
+ * experiences the workflow. Without markers they face one card per step and no story;
1175
+ * group the whole script, top to bottom.
1176
+ *
1177
+ * Name phases for the user, in the language the user is speaking in this session: a short
1178
+ * natural phrase saying what the stage accomplishes ("Research each changed file in parallel",
1179
+ * "汇总并产出最终报告"). Graph-building vocabulary the user never chose — "fan-out", "gate",
1180
+ * "aggregate" — is not a name; the user approves stages by what they do. Say it the way you
1181
+ * would tell a colleague what is happening: "确认测试仍然通过", not "执行测试验证任务".
1182
+ *
1183
+ * The scope is the rest of the enclosing block: the marker claims every step issued
1184
+ * from it to the end of the block it stands in — nested blocks and inlined helper
1185
+ * calls included — and the enclosing phase resumes once that block ends. A marker
1186
+ * inside an if-branch therefore groups that branch and does not leak past it. Two
1187
+ * markers with the same name are one phase: repeating a name continues that phase,
1188
+ * which is the opposite of an actor's name — that one has to be unique.
1189
+ *
1190
+ * Two rules the compiler enforces. The name must be a compile-time string literal
1191
+ * ("review the diff" or a no-substitution template) and non-empty, because the phase
1192
+ * names label the graph the user confirms before anything runs. And the call must
1193
+ * stand alone as its own statement: a marker in expression position has no
1194
+ * rest-of-block to claim.
1195
+ *
1196
+ * Every phase must contain at least one subagent ask or one world.run. A phase is a
1197
+ * stage the user watches progress through; plain script logic between two asks (reading
1198
+ * args, shaping a prompt, building the return) runs in a flash and shows no progress, so
1199
+ * it is not a stage. Fold it into the phase before or after it; never open a phase for
1200
+ * the setup at the top or the return at the bottom.
1201
+ *
1202
+ * Idiom: one marker at the head of each stage that does work — name the loop body and
1203
+ * its check where they start, name the close-out that asks or runs after the loop.
1204
+ */
1205
+ declare function phase(name: string): void;
1206
+
1207
+ /** One matching line found by files.grep. */
1208
+ declare interface GrepMatch {
1209
+ /** Workspace-relative path of the file the match was found in. */
1210
+ path: string;
1211
+ /** One-based line number of the match. */
1212
+ line: number;
1213
+ /** The full text of the matching line. */
1214
+ text: string;
1215
+ }
1216
+
1217
+ /**
1218
+ * Journaled read-only observations of the workspace, executed by the harness.
1219
+ * Replay returns the journal-recorded value. Prefer passing paths to agents and
1220
+ * letting them read files with their own tools; read() and grep() are for when the
1221
+ * script itself must shard or branch on content. There is no write — writing to the
1222
+ * world is an agent task.
1223
+ */
1224
+ declare const files: {
1225
+ /**
1226
+ * List workspace files matching a glob pattern, as workspace-relative paths sorted
1227
+ * lexicographically. Capped at 2000 files: over the cap the call rejects instead of
1228
+ * returning a partial view — narrow the pattern.
1229
+ */
1230
+ glob(pattern: string): Promise<string[]>;
1231
+ /** Read one workspace file as UTF-8 text. Size-capped. */
1232
+ read(path: string): Promise<string>;
1233
+ /**
1234
+ * Search file contents with a ripgrep-compatible regular expression, optionally
1235
+ * narrowed to a glob over paths (the same syntax glob() takes: "*.ts", "src/**").
1236
+ * Returns one entry per matching line, with workspace-relative paths and one-based
1237
+ * line numbers.
1238
+ *
1239
+ * Capped at 2000 matches or 256KB of results, whichever comes first. Over the cap
1240
+ * the call rejects instead of returning a partial view — a silently truncated search
1241
+ * is the one result you cannot reason about — so narrow the pattern or add a glob.
1242
+ */
1243
+ grep(pattern: string, glob?: string): Promise<GrepMatch[]>;
1244
+ };
1245
+
1246
+ /** The working tree's status, as reported by git.status(). */
1247
+ declare interface GitStatus {
1248
+ /** Current branch name; absent when HEAD is detached. */
1249
+ branch?: string;
1250
+ /** True when nothing is staged, modified, or untracked. */
1251
+ clean: boolean;
1252
+ /** Workspace-relative paths staged for the next commit. */
1253
+ staged: string[];
1254
+ /** Workspace-relative paths modified in the working tree but not staged. */
1255
+ unstaged: string[];
1256
+ /** Workspace-relative paths git does not track (honouring .gitignore). */
1257
+ untracked: string[];
1258
+ }
1259
+
1260
+ /** One commit, as reported by git.log(). */
1261
+ declare interface GitCommit {
1262
+ /** Full commit hash. */
1263
+ hash: string;
1264
+ /** First line of the commit message. */
1265
+ subject: string;
1266
+ /** Author name. */
1267
+ author: string;
1268
+ /** Author date, ISO 8601. */
1269
+ date: string;
1270
+ }
1271
+
1272
+ /**
1273
+ * Journaled read-only git observations — the same bargain as files.*: executed by the
1274
+ * harness, recorded in the journal, and replayed from the record, so a resumed run
1275
+ * sees the repository as it was rather than as it is now.
1276
+ *
1277
+ * Read-only by construction rather than by permission: the harness builds a fixed
1278
+ * argument list for one allowlisted subcommand and never a shell string, so there is
1279
+ * no call this surface can express that writes. A base must name a single ref — no
1280
+ * ".." ranges in this version — and paths are workspace-relative.
1281
+ *
1282
+ * Observations are scoped to the workspace, which is the same world files.* observes:
1283
+ * every path you get back is relative to the workspace and safe to pass straight to
1284
+ * files.read(). If the workspace is a subdirectory of the repository, changes outside
1285
+ * it are not reported — the workspace is the world. git.log is the exception, because
1286
+ * commits are repository-wide objects rather than paths.
1287
+ *
1288
+ * Caps reject rather than truncate (diff at 512KB, log at 100 commits), for the same
1289
+ * reason grep does. Outside a git repository, or with no git available, every call
1290
+ * rejects with a catchable error, so the idiom is try/catch with a files.glob fallback.
1291
+ */
1292
+ declare const git: {
1293
+ /**
1294
+ * Workspace-relative paths that changed. With no base: files modified against HEAD
1295
+ * plus untracked files, because a brand-new file is a change to anyone reading. With
1296
+ * a base ref: files differing from that ref, tracked history only.
1297
+ */
1298
+ changedFiles(base?: string): Promise<string[]>;
1299
+ /**
1300
+ * Unified diff against base (default HEAD). Covers the whole workspace unless you
1301
+ * narrow it to one workspace-relative path.
1302
+ */
1303
+ diff(base?: string, path?: string): Promise<string>;
1304
+ /** The current working-tree status, for the workspace. */
1305
+ status(): Promise<GitStatus>;
1306
+ /**
1307
+ * The most recent commits, newest first. Default 20, maximum 100. Unlike the other
1308
+ * members this reads repository-wide history, not workspace paths.
1309
+ */
1310
+ log(count?: number): Promise<GitCommit[]>;
1311
+ };
1312
+
1313
+ /** The outcome of one world.run command, including nonzero exits. */
1314
+ declare interface WorldRunResult {
1315
+ /** The process exit code. Nonzero is a normal, returned outcome — branch on it. */
1316
+ exitCode: number;
1317
+ /** Captured stdout (UTF-8). Capped at 256KB; over the cap the call rejects. */
1318
+ stdout: string;
1319
+ /** Captured stderr (UTF-8). Same cap and rejection semantics as stdout. */
1320
+ stderr: string;
1321
+ }
1322
+
1323
+ /**
1324
+ * Journaled command execution — the effect primitive. Executed by the harness exactly
1325
+ * once per call site and iteration, recorded in the journal, and replayed from the
1326
+ * record on resume (resume is crash recovery, not re-verification).
1327
+ *
1328
+ * Deliberately unlike git.*: a completed process with a NONZERO exit code RESOLVES to
1329
+ * a WorldRunResult — a failing check is the gating loop's normal case and must not
1330
+ * travel exception control flow. The promise only rejects (catchably) when the
1331
+ * command could not run as an observation at all: spawn failure, or timeout (default
1332
+ * 300000ms, override per call via timeoutMs, no upper cap).
1333
+ *
1334
+ * cmd must be a compile-time string literal: the script's command set is shown to the
1335
+ * user when the run is confirmed, and only those commands are executable. Fixed argv,
1336
+ * never a shell — no pipes, no redirection, no variable expansion; compose with
1337
+ * multiple calls and plain code. cwd is the workspace. Idiom: model generates, code
1338
+ * gates — run the check here, parse its output with pure script logic, and hand
1339
+ * failures to an agent to fix. A helper that needs Node builtins can be inlined as
1340
+ * world.run("node", ["-e", code]) — the code string lives inside the script, so it is
1341
+ * pinned by the journal key like every other argument.
1342
+ */
1343
+ declare const world: {
1344
+ run(cmd: string, args?: string[], opts?: { timeoutMs?: number }): Promise<WorldRunResult>;
1345
+ };
1346
+ ```
1347
+ <!-- facade-dts:end -->
1348
+
1349
+ ### 16.3 Rules the compiler and the analyzer enforce
1350
+
1351
+ - Plain TypeScript. Define result types with a plain `interface Foo { ... }` or
1352
+ `type Foo = ...` and pass them as `ask<T>` type arguments.
1353
+ - Compiled under `strict` with `noUncheckedIndexedAccess` off: indexing an array or record
1354
+ (`items[i]`) needs no guard. `.find()`, `.match()`, `Map.get()` and optional properties
1355
+ still yield `T | undefined` / `null` and must be guarded before use.
1356
+ - Never use the `declare` modifier: the script is compiled inside a function body, where
1357
+ ambient declarations are illegal. No `export` statements — the workflow's output is its
1358
+ final `return`. No `import` statements.
1359
+ - Top-level `await` and a final `return <value>` are allowed; the returned value is exactly
1360
+ what the completion notification carries.
1361
+ - No Node or web APIs: `process`, `fetch`, `fs` do not exist and fail typechecking.
1362
+ - `world.run` executes a real command. Its first argument must be a compile-time string
1363
+ literal — the script's command set is shown to the user at confirmation — so interpolate
1364
+ runtime values into the args array, never into the command name. A nonzero exit code
1365
+ comes back as a value (`{ exitCode, stdout, stderr }`), not an exception: branch on
1366
+ `exitCode` for gate checks. Default timeout 300s; override per call with `timeoutMs` (no
1367
+ cap). Spawn failures and timeouts reject; stdout or stderr over 256KB rejects like any
1368
+ other over-cap world read.
1369
+ - Phases are required (§8): cover the whole script with `phase("...")` markers, one at the
1370
+ head of each stage. The name is a compile-time string literal and the call is a standalone
1371
+ statement; the marker claims the rest of its enclosing block, nested blocks and inlined
1372
+ helper calls included, so a marker inside an `if` covers that branch only. Two markers
1373
+ with the same name are one phase, which is how a retry loop stays two nodes instead of
1374
+ per-round sprawl. Every phase contains at least one subagent `ask` or one `world.run`;
1375
+ plain script logic between two asks is not a stage, so do not open a phase for the setup
1376
+ at the top or the `return` at the bottom.
1377
+ - Subagent names: the name you pass to `agent("...")` is the card the user sees, so write
1378
+ it for the user in the session's language (§9). It is also an identity: unique within the
1379
+ run, and the key an amended run matches its cached results by. Keep names stable across
1380
+ revisions of the same script, and give duplicates in a loop their own computed names.
1381
+ - Artifact ids and the `report` tag are compile-time literals; one id belongs to one
1382
+ artifact kind; at most one artifact carries `primary: true`; a preset artifact is declared
1383
+ at the top level, not inside a loop, callback or branch (§10). Publishing rejects
1384
+ catchably when the file is missing or too large.
1385
+ - Model-side errors never reach the script. Rate limits, concurrency limits, overload,
1386
+ network errors, timeouts and unknown provider errors are retried by the runtime without
1387
+ limit while it adapts the fan-out to what the provider accepts; a deterministic one
1388
+ (expired sign-in, model not in the plan, quota cap, invalid request) stops the whole run as
1389
+ `stopped` so the user can fix the cause and resume it. So do not write retry loops or
1390
+ `try`/`catch` for provider errors. Reserve them for logic failures — a subagent result
1391
+ that failed validation, a gate that did not pass, a world read over its cap, an artifact
1392
+ publish whose source file is missing, or a `ContextLimit` (the ask was too large for the
1393
+ model's context even after compaction: split the work or send less).
1394
+ - The final `return` is the model-facing result; artifacts are the user-facing deliverable.
1395
+ Never put the same content in both.
1396
+ - On diagnostics, edit the file the result names and call the tool again with `path`; never
1397
+ paste the script a second time.
1398
+
1399
+ ### 16.4 `AmendWorkflow`
1400
+
1401
+ Revises an existing run: it starts a new run that supersedes the old one and imports its
1402
+ finished work as a cache, so only what you changed is paid for again. §13 has the cache
1403
+ rules and the repair-while-running move. It works on any run of this project — completed,
1404
+ errored, stopped or still running; a running predecessor is stopped and superseded in the
1405
+ same call, so never `TaskStop` it first and never rewrite it from scratch with
1406
+ `CreateWorkflow`. To continue a stopped run unchanged, use `ResumeWorkflowRun` instead.
1407
+
1408
+ **Fields — every field you omit keeps the predecessor's value.**
1409
+
1410
+ - `run_id` (required): from a `CreateWorkflow` or `AmendWorkflow` result, a notification,
1411
+ `GetWorkflowRun` or `ListWorkflowRuns`.
1412
+ - `path` or `script`, never both. `path` is the usual form: the errored notification and
1413
+ `GetWorkflowRun` name the run's script file — edit it in place and pass the same path
1414
+ back, so a revision costs one `Edit` instead of a second copy of the whole script. A file
1415
+ whose bytes you did not change is refused (`script_unchanged`) unless the call also
1416
+ changes `max_concurrency` or `subagent_model`; nothing is stopped and nothing is created.
1417
+ `script` carries a whole revised script inline, written against the same facade and rules;
1418
+ it is saved to a draft file the result names, so the next revision can go back to `path`.
1419
+ Omit both to keep the predecessor's script byte for byte and change only the settings
1420
+ below; its finished work still replays from the cache.
1421
+ - `name`: a new display label; defaults to the predecessor's.
1422
+ - `max_concurrency`: omit to keep the predecessor's limit, pass `null` to remove it, pass a
1423
+ number to change it (only when the user asks). A call carrying nothing but `run_id` and
1424
+ `max_concurrency`, against a run that is still going, retunes that run in place instead of
1425
+ starting a new one: same run, nothing stopped, nothing re-run.
1426
+ - `subagent_model`: omit to keep the predecessor's choice, pass `null` to put the subagents
1427
+ back on the session model, pass a model id to change it (only when the user asks).
1428
+ `ListModels` lists the ids.
1429
+
1430
+ Changing only a setting on a running run still stops it; what it had in flight runs again in
1431
+ the new run, except that a named subagent whose unfinished ask you did not change picks that
1432
+ ask up where it left off instead of starting it over.
1433
+
1434
+ **How the cache works.** Named subagents are matched by name across the two scripts; each
1435
+ one's asks are matched in order by byte-identical instructions. A match settles from the
1436
+ recorded result at zero tokens; a changed or added ask runs live. The cache stays open until a
1437
+ live subagent makes its first write to the workspace (or a live `world.run` executes): from
1438
+ that moment, cached world reads and cached asks whose subagent had read or run something
1439
+ would describe a workspace that no longer exists, so they run live too. Asks that only
1440
+ answered keep settling from the cache. Editing an ask's text is how you force it to run
1441
+ again; keep names stable and keep tunable constants out of ask text (§13).
1442
+
1443
+ An inline `script` that does not compile comes back as diagnostics: fix the file the result
1444
+ names and call again with `path` — nothing was stopped and nothing was started.
1445
+
1446
+ **Confirmation.** A run this session started (through `CreateWorkflow`, a previous
1447
+ `AmendWorkflow` or the workflows hub) is amended without a confirmation window, even while
1448
+ it is running. A run the user stopped, or a run another session started, asks the user
1449
+ first. The result names the run that was superseded (if one was stopped) and the new run's
1450
+ id. The superseded run sends no notification of its own; the new run notifies when it
1451
+ settles. Do not wait for it or poll it with `TaskOutput`.
1452
+
1453
+ ### 16.5 `SaveWorkflow`
1454
+
1455
+ Saves a script with its metadata so it can be run again by name — through `CreateWorkflow`'s
1456
+ `saved` source, discovered with `ListSavedWorkflows`. Project definitions go in
1457
+ `.zcode/workflows/<name>.dwf.ts`, committed with the repository and visible only inside it;
1458
+ global definitions go in `~/.zcode/workflows/<name>.dwf.ts` and are available from every
1459
+ project on this machine.
1460
+
1461
+ **When to call it.**
1462
+
1463
+ - Never unsolicited. Saving writes a file into the user's repository; that is their
1464
+ decision, not yours.
1465
+ - When a workflow you just built looks reusable — it would plausibly run again with
1466
+ different inputs — suggest saving it in prose, one sentence naming what you would save and
1467
+ why, then stop and wait. Call `SaveWorkflow` only after the user agrees, or when the user
1468
+ asks directly ("save this workflow", "保存这个工作流"). A one-off script tailored to a
1469
+ single question is not worth suggesting; it wastes the user's attention and clutters the
1470
+ project.
1471
+
1472
+ **Fields.**
1473
+
1474
+ - `name`: a file-safe identifier (letters, digits, dot, dash and underscore). Saving over an
1475
+ existing name replaces that workflow; the confirmation tells the user whether this is a
1476
+ new file or an overwrite, so reuse a name to update a workflow and pick a new one to add a
1477
+ variant.
1478
+ - `description` (required) and `whenToUse`: written for a reader who has not seen this
1479
+ conversation. `description` shows up wherever the workflow is listed.
1480
+ - `scope` (required, no default): `project` when the script references this repository's
1481
+ files, commands, conventions or layout; `global` when it depends on nothing in the
1482
+ project.
1483
+ - `script` or `script_path`, never both. `script_path` saves a draft a `CreateWorkflow` or
1484
+ `AmendWorkflow` result named without re-emitting it; a `/* zcode-workflow` block in that
1485
+ file is dropped, because the metadata comes from this call's fields. `script` is the body
1486
+ only — no metadata block.
1487
+ - `args`: name exactly the values that would change between runs — a PR number, a
1488
+ directory, a depth — and no more; every declared argument is one more thing a future
1489
+ caller has to get right. Each declaration gives a `type` (`string`, `number`, `boolean`,
1490
+ or `json` for anything else), and optionally a `description`, `required: true` and a
1491
+ `default`. Declared arguments are the workflow's calling convention; every future call is
1492
+ validated against them.
1493
+
1494
+ The saved file is valid TypeScript: a `/* zcode-workflow` block of YAML metadata, then the
1495
+ script verbatim. The script is typechecked by the same compiler as `CreateWorkflow`, before
1496
+ the user is asked; diagnostics mean nothing was written. The rules in §16.3 apply, phases
1497
+ included — future callers did not see this conversation, so the phase names are all they
1498
+ get.
1499
+
1500
+ ### 16.6 `EvalWorkflowSnippet`
1501
+
1502
+ Compiles and runs a small snippet synchronously against the same compiler, sandbox and
1503
+ world-read execution path a real run uses, and returns the result in the tool call. Nothing
1504
+ persists: no journal rows, no background task, no run. It is the test bench for authoring
1505
+ (§6): before writing or revising a script, check a parser against real command output, see
1506
+ what a glob actually returns (workspace-relative sorted paths, cap rejections), or exercise a
1507
+ gate predicate on real repository state, instead of guessing. It is not for orchestration:
1508
+ there is no `agent()` here.
1509
+
1510
+ - `code` or `path`, never both: the snippet inline, or a file holding it, read whole with no
1511
+ metadata handling.
1512
+ - `timeoutMs`: the wall clock for the whole snippet in milliseconds; default 60000, at most
1513
+ 600000.
1514
+ - The snippet facade is the `args`, `log`, `files`/`git` and `world.run` parts of the block
1515
+ in §16.2; `agent()`, `report()`, `artifact.*` and the `phase` marker do not exist here and
1516
+ fail typechecking. The language rules are a script's: plain interfaces, top-level `await`, a
1517
+ final `return <value>`. The returned value is serialized into the result, so return a
1518
+ summary, not a dump; over 256KB fails the call. `log(...)` lines come back in order. A
1519
+ snippet that contains `world.run` asks the user for confirmation before running. On
1520
+ diagnostics nothing ran: fix the snippet and call again.