@sigmacamellia/dsh-dynamic-workflow 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1110 @@
1
+ # Worked dynamic-workflow examples
2
+
3
+ Seven complete scripts, end to end. Each is a whole arc — world read, topology, loop or
4
+ fan-out, salvage, artifacts, return shape — so read one when you want to see how the pieces
5
+ sit together rather than looking up a single shape (`patterns.md` is for that).
6
+
7
+ Every script here is submitted as the `script` argument of the `create_workflow` tool. The
8
+ API surface they are written against is `SKILL.md` §16 (the facade block in §16.2 and the
9
+ rules in §16.3), not the tool description.
10
+
11
+ ---
12
+
13
+ ## 1. Adversarial implement ↔ verify loop
14
+
15
+ Two subagents with opposed jobs, looping until the verifier cannot break the implementation.
16
+ The shape generalizes to anything with an author and a skeptic: code and property test, proof
17
+ and counter-example, schema and fuzzer.
18
+
19
+ <!-- compile -->
20
+ ```ts
21
+ interface ImplUpdate {
22
+ /** Files this round changed. */
23
+ changed: string[];
24
+ /** How this version addresses the previous counter-example. */
25
+ notes: string;
26
+ /** Whether the author's own build and tests passed before handing off. */
27
+ selfCheckPassed: boolean;
28
+ }
29
+
30
+ interface Verdict {
31
+ /** True only when the property was actually verified, not merely left untested. */
32
+ verified: boolean;
33
+ /** Where the verification lives, when it succeeded. */
34
+ proofPath?: string;
35
+ /** Concrete inputs that break the implementation, when it failed. */
36
+ counterExamples?: string[];
37
+ /** Why. This is the input to the implementer's next round. */
38
+ reason: string;
39
+ }
40
+
41
+ const IMPL_PATH = "src/compress.ts";
42
+ const TEST_PATH = "src/compress.property.test.ts";
43
+ const PROPERTY = "decompress(compress(s)) === s for every string s";
44
+
45
+ const implementer = agent("implementer", {
46
+ system:
47
+ `You implement in ${IMPL_PATH}. Run the build and \`npx vitest run\` before handing off, ` +
48
+ "and say in your notes exactly which commands you ran. " +
49
+ "Your deliverable is the file itself: describe what you changed, never paste the source back.",
50
+ });
51
+
52
+ const verifier = agent("verifier", {
53
+ system:
54
+ `You are an adversarial verifier. Read ${IMPL_PATH} and write property tests into ${TEST_PATH}. ` +
55
+ "If you cannot break it, report verified. If you can, give the exact failing input. " +
56
+ "Never claim a verification you did not actually run.",
57
+ });
58
+
59
+ const MAX_ROUNDS = 8;
60
+
61
+ // What a watcher wants to know mid-run: which round, and how many attacks are still open.
62
+ artifact.metrics("progress", {
63
+ title: "Verification progress",
64
+ metrics: [{ field: "round", label: "Round" }, { field: "open", label: "Open counter-examples" }],
65
+ });
66
+
67
+ phase("Implement the first version of the compression");
68
+ let impl = await implementer.ask<ImplUpdate>(
69
+ `Implement compress and decompress in ${IMPL_PATH} so that ${PROPERTY}.`,
70
+ );
71
+ phase("Try to break it with property tests");
72
+ let verdict = await verifier.ask<Verdict>(
73
+ `Verify or refute: ${PROPERTY}\n` +
74
+ `Changed: ${impl.changed.join(", ")}\nAuthor's notes: ${impl.notes}\n` +
75
+ `Author's self-check: ${impl.selfCheckPassed ? "passed" : "did not pass"}`,
76
+ );
77
+
78
+ let round = 1;
79
+ while (!verdict.verified && round < MAX_ROUNDS) {
80
+ phase("Fix what the tests broke");
81
+ round = round + 1;
82
+ const open = verdict.counterExamples?.length ?? 0;
83
+ log(`round ${round}: ${open} counter-examples`);
84
+ report({ round, open, reason: verdict.reason, counterExamples: verdict.counterExamples ?? [] }, "progress");
85
+
86
+ impl = await implementer.ask<ImplUpdate>(
87
+ `Verification failed.\nReason: ${verdict.reason}\n` +
88
+ `Counter-examples: ${JSON.stringify(verdict.counterExamples ?? [])}\n` +
89
+ `Fix ${IMPL_PATH} directly; the failing tests are in ${TEST_PATH}. Re-run your own check.`,
90
+ );
91
+ phase("Re-verify the fixed implementation");
92
+ verdict = await verifier.ask<Verdict>(
93
+ `The implementation changed (${impl.notes}). Verify or refute ${PROPERTY} again.`,
94
+ );
95
+ }
96
+
97
+ // The verifier's word is a claim; the test file is a fact. Run it once for real before the
98
+ // result is called verified — the verifier may have run it, but this is the run that counts.
99
+ phase("Run the property tests for real");
100
+ const proof = await world.run("npx", ["vitest", "run", TEST_PATH], { timeoutMs: 600_000 });
101
+ const verified = verdict.verified && proof.exitCode === 0;
102
+ if (verdict.verified && !verified) log(`the verifier said verified but vitest exited ${proof.exitCode}`);
103
+
104
+ await artifact.markdown(
105
+ "report",
106
+ [
107
+ `# ${PROPERTY}`,
108
+ "",
109
+ verified
110
+ ? `Verified after ${round} round(s); the property tests live in ${verdict.proofPath ?? TEST_PATH} and pass under vitest.`
111
+ : verdict.verified
112
+ ? `The verifier reported verified, but \`npx vitest run ${TEST_PATH}\` exited ${proof.exitCode}; treat the result as unverified.`
113
+ : `Still refuted after ${round} rounds: ${verdict.reason}`,
114
+ "",
115
+ `Implementation: ${IMPL_PATH}. Last change: ${impl.notes}`,
116
+ ].join("\n"),
117
+ {
118
+ title: "Verification report",
119
+ description: "Whether the property holds, how many rounds it took, and where the tests live.",
120
+ primary: true,
121
+ },
122
+ );
123
+
124
+ return {
125
+ conclusion: verified
126
+ ? `${PROPERTY} holds; the verifier could not break the implementation after ${round} round(s), and the property tests pass under vitest.`
127
+ : verdict.verified
128
+ ? `${PROPERTY} is not verified: the verifier reported success but the property tests exit ${proof.exitCode} when run for real.`
129
+ : `${PROPERTY} is still refuted after ${round} rounds: ${verdict.reason}`,
130
+ verified,
131
+ rounds: round,
132
+ implPath: IMPL_PATH,
133
+ proofPath: verdict.proofPath,
134
+ finalVerdict: verdict,
135
+ checks: [`npx vitest run ${TEST_PATH} exited ${proof.exitCode}`],
136
+ notCovered: ["inputs the property tests did not generate", "performance"],
137
+ };
138
+ ```
139
+
140
+ **Why it is written this way.** Both subagents live outside the loop, so each keeps everything
141
+ it learned: the implementer remembers the approaches it already tried, and the verifier
142
+ remembers which attacks already worked. Both genuinely edit and run files.
143
+
144
+ The subagents exchange **paths and descriptions, never file contents**; each reads the other's
145
+ work with its own tools. Each round is reported as it happens, so a run that dies on round
146
+ six still shows five rounds of counter-examples. And the return value says `verified` and
147
+ `rounds`, so a caller can tell convergence from exhaustion — and opens with a `conclusion`
148
+ and closes with `notCovered`, because the return value is what the main agent retells.
149
+
150
+ `verified` is not the verifier's word. The verifier is a subagent, and a subagent's "I ran
151
+ the tests" is a claim; the `world.run` at the end runs the test file for real and its exit
152
+ code is what the result rests on. The implementer's persona names the exact commands it
153
+ must run for the same reason — "run the tests" lets a subagent pick the fastest thing that
154
+ turns green.
155
+
156
+ Two artifacts, each for a different moment. The metrics tile is for whoever is watching the
157
+ loop: round and open counter-examples, fed by the `report` call the script was already
158
+ making. The markdown report is for afterwards — the same facts as the return, in the long
159
+ form the user keeps. The tests themselves are not published: they live in the repository,
160
+ and a card for a file the user would open in the editor anyway says nothing new.
161
+
162
+ ---
163
+
164
+ ## 2. Flaky test triage
165
+
166
+ Scan, then plan a fix under critique, then judge each finding independently. Three
167
+ topologies in one script, each chosen for a different reason.
168
+
169
+ <!-- compile -->
170
+ ```ts
171
+ interface Finding {
172
+ /** Test identifier as the runner reports it. */
173
+ testId: string;
174
+ /** Workspace-relative path of the test file. */
175
+ file: string;
176
+ /** What makes it flaky. */
177
+ kind: "timing" | "ordering" | "external";
178
+ /** 0-1. How confident the scan is that this is really flaky. */
179
+ confidence: number;
180
+ }
181
+ interface Scan {
182
+ findings: Finding[];
183
+ }
184
+ interface Plan {
185
+ /** One entry per test, in the order the fixes should be applied. */
186
+ steps: { testId: string; change: string }[];
187
+ /** Anything the plan deliberately does not address. */
188
+ outOfScope: string[];
189
+ }
190
+ interface Review {
191
+ approved: boolean;
192
+ /** What is wrong with the plan. Empty when approved. */
193
+ feedback: string;
194
+ }
195
+ interface Judgement {
196
+ /** False when the finding is a false positive. */
197
+ real: boolean;
198
+ reason: string;
199
+ }
200
+ interface Confirmation {
201
+ /** True only when you reproduced the flakiness yourself (re-ran the test, read the timing dependence). */
202
+ reproduced: boolean;
203
+ /** What you did to check, one sentence. */
204
+ note: string;
205
+ }
206
+ interface ReportedFinding extends Finding {
207
+ /** "verified" when the confirmer reproduced it; "unconfirmed" when it could not. */
208
+ status: "verified" | "unconfirmed";
209
+ }
210
+ interface FlakyReport {
211
+ /** Two or three sentences answering what the user asked for. */
212
+ conclusion: string;
213
+ findings: ReportedFinding[];
214
+ /** The approved plan, when the loop converged. */
215
+ plan?: Plan;
216
+ converged: boolean;
217
+ rounds: number;
218
+ /** What the run checked and how. */
219
+ verified: string[];
220
+ /** What the run did not look at or could not check, and why. */
221
+ notCovered: string[];
222
+ }
223
+
224
+ // Every candidate is a card; it moves column as the run makes up its mind about it.
225
+ artifact.board("candidates", {
226
+ title: "Flaky test candidates",
227
+ key: "testId",
228
+ status: "status",
229
+ columns: ["candidate", "false positive", "verified", "unconfirmed"],
230
+ detail: [{ field: "file" }, { field: "kind" }],
231
+ });
232
+
233
+ phase("Scan the repository for flaky tests");
234
+ const scan = await agent("scanner", "You identify flaky tests from test code and CI history.")
235
+ .ask<Scan>("Find flaky tests in this repository. Prefer precision over recall.");
236
+
237
+ log(`${scan.findings.length} candidate flaky tests`);
238
+ for (const finding of scan.findings) report({ ...finding, status: "candidate" }, "candidates");
239
+ if (scan.findings.length === 0) {
240
+ const empty: FlakyReport = {
241
+ conclusion: "No flaky tests found.",
242
+ findings: [],
243
+ converged: true,
244
+ rounds: 0,
245
+ verified: ["scanned test code and CI history"],
246
+ notCovered: ["tests that only flake under load the scan could not observe"],
247
+ };
248
+ return empty;
249
+ }
250
+
251
+ // Independent judges: one fresh context per finding, because a judge that has seen the
252
+ // other findings starts grading on a curve instead of on the merits. Each carries the
253
+ // test id in its name — one subagent per finding means one name per finding.
254
+ //
255
+ // A judge's verdict is a judgement, not a reproduction, so each survivor goes on to a fresh
256
+ // confirmer that re-runs the test and reads the timing dependence itself; the ask forbids
257
+ // edits. The confirmer is chained right after its own judge, inside the same callback: a
258
+ // candidate is confirmed the moment its judge rules, not after every judge has. What the
259
+ // confirmer cannot reproduce is kept and labelled, not dropped.
260
+ phase("Judge each candidate and confirm the real ones as they are judged");
261
+ // One join: the planner below needs every real finding before it can plan.
262
+ const outcomes = await Promise.all(
263
+ scan.findings.map(async (finding): Promise<ReportedFinding | undefined> => {
264
+ const judgement = await agent(`judge-${finding.testId}`).ask<Judgement>(
265
+ `Is this really flaky, or a false positive?\n${JSON.stringify(finding)}`,
266
+ );
267
+ if (!judgement.real) {
268
+ report({ ...finding, status: "false positive" }, "candidates");
269
+ return undefined;
270
+ }
271
+ const check = await agent(`confirmer-${finding.testId}`).ask<Confirmation>(
272
+ `Reproduce this flakiness from the evidence alone: run the test, read the timing dependence. Do not edit any file.\n${JSON.stringify(finding)}`,
273
+ );
274
+ const reported: ReportedFinding = {
275
+ ...finding,
276
+ status: check.reproduced ? "verified" : "unconfirmed",
277
+ };
278
+ report(reported, "candidates");
279
+ return reported;
280
+ }),
281
+ );
282
+ const real = outcomes.filter((o): o is ReportedFinding => o !== undefined);
283
+ log(`${real.length} of ${scan.findings.length} survived judging`);
284
+ if (real.length === 0) {
285
+ const empty: FlakyReport = {
286
+ conclusion: "Every candidate was judged a false positive.",
287
+ findings: [],
288
+ converged: true,
289
+ rounds: 0,
290
+ verified: ["scanned test code and CI history", "judged each candidate independently"],
291
+ notCovered: ["tests that only flake under load the scan could not observe"],
292
+ };
293
+ return empty;
294
+ }
295
+
296
+ // Planner and reviewer: created once, reused every round, so each accumulates context.
297
+ const planner = agent("planner", "You write minimal, concrete fixes for flaky tests.");
298
+ const reviewer = agent("reviewer", "You find the flaw in a fix plan. Approve only when you cannot find one. You never edit files.");
299
+
300
+ let feedback = "none";
301
+ let approved: Plan | undefined;
302
+ let rounds = 0;
303
+ for (let round = 0; round < 5; round++) {
304
+ rounds = round + 1;
305
+ phase("Draft a fix plan");
306
+ const plan = await planner.ask<Plan>(
307
+ `Plan fixes for these flaky tests:\n${JSON.stringify(real)}\nPrevious critique: ${feedback}`,
308
+ );
309
+ phase("Critique the plan");
310
+ const review = await reviewer.ask<Review>(`Critique this plan:\n${JSON.stringify(plan)}`);
311
+ if (review.approved) {
312
+ approved = plan;
313
+ break;
314
+ }
315
+ log(`plan rejected in round ${rounds}: ${review.feedback}`);
316
+ feedback = review.feedback;
317
+ }
318
+
319
+ const verified = ["scanned test code and CI history", "each survivor reproduced by an independent confirmer"];
320
+ const done: FlakyReport = approved
321
+ ? {
322
+ conclusion: `${real.length} flaky tests confirmed; a fix plan was approved after ${rounds} round(s).`,
323
+ findings: real,
324
+ plan: approved,
325
+ converged: true,
326
+ rounds,
327
+ verified,
328
+ notCovered: approved.outOfScope,
329
+ }
330
+ : {
331
+ conclusion: `${real.length} flaky tests confirmed, but no fix plan survived review in ${rounds} rounds; last critique: ${feedback}`,
332
+ findings: real,
333
+ converged: false,
334
+ rounds,
335
+ verified,
336
+ notCovered: ["a fix plan — none was approved"],
337
+ };
338
+
339
+ await artifact.markdown(
340
+ "report",
341
+ [
342
+ `# ${done.conclusion}`,
343
+ "",
344
+ ...real.map((f) => `- ${f.testId} (${f.file}, ${f.kind}): ${f.status}`),
345
+ "",
346
+ approved
347
+ ? approved.steps.map((step) => `1. ${step.testId}: ${step.change}`).join("\n")
348
+ : `No plan was approved. Last critique: ${feedback}`,
349
+ ].join("\n"),
350
+ { title: "Flaky test report" },
351
+ );
352
+ return done;
353
+ ```
354
+
355
+ **Why it is written this way.** The judges are fresh per finding and the planner/reviewer pair
356
+ is hoisted — opposite choices, both deliberate. Judging wants independence, so sharing a
357
+ context would actively corrupt it; planning wants memory, so a fresh planner each round would
358
+ waste it. The confirmers are a third kind: fresh and per finding, told not to edit, because a
359
+ judge's verdict is an opinion about a description, and only re-running the test turns it into
360
+ a fact. What they cannot reproduce stays in the report as `unconfirmed`. Each confirmer
361
+ follows its own judge inside one callback, so the fan-out has one join instead of two:
362
+ confirming candidate three never waits for candidate forty's judge.
363
+
364
+ The two early returns matter. A scan that finds nothing and a judging pass that rejects
365
+ everything are both *successes* with an empty result, not failures — and each avoids paying
366
+ for a planning loop over an empty list. Both still return the full report shape, with a
367
+ `conclusion` that says which of the two happened. Findings are reported before planning
368
+ starts, so even a planning loop that never converges hands back the confirmed findings.
369
+
370
+ The board is the watcher's view of a fan-out: every candidate appears the moment the scan
371
+ returns and moves column as a judge or a confirmer rules on it, because a later item with the
372
+ same `testId` replaces the card. The report is published once, after the planning loop, which
373
+ is why the loop `break`s to a single return instead of returning from inside. The two early
374
+ returns publish nothing: "No flaky tests found" is a one-line answer, and a page that
375
+ restates it would be noise.
376
+
377
+ ---
378
+
379
+ ## 3. Call-site migration
380
+
381
+ Discover, transform in parallel, then verify. The transforming subagents write files, so this is
382
+ the one shape where isolation and verification really matter.
383
+
384
+ <!-- compile -->
385
+ ```ts
386
+ interface Migration {
387
+ /** Whether this file needed changing at all. */
388
+ changed: boolean;
389
+ /** What was rewritten, one line. */
390
+ summary: string;
391
+ /** Anything the migrator could not do safely and left alone. */
392
+ skipped: string[];
393
+ }
394
+ interface Check {
395
+ /** True when the file compiles and its tests pass after the change. */
396
+ clean: boolean;
397
+ /** What broke, when it did not. */
398
+ problem: string;
399
+ }
400
+
401
+ const OLD_API = "getUserSync";
402
+ const NEW_API = "getUser";
403
+
404
+ artifact.table("migration", {
405
+ title: "Migration by file",
406
+ key: "path",
407
+ columns: [
408
+ { field: "path", label: "File" },
409
+ { field: "summary", label: "Change" },
410
+ { field: "clean", label: "Verified" },
411
+ ],
412
+ });
413
+
414
+ phase("Find every call site of the old API");
415
+ const hits = await files.grep(`\\b${OLD_API}\\b`, "src/**/*.ts");
416
+ const paths = [...new Set(hits.map((h) => h.path))];
417
+ log(`${OLD_API} appears in ${paths.length} files (${hits.length} call sites)`);
418
+ if (paths.length === 0) return { migrated: [], failed: [], note: "nothing to migrate" };
419
+
420
+ // One persona, reused by every migrator subagent. Personas are values you can share; subagents
421
+ // and their names are not — each file gets its own of both.
422
+ const MIGRATOR = {
423
+ system:
424
+ `You migrate call sites from ${OLD_API} to the async ${NEW_API}, adding await and making ` +
425
+ "the enclosing function async where needed. Change nothing else. If a call site cannot be " +
426
+ "migrated safely, leave it and say why.",
427
+ };
428
+
429
+ // One migrator per file: the edits are disjoint, so they can run at once, and a fresh
430
+ // context per file keeps one file's oddities from leaking into another's rewrite.
431
+ phase("Migrate each file and verify the result");
432
+ // One join: the whole-tree suite below needs every file migrated first.
433
+ const results = await Promise.all(
434
+ paths.map(async (path) => {
435
+ try {
436
+ const migration = await agent(`migrator-${path}`, MIGRATOR).ask<Migration>(
437
+ `Migrate every ${OLD_API} call in ${path} to ${NEW_API}.`,
438
+ );
439
+ if (!migration.changed) return { path, migration, check: undefined };
440
+
441
+ // Verify with a separate context: a subagent asked to check its own work grades
442
+ // generously. It compiles and runs tests; the ask forbids edits.
443
+ const check = await agent(`checker-${path}`).ask<Check>(
444
+ `Does ${path} still compile and pass its tests after the ${NEW_API} migration? ` +
445
+ `Run the checks; do not edit any file. The change was: ${migration.summary}`,
446
+ );
447
+ report({ path, summary: migration.summary, clean: check.clean }, "migration");
448
+ return { path, migration, check };
449
+ } catch (error) {
450
+ log(`skipped ${path}: ${String(error)}`);
451
+ report({ path, summary: `skipped: ${String(error)}`, clean: false }, "migration");
452
+ return { path, migration: undefined, check: undefined, error: String(error) };
453
+ }
454
+ }),
455
+ );
456
+
457
+ const migrated = results.filter((r) => r.check?.clean === true).map((r) => r.path);
458
+ const failed = results.filter((r) => r.check?.clean === false || r.error !== undefined);
459
+
460
+ // Every file passed its own check; now the tree as a whole, once. A per-file checker cannot
461
+ // see the caller in another file that a migrated signature broke — the full suite can, and
462
+ // it is the check the user will run themselves.
463
+ phase("Run the whole test suite once over the migrated tree");
464
+ const suite = await world.run("npm", ["test"], { timeoutMs: 1_800_000 });
465
+ const suiteClean = suite.exitCode === 0;
466
+ if (!suiteClean) log(`npm test failed after the migration:\n${suite.stderr.slice(-2000)}`);
467
+
468
+ await artifact.markdown(
469
+ "report",
470
+ [
471
+ suiteClean
472
+ ? `# ${OLD_API} → ${NEW_API}: ${migrated.length} of ${paths.length} files migrated and verified`
473
+ : `# ${OLD_API} → ${NEW_API}: ${migrated.length} of ${paths.length} files migrated, but the full suite fails`,
474
+ "",
475
+ ...migrated.map((p) => `- ${p}: migrated; compiled and tests passed`),
476
+ ...failed.map((r) => `- ${r.path}: failed — ${r.check?.problem ?? r.error}`),
477
+ "",
478
+ `Full suite (\`npm test\`): exit ${suite.exitCode}`,
479
+ ].join("\n"),
480
+ { title: "Migration report" },
481
+ );
482
+
483
+ return {
484
+ conclusion: suiteClean
485
+ ? `${migrated.length} of ${paths.length} files migrated from ${OLD_API} to ${NEW_API} and verified; ${failed.length} failed; the full suite passes.`
486
+ : `${migrated.length} of ${paths.length} files migrated from ${OLD_API} to ${NEW_API}, but the full suite fails after the migration, so the result is not verified: ${suite.stderr.slice(-300)}`,
487
+ migrated,
488
+ failed: failed.map((r) => ({ path: r.path, problem: r.check?.problem ?? r.error })),
489
+ skipped: results.flatMap((r) => r.migration?.skipped ?? []),
490
+ verified: [
491
+ ...migrated.map((p) => `${p}: compiled and tests passed, checked by a separate subagent`),
492
+ `npm test over the whole tree exited ${suite.exitCode}`,
493
+ ],
494
+ notCovered: ["call sites outside src/**/*.ts", "callers in other packages that import the migrated functions"],
495
+ };
496
+ ```
497
+
498
+ **Why it is written this way.** `files.grep` narrows before the fan-out: globbing `src/**/*.ts`
499
+ and asking every file whether it uses the old API would spend a session per file to learn
500
+ what one search already knew. Because `grep` rejects instead of truncating when it overruns
501
+ its cap, the path list is either complete or absent — never quietly partial, which for a
502
+ migration is the difference between finished and silently half-finished.
503
+
504
+ Both subagents in the fan-out are named per path. That is not decoration: a run rejects two
505
+ subagents sharing a name, so `agent("migrator")` inside the `map` would not survive its second
506
+ file — and the per-path names are also what a corrected re-run (`amend_workflow`) matches its
507
+ imported cache against, so re-running this script after fixing one detail does not re-migrate
508
+ the files that already came out clean.
509
+
510
+ The checker is a **separate subagent** from the migrator, which is what makes the check
511
+ meaningful: a subagent asked to grade its own migration grades generously. It builds and
512
+ tests, and the ask is what forbids it to patch what it finds broken. The checker also runs
513
+ inside the same callback as its migrator — a per-item pipeline with one join — so the first
514
+ file is verified while the fortieth is still being rewritten, instead of every checker
515
+ waiting behind a `Promise.all` for the slowest migration. The
516
+ `try`/`catch` is per file, so one unmigratable file costs one file rather than the run. And
517
+ the return value separates `migrated` from `failed` from `skipped`, because "we changed 40
518
+ files" is not an outcome anyone can act on.
519
+
520
+ The fan-out verifies each file; the `world.run` after it verifies the tree. Those are
521
+ different checks: forty files that each pass their own tests can still not compile together,
522
+ and the caller in a file nobody migrated is exactly what a per-file checker never opens. The
523
+ whole-suite run is the check the user would run before merging, so it runs here, once, with
524
+ the timeout a real suite needs — and when it fails, `conclusion` says the result is
525
+ unverified rather than letting the forty green rows speak for the tree.
526
+
527
+ The table is the fan-out seen live: one row per file, keyed by path, filled in as each
528
+ checker answers, with the skipped files landing in it too. The report at the end is the
529
+ same list in prose for the user to keep. The migrated files themselves are not published —
530
+ they are the repository, and the user reads them there. The early return for "nothing to
531
+ migrate" publishes nothing: a one-line answer needs no page.
532
+
533
+ ---
534
+
535
+ ## 4. Prover loop gated by the real checker
536
+
537
+ One subagent doing open-ended repair, and a gate that cannot be talked past: `world.run`
538
+ executes the actual proof checker, and the loop advances on its exit code, not on anyone's
539
+ claim. Compare example 1, where the skeptic is another subagent — right when breaking the work
540
+ takes creativity. When a command can render the verdict, the command should.
541
+
542
+ <!-- compile -->
543
+ ```ts
544
+ interface FixNotes {
545
+ /** What changed this round, one line. */
546
+ summary: string;
547
+ }
548
+
549
+ const TARGET = "Proofs/Main.lean";
550
+ const MAX_ROUNDS = 10;
551
+
552
+ const prover = agent("prover", {
553
+ system:
554
+ `You write and repair Lean proofs in ${TARGET}. Fix exactly what the checker reports; ` +
555
+ "never delete or weaken a theorem to silence an error.",
556
+ });
557
+
558
+ phase("Write the first proof attempt");
559
+ let notes = await prover.ask<FixNotes>(`Prove the open theorem in ${TARGET}.`);
560
+
561
+ const attempts: string[] = [];
562
+ let clean = false;
563
+ let rounds = 0;
564
+ for (let round = 1; round <= MAX_ROUNDS; round++) {
565
+ rounds = round;
566
+ attempts.push(notes.summary);
567
+ phase("Check the file with the fast checker");
568
+ // The fast tier: one file, seconds. It exits 0 on a proof that still says `sorry` and
569
+ // only warns on stderr, so the exit code alone is not the verdict.
570
+ const check = await world.run("lake", ["env", "lean", TARGET], { timeoutMs: 600_000 });
571
+ clean = check.exitCode === 0 && !check.stderr.includes("sorry");
572
+ if (clean) {
573
+ report({ round, summary: notes.summary, checkerClean: true });
574
+ break;
575
+ }
576
+
577
+ log(`round ${round}: checker rejected`);
578
+ report({ round, summary: notes.summary, checkerClean: false });
579
+ phase("Repair what the checker rejected");
580
+ notes = await prover.ask<FixNotes>(
581
+ `The Lean checker rejected the file. Its output:\n${check.stderr}\nRepair ${TARGET}.`,
582
+ );
583
+ }
584
+
585
+ // The strong tier, once: the whole project builds with the new proof in it. That is what
586
+ // the request was about, and it runs even though the fast tier already said yes.
587
+ let proved = false;
588
+ if (clean) {
589
+ phase("Build the whole project with the new proof");
590
+ const build = await world.run("lake", ["build"], { timeoutMs: 1_800_000 });
591
+ proved = build.exitCode === 0;
592
+ if (!proved) log(`lake build rejected what the fast checker accepted:\n${build.stderr}`);
593
+ }
594
+
595
+ await artifact.markdown(
596
+ "report",
597
+ [
598
+ proved
599
+ ? `# ${TARGET}: proved in round ${rounds}`
600
+ : `# ${TARGET}: not proved after ${MAX_ROUNDS} rounds`,
601
+ "",
602
+ ...attempts.map((summary, index) => `${index + 1}. ${summary}`),
603
+ ].join("\n"),
604
+ { title: "Proof report" },
605
+ );
606
+
607
+ return proved
608
+ ? {
609
+ conclusion: `The open theorem in ${TARGET} is proved; the file checked clean in round ${rounds} and the whole project builds.`,
610
+ proved: true,
611
+ rounds,
612
+ lastChange: notes.summary,
613
+ verified: [`lake env lean ${TARGET} exited 0 with no sorry warning`, "lake build exited 0"],
614
+ notCovered: [],
615
+ }
616
+ : clean
617
+ ? {
618
+ conclusion: `Not proved: ${TARGET} checks clean on its own, but lake build fails with the new proof in the project.`,
619
+ proved: false,
620
+ rounds,
621
+ lastChange: notes.summary,
622
+ verified: [`lake env lean ${TARGET} exited 0 with no sorry warning`, "lake build exited nonzero"],
623
+ notCovered: ["why the whole-project build disagrees with the single-file check"],
624
+ }
625
+ : {
626
+ conclusion: `Not proved: the Lean checker still rejects ${TARGET} after ${MAX_ROUNDS} rounds.`,
627
+ proved: false,
628
+ rounds,
629
+ lastChange: notes.summary,
630
+ verified: [`lake env lean ${TARGET} run ${MAX_ROUNDS} times, none clean`],
631
+ notCovered: ["approaches the prover did not try", "lake build — never reached"],
632
+ };
633
+ ```
634
+
635
+ **Why it is written this way.** The prover is created once and keeps its context, so round
636
+ seven remembers what rounds one through six already tried. The checker is not a subagent at
637
+ all: `world.run` runs the real command, a nonzero exit comes back as a **value**, and the
638
+ loop's normal case is reading `exitCode` and handing `stderr` to the prover as the next
639
+ round's instructions — no `catch` anywhere, because rejections are reserved for the world
640
+ failing to answer (spawn failure, timeout, over-cap output).
641
+
642
+ There are two checks, and they are not interchangeable. `lake env lean` on one file is the
643
+ fast tier: it drives the rounds because it answers in seconds, and it reads stderr as well
644
+ as the exit code because a proof that still says `sorry` exits 0 with a warning. `lake
645
+ build` over the whole project is the strong tier — the check the request is really about —
646
+ and it runs once at the end whether or not the fast tier already passed. A loop gated on
647
+ the fast tier alone would return "proved" for a file that still contains `sorry`, and never
648
+ learn that the new proof breaks a module that imports it. Which two commands play these
649
+ roles is a fact about the repository, read from its README or build files before the script
650
+ is written, not a habit carried in from the last project.
651
+
652
+ The command name is a literal and the varying part — the target path — rides in the args
653
+ array; that is the rule, and it is also what the user sees and approves at confirmation.
654
+ The long `timeoutMs` is deliberate: proof checking is allowed to be slow, and the per-call
655
+ override exists precisely for real build-sized checks. Every round is reported as it lands,
656
+ so a run that dies on round eight still shows seven rounds of attempts. Before wiring a
657
+ different checker command, test what its stderr actually looks like with a one-line
658
+ `eval_workflow_snippet` call — the parse you write against a guess is the parse that breaks.
659
+
660
+ One artifact, deliberately. The report lists every attempt, which is more than the
661
+ `conclusion` can say, so it earns its page. There is no dashboard: the only state a watcher
662
+ could follow is the round number and whether the checker passed, and the phase timeline
663
+ lighting up "Repair what the checker rejected" again already shows exactly that. A metrics
664
+ tile would repeat it, and the proof file is the repository's to show, not a card's.
665
+
666
+ ## 5. Changed-file review with confirmation as reviews land
667
+
668
+ Review every changed file, triage its findings on one scale, confirm each kept finding
669
+ independently, and hand back a report. Everything a file needs happens as soon as its own
670
+ review lands; the only join is the cross-file deduplication that needs every finding.
671
+
672
+ <!-- compile -->
673
+ ```ts
674
+ interface Finding {
675
+ /** Workspace-relative path, with a line when it applies: "src/a.ts:42". */
676
+ where: string;
677
+ /** One sentence: what is wrong. */
678
+ what: string;
679
+ /** What showed it: the lines read, or the command and the output that proved it. */
680
+ evidence: string;
681
+ /** How much it matters. Reserve "high" for data loss, a crash, or a wrong result. */
682
+ severity: "low" | "medium" | "high";
683
+ }
684
+ interface Review {
685
+ findings: Finding[];
686
+ }
687
+ interface Keep {
688
+ /** True when this finding is worth putting in front of a human. */
689
+ keep: boolean;
690
+ }
691
+ interface Confirmation {
692
+ /** True only when you reproduced the problem yourself from the evidence. */
693
+ reproduced: boolean;
694
+ /** What you did to check, one sentence. */
695
+ note: string;
696
+ }
697
+ interface ReportedFinding extends Finding {
698
+ /** "verified" when the confirmer reproduced it; "unconfirmed" when it could not. */
699
+ status: "verified" | "unconfirmed";
700
+ }
701
+ interface Digest {
702
+ /** The confirmed findings with duplicates across files merged, one line each. */
703
+ lines: string[];
704
+ /** Two or three sentences a reader can act on. */
705
+ summary: string;
706
+ }
707
+ interface WorkflowReport {
708
+ /** Two or three sentences answering what the user asked for. */
709
+ conclusion: string;
710
+ findings: ReportedFinding[];
711
+ /** What the run checked and how. */
712
+ verified: string[];
713
+ /** What the run did not look at or could not check, and why. */
714
+ notCovered: string[];
715
+ }
716
+
717
+ phase("Review each changed file and confirm its findings as they land");
718
+ let paths: string[];
719
+ try {
720
+ paths = await git.changedFiles("origin/main");
721
+ } catch {
722
+ paths = await files.glob("src/**/*.ts");
723
+ }
724
+ log(`reviewing ${paths.length} changed files`);
725
+
726
+ // One triage subagent for all findings: severity only means anything if it is judged on a
727
+ // consistent scale. It is a queue, not a barrier — asks on it run FIFO, so a finding reaches
728
+ // it the moment its file's review lands, whichever file that is.
729
+ const triage = agent("triage", "You decide which review findings deserve a human's attention. Be strict.");
730
+
731
+ // One reviewer per file, fresh each: the files are unrelated, so nothing is gained by
732
+ // sharing a context and everything is gained by running them at once. Triage and
733
+ // confirmation live inside the same callback, so no file waits for the slowest review
734
+ // before its findings move on; the outer `Promise.all` is the only join the report waits on.
735
+ const perFile = await Promise.all(
736
+ paths.map(async (p) => {
737
+ const review = await agent(`reviewer-${p}`).ask<Review>(`Review ${p} for correctness bugs.`);
738
+
739
+ const kept: Finding[] = [];
740
+ for (const finding of review.findings) {
741
+ const verdict = await triage.ask<Keep>(`Worth reporting? ${JSON.stringify(finding)}`);
742
+ if (verdict.keep) kept.push(finding);
743
+ }
744
+
745
+ // A separate confirmer per kept finding, blind to the reviewer that raised it: it reads
746
+ // the code, runs a check if one decides it, and is told not to fix anything. The name
747
+ // carries the path and the index, because every subagent name in a run must be unique.
748
+ return Promise.all(
749
+ kept.map(async (finding, index) => {
750
+ const check = await agent(`confirmer-${p}-${index}`).ask<Confirmation>(
751
+ `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)}`,
752
+ );
753
+ const reported: ReportedFinding = {
754
+ ...finding,
755
+ status: check.reproduced ? "verified" : "unconfirmed",
756
+ };
757
+ report(reported); // published now, with its status, so it survives a later failure
758
+ return reported;
759
+ }),
760
+ );
761
+ }),
762
+ );
763
+ const confirmed = perFile.flat();
764
+ log(`${confirmed.length} findings confirmed or labelled`);
765
+
766
+ // The one stage that genuinely needs every finding: two reviewers can flag the same root
767
+ // cause from two files, and only a reader of the whole list can merge them.
768
+ phase("Merge duplicate findings across files and write them up");
769
+ const digest = await agent("editor", "You merge review findings that share a root cause and write them up for the engineer who fixes them.")
770
+ .ask<Digest>(`Merge duplicates and write these up:\n${JSON.stringify(confirmed)}`);
771
+
772
+ const verifiedCount = confirmed.filter((f) => f.status === "verified").length;
773
+ await artifact.markdown(
774
+ "report",
775
+ [
776
+ `# Review of ${paths.length} changed files: ${confirmed.length} findings, ${verifiedCount} reproduced`,
777
+ "",
778
+ digest.summary,
779
+ "",
780
+ ...digest.lines.map((line) => `- ${line}`),
781
+ "",
782
+ "## Every finding",
783
+ ...confirmed.map((f) => `- **${f.where}** (${f.severity}, ${f.status}): ${f.what}\n ${f.evidence}`),
784
+ ].join("\n"),
785
+ { title: "Review report" },
786
+ );
787
+ const result: WorkflowReport = {
788
+ conclusion: digest.summary,
789
+ findings: confirmed,
790
+ verified: paths.map((p) => `reviewed ${p}; every kept finding re-checked by a separate subagent`),
791
+ notCovered: ["files outside the change set", "runtime behaviour no existing test exercises"],
792
+ };
793
+ return result;
794
+ ```
795
+
796
+ Three shapes in one script, each chosen for a reason. The reviewers are fresh and parallel
797
+ because the files are unrelated. The triage subagent is shared because severity must mean the
798
+ same thing twice — and sharing costs nothing here, because its FIFO queue is fed as reviews
799
+ land rather than after all of them. The confirmers are fresh, per finding and blind to the
800
+ reviewer, and they start the moment their file's triage is done: with twelve files and one
801
+ slow reviewer, eleven files' findings are confirmed and reported while it is still reading.
802
+ Nothing gets a second reader on top: each finding was confirmed, and the editor's job is
803
+ merging and writing up, not re-checking.
804
+
805
+ ## 6. Fact-finding pipeline with a fresh verifier per fact
806
+
807
+ Research a topic from five angles at once, check every fact as it arrives with a verifier
808
+ that did not do the research, then write the report from the facts that held. The hand-off
809
+ from research to verification is a channel, so the first verifier starts while four
810
+ researchers are still reading; the writer sits after the one join, because it needs every
811
+ verified fact.
812
+
813
+ <!-- compile -->
814
+ ```ts
815
+ interface Fact {
816
+ /** Stable id built from the angle and a sequence number: "tests-3". */
817
+ id: string;
818
+ /** One sentence that can be checked against the repository. */
819
+ claim: string;
820
+ /** Where the researcher saw it: a path with a line, or a command and its output. */
821
+ source: string;
822
+ /** The research angle it came from. */
823
+ angle: string;
824
+ }
825
+ interface Research {
826
+ facts: { claim: string; source: string }[];
827
+ }
828
+ interface Verdict {
829
+ /** True only when you confirmed the claim yourself from the source given. */
830
+ holds: boolean;
831
+ /** What you did to check, one sentence. */
832
+ note: string;
833
+ }
834
+ interface Finding {
835
+ /** Where the fact lives: the source the verifier confirmed. */
836
+ where: string;
837
+ /** The fact, one sentence. */
838
+ what: string;
839
+ /** How the verifier confirmed it. */
840
+ evidence: string;
841
+ /** Every finding here was confirmed by a verifier that did not do the research. */
842
+ status: "verified";
843
+ }
844
+ interface Draft {
845
+ /** The report in markdown, for the user. */
846
+ markdown: string;
847
+ /** Two or three sentences a reader can act on. */
848
+ summary: string;
849
+ }
850
+ interface WorkflowReport {
851
+ /** Two or three sentences answering what the user asked for. */
852
+ conclusion: string;
853
+ findings: Finding[];
854
+ /** What the run checked and how. */
855
+ verified: string[];
856
+ /** What the run did not look at or could not check, and why. */
857
+ notCovered: string[];
858
+ }
859
+
860
+ const topic = String(args.topic ?? "this repository");
861
+ const angles = ["architecture", "data flow", "error handling", "tests", "history"];
862
+
863
+ // The hand-off between research and verification: a researcher that is still reading keeps
864
+ // sending while verifiers already work on what has landed. The research stage owns the close.
865
+ const facts = channel<Fact>("facts");
866
+ const passed: Finding[] = [];
867
+ const rejected: string[] = [];
868
+
869
+ const research = future(async () => {
870
+ phase("Research the topic from five angles");
871
+ try {
872
+ await Promise.all(
873
+ angles.map(async (angle) => {
874
+ const found = await agent(
875
+ `researcher-${angle}`,
876
+ "You research a codebase and state only what you saw, each fact with the place you saw it.",
877
+ ).ask<Research>(
878
+ `Research ${topic} from the angle of ${angle}. Return up to eight facts, each with its source.`,
879
+ );
880
+ found.facts.forEach((fact, index) => facts.send({ ...fact, id: `${angle}-${index + 1}`, angle }));
881
+ log(`${angle}: ${found.facts.length} facts found`);
882
+ }),
883
+ );
884
+ } finally {
885
+ facts.close(); // a failed researcher still ends the stream for the verifiers
886
+ }
887
+ });
888
+
889
+ const verify = future(async () => {
890
+ phase("Check each fact as it arrives");
891
+ // A fresh verifier per fact, named after it: cache identity stays per fact on a revised
892
+ // run, and the name says which fact each card is about.
893
+ const checks: Promise<void>[] = [];
894
+ for await (const fact of facts) {
895
+ checks.push(
896
+ future(async () => {
897
+ const verdict = await agent(
898
+ `verifier-${fact.id}`,
899
+ "You check one claim about a codebase against its source. Do not edit any file.",
900
+ ).ask<Verdict>(`Does this hold? Read the source yourself.\n${JSON.stringify(fact)}`);
901
+ if (verdict.holds) {
902
+ const finding: Finding = { where: fact.source, what: fact.claim, evidence: verdict.note, status: "verified" };
903
+ passed.push(finding);
904
+ report(finding); // published now, so it survives a later failure
905
+ } else {
906
+ rejected.push(`${fact.claim} (${verdict.note})`);
907
+ }
908
+ }),
909
+ );
910
+ }
911
+ // The join is what tells this stage it is done: without it the stage ends when the channel
912
+ // closes, with checks still running and half the results missing.
913
+ await Promise.all(checks);
914
+ });
915
+
916
+ // Start both, then join once. No await in between: while the script awaits one stage, a
917
+ // failure in the other has no listener and surfaces as an unhandled rejection instead of
918
+ // failing the run with its error.
919
+ await Promise.all([research, verify]);
920
+ log(`${passed.length} facts verified, ${rejected.length} did not hold`);
921
+
922
+ phase("Write the report from the verified facts");
923
+ const draft = await agent(
924
+ "writer",
925
+ "You write short technical reports for engineers from verified facts only.",
926
+ ).ask<Draft>(`Write a report on ${topic} from these verified facts:\n${JSON.stringify(passed)}`);
927
+ await artifact.markdown("report", draft.markdown, { title: `What we know about ${topic}` });
928
+
929
+ const result: WorkflowReport = {
930
+ conclusion: draft.summary,
931
+ findings: passed,
932
+ verified: [`${passed.length} facts each re-checked against their source by a separate subagent`],
933
+ notCovered: rejected.length > 0 ? rejected.map((claim) => `did not hold on re-check: ${claim}`) : [],
934
+ };
935
+ return result;
936
+ ```
937
+
938
+ Two stages as futures, one channel, one join. Each future opens with its own phase marker,
939
+ and stamping is lexical, so the two stages that run at the same time keep their own steps on
940
+ the timeline. The research stage owns `facts.close()` in a `finally`: a researcher that fails
941
+ still ends the stream, so the verifiers finish instead of parking on a channel nobody will
942
+ send to. The verifiers are fresh and named per fact rather than pooled, because the facts are
943
+ independent and a revised run should miss the cache for one changed fact, not for the whole
944
+ pool. The `checks` array is the part people forget: the verify stage is done when its
945
+ verifiers are, not when the channel closes, and the deadlock detector cannot catch a stage that
946
+ returns early with work still in flight.
947
+
948
+ ---
949
+
950
+ ## 7. Repository guide grown step by step through tail holes
951
+
952
+ The task — "write a guide to this repository" — has no workflow until the repository has
953
+ been looked at. So the script does the one thing it can plan, the survey, and ends in a tail
954
+ hole. Two fills later the run has six chapter writers, an independent reader, a reviser and a
955
+ published guide, none of which the seed script named. (`SKILL.md` §15.)
956
+
957
+ The seed script, submitted with `create_workflow`:
958
+
959
+ <!-- compile -->
960
+ ```ts
961
+ interface Dir {
962
+ /** Workspace-relative path of a top-level entry. */
963
+ path: string;
964
+ /** One sentence: what it is for. */
965
+ purpose: string;
966
+ }
967
+ interface Survey {
968
+ dirs: Dir[];
969
+ }
970
+ interface Chapter {
971
+ title: string;
972
+ /** Paths the chapter actually covers. */
973
+ covers: string[];
974
+ /** Body, Markdown, for a first-time reader. */
975
+ body: string;
976
+ }
977
+ interface Guide {
978
+ title: string;
979
+ chapters: Chapter[];
980
+ notCovered: string[];
981
+ }
982
+
983
+ phase("盘点仓库顶层目录");
984
+ const surveyor = agent("勘察员", "你快速摸清一个仓库的结构:实际查看目录和关键文件,如实汇报。");
985
+ const survey = await surveyor.ask<Survey>("列出顶层目录(跳过 .venv、.dsh 等产物),各用一句话说明作用。");
986
+ log(`盘点完成:${survey.dirs.length} 个条目`);
987
+
988
+ return await hole<Guide>(
989
+ "第1步:决定导览结构",
990
+ `盘点:\n${survey.dirs.map((d) => `- ${d.path}:${d.purpose}`).join("\n")}`,
991
+ );
992
+ ```
993
+
994
+ The run reaches the hole and the notification carries the survey in the prompt. The first
995
+ fill (the statements only, sent as `script`) decides the chapters, fans out a writer per
996
+ directory and leaves the next hole:
997
+
998
+ ```ts
999
+ phase("分章并行撰写初稿");
1000
+ // The critic in the next step reads every chapter at once, so this join waits for all.
1001
+ const drafts = await Promise.all(
1002
+ survey.dirs.map((d) =>
1003
+ agent(`写手·${d.path}`, "你只写自己打开核实过的内容。").ask<Chapter>(
1004
+ `写《仓库导览》的「${d.path}」一章(200–400 字 Markdown):${d.purpose}。covers 如实填写。`,
1005
+ ),
1006
+ ),
1007
+ );
1008
+ log(`${drafts.length} 章初稿完成`);
1009
+ return await hole<Guide>(
1010
+ "第2步:审读与交付",
1011
+ `${drafts.length} 章初稿已就绪:${drafts.map((d) => d.title).join("、")}`,
1012
+ );
1013
+ ```
1014
+
1015
+ The second fill reads `drafts` from the enclosing scope, adds an independent read and a
1016
+ revision, publishes the guide and returns it, which closes the chain:
1017
+
1018
+ ```ts
1019
+ phase("独立审读初稿");
1020
+ const critique = await agent("审读员", "你只依据文本挑毛病,不读仓库,不夸奖。").ask<string>(
1021
+ `逐章挑毛病:\n${drafts.map((d) => `## ${d.title}\n${d.body}`).join("\n\n")}`,
1022
+ );
1023
+ phase("按审读意见修订并交付");
1024
+ const chapters = await agent("修订编辑").ask<Chapter[]>(
1025
+ `按意见修订,保持章序:${critique}\n\n${JSON.stringify(drafts)}`,
1026
+ );
1027
+ const guide: Guide = { title: "仓库导览", chapters, notCovered: [".venv、.dsh 等产物目录未纳入"] };
1028
+ await artifact.markdown("guide", chapters.map((c) => `## ${c.title}\n\n${c.body}`).join("\n\n"), {
1029
+ title: guide.title,
1030
+ description: "按目录分章的仓库导览。",
1031
+ primary: true,
1032
+ });
1033
+ return guide;
1034
+ ```
1035
+
1036
+ After both fills the run's draft holds the effective script — the seed with each body spliced
1037
+ in as the last argument of its hole — which is what a resume replays and an amend revises:
1038
+
1039
+ <!-- compile -->
1040
+ ```ts
1041
+ interface Dir {
1042
+ /** Workspace-relative path of a top-level entry. */
1043
+ path: string;
1044
+ /** One sentence: what it is for. */
1045
+ purpose: string;
1046
+ }
1047
+ interface Survey {
1048
+ dirs: Dir[];
1049
+ }
1050
+ interface Chapter {
1051
+ title: string;
1052
+ /** Paths the chapter actually covers. */
1053
+ covers: string[];
1054
+ /** Body, Markdown, for a first-time reader. */
1055
+ body: string;
1056
+ }
1057
+ interface Guide {
1058
+ title: string;
1059
+ chapters: Chapter[];
1060
+ notCovered: string[];
1061
+ }
1062
+
1063
+ phase("盘点仓库顶层目录");
1064
+ const surveyor = agent("勘察员", "你快速摸清一个仓库的结构:实际查看目录和关键文件,如实汇报。");
1065
+ const survey = await surveyor.ask<Survey>("列出顶层目录(跳过 .venv、.dsh 等产物),各用一句话说明作用。");
1066
+ log(`盘点完成:${survey.dirs.length} 个条目`);
1067
+
1068
+ return await hole<Guide>(
1069
+ "第1步:决定导览结构",
1070
+ `盘点:\n${survey.dirs.map((d) => `- ${d.path}:${d.purpose}`).join("\n")}`, async () => {
1071
+ phase("分章并行撰写初稿");
1072
+ // The critic in the next step reads every chapter at once, so this join waits for all.
1073
+ const drafts = await Promise.all(
1074
+ survey.dirs.map((d) =>
1075
+ agent(`写手·${d.path}`, "你只写自己打开核实过的内容。").ask<Chapter>(
1076
+ `写《仓库导览》的「${d.path}」一章(200–400 字 Markdown):${d.purpose}。covers 如实填写。`,
1077
+ ),
1078
+ ),
1079
+ );
1080
+ log(`${drafts.length} 章初稿完成`);
1081
+ return await hole<Guide>(
1082
+ "第2步:审读与交付",
1083
+ `${drafts.length} 章初稿已就绪:${drafts.map((d) => d.title).join("、")}`, async () => {
1084
+ phase("独立审读初稿");
1085
+ const critique = await agent("审读员", "你只依据文本挑毛病,不读仓库,不夸奖。").ask<string>(
1086
+ `逐章挑毛病:\n${drafts.map((d) => `## ${d.title}\n${d.body}`).join("\n\n")}`,
1087
+ );
1088
+ phase("按审读意见修订并交付");
1089
+ const chapters = await agent("修订编辑").ask<Chapter[]>(
1090
+ `按意见修订,保持章序:${critique}\n\n${JSON.stringify(drafts)}`,
1091
+ );
1092
+ const guide: Guide = { title: "仓库导览", chapters, notCovered: [".venv、.dsh 等产物目录未纳入"] };
1093
+ await artifact.markdown("guide", chapters.map((c) => `## ${c.title}\n\n${c.body}`).join("\n\n"), {
1094
+ title: guide.title,
1095
+ description: "按目录分章的仓库导览。",
1096
+ primary: true,
1097
+ });
1098
+ return guide;
1099
+ },
1100
+ );
1101
+ },
1102
+ );
1103
+ ```
1104
+
1105
+ What to notice: each step's hole has its own name, because a hole is a phase and two holes
1106
+ with one name would be one phase; the prompts carry only what the next author needs, since
1107
+ the bindings carry the data; and the chain closed at step two because the author decided it
1108
+ was done, not because anything ran out. The writers are named per directory inside the
1109
+ `map`, so a revised run that changes one directory's chapter misses the cache for that one
1110
+ writer only.