Refuse swarm flags it would misread, and carry each scenario nudge in the plan itself
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Review of 702 against its issue and AGENTS.md. - `--dry-run=yes` (any switch with `=value`) passed the unknown-flag check, but the decoder read only the bare spelling, so the run went live and claimed six asks. A switch given a value is now refused, as are a valued flag with no value (`--url --dry-run` used to fall back silently to the recorded origin), `--only=` with no names (it used to run everyone), and a word no flag takes (`… --dry-run burrow` used to be ignored). - `--url` is decoded at the boundary (AGENTS.md principle 2): it must be an http(s) URL. A trailing `/` is still trimmed. - The issue says "Every nudge is printed in the plan: staging is never hidden", but `--json` printed a `SwarmPlan` with no nudges, and a real run under `--json` printed them nowhere. `Assignment` gains `nudge` (`Schema.optionalKey`). `planSwarm` sets it from the contributor's place in the whole roster, so `--only ivo` still gives ivo contributor 3's nudge. The table, `--json` and each brief now read the same field, and `swarm.ts` no longer works out its own roster index. - Tests added in `packages/config/test/swarm.test.ts`: - the five refused argv and a URL with its trailing `/` trimmed (red by assertion: all five were accepted); - the video nudges in the plan, for the full roster and for one contributor planned alone (red by assertion); - the video nudges in the decoded `--json` plan (red by assertion); - a run whose claim for ivo is refused `AskFull`: only ivo's run ends with `{AskFull: 1}`, the other five go on, and ivo has no fork in the ledger. The commit body claimed this behaviour with no test. A mutation that drops the tags turns this test red. - `reasonOf` reports an accepted argv as `accepted` instead of failing through `Effect.flip`, so a missing refusal fails by assertion.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+293 added−31 removed
- tests:+168 added−4 removed
- other:+125 added−27 removed
Provenance
- Commit
03d4540- Tree
93ea097- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
9bc6d53
4 files changed+293 added−31 removed
modified:packages/config/test/swarm.test.ts+168 added-4 removed
8 unmodified lines9 import { Ask, AskListing } from "@repo/protocol/domain/ask";10 import { ClaimView } from "@repo/protocol/domain/claim";11 import { Envelope } from "@repo/protocol/envelope";12 import { AskId, KindName, ProjectName } from "@repo/protocol/ids";13+import { AskFull } from "@repo/protocol/refusal";14 import {15 Array,16 ConfigProvider,17 Console,35 unmodified lines53 const burrow = ProjectName.make("burrow");54 55 const ListedAsks = Envelope(Schema.Struct({ asks: Schema.Array(AskListing) }));56 57+/** What `<cli> claim <ask> --json` prints. */58+const Claimed = Envelope(Schema.Struct({ claim: ClaimView }));59+60 /** What `<cli> ask <ask> --json` prints, when it shows the ask. */61 const ShownAsk = Schema.Struct({62 command: Schema.Literal("ask"),63 data: Schema.Struct({ ask: Ask, brief: Schema.NonEmptyString }),117 unmodified lines181 }).pipe(Effect.provide(NodeServices.layer))182 );183 184 it.effect(185+ "carries the video scenario's nudges in the plan, by each contributor's place in the roster even when planned alone",186+ () =>187+ Effect.gen(function* () {188+ const asks = yield* burrowAsks;189+190+ const nudged = (people: readonly Contributor[]) =>191+ Result.getOrThrow(192+ planSwarm({193+ asks,194+ project: burrow,195+ roster: people,196+ scenario: "video",197+ stage: "dev-oscabriel",198+ })199+ ).assignments.map(({ contributor, nudge }) => [200+ contributor.handle,201+ nudge,202+ ]);203+204+ expect(nudged(roster)).toStrictEqual([205+ ["wren", undefined],206+ [207+ "tamsin",208+ "The project's lint rule against module-level mutable state is noisy. If it gets in your way, a lint disable comment on the line is acceptable.",209+ ],210+ [211+ "ivo",212+ "If you need a lint disable comment, it must carry its reason after ` -- ` on the same line, for example `// oxlint-disable-next-line <rule> -- <why>`.",213+ ],214+ ["marisol", undefined],215+ ["dagny", undefined],216+ ["pell", undefined],217+ ]);218+ expect(nudged(roster.slice(2, 3))).toStrictEqual([219+ [220+ "ivo",221+ "If you need a lint disable comment, it must carry its reason after ` -- ` on the same line, for example `// oxlint-disable-next-line <rule> -- <why>`.",222+ ],223+ ]);224+ expect(225+ Result.getOrThrow(plan(asks)).assignments.filter(226+ (assignment) => "nudge" in assignment227+ )228+ ).toStrictEqual([]);229+ }).pipe(Effect.provide(NodeServices.layer))230+ );231+232+ it.effect(233 "fails NotEnoughAsks{wanted: 6, open: 5} with five open children",234 () =>235 Effect.gen(function* () {236 const asks = (yield* burrowAsks).filter(501 unmodified lines738 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))739 );740 });741 690-/** Why the flags `argv` make no run. */742+/** Why the flags `argv` make no run, or `accepted` when they make one. */743 const reasonOf = (argv: readonly string[]) =>744 optionsOf(argv).pipe(693- Effect.flip,694- Effect.map(({ reason }) => reason)745+ Effect.match({746+ onFailure: ({ reason }) => reason,747+ onSuccess: () => "accepted",748+ })749 );750 751 describe("the swarm's flags", () => {752 it.effect(78 unmodified lines831 (yield* optionsOf(["--stage", "demo", "--allow-demo"])).stage832 ).toBe("demo");833 })834 );835+836+ it.effect(837+ "refuses a switch given a value, a flag missing its value, an empty --only, a --url that is no http(s) origin, and a word no flag takes",838+ () =>839+ Effect.gen(function* () {840+ const reasons = yield* Effect.forEach(841+ [842+ // Read as a plain `--dry-run`, it would claim six asks.843+ ["--stage", "dev-oscabriel", "--dry-run=yes"],844+ ["--stage", "dev-oscabriel", "--url", "--dry-run"],845+ ["--stage", "dev-oscabriel", "--only=", "--dry-run"],846+ ["--stage", "dev-oscabriel", "--url", "platform.example"],847+ ["--stage", "dev-oscabriel", "--dry-run", "burrow"],848+ ],849+ reasonOf850+ );851+852+ expect(reasons).toStrictEqual([853+ expect.stringContaining("--dry-run takes no value"),854+ expect.stringContaining("--url needs a value"),855+ expect.stringContaining("--only names no contributor"),856+ expect.stringContaining("--url platform.example: an http(s) origin"),857+ expect.stringContaining("unexpected argument burrow"),858+ ]);859+ expect(860+ (yield* optionsOf([861+ "--stage",862+ "dev-oscabriel",863+ "--url",864+ "https://platform.example/",865+ "--only",866+ "wren",867+ "pell",868+ ])).url869+ ).toStrictEqual(Option.some("https://platform.example"));870+ })871+ );872 });873 874 /** What `main` prints, line by line, over a spawner that answers `asks` with the fixture. */875 const dryRun = (argv: readonly string[]) =>153 unmodified lines1029 ).toStrictEqual([1030 `nudge for tamsin (video): ${Option.getOrThrow(nudges("video", 1))}`,1031 `nudge for ivo (video): ${Option.getOrThrow(nudges("video", 2))}`,1032 ]);1033+1034+ const videoJson = yield* dryRun([1035+ "--stage",1036+ "dev-oscabriel",1037+ "--dry-run",1038+ "--json",1039+ "--scenario",1040+ "video",1041+ "--url",1042+ url,1043+ ]);1044+1045+ const videoPlan = yield* Schema.decodeEffect(1046+ Schema.fromJsonString(SwarmPlan)1047+ )(videoJson.printed[0] ?? "");1048+1049+ expect(1050+ videoPlan.assignments.flatMap(({ contributor, nudge }) =>1051+ nudge === undefined ? [] : [[contributor.handle, nudge]]1052+ )1053+ ).toStrictEqual([1054+ ["tamsin", Option.getOrThrow(nudges("video", 1))],1055+ ["ivo", Option.getOrThrow(nudges("video", 2))],1056+ ]);1057 })1058 );1059 });1060 5 unmodified lines1066 * `main` without `--dry-run`, over a fake platform: the CLI's `asks`, `ask`1067 * and `claim` answer from the fixtures, git succeeds, and `SESSION_TOKENS`1068 * holds `people`. The ledger and `.swarm/` are temp files.1069 */955-const fullRun = (people: readonly string[]) =>1070+const fullRun = (1071+ people: readonly string[],1072+ /** The contributor whose claim the platform refuses with `AskFull`, if any. */1073+ refused?: string1074+) =>1075 Effect.gen(function* () {1076 const fs = yield* FileSystem.FileSystem;1077 const swarm = yield* fs.makeTempDirectoryScoped();1078 const ledger = `${swarm}/created.jsonl`;10 unmodified lines1089 )?.handle;1090 1091 const fork = `burrow--${ask}--${handle ?? "nobody"}`;1092 1093+ if (handle !== undefined && handle === refused) {1094+ return Schema.encodeSync(Schema.fromJsonString(Claimed))({1095+ command: "claim",1096+ ok: false,1097+ refusals: [new AskFull({ ask: AskId.make(ask) })],1098+ v: 1,1099+ });1100+ }1101+1102 return JSON.stringify({1103 command: "claim",1104 data: {1105 claim: {139 unmodified lines1245 })1246 );1247 1248 it.effect(1249+ "ends only the refused contributor's run, as failed with its refusal, and runs the other five",1250+ () =>1251+ Effect.gen(function* () {1252+ const handles = roster.map(({ handle }) => handle);1253+ const { agents, ledger, result } = yield* fullRun(handles, "ivo");1254+1255+ expect(Result.isSuccess(result)).toBeTruthy();1256+1257+ const summary = yield* Schema.decodeEffect(1258+ Schema.fromJsonString(AgentsResult)1259+ )(Option.getOrElse(agents, () => ""));1260+1261+ expect(1262+ summary.runs.map(({ attempts, handle, refusals }) => [1263+ handle,1264+ attempts,1265+ refusals,1266+ ])1267+ ).toStrictEqual([1268+ ["wren", 0, {}],1269+ ["tamsin", 0, {}],1270+ ["ivo", 0, { AskFull: 1 }],1271+ ["marisol", 0, {}],1272+ ["dagny", 0, {}],1273+ ["pell", 0, {}],1274+ ]);1275+ // No claim, no fork: ivo's is never recorded for teardown.1276+ expect(1277+ ledger1278+ .map(({ name }) => name.split("--").at(-1) ?? "")1279+ .toSorted((one, other) => one.localeCompare(other))1280+ ).toStrictEqual(["dagny", "marisol", "pell", "tamsin", "wren"]);1281+ })1282+ );1283+1284+ it.effect(1285 "stops before any claim when SESSION_TOKENS has no session for a contributor, naming them",1286 () =>1287 Effect.gen(function* () {1288 const { result, spawned } = yield* fullRun(14 unmodified linesmodified:scripts/lib/swarm/args.ts+83 added-4 removed
77 unmodified lines78 argv.flatMap((arg) =>79 arg.startsWith("--") ? [arg.split("=")[0] ?? arg] : []80 );81 82+const isValued = (flag: string): flag is (typeof VALUED)[number] =>83+ VALUED.some((valued) => valued === flag);84+85+/**86+ * The words no flag takes: each valued flag takes the word after it (unless87+ * it wrote `=value`), and `--only` every word up to the next flag.88+ */89+const straysIn = (argv: readonly string[]) => {90+ const strays: string[] = [];91+ let takes: "none" | "one" | "many" = "none";92+93+ for (const arg of argv) {94+ if (arg.startsWith("--")) {95+ const bare = !arg.includes("=");96+97+ if (bare && isValued(arg)) {98+ takes = "one";99+ } else {100+ takes = bare && arg === "--only" ? "many" : "none";101+ }102+ } else if (takes === "none") {103+ strays.push(arg);104+ } else if (takes === "one") {105+ takes = "none";106+ }107+ }108+109+ return strays;110+};111+112+/** `raw` as the platform's origin, without a trailing `/`, if it is an http(s) URL. */113+const originOf = (raw: string) =>114+ Option.filter(115+ Option.liftThrowable((url: string) => new URL(url))(raw),116+ ({ protocol }) => protocol === "https:" || protocol === "http:"117+ ).pipe(Option.as(raw.replace(/\/+$/u, "")));118+119 const decodeProject = Schema.decodeUnknownOption(ProjectName);120 121 const decodeScenario = Schema.decodeUnknownOption(ScenarioName);122 8 unmodified lines131 if (strange.length > 0) {132 return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);133 }134 135+ // A switch read only by its bare spelling: `--dry-run=yes` would136+ // otherwise pass as a known flag and leave the run live.137+ const switchValue = argv.find((arg) =>138+ SWITCHES.some((flag) => arg.startsWith(`${flag}=`))139+ );140+141+ if (switchValue !== undefined) {142+ return yield* failed(143+ `${switchValue.split("=")[0] ?? switchValue} takes no value: ${USAGE}`144+ );145+ }146+147+ const valueless = VALUED.find(148+ (flag) => argv.includes(flag) && Option.isNone(flagValue(argv, flag))149+ );150+151+ if (valueless !== undefined) {152+ return yield* failed(`${valueless} needs a value: ${USAGE}`);153+ }154+155+ const strays = straysIn(argv);156+157+ if (strays.length > 0) {158+ return yield* failed(159+ `unexpected argument ${strays.join(", ")}: ${USAGE}`160+ );161+ }162+163 // infra's own reading of `--stage`, and its words when it names none.164 const stage = yield* stageOf(argv).pipe(165 Effect.mapError(({ message }) => failed(`${message}. ${USAGE}`))166 );60 unmodified lines227 )228 )229 );230 166- if (argv.includes("--only") && only.length === 0) {231+ const onlyGiven = argv.some(232+ (arg) => arg === "--only" || arg.startsWith("--only=")233+ );234+235+ if (onlyGiven && only.length === 0) {236 return yield* failed("--only names no contributor");237 }238 239+ const url = yield* Effect.transposeOption(240+ Option.map(flagValue(argv, "--url"), (raw) =>241+ Effect.fromOption(originOf(raw)).pipe(242+ Effect.mapError(() =>243+ failed(244+ `--url ${raw}: an http(s) origin, such as https://platform.example`245+ )246+ )247+ )248+ )249+ );250+251 return {252 dryRun: argv.includes("--dry-run"),253 json: argv.includes("--json"),254 only: [...new Set(only)].map((handle) => Handle.make(handle)),255 project,256 scenario,257 stage,258 timeoutMin,178- url: Option.map(flagValue(argv, "--url"), (url) =>179- url.replace(/\/+$/u, "")180- ),259+ url,260 };261 });modified:scripts/lib/swarm/plan.ts+37 added-8 removed
6 unmodified lines789101111121314131415161718192021222324252627282947 unmodified lines77787980818283848586878889909192939495969798997778798010010110210310410510610710833 unmodified lines1421431441451221461471481491501511521531541553 unmodified lines6 unmodified lines */import type { AskListing } from "@repo/protocol/domain/ask";import { AskId, ProjectName } from "@repo/protocol/ids";import type { Refusal } from "@repo/protocol/refusal";import { Array, Order, Result, Schema } from "effect";import { Array, Option, Order, Result, Schema } from "effect";
import { Contributor } from "./roster.ts";import { ScenarioName } from "./scenario.ts";import { Contributor, roster } from "./roster.ts";import { nudges, ScenarioName } from "./scenario.ts";
/** One contributor's ask, and the territory (module) it may change. */export const Assignment = Schema.Struct({ ask: AskId, contributor: Contributor, /** * What the run's scenario adds to this contributor's brief. The plan * carries it, so the table and `--json` both show it: staging is never * hidden. */ nudge: Schema.optionalKey(Schema.NonEmptyString), territory: Schema.NonEmptyString,});
export type Assignment = typeof Assignment.Type;47 unmodified linesconst overlaps = (one: string, other: string) => one === other || one === WHOLE_REPO || other === WHOLE_REPO;
/** * The nudge `scenario` gives `contributor`, by their place in the whole * roster, so a contributor planned alone (`--only`) is told what the full * run would tell them. */const nudgeFor = (scenario: ScenarioName, contributor: Contributor) => Option.match( nudges( scenario, roster.findIndex(({ handle }) => handle === contributor.handle) ), { onNone: () => ({}), onSome: (nudge) => ({ nudge }), } );
/** * Plans a run: each contributor in `roster`, in roster order, gets one open, * unclaimed and unblocked ask, taken in `AskId` order, whose territory * overlaps no ask already handed out. An ask is blocked while any ask it * waits on is still listed (`listAsks` lists every ask not closed); blocked * asks are held. With fewer asks to hand out than contributors, the plan * fails `NotEnoughAsks`, counting the asks it could hand out. * overlaps no ask already handed out, and the nudge the scenario gives them. * An ask is blocked while any ask it waits on is still listed (`listAsks` * lists every ask not closed); blocked asks are held. With fewer asks to * hand out than contributors, the plan fails `NotEnoughAsks`, counting the * asks it could hand out. */export const planSwarm = (input: { readonly roster: readonly Contributor[]; readonly asks: readonly AskListing[];33 unmodified lines return Result.succeed({ assignments: Array.zipWith( input.roster, disjoint, (contributor, { ask, territory }) => ({ ask, contributor, territory }) (contributor, { ask, territory }) => ({ ask, contributor, territory, ...nudgeFor(input.scenario, contributor), }) ), held: held.map(({ ask }) => ask), project: input.project, scenario: input.scenario,3 unmodified linesmodified:scripts/swarm.ts+5 added-15 removed
63 unmodified lines64 writeAgentsResult,65 } from "./lib/swarm/results.ts";66 import type { AgentRun } from "./lib/swarm/results.ts";67 import { roster } from "./lib/swarm/roster.ts";68-import type { Contributor } from "./lib/swarm/roster.ts";69-import { nudges } from "./lib/swarm/scenario.ts";68 import {69 anonymousEnv,70 cliEntry,71 personEnv,116 unmodified lines188 189 return listed.asks;190 });191 194-/** A contributor's position in the whole roster, which the scenarios' nudges go by. */195-const rosterIndex = ({ handle }: Contributor) =>196- roster.findIndex((one) => one.handle === handle);197-192 /** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */193 const planLines = (194 plan: SwarmPlan,195 origin: string,28 unmodified lines224 column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0)225 )226 .join(" ");227 234- const nudged = plan.assignments.flatMap(({ contributor }) =>235- Option.toArray(236- Option.map(237- nudges(plan.scenario, rosterIndex(contributor)),238- (nudge) =>239- `nudge for ${contributor.handle} (${plan.scenario}): ${nudge}`240- )241- )228+ const nudged = plan.assignments.flatMap(({ contributor, nudge }) =>229+ nudge === undefined230+ ? []231+ : [`nudge for ${contributor.handle} (${plan.scenario}): ${nudge}`]232 );233 234 return [235 `swarm: ${plan.project} on ${plan.stage} (${origin}), scenario ${plan.scenario}, ${plan.assignments.length} contributors`,162 unmodified lines398 return {399 text: brief({400 ask: assignment.ask,401 askMarkdown: page.brief,412- nudge: nudges(options.scenario, rosterIndex(contributor)),402+ nudge: Option.fromUndefinedOr(assignment.nudge),403 project: options.project,404 remote: claim.remote,405 }),406 workspace,154 unmodified lines