Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent 9bc6d53 · Browse files · 4 files+293 added−31 removed
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

4 files+293 added−31 removed

modified:packages/config/test/swarm.test.ts+168 added-4 removed
8 unmodified lines
9import { Ask, AskListing } from "@repo/protocol/domain/ask";10import { ClaimView } from "@repo/protocol/domain/claim";11import { Envelope } from "@repo/protocol/envelope";12import { AskId, KindName, ProjectName } from "@repo/protocol/ids";13import { AskFull } from "@repo/protocol/refusal";14import {15 Array,16 ConfigProvider,17 Console,
35 unmodified lines
53const burrow = ProjectName.make("burrow");5455const ListedAsks = Envelope(Schema.Struct({ asks: Schema.Array(AskListing) }));5657/** What `<cli> claim <ask> --json` prints. */58const Claimed = Envelope(Schema.Struct({ claim: ClaimView }));5960/** What `<cli> ask <ask> --json` prints, when it shows the ask. */61const ShownAsk = Schema.Struct({62 command: Schema.Literal("ask"),63 data: Schema.Struct({ ask: Ask, brief: Schema.NonEmptyString }),
117 unmodified lines
181 }).pipe(Effect.provide(NodeServices.layer))182 );183184 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;189190 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 ]);203204 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 );231232 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 lines
738 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))739 );740});741690/** Why the flags `argv` make no run. */742/** Why the flags `argv` make no run, or `accepted` when they make one. */743const 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 );750751describe("the swarm's flags", () => {752 it.effect(
78 unmodified lines
831 (yield* optionsOf(["--stage", "demo", "--allow-demo"])).stage832 ).toBe("demo");833 })834 );835836 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 );851852 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});873874/** What `main` prints, line by line, over a spawner that answers `asks` with the fixture. */875const dryRun = (argv: readonly string[]) =>
153 unmodified lines
1029 ).toStrictEqual([1030 `nudge for tamsin (video): ${Option.getOrThrow(nudges("video", 1))}`,1031 `nudge for ivo (video): ${Option.getOrThrow(nudges("video", 2))}`,1032 ]);10331034 const videoJson = yield* dryRun([1035 "--stage",1036 "dev-oscabriel",1037 "--dry-run",1038 "--json",1039 "--scenario",1040 "video",1041 "--url",1042 url,1043 ]);10441045 const videoPlan = yield* Schema.decodeEffect(1046 Schema.fromJsonString(SwarmPlan)1047 )(videoJson.printed[0] ?? "");10481049 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 lines
1066 * `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 */955const fullRun = (people: readonly string[]) =>1070const 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 lines
1089 )?.handle;10901091 const fork = `burrow--${ask}--${handle ?? "nobody"}`;10921093 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 }11011102 return JSON.stringify({1103 command: "claim",1104 data: {1105 claim: {
139 unmodified lines
1245 })1246 );12471248 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");12541255 expect(Result.isSuccess(result)).toBeTruthy();12561257 const summary = yield* Schema.decodeEffect(1258 Schema.fromJsonString(AgentsResult)1259 )(Option.getOrElse(agents, () => ""));12601261 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 );12831284 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 lines
modified:scripts/lib/swarm/args.ts+83 added-4 removed
77 unmodified lines
78 argv.flatMap((arg) =>79 arg.startsWith("--") ? [arg.split("=")[0] ?? arg] : []80 );8182const isValued = (flag: string): flag is (typeof VALUED)[number] =>83 VALUED.some((valued) => valued === flag);8485/**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 */89const straysIn = (argv: readonly string[]) => {90 const strays: string[] = [];91 let takes: "none" | "one" | "many" = "none";9293 for (const arg of argv) {94 if (arg.startsWith("--")) {95 const bare = !arg.includes("=");9697 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 }108109 return strays;110};111112/** `raw` as the platform's origin, without a trailing `/`, if it is an http(s) URL. */113const 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, "")));118119const decodeProject = Schema.decodeUnknownOption(ProjectName);120121const decodeScenario = Schema.decodeUnknownOption(ScenarioName);122
8 unmodified lines
131 if (strange.length > 0) {132 return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);133 }134135 // 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 );140141 if (switchValue !== undefined) {142 return yield* failed(143 `${switchValue.split("=")[0] ?? switchValue} takes no value: ${USAGE}`144 );145 }146147 const valueless = VALUED.find(148 (flag) => argv.includes(flag) && Option.isNone(flagValue(argv, flag))149 );150151 if (valueless !== undefined) {152 return yield* failed(`${valueless} needs a value: ${USAGE}`);153 }154155 const strays = straysIn(argv);156157 if (strays.length > 0) {158 return yield* failed(159 `unexpected argument ${strays.join(", ")}: ${USAGE}`160 );161 }162163 // 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 lines
227 )228 )229 );230166 if (argv.includes("--only") && only.length === 0) {231 const onlyGiven = argv.some(232 (arg) => arg === "--only" || arg.startsWith("--only=")233 );234235 if (onlyGiven && only.length === 0) {236 return yield* failed("--only names no contributor");237 }238239 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 );250251 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
modified:scripts/swarm.ts+5 added-15 removed
63 unmodified lines
64 writeAgentsResult,65} from "./lib/swarm/results.ts";66import type { AgentRun } from "./lib/swarm/results.ts";67import { roster } from "./lib/swarm/roster.ts";68import type { Contributor } from "./lib/swarm/roster.ts";69import { nudges } from "./lib/swarm/scenario.ts";68import {69 anonymousEnv,70 cliEntry,71 personEnv,
116 unmodified lines
188189 return listed.asks;190 });191194/** A contributor's position in the whole roster, which the scenarios' nudges go by. */195const rosterIndex = ({ handle }: Contributor) =>196 roster.findIndex((one) => one.handle === handle);197192/** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */193const planLines = (194 plan: SwarmPlan,195 origin: string,
28 unmodified lines
224 column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0)225 )226 .join(" ");227234 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 );233234 return [235 `swarm: ${plan.project} on ${plan.stage} (${origin}), scenario ${plan.scenario}, ${plan.assignments.length} contributors`,
162 unmodified lines
398 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