@nice-code/commander 0.95.0 → 0.96.0

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.
package/build/cli.mjs CHANGED
@@ -12,10 +12,10 @@ import { createRequire as createRequire$1 } from "module";
12
12
  import { WebSocket as WebSocket$1 } from "ws";
13
13
  import { homedir, networkInterfaces } from "node:os";
14
14
  import { execFile, spawn } from "node:child_process";
15
- import { createInterface } from "node:readline/promises";
15
+ import { connect } from "node:net";
16
16
  import { lookup } from "node:dns/promises";
17
17
  import { promisify } from "node:util";
18
- import { connect } from "node:net";
18
+ import { createInterface } from "node:readline/promises";
19
19
  //#region \0rolldown/runtime.js
20
20
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
21
21
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
@@ -152,7 +152,7 @@ function validStartStamp(value) {
152
152
  function isInstanceRecord(value) {
153
153
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
154
154
  const record = value;
155
- return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && record.protocolVersion === 5;
155
+ return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && record.protocolVersion === 6;
156
156
  }
157
157
  async function writeInstanceRecord(path, record) {
158
158
  await mkdir(dirname(path), {
@@ -202,7 +202,7 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
202
202
  if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
203
203
  if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
204
204
  if (!boundedInt(record["port"], 1, 65535)) return null;
205
- const sameProtocol = record["protocolVersion"] === 5;
205
+ const sameProtocol = record["protocolVersion"] === 6;
206
206
  const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
207
207
  if (sameProtocol && sameRealm) return null;
208
208
  return {
@@ -299,6 +299,102 @@ async function pingDaemon(record, timeoutMs = 2e3) {
299
299
  }
300
300
  }
301
301
  //#endregion
302
+ //#region src/config/tags.ts
303
+ /** `key=value` → `[key, value]`, or null when the term is not tag-shaped. */
304
+ function parseTagTerm(term) {
305
+ const eq = term.indexOf("=");
306
+ return eq > 0 ? [term.slice(0, eq), term.slice(eq + 1)] : null;
307
+ }
308
+ function hasTag(tags, key, value) {
309
+ return tags[key]?.includes(value) === true;
310
+ }
311
+ /** Every entry must match (AND). */
312
+ function matchesTagQuery(tags, query) {
313
+ return Object.entries(query).every(([key, value]) => hasTag(tags, key, value));
314
+ }
315
+ /** Every `key=value` a process carries, in key order. */
316
+ function tagTermsOf(tags) {
317
+ return Object.entries(tags).flatMap(([key, values]) => values.map((value) => `${key}=${value}`));
318
+ }
319
+ //#endregion
320
+ //#region src/config/tagGroups.ts
321
+ /** Which of `terms` these tags carry, in `terms` order. */
322
+ function tagSignature(tags, terms) {
323
+ return terms.filter((term) => {
324
+ const parsed = parseTagTerm(term);
325
+ return parsed != null && tags[parsed[0]]?.includes(parsed[1]) === true;
326
+ });
327
+ }
328
+ /**
329
+ * Bucket by signature: most matched terms first, then by where the signature's terms sit in the
330
+ * filter — never by anything live, so buckets hold still while processes change state. In `any`
331
+ * mode the first bucket is the `all` result whenever anything matches every term.
332
+ */
333
+ function tagGroupsFor(items, terms, mode) {
334
+ const buckets = /* @__PURE__ */ new Map();
335
+ for (const item of items) {
336
+ const signature = tagSignature(item.tags, terms);
337
+ if (signature.length === 0 || mode === "all" && signature.length < terms.length) continue;
338
+ const key = signature.join(",");
339
+ const bucket = buckets.get(key) ?? {
340
+ signature,
341
+ members: []
342
+ };
343
+ bucket.members.push(item);
344
+ buckets.set(key, bucket);
345
+ }
346
+ const rank = (group) => group.signature.map((term) => terms.indexOf(term));
347
+ return [...buckets.values()].sort((a, b) => {
348
+ if (a.signature.length !== b.signature.length) return b.signature.length - a.signature.length;
349
+ const [ra, rb] = [rank(a), rank(b)];
350
+ for (let i = 0; i < ra.length; i += 1) if (ra[i] !== rb[i]) return (ra[i] ?? 0) - (rb[i] ?? 0);
351
+ return 0;
352
+ });
353
+ }
354
+ function sameSignature(a, b) {
355
+ return a.length === b.length && a.every((term) => b.includes(term));
356
+ }
357
+ function savedFilterId(query) {
358
+ const terms = [...query.terms].sort();
359
+ const bucket = query.bucket == null ? "" : `|${[...query.bucket].sort().join(",")}`;
360
+ return `${query.mode}:${terms.join(",")}${bucket}`;
361
+ }
362
+ /** The members a saved filter selects right now. `optIn` processes are never bulk members. */
363
+ function savedFilterMembers(query, items) {
364
+ const groups = tagGroupsFor(items.filter((item) => !item.optIn), [...query.terms].sort(), query.mode);
365
+ const bucket = query.bucket;
366
+ return (bucket == null ? groups : groups.filter((group) => sameSignature(group.signature, bucket))).flatMap((group) => group.members);
367
+ }
368
+ function asTerms(value) {
369
+ if (!Array.isArray(value) || value.length === 0 || value.length > 16) return null;
370
+ const terms = [];
371
+ for (const entry of value) {
372
+ if (typeof entry !== "string" || entry.length > 512 || parseTagTerm(entry) == null) return null;
373
+ if (!terms.includes(entry)) terms.push(entry);
374
+ }
375
+ return terms.sort();
376
+ }
377
+ /** The one place an untrusted value (the wire, or the file) becomes a query. */
378
+ function checkSavedFilterQuery(value) {
379
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return "expected an object";
380
+ const record = { ...value };
381
+ const mode = record["mode"];
382
+ if (mode !== "all" && mode !== "any") return "mode: expected \"all\" | \"any\"";
383
+ const terms = asTerms(record["terms"]);
384
+ if (terms == null) return `terms: expected 1–16 tag=value strings`;
385
+ if (record["bucket"] == null) return {
386
+ mode,
387
+ terms
388
+ };
389
+ const bucket = asTerms(record["bucket"]);
390
+ if (bucket == null || !bucket.every((term) => terms.includes(term))) return "bucket: expected a subset of terms";
391
+ return {
392
+ mode,
393
+ terms,
394
+ bucket
395
+ };
396
+ }
397
+ //#endregion
302
398
  //#region src/config/resolve.ts
303
399
  /** Topological order of the given id set over the dependsOn graph; config order breaks ties. */
304
400
  function orderByDependency(processes, ids) {
@@ -352,40 +448,53 @@ function withDependencies(processes, ids) {
352
448
  * Resolve CLI/UI selection terms against the model. An empty `terms` is the caller's problem
353
449
  * (bare `up` consults `defaultSelection` before ever reaching here).
354
450
  */
355
- function resolveSelection(config, terms, extraIds = []) {
451
+ function resolveSelection(config, terms, options = {}) {
452
+ const extraIds = options.extraIds ?? [];
453
+ const bulk = (id) => options.purpose === "address" || config.processes.find((proc) => proc.id === id)?.optIn !== true;
356
454
  const errors = [];
357
455
  const selectors = /* @__PURE__ */ new Set();
358
456
  const tagTerms = [];
359
457
  for (const term of terms) {
360
- const eq = term.indexOf("=");
361
- if (eq > 0) {
362
- tagTerms.push([term.slice(0, eq), term.slice(eq + 1)]);
458
+ if (term.startsWith("@")) {
459
+ const pin = options.pins?.find((candidate) => candidate.name === term.slice(1));
460
+ if (pin == null) {
461
+ errors.push(`unknown pin "${term}" (pins are saved from the web UI)`);
462
+ continue;
463
+ }
464
+ for (const proc of savedFilterMembers(pin, config.processes)) selectors.add(proc.id);
465
+ continue;
466
+ }
467
+ const tagTerm = parseTagTerm(term);
468
+ if (tagTerm != null) {
469
+ tagTerms.push(tagTerm);
363
470
  continue;
364
471
  }
365
472
  if (term === "all") {
366
- for (const proc of config.processes) selectors.add(proc.id);
473
+ for (const proc of config.processes) if (bulk(proc.id)) selectors.add(proc.id);
367
474
  for (const id of extraIds) selectors.add(id);
368
475
  continue;
369
476
  }
370
- if (config.groups[term] != null) {
371
- for (const id of config.groups[term].ids) selectors.add(id);
477
+ if (config.suites[term] != null) {
478
+ for (const id of config.suites[term].ids) selectors.add(id);
372
479
  continue;
373
480
  }
374
481
  if (config.processes.some((proc) => proc.id === term) || extraIds.includes(term)) {
375
482
  selectors.add(term);
376
483
  continue;
377
484
  }
378
- errors.push(`unknown selection "${term}" (not a process id, group, tag=value, or "all")`);
485
+ errors.push(`unknown selection "${term}" (not a process id, suite, @pin, tag=value, or "all")`);
379
486
  }
380
487
  if (errors.length > 0) return {
381
488
  ok: false,
382
489
  errors
383
490
  };
384
491
  let direct = [...selectors];
385
- if (selectors.size === 0 && tagTerms.length > 0) direct = config.processes.map((proc) => proc.id);
492
+ if (selectors.size === 0 && tagTerms.length > 0) direct = config.processes.filter((proc) => bulk(proc.id)).map((proc) => proc.id);
386
493
  if (tagTerms.length > 0) direct = direct.filter((id) => {
387
494
  const proc = config.processes.find((candidate) => candidate.id === id);
388
- return proc != null && tagTerms.every(([key, value]) => proc.tags[key] === value);
495
+ if (proc == null) return false;
496
+ const matches = ([key, value]) => hasTag(proc.tags, key, value);
497
+ return options.any === true ? tagTerms.some(matches) : tagTerms.every(matches);
389
498
  });
390
499
  const closed = withDependencies(config.processes, direct);
391
500
  const ordered = orderByDependency(config.processes, closed);
@@ -652,6 +761,8 @@ function staleOverrides(config, overrides) {
652
761
  }
653
762
  return stale;
654
763
  }
764
+ const SUITE_PARALLEL_DEFAULT = 4;
765
+ const SUITE_STAGGER_DEFAULT_MS = 100;
655
766
  /** C0/DEL/C1 control characters have no business in tag keys/values or env keys. */
656
767
  function hasControlChars(value) {
657
768
  for (let i = 0; i < value.length; i += 1) {
@@ -661,6 +772,7 @@ function hasControlChars(value) {
661
772
  return false;
662
773
  }
663
774
  const MAX_TAGS = 32;
775
+ const MAX_TAG_VALUES = 16;
664
776
  function isRecord(value) {
665
777
  return typeof value === "object" && value != null && !Array.isArray(value);
666
778
  }
@@ -749,8 +861,52 @@ function findCycle(graph) {
749
861
  }
750
862
  return null;
751
863
  }
752
- function matchesTags(tags, query) {
753
- return Object.entries(query).every(([key, value]) => tags[key] === value);
864
+ /**
865
+ * Expand `include`/`where`/`exclude` over a set of sibling definitions. A `where` never picks up
866
+ * an `optIn` process; an explicit `include` does. Callers guarantee the reference graph is
867
+ * acyclic; `seen` only keeps a malformed one from recursing forever.
868
+ */
869
+ function expandSelection(name, inputs, byId, seen = /* @__PURE__ */ new Set()) {
870
+ const out = /* @__PURE__ */ new Set();
871
+ const input = inputs[name];
872
+ if (seen.has(name) || !isRecord(input)) return out;
873
+ seen.add(name);
874
+ const selection = input;
875
+ for (const entry of selection.include ?? []) if (byId.has(entry)) out.add(entry);
876
+ else if (typeof entry === "string" && entry in inputs) for (const id of expandSelection(entry, inputs, byId, seen)) out.add(id);
877
+ for (const query of normalizeTagQueryOr(selection.where) ?? []) for (const proc of byId.values()) if (!proc.optIn && matchesTagQuery(proc.tags, query)) out.add(proc.id);
878
+ const { ids: excludedIds, queries } = normalizeExcludes(selection.exclude);
879
+ for (const id of excludedIds) out.delete(id);
880
+ for (const id of [...out]) {
881
+ const proc = byId.get(id);
882
+ if (proc != null && queries.some((query) => matchesTagQuery(proc.tags, query))) out.delete(id);
883
+ }
884
+ seen.delete(name);
885
+ return out;
886
+ }
887
+ /** The tag selection that picks out exactly `ids`, if one exists — smallest first. */
888
+ function equivalentTagSelection(ids, byId) {
889
+ const [first, ...rest] = [...ids].flatMap((id) => byId.get(id) ?? []);
890
+ if (first == null) return null;
891
+ const common = tagTermsOf(first.tags).filter((term) => rest.every((proc) => tagTermsOf(proc.tags).includes(term)));
892
+ const selects = (terms) => {
893
+ const matched = [...byId.values()].filter((proc) => !proc.optIn && terms.every((term) => tagTermsOf(proc.tags).includes(term)));
894
+ return matched.length === ids.size && matched.every((proc) => ids.has(proc.id));
895
+ };
896
+ for (const term of common) if (selects([term])) return [term];
897
+ return common.length > 1 && selects(common) ? common : null;
898
+ }
899
+ /** `groups` was removed — say what each one becomes instead of just refusing the key. */
900
+ function groupMigrationErrors(groupsInput, byId) {
901
+ const errors = ["groups: removed — processes are organised by tags, and a run-unit is a `suite`. Per group:"];
902
+ for (const name of Object.keys(groupsInput)) {
903
+ const ids = expandSelection(name, groupsInput, byId);
904
+ const tagSelection = equivalentTagSelection(ids, byId);
905
+ if (ids.size < 2) errors.push(`groups.${name}: one member — delete it and use the id "${[...ids][0] ?? "?"}" directly`);
906
+ else if (tagSelection != null) errors.push(`groups.${name}: this is the tag selection \`${tagSelection.join(" ")}\` — delete it and select by tag (pin it in the UI), or move it under \`suites\` if it is a real run-unit`);
907
+ else errors.push(`groups.${name}: move it under \`suites\` unchanged`);
908
+ }
909
+ return errors;
754
910
  }
755
911
  /**
756
912
  * Validate a raw loaded config and build the resolved model. `configDir`/`configPath` are the
@@ -832,16 +988,25 @@ function validateCommanderConfig(raw, anchor) {
832
988
  if (resolved != null) envVars.push(resolved);
833
989
  }
834
990
  for (const declared of envVars) if (declared.default != null) env[declared.name] = declared.default;
835
- const tags = {
991
+ const tagEntries = Object.entries({
836
992
  ...config.defaults?.tags,
837
993
  ...proc.tags
838
- };
839
- const tagEntries = Object.entries(tags);
994
+ });
840
995
  if (tagEntries.length > MAX_TAGS) errors.push(`${at}.tags: ${tagEntries.length} entries exceeds the ${MAX_TAGS} bound`);
996
+ const tags = {};
841
997
  for (const [key, value] of tagEntries) {
842
- if (key === "" || key.length > 64 || hasControlChars(key)) errors.push(`${at}.tags: invalid key ${JSON.stringify(key)}`);
843
- if (typeof value !== "string" || value.length > 256 || hasControlChars(value)) errors.push(`${at}.tags[${JSON.stringify(key)}]: invalid value`);
998
+ if (key === "" || key.length > 64 || key.includes("=") || hasControlChars(key)) errors.push(`${at}.tags: invalid key ${JSON.stringify(key)}`);
999
+ const values = typeof value === "string" ? [value] : value;
1000
+ if (!Array.isArray(values) || values.length === 0 || values.length > MAX_TAG_VALUES) {
1001
+ errors.push(`${at}.tags[${JSON.stringify(key)}]: expected a string or 1–${MAX_TAG_VALUES} strings`);
1002
+ continue;
1003
+ }
1004
+ const clean = [];
1005
+ for (const entry of values) if (typeof entry !== "string" || entry.length > 256 || entry.includes(",") || hasControlChars(entry)) errors.push(`${at}.tags[${JSON.stringify(key)}]: invalid value`);
1006
+ else if (!clean.includes(entry)) clean.push(entry);
1007
+ tags[key] = clean;
844
1008
  }
1009
+ if (proc.optIn != null && typeof proc.optIn !== "boolean") errors.push(`${at}.optIn: expected a boolean`);
845
1010
  const endpoints = [];
846
1011
  const endpointNames = /* @__PURE__ */ new Set();
847
1012
  for (const [endpointIndex, endpoint] of (proc.endpoints ?? []).entries()) {
@@ -926,6 +1091,7 @@ function validateCommanderConfig(raw, anchor) {
926
1091
  envVars,
927
1092
  stdin,
928
1093
  tags,
1094
+ optIn: proc.optIn === true,
929
1095
  dependsOn,
930
1096
  endpoints,
931
1097
  ...proc.url != null ? { url: proc.url } : {},
@@ -943,60 +1109,57 @@ function validateCommanderConfig(raw, anchor) {
943
1109
  for (const [id, deps] of dependsGraph) for (const dep of deps) if (!byId.has(dep)) errors.push(`process "${id}" dependsOn: unknown id "${dep}"`);
944
1110
  const processCycle = findCycle(dependsGraph);
945
1111
  if (processCycle != null) errors.push(`dependsOn cycle: ${processCycle.join(" → ")}`);
946
- const groupsInput = config.groups ?? {};
947
- const groupRefs = /* @__PURE__ */ new Map();
948
- for (const [name, group] of Object.entries(groupsInput)) {
949
- if (!COMMANDER_ID_PATTERN.test(name)) errors.push(`groups.${JSON.stringify(name)}: must match ${COMMANDER_ID_PATTERN}`);
950
- if (name === "all") errors.push(`groups.${name}: "all" is the built-in selector`);
951
- if (byId.has(name)) errors.push(`groups.${name}: collides with a process id`);
952
- if (typeof group !== "object" || group == null || Array.isArray(group)) {
953
- errors.push(`groups.${name}: expected an object`);
1112
+ const removedGroups = raw.groups;
1113
+ if (removedGroups != null) errors.push(...groupMigrationErrors(isRecord(removedGroups) ? removedGroups : {}, byId));
1114
+ const suitesInput = isRecord(config.suites) ? config.suites : {};
1115
+ if (config.suites != null && !isRecord(config.suites)) errors.push("suites: expected an object keyed by suite name");
1116
+ const suiteRefs = /* @__PURE__ */ new Map();
1117
+ for (const [name, suite] of Object.entries(suitesInput)) {
1118
+ const at = `suites.${name}`;
1119
+ if (!COMMANDER_ID_PATTERN.test(name)) errors.push(`suites.${JSON.stringify(name)}: must match ${COMMANDER_ID_PATTERN}`);
1120
+ if (name === "all") errors.push(`${at}: "all" is the built-in selector`);
1121
+ if (byId.has(name)) errors.push(`${at}: collides with a process id`);
1122
+ if (!isRecord(suite)) {
1123
+ errors.push(`${at}: expected an object`);
954
1124
  continue;
955
1125
  }
956
- for (const entry of group.include ?? []) if (typeof entry !== "string") errors.push(`groups.${name}.include: expected id/group strings`);
957
- else if (!byId.has(entry) && !(entry in groupsInput)) errors.push(`groups.${name}.include: unknown id or group "${entry}"`);
958
- const { ids: excludedIds, queries: excludeQueries } = normalizeExcludes(group.exclude);
959
- for (const id of excludedIds) if (!byId.has(id)) errors.push(`groups.${name}.exclude: unknown id "${id}"`);
960
- for (const query of [...normalizeTagQueryOr(group.where) ?? [], ...excludeQueries]) {
961
- if (Object.keys(query).length === 0) warnings.push(`groups.${name}: an empty tag query matches everything`);
962
- for (const [key, value] of Object.entries(query)) if (typeof value !== "string") errors.push(`groups.${name}: tag query ${JSON.stringify(key)} must map to a string`);
963
- }
964
- groupRefs.set(name, (group.include ?? []).filter((entry) => typeof entry === "string" && entry in groupsInput));
965
- }
966
- const groupCycle = findCycle(groupRefs);
967
- if (groupCycle != null) errors.push(`group include cycle: ${groupCycle.join(" → ")}`);
968
- const groups = {};
969
- if (groupCycle == null) {
970
- const expand = (name, seen) => {
971
- if (seen.has(name)) return /* @__PURE__ */ new Set();
972
- seen.add(name);
973
- const group = groupsInput[name];
974
- const out = /* @__PURE__ */ new Set();
975
- if (typeof group === "object" && group != null && !Array.isArray(group)) {
976
- for (const entry of group.include ?? []) if (byId.has(entry)) out.add(entry);
977
- else if (typeof entry === "string" && entry in groupsInput) for (const id of expand(entry, seen)) out.add(id);
978
- for (const query of normalizeTagQueryOr(group.where) ?? []) for (const proc of byId.values()) if (matchesTags(proc.tags, query)) out.add(proc.id);
979
- const { ids: excludedIds, queries } = normalizeExcludes(group.exclude);
980
- for (const id of excludedIds) out.delete(id);
981
- if (queries.length > 0) for (const id of out) {
982
- const proc = byId.get(id);
983
- if (proc != null && queries.some((query) => matchesTags(proc.tags, query))) out.delete(id);
984
- }
985
- }
986
- seen.delete(name);
987
- return out;
988
- };
989
- for (const name of Object.keys(groupsInput)) {
990
- const expanded = expand(name, /* @__PURE__ */ new Set());
991
- const ordered = [...byId.keys()].filter((id) => expanded.has(id));
992
- if (ordered.length === 0) warnings.push(`groups.${name}: expands to zero processes`);
993
- const staggerMs = groupsInput[name]?.staggerMs;
994
- groups[name] = {
995
- name,
996
- ids: ordered,
997
- staggerMs: typeof staggerMs === "number" ? staggerMs : 100
998
- };
1126
+ const definition = suite;
1127
+ if (definition.description != null && typeof definition.description !== "string") errors.push(`${at}.description: expected a string`);
1128
+ if (definition.parallel != null && (!Number.isInteger(definition.parallel) || definition.parallel < 1)) errors.push(`${at}.parallel: expected an integer ≥ 1`);
1129
+ if (definition.failFast != null && typeof definition.failFast !== "boolean") errors.push(`${at}.failFast: expected a boolean`);
1130
+ if (definition.staggerMs != null && (typeof definition.staggerMs !== "number" || definition.staggerMs < 0)) errors.push(`${at}.staggerMs: expected a non-negative number`);
1131
+ for (const entry of definition.include ?? []) if (typeof entry !== "string") errors.push(`${at}.include: expected id/suite strings`);
1132
+ else if (!byId.has(entry) && !(entry in suitesInput)) errors.push(`${at}.include: unknown id or suite "${entry}"`);
1133
+ const { ids: excludedIds, queries: excludeQueries } = normalizeExcludes(definition.exclude);
1134
+ for (const id of excludedIds) if (!byId.has(id)) errors.push(`${at}.exclude: unknown id "${id}"`);
1135
+ for (const query of [...normalizeTagQueryOr(definition.where) ?? [], ...excludeQueries]) {
1136
+ if (Object.keys(query).length === 0) warnings.push(`${at}: an empty tag query matches everything`);
1137
+ for (const [key, value] of Object.entries(query)) if (typeof value !== "string") errors.push(`${at}: tag query ${JSON.stringify(key)} must map to a string`);
1138
+ }
1139
+ suiteRefs.set(name, (definition.include ?? []).filter((entry) => typeof entry === "string" && entry in suitesInput));
1140
+ }
1141
+ const suiteCycle = findCycle(suiteRefs);
1142
+ if (suiteCycle != null) errors.push(`suite include cycle: ${suiteCycle.join(" → ")}`);
1143
+ const suites = {};
1144
+ if (suiteCycle == null) for (const [name, suite] of Object.entries(suitesInput)) {
1145
+ if (!isRecord(suite)) continue;
1146
+ const definition = suite;
1147
+ const expanded = expandSelection(name, suitesInput, byId);
1148
+ const ordered = [...byId.keys()].filter((id) => expanded.has(id));
1149
+ if (ordered.length < 2) {
1150
+ errors.push(ordered.length === 0 ? `suites.${name}: expands to zero processes` : `suites.${name}: one member — run "${ordered[0]}" directly; use a tag if you wanted a label`);
1151
+ continue;
999
1152
  }
1153
+ const tagSelection = Object.keys(definition).every((key) => key === "where") ? equivalentTagSelection(expanded, byId) : null;
1154
+ if (tagSelection != null && tagSelection.length === 1) warnings.push(`suites.${name}: this is exactly the tag selection \`${tagSelection[0]}\` — a pinned tag group may be all you need`);
1155
+ suites[name] = {
1156
+ name,
1157
+ ...typeof definition.description === "string" ? { description: definition.description } : {},
1158
+ ids: ordered,
1159
+ parallel: definition.parallel ?? SUITE_PARALLEL_DEFAULT,
1160
+ failFast: definition.failFast === true,
1161
+ staggerMs: definition.staggerMs ?? SUITE_STAGGER_DEFAULT_MS
1162
+ };
1000
1163
  }
1001
1164
  const portClaims = /* @__PURE__ */ new Map();
1002
1165
  for (const proc of byId.values()) for (const ep of proc.endpoints) {
@@ -1017,7 +1180,7 @@ function validateCommanderConfig(raw, anchor) {
1017
1180
  }
1018
1181
  if (config.defaultSelection != null) {
1019
1182
  const selection = config.defaultSelection;
1020
- if (!byId.has(selection) && !(selection in groups)) errors.push(`defaultSelection: unknown id or group "${selection}"`);
1183
+ if (typeof selection !== "string" || !byId.has(selection) && !(selection in suitesInput) && parseTagTerm(selection) == null) errors.push(`defaultSelection: expected a process id, a suite, or one tag=value term`);
1021
1184
  }
1022
1185
  const watchFiles = [anchor.configPath];
1023
1186
  for (const file of config.watchFiles ?? []) {
@@ -1037,7 +1200,7 @@ function validateCommanderConfig(raw, anchor) {
1037
1200
  const resolvedBase = {
1038
1201
  name,
1039
1202
  processes,
1040
- groups,
1203
+ suites,
1041
1204
  defaultSelection: config.defaultSelection,
1042
1205
  daemon: { port: typeof config.daemon?.port === "number" ? config.daemon.port : 4900 }
1043
1206
  };
@@ -1097,7 +1260,7 @@ async function loadConfigOrExit(configPath) {
1097
1260
  */
1098
1261
  function requireSelectionTerms(ctx) {
1099
1262
  if (ctx.args.positionals.length > 0 || ctx.args.flags.get("--all") === true) return;
1100
- throw new CliExit(EXIT.usage, `${ctx.args.command} requires a selection (ids, group, tag=val) or --all`);
1263
+ throw new CliExit(EXIT.usage, `${ctx.args.command} requires a selection (ids, suite, @pin, tag=val) or --all`);
1101
1264
  }
1102
1265
  function selectOrExit(ctx, options) {
1103
1266
  const { args, config } = ctx;
@@ -1105,19 +1268,24 @@ function selectOrExit(ctx, options) {
1105
1268
  if (args.flags.get("--all") === true) terms = [...terms, "all"];
1106
1269
  if (terms.length === 0) if (options.bare === "default" && config.defaultSelection != null) terms = [config.defaultSelection];
1107
1270
  else if (options.bare === "default") {
1108
- const groups = Object.keys(config.groups);
1109
- throw new CliExit(EXIT.usage, `bare ${args.command}: the config has no defaultSelection. Groups: ${groups.length > 0 ? groups.join(", ") : "(none)"} — or name ids, tag=val, --all`);
1271
+ const suites = Object.keys(config.suites);
1272
+ throw new CliExit(EXIT.usage, `bare ${args.command}: the config has no defaultSelection. Suites: ${suites.length > 0 ? suites.join(", ") : "(none)"} — or name ids, tag=val, --all`);
1110
1273
  } else requireSelectionTerms(ctx);
1111
- const result = resolveSelection(config, terms, options.extraIds ?? []);
1274
+ const result = resolveSelection(config, terms, {
1275
+ extraIds: options.extraIds ?? [],
1276
+ any: args.flags.get("--any") === true,
1277
+ purpose: args.command === "down" || args.command === "logs" ? "address" : "start",
1278
+ pins: ctx.pins ?? []
1279
+ });
1112
1280
  if (!result.ok) throw new CliExit(EXIT.usage, result.errors.join("\n"));
1113
1281
  return result.selection;
1114
1282
  }
1115
- /** Group stagger for a start: the widest stagger among the groups named in the terms. */
1283
+ /** Suite stagger for a start: the widest stagger among the suites named in the terms. */
1116
1284
  function staggerFor(config, terms) {
1117
1285
  let stagger = 0;
1118
1286
  for (const term of terms) {
1119
- const group = config.groups[term];
1120
- if (group != null) stagger = Math.max(stagger, group.staggerMs);
1287
+ const suite = config.suites[term];
1288
+ if (suite != null) stagger = Math.max(stagger, suite.staggerMs);
1121
1289
  }
1122
1290
  return stagger;
1123
1291
  }
@@ -5163,7 +5331,7 @@ function reject(reason, id) {
5163
5331
  /**
5164
5332
  * The machine-readable reject id an untrusted verify key produces: the presented key differs from
5165
5333
  * the one pinned for this client identity (trust-on-first-use). Carried on the reject frame's `id`
5166
- * and surfaced to the dialing side as `err_nice_wire_connect.identity_pin_mismatch`, so an app can
5334
+ * and surfaced to the dialing side as `err_wire_connect` id `identity_pin_mismatch`, so an app can
5167
5335
  * branch on it (`err.hasId("identity_pin_mismatch")`) — the obvious recovery being "this identity
5168
5336
  * is unusable with this key: clear the client's identity storage / mint a new persistent id".
5169
5337
  */
@@ -5833,6 +6001,9 @@ dropLink: async (opts) => {
5833
6001
  * Close any live long-lived connection (e.g. a WebSocket) before dropping it, so a teardown
5834
6002
  * actually releases the socket instead of leaving it open until GC. HTTP/stateless transports
5835
6003
  * don't implement `disconnect`, so they're simply forgotten.
6004
+ *
6005
+ * @internal Bare cache drop with no redial suppression. Apps call {@link clearTransportCache} or
6006
+ * {@link releaseLink} instead.
5836
6007
  */
5837
6008
  clearCache() {
5838
6009
  for (const entry of this._cache.values()) if (entry instanceof Promise) entry.then((ready) => ready.methods.disconnect?.()).catch(() => {});
@@ -10202,6 +10373,34 @@ var ReliableLog = class {
10202
10373
  }
10203
10374
  return prefix;
10204
10375
  }
10376
+ /**
10377
+ * {@link contiguousPrefix} with each payload's `seq` attached, optionally only the entries after
10378
+ * `afterSeq`. Pruned or compacted seqs are absent, so the first entry's `seq` says where the stored
10379
+ * history now starts.
10380
+ */
10381
+ contiguousEntries(streamId, afterSeq = -1) {
10382
+ const highWater = this._store.getHighWater(streamId);
10383
+ const entries = [];
10384
+ for (let seq = Math.max(afterSeq + 1, 0); seq <= highWater; seq++) {
10385
+ const raw = this._store.getPayload(streamId, seq);
10386
+ if (raw != null) entries.push({
10387
+ seq,
10388
+ payload: this._deserialize(raw)
10389
+ });
10390
+ }
10391
+ return entries;
10392
+ }
10393
+ /**
10394
+ * Delete a stream's stored frames with `seq <= through` (the replay recipe's prune, once the consumer
10395
+ * confirmed them). Clamped to the high-water, so a too-large `through` never touches undelivered frames.
10396
+ * Returns `false` when the store has no `deleteThrough` and nothing was pruned.
10397
+ */
10398
+ pruneThrough(streamId, through) {
10399
+ if (this._store.deleteThrough == null) return false;
10400
+ const clamped = Math.min(through, this._store.getHighWater(streamId));
10401
+ if (clamped >= 0) this._store.deleteThrough(streamId, clamped);
10402
+ return true;
10403
+ }
10205
10404
  };
10206
10405
  /**
10207
10406
  * An in-memory {@link IReliableLogStore} — used by tests to stand in for a Durable Object's SQL storage. It
@@ -10212,7 +10411,7 @@ var ReliableLog = class {
10212
10411
  function createMemoryReliableLogStore() {
10213
10412
  const frames = /* @__PURE__ */ new Map();
10214
10413
  const highWater = /* @__PURE__ */ new Map();
10215
- const key = (streamId, seq) => `${streamId}${seq}`;
10414
+ const key = (streamId, seq) => `${streamId}\u0000${seq}`;
10216
10415
  return {
10217
10416
  insertIgnore: (streamId, seq, payload) => {
10218
10417
  const k = key(streamId, seq);
@@ -10226,7 +10425,7 @@ function createMemoryReliableLogStore() {
10226
10425
  for (let seq = 0; seq <= through; seq++) frames.delete(key(streamId, seq));
10227
10426
  },
10228
10427
  deleteStream: (streamId) => {
10229
- const prefix = `${streamId} `;
10428
+ const prefix = `${streamId}\u0000`;
10230
10429
  for (const k of frames.keys()) if (k.startsWith(prefix)) frames.delete(k);
10231
10430
  highWater.delete(streamId);
10232
10431
  }
@@ -15113,7 +15312,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15113
15312
  this._sendPayload(connection, action, runtime.coordinate);
15114
15313
  runningAction._completeWithResult(action.successResult(void 0));
15115
15314
  } catch (err) {
15116
- runningAction._abort(err);
15315
+ runningAction._abort(this._pushSendError(action.id, err));
15117
15316
  }
15118
15317
  return runningAction;
15119
15318
  }
@@ -15126,10 +15325,19 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15126
15325
  try {
15127
15326
  this._sendPayload(connection, action, runtime.coordinate);
15128
15327
  } catch (err) {
15129
- runningAction._abort(err);
15328
+ runningAction._abort(this._pushSendError(action.id, err));
15130
15329
  }
15131
15330
  return runningAction;
15132
15331
  }
15332
+ /** A failed push send as a typed `send_failed`, keeping the carrier's error as the origin. */
15333
+ _pushSendError(actionId, cause) {
15334
+ if (err_nice_transport.isExact(cause)) return cause;
15335
+ return err_nice_transport.fromId("send_failed", {
15336
+ actionId,
15337
+ actionState: "request",
15338
+ message: cause instanceof Error ? cause.message : String(cause)
15339
+ }).withOriginError(cause);
15340
+ }
15133
15341
  /** Encode + send one payload; returns the encoded frame's size so a logger can report it. */
15134
15342
  _sendPayload(connection, payload, localClient, reliability) {
15135
15343
  const encoding = this._connEncoding.get(connection) ?? "binary";
@@ -16006,8 +16214,10 @@ function deriveDictionaryVersion(domains) {
16006
16214
  * Declare a transport-agnostic channel by role — the single source of truth both peers share. Each end
16007
16215
  * MUST call this with the same domains in the same order (the binary wire dictionary is positional); the
16008
16216
  * `dictionaryVersion` is derived from those domains unless you pin an explicit one. The wire dictionary
16009
- * spans `[...toAcceptor, ...toConnector]` in that order, so add new domains to the end of their list to
16010
- * keep older peers compatible.
16217
+ * spans `[...toAcceptor, ...toConnector]` in that order. Any change to the domains or their actions moves
16218
+ * the derived version, and the handshake rejects a peer whose version differs, so deploy both ends
16219
+ * together. Appending stays compatible with older peers only under a hand-pinned `dictionaryVersion`
16220
+ * you leave unchanged, and only when the additions come last in the whole dictionary.
16011
16221
  *
16012
16222
  * Declare the domains *by role* — `toAcceptor` (connector→acceptor requests) and `toConnector`
16013
16223
  * (acceptor→connector pushes) — so the routing for both ends is derived from the channel (see
@@ -16710,7 +16920,7 @@ function serveChannel(runtime, channel, options) {
16710
16920
  const pushToClient = (target, request, pushOptions) => {
16711
16921
  if (disposed) throw new Error("serveChannel: server disposed");
16712
16922
  const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
16713
- if (owner == null) throw new Error("serveChannel: no duplex carrier holds a connection for the push target");
16923
+ if (owner == null) throw err_nice_transport.fromId("not_found", { actionId: target instanceof RuntimeCoordinate ? target.stringId : "push-target-connection" });
16714
16924
  return owner.pushToClient(runtime, target, request, pushOptions);
16715
16925
  };
16716
16926
  const broadcast = (makeRequest, broadcastOptions) => {
@@ -18672,11 +18882,11 @@ const err_realm = err_nice.createChildDomain({
18672
18882
  message: ({ lastKnownVersion, oldestReplayable }) => `Version ${lastKnownVersion} is behind the replayable window (oldest ${oldestReplayable}) — full rehydration required.`,
18673
18883
  context: { required: true }
18674
18884
  }),
18675
- /** A `realm.update()` ran before the first hydrate (PLAN-FEATURE-COMPLETE §1.1): the
18676
- * projection is still `{}`, so the draft has nothing to write into. Await
18677
- * `realm.whenLive()` first — or use `assertOnAttach` for state that must exist on attach. */
18885
+ /** A write or intent made before the first hydrate is queued for it; this is the queued
18886
+ * handle's rejection when that hydrate never came (the realm detached, or `pendingExpiryMs`
18887
+ * passed first). Definite: nothing was sent. A refused attach rejects with the attach error. */
18678
18888
  write_before_hydrate: err({
18679
- message: ({ realmId }) => `realm.update() on "${realmId}" before the first hydrate — the store is still empty. Await realm.whenLive() before writing (or use the assertOnAttach connect option for state that must exist whenever this avatar is attached).`,
18889
+ message: ({ realmId }) => `A write on "${realmId}" was queued for the first hydrate, which never arrived (the realm detached, or the pending expiry passed first) — nothing was sent.`,
18680
18890
  context: { required: true }
18681
18891
  }),
18682
18892
  /**
@@ -19837,7 +20047,7 @@ const DEFAULT_PROBE_REPLY_TIMEOUT_MS = 1e4;
19837
20047
  function connectRealm(realm, options) {
19838
20048
  const coordinate = options.connection.coordinate;
19839
20049
  const persistentId = options.avatar.persistentId ?? coordinate?.perId;
19840
- if (persistentId == null) throw new Error("connectRealm: no avatar identity — pass avatar.persistentId, or attach through a connection that carries the local coordinate (realmConnection(connector), with the connection returned by connectChannel).");
20050
+ if (persistentId == null) throw new Error("connectRealm: no avatar identity — the connection carries no persistent id. Give it one where you open the connection (identity: coord.specify({ perId })), or pass avatar.persistentId explicitly.");
19841
20051
  const avatar = {
19842
20052
  type: options.avatar.type,
19843
20053
  persistentId,
@@ -19878,8 +20088,10 @@ function connectRealm(realm, options) {
19878
20088
  if (next === "live") hasBeenLive = true;
19879
20089
  for (const listener of [...statusListeners]) listener(next, { hasBeenLive });
19880
20090
  devtools?.onStatus?.(next, { hasBeenLive });
20091
+ if (next === "detached") rejectHydrateQueue();
19881
20092
  };
19882
20093
  let pending = [];
20094
+ const hydrateQueue = [];
19883
20095
  let nextSeq = 0;
19884
20096
  let flushScheduled = false;
19885
20097
  let projecting = false;
@@ -20341,8 +20553,7 @@ function connectRealm(realm, options) {
20341
20553
  if (coalesceWindowMs > 0) unrefTimer(setTimeout(flushOutbox, coalesceWindowMs));
20342
20554
  else queueMicrotask(flushOutbox);
20343
20555
  };
20344
- const rejectImmediately = (kind, error, intentName) => {
20345
- const controller = createWriteHandle();
20556
+ const rejectUnsent = (controller, kind, error, intentName) => {
20346
20557
  controller.reject(error);
20347
20558
  emitRejection({
20348
20559
  error,
@@ -20360,6 +20571,56 @@ function connectRealm(realm, options) {
20360
20571
  });
20361
20572
  return controller.handle;
20362
20573
  };
20574
+ const rejectImmediately = (kind, error, intentName) => rejectUnsent(createWriteHandle(), kind, error, intentName);
20575
+ const neverHydratedError = () => attachError ?? err_realm.fromId("write_before_hydrate", { realmId: realm.id });
20576
+ const rejectQueued = (queued, error) => {
20577
+ if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
20578
+ rejectUnsent(queued.controller, queued.kind, error, queued.intentName);
20579
+ };
20580
+ const mustQueueUntilHydrate = () => confirmedVersion === -1 || hydrateQueue.length > 0;
20581
+ const queueUntilHydrate = (queuedWrite, durability) => {
20582
+ const controller = createWriteHandle();
20583
+ if (status === "detached") return rejectUnsent(controller, queuedWrite.kind, neverHydratedError(), queuedWrite.intentName);
20584
+ const queued = {
20585
+ ...queuedWrite,
20586
+ controller,
20587
+ expiryTimer: void 0
20588
+ };
20589
+ if (durability !== "reassert") {
20590
+ queued.expiryTimer = setTimeout(() => {
20591
+ const index = hydrateQueue.indexOf(queued);
20592
+ if (index < 0) return;
20593
+ hydrateQueue.splice(index, 1);
20594
+ rejectQueued(queued, neverHydratedError());
20595
+ notifyPending();
20596
+ }, expiryMs);
20597
+ unrefTimer(queued.expiryTimer);
20598
+ }
20599
+ hydrateQueue.push(queued);
20600
+ notifyPending();
20601
+ return controller.handle;
20602
+ };
20603
+ const drainHydrateQueue = () => {
20604
+ for (let queued = hydrateQueue.shift(); queued != null; queued = hydrateQueue.shift()) {
20605
+ if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
20606
+ const { controller } = queued;
20607
+ let sent;
20608
+ try {
20609
+ sent = queued.run();
20610
+ } catch (cause) {
20611
+ console.error(`${warnTag()} a write queued before the first hydrate threw`, cause);
20612
+ rejectQueued(queued, castNiceError(cause));
20613
+ continue;
20614
+ }
20615
+ const settled = sent;
20616
+ settled.then(controller.confirm, () => {
20617
+ if (settled.error != null) controller.reject(settled.error);
20618
+ });
20619
+ }
20620
+ };
20621
+ const rejectHydrateQueue = () => {
20622
+ for (const queued of hydrateQueue.splice(0)) rejectQueued(queued, neverHydratedError());
20623
+ };
20363
20624
  const enqueueWrite = (patches, writeOptions) => {
20364
20625
  const durability = writeOptions?.durability;
20365
20626
  const immediate = writeOptions?.flush === "immediate";
@@ -20412,19 +20673,8 @@ function connectRealm(realm, options) {
20412
20673
  } else scheduleFlush();
20413
20674
  return controller.handle;
20414
20675
  };
20415
- const update = (fn, updateOptions) => {
20676
+ const applyUpdate = (fn, updateOptions) => {
20416
20677
  const projected = store.state;
20417
- if (confirmedVersion === -1) {
20418
- const error = err_realm.fromId("write_before_hydrate", { realmId: realm.id });
20419
- try {
20420
- produceWithPatches(projected, (draft) => {
20421
- fn(draft);
20422
- });
20423
- } catch (cause) {
20424
- throw new Error(error.message, { cause });
20425
- }
20426
- return rejectImmediately("write", error);
20427
- }
20428
20678
  let returned;
20429
20679
  const [next, patches] = produceWithPatches(projected, (draft) => {
20430
20680
  returned = fn(draft);
@@ -20446,7 +20696,16 @@ function connectRealm(realm, options) {
20446
20696
  if (verdict !== true) return rejectImmediately("write", verdict);
20447
20697
  return enqueueWrite(canonical, updateOptions);
20448
20698
  };
20449
- const runIntent = (name, input) => {
20699
+ const update = (fn, updateOptions) => mustQueueUntilHydrate() ? queueUntilHydrate({
20700
+ kind: "write",
20701
+ run: () => applyUpdate(fn, updateOptions)
20702
+ }, updateOptions?.durability) : applyUpdate(fn, updateOptions);
20703
+ const runIntent = (name, input) => mustQueueUntilHydrate() ? queueUntilHydrate({
20704
+ kind: "intent",
20705
+ intentName: name,
20706
+ run: () => sendIntent(name, input)
20707
+ }) : sendIntent(name, input);
20708
+ const sendIntent = (name, input) => {
20450
20709
  const def = realm.intents[name];
20451
20710
  if (def == null) return rejectImmediately("intent", err_realm.fromId("intent_unknown", { intent: name }), name);
20452
20711
  const invalid = validateValue(def.input, input);
@@ -20627,7 +20886,8 @@ function connectRealm(realm, options) {
20627
20886
  if (!isFirstHydrate && realm.transient.length > 0 && options.assertOnAttach != null && !hasPendingSystemAssert()) enqueueSystemAssert(confirmed);
20628
20887
  revalidateAndResendPending();
20629
20888
  project({ fullReplace: true });
20630
- if (options.assertOnAttach != null && !hasPendingSystemAssert()) update(options.assertOnAttach);
20889
+ if (options.assertOnAttach != null && !hasPendingSystemAssert()) applyUpdate(options.assertOnAttach);
20890
+ drainHydrateQueue();
20631
20891
  checkReownWatch();
20632
20892
  return;
20633
20893
  }
@@ -20934,11 +21194,12 @@ function connectRealm(realm, options) {
20934
21194
  }
20935
21195
  const handle = {
20936
21196
  store,
21197
+ avatar,
20937
21198
  update,
20938
21199
  intents: Object.fromEntries(realm.intentNames.map((name) => [name, (input) => runIntent(name, input)])),
20939
21200
  pending: {
20940
21201
  get count() {
20941
- return pending.reduce((n, frame) => frame.isSystemAssert ? n : n + 1, 0);
21202
+ return pending.reduce((n, frame) => frame.isSystemAssert ? n : n + 1, 0) + hydrateQueue.length;
20942
21203
  },
20943
21204
  has(pathPrefix) {
20944
21205
  return pending.some((frame) => !frame.isSystemAssert && frame.patches.some((patch) => patch.path.join(".").startsWith(pathPrefix)));
@@ -23314,7 +23575,8 @@ function commanderStatePaths(dataDir, configKey) {
23314
23575
  upLockPath: join(stateDir, "up.lock"),
23315
23576
  bootLogPath: join(stateDir, "daemon-boot.log"),
23316
23577
  ingestSeqPath: join(stateDir, "ingest-seq"),
23317
- envOverridesPath: join(stateDir, "env-overrides.json")
23578
+ envOverridesPath: join(stateDir, "env-overrides.json"),
23579
+ savedFiltersPath: join(stateDir, "saved-filters.json")
23318
23580
  };
23319
23581
  }
23320
23582
  async function ensureStateDir(paths) {
@@ -23408,7 +23670,8 @@ const commanderStatusRealm = defineRealm({
23408
23670
  degraded: t.boolean(),
23409
23671
  notes: t.array(t.string())
23410
23672
  })),
23411
- tags: t.record(t.id("tag"), t.string()),
23673
+ tags: t.record(t.id("tag"), t.array(t.string())),
23674
+ optIn: t.boolean(),
23412
23675
  detail: t.object({
23413
23676
  command: t.string(),
23414
23677
  cwd: t.string(),
@@ -23434,7 +23697,30 @@ const commanderStatusRealm = defineRealm({
23434
23697
  }))
23435
23698
  })
23436
23699
  })),
23437
- groups: t.record(t.id("groupName"), t.object({ members: t.array(t.string()) }))
23700
+ suites: t.record(t.id("suiteName"), t.object({
23701
+ description: t.optional(t.string()),
23702
+ members: t.array(t.string()),
23703
+ parallel: t.number(),
23704
+ failFast: t.boolean()
23705
+ })),
23706
+ runs: t.record(t.id("runKey"), t.object({
23707
+ suite: t.optional(t.string()),
23708
+ filterId: t.optional(t.string()),
23709
+ startedAt: t.number(),
23710
+ endedAt: t.optional(t.number()),
23711
+ outcome: t.optional(t.union(t.literal("passed"), t.literal("failed"))),
23712
+ previousDurationMs: t.optional(t.number()),
23713
+ members: t.record(t.id("processId"), t.union(t.literal("pending"), t.literal("running"), t.literal("pass"), t.literal("fail"), t.literal("blocked"), t.literal("skipped")))
23714
+ })),
23715
+ savedFilters: t.array(t.object({
23716
+ id: t.string(),
23717
+ name: t.optional(t.string()),
23718
+ mode: t.union(t.literal("all"), t.literal("any")),
23719
+ terms: t.array(t.string()),
23720
+ bucket: t.optional(t.array(t.string())),
23721
+ pinned: t.boolean(),
23722
+ lastRunAt: t.optional(t.number())
23723
+ }))
23438
23724
  },
23439
23725
  rules: (r) => [r.path("**").view(r.everyone).alter(r.serverOnly)]
23440
23726
  });
@@ -23567,7 +23853,7 @@ var CommanderDaemonBootError = class extends Error {
23567
23853
  * a live dev environment, and an upgrade must never be the thing that kills one.
23568
23854
  */
23569
23855
  async function replaceSkewedDaemon(paths, skewed) {
23570
- const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v5${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
23856
+ const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v6${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
23571
23857
  let liveIds = [];
23572
23858
  try {
23573
23859
  liveIds = (await openProcessLedger({
@@ -23818,6 +24104,67 @@ function checkIds(value) {
23818
24104
  const ids = asIdList(record["ids"]);
23819
24105
  return ids == null ? "ids: expected an array of process ids" : { ids };
23820
24106
  }
24107
+ function checkRunSuite(value) {
24108
+ const record = asRecord(value);
24109
+ if (record == null) return "expected an object";
24110
+ const input = {};
24111
+ const suite = record["suite"];
24112
+ if (suite != null) {
24113
+ if (typeof suite !== "string" || suite === "") return "suite: expected a suite name";
24114
+ input.suite = suite;
24115
+ }
24116
+ if (record["ids"] != null) {
24117
+ const ids = asIdList(record["ids"]);
24118
+ if (ids == null) return "ids: expected an array of process ids";
24119
+ input.ids = ids;
24120
+ }
24121
+ if (input.suite == null === (input.ids == null)) return "expected exactly one of suite | ids";
24122
+ const parallel = record["parallel"];
24123
+ if (parallel != null) {
24124
+ if (typeof parallel !== "number" || !Number.isInteger(parallel) || parallel < 1) return "parallel: expected an integer ≥ 1";
24125
+ input.parallel = parallel;
24126
+ }
24127
+ const failFast = record["failFast"];
24128
+ if (failFast != null) {
24129
+ if (typeof failFast !== "boolean") return "failFast: expected a boolean";
24130
+ input.failFast = failFast;
24131
+ }
24132
+ if (record["filter"] != null) {
24133
+ const filter = checkSavedFilterQuery(record["filter"]);
24134
+ if (typeof filter === "string") return `filter.${filter}`;
24135
+ input.filter = filter;
24136
+ }
24137
+ return input;
24138
+ }
24139
+ function checkRunSuiteReport(value) {
24140
+ const record = asRecord(value);
24141
+ if (record == null || typeof record["accepted"] !== "boolean") return "expected { accepted }";
24142
+ const { runKey, reason } = record;
24143
+ return {
24144
+ accepted: record["accepted"],
24145
+ ...typeof runKey === "string" ? { runKey } : {},
24146
+ ...typeof reason === "string" ? { reason } : {}
24147
+ };
24148
+ }
24149
+ function checkSaveFilter(value) {
24150
+ const record = asRecord(value);
24151
+ if (record == null) return "expected an object";
24152
+ const filter = checkSavedFilterQuery(record["filter"]);
24153
+ if (typeof filter === "string") return `filter.${filter}`;
24154
+ const name = record["name"];
24155
+ if (typeof name !== "string") return "name: expected a string";
24156
+ return {
24157
+ filter,
24158
+ name
24159
+ };
24160
+ }
24161
+ function checkRemoveFilter(value) {
24162
+ const id = asRecord(value)?.["id"];
24163
+ return typeof id === "string" && id !== "" ? { id } : "id: expected a saved filter id";
24164
+ }
24165
+ function checkOk(value) {
24166
+ return asRecord(value)?.["ok"] === true ? { ok: true } : "expected { ok: true }";
24167
+ }
23821
24168
  function checkEmpty(value) {
23822
24169
  return asRecord(value) == null ? "expected an object" : {};
23823
24170
  }
@@ -23898,9 +24245,12 @@ const commanderControlDomain = createActionRootDomain({ domain: "commander" }).c
23898
24245
  start: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
23899
24246
  stop: actionSchema().input({ schema: handSchema(checkIds) }).output({ schema: handSchema(checkReport) }),
23900
24247
  restart: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
24248
+ runSuite: actionSchema().input({ schema: handSchema(checkRunSuite) }).output({ schema: handSchema(checkRunSuiteReport) }),
24249
+ saveFilter: actionSchema().input({ schema: handSchema(checkSaveFilter) }).output({ schema: handSchema(checkOk) }),
24250
+ removeFilter: actionSchema().input({ schema: handSchema(checkRemoveFilter) }).output({ schema: handSchema(checkOk) }),
23901
24251
  setEnv: actionSchema().input({ schema: handSchema(checkSetEnv) }).output({ schema: handSchema(checkEnvReport) }),
23902
24252
  reloadConfig: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkReloadResult) }),
23903
- shutdown: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema((value) => value != null && value.ok === true ? { ok: true } : "expected { ok: true }") })
24253
+ shutdown: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkOk) })
23904
24254
  }
23905
24255
  });
23906
24256
  /** One socket carries control actions (toAcceptor) + the status realm (a mux protocol, D1). */
@@ -23944,7 +24294,7 @@ async function findDaemon(config) {
23944
24294
  async function findSkewedDaemon(config) {
23945
24295
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
23946
24296
  if (skewed == null || !pidAlive$1(skewed.pid)) return null;
23947
- const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v5` : "was started before an upgrade changed the status schema";
24297
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v6` : "was started before an upgrade changed the status schema";
23948
24298
  return {
23949
24299
  message: `the daemon for this config (pid ${skewed.pid}, port ${skewed.port}, build ${skewed.packageVersion}) ${difference} — this CLI (build ${await commanderPackageVersion()}) cannot talk to it. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`,
23950
24300
  pid: skewed.pid,
@@ -24042,7 +24392,7 @@ async function connectDaemon(handle) {
24042
24392
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
24043
24393
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
24044
24394
  const report = parseActionReport(payload.result.output);
24045
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 5`);
24395
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 6`);
24046
24396
  return report;
24047
24397
  },
24048
24398
  setEnv: async (input) => {
@@ -24129,7 +24479,8 @@ async function cmdUp(ctx) {
24129
24479
  const bad = unknownFlags(ctx.args.flags, [
24130
24480
  "--no-wait",
24131
24481
  "--dry-run",
24132
- "--all"
24482
+ "--all",
24483
+ "--any"
24133
24484
  ]);
24134
24485
  if (bad != null) throw new CliExit(EXIT.usage, bad);
24135
24486
  const selection = selectOrExit(ctx, { bare: "default" });
@@ -24163,7 +24514,11 @@ async function cmdUp(ctx) {
24163
24514
  }
24164
24515
  }
24165
24516
  async function controlVerb(ctx, verb) {
24166
- const known = verb === "restart" ? ["--no-wait", "--all"] : ["--all"];
24517
+ const known = verb === "restart" ? [
24518
+ "--no-wait",
24519
+ "--all",
24520
+ "--any"
24521
+ ] : ["--all", "--any"];
24167
24522
  const bad = unknownFlags(ctx.args.flags, known);
24168
24523
  if (bad != null) throw new CliExit(EXIT.usage, bad);
24169
24524
  requireSelectionTerms(ctx);
@@ -24258,6 +24613,85 @@ function reportSignalShutdown(ctx, result) {
24258
24613
  }
24259
24614
  }
24260
24615
  //#endregion
24616
+ //#region src/daemon/envOverrides.ts
24617
+ const STORE_VERSION$1 = 1;
24618
+ /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
24619
+ const MAX_VALUE_LENGTH = 4096;
24620
+ const EMPTY_ENV_OVERRIDES = Object.freeze({});
24621
+ function readable$1(value) {
24622
+ if (value == null || typeof value !== "object") return null;
24623
+ const processes = value.processes;
24624
+ if (processes == null || typeof processes !== "object" || Array.isArray(processes)) return null;
24625
+ const clean = {};
24626
+ for (const [id, values] of Object.entries(processes)) {
24627
+ if (values == null || typeof values !== "object" || Array.isArray(values)) continue;
24628
+ const entries = {};
24629
+ for (const [name, entry] of Object.entries(values)) if (typeof entry === "string" && entry.length <= MAX_VALUE_LENGTH) entries[name] = entry;
24630
+ if (Object.keys(entries).length > 0) clean[id] = entries;
24631
+ }
24632
+ return clean;
24633
+ }
24634
+ /**
24635
+ * Missing, unreadable or corrupt all read as "no overrides". A bad file must never block a start:
24636
+ * the config alone is always enough to run, and the surfaces that report overrides say when the
24637
+ * store could not be read.
24638
+ */
24639
+ async function readEnvOverrides(path) {
24640
+ try {
24641
+ return readable$1(JSON.parse(await readFile(path, "utf8"))) ?? EMPTY_ENV_OVERRIDES;
24642
+ } catch {
24643
+ return EMPTY_ENV_OVERRIDES;
24644
+ }
24645
+ }
24646
+ /** 0600 and atomic — it can hold a token, and a half-written file must never be read as empty. */
24647
+ async function writeEnvOverrides(path, overrides) {
24648
+ await mkdir(dirname(path), {
24649
+ recursive: true,
24650
+ mode: 448
24651
+ });
24652
+ const store = {
24653
+ version: STORE_VERSION$1,
24654
+ processes: Object.fromEntries(Object.entries(overrides).filter(([, values]) => Object.keys(values).length > 0).map(([id, values]) => [id, { ...values }]))
24655
+ };
24656
+ const temp = `${path}.${process.pid}.tmp`;
24657
+ await writeFile(temp, `${JSON.stringify(store, null, 2)}\n`, {
24658
+ encoding: "utf8",
24659
+ mode: 384
24660
+ });
24661
+ await rename(temp, path);
24662
+ }
24663
+ /** Pure: the store that results from applying `change`. Empty processes are pruned. */
24664
+ function mutateEnvOverrides(current, change) {
24665
+ const next = {};
24666
+ for (const [id, values] of Object.entries(current)) next[id] = { ...values };
24667
+ for (const id of change.clear ?? []) delete next[id];
24668
+ for (const [id, values] of Object.entries(change.mutations ?? {})) {
24669
+ const entries = next[id] ?? {};
24670
+ for (const [name, value] of Object.entries(values)) if (value == null) delete entries[name];
24671
+ else entries[name] = value;
24672
+ if (Object.keys(entries).length > 0) next[id] = entries;
24673
+ else delete next[id];
24674
+ }
24675
+ return next;
24676
+ }
24677
+ /**
24678
+ * Read → check against the config → mutate → write, atomically enough for a file two surfaces
24679
+ * touch. The one implementation behind both writers, so the daemon's `setEnv` and the CLI's
24680
+ * no-daemon path can never diverge on what they accept.
24681
+ */
24682
+ async function applyEnvMutation(path, config, input) {
24683
+ const checked = checkEnvMutations(config, input);
24684
+ const next = mutateEnvOverrides(await readEnvOverrides(path), checked);
24685
+ await writeEnvOverrides(path, next);
24686
+ return {
24687
+ overrides: next,
24688
+ warnings: checked.warnings
24689
+ };
24690
+ }
24691
+ function countOverrides(overrides) {
24692
+ return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);
24693
+ }
24694
+ //#endregion
24261
24695
  //#region src/ports/listeners.ts
24262
24696
  const exec = promisify(execFile);
24263
24697
  const ACTIVE = new Set([
@@ -24491,181 +24925,6 @@ function createPortInspector(options) {
24491
24925
  return { run };
24492
24926
  }
24493
24927
  //#endregion
24494
- //#region src/cli/commands/ports.ts
24495
- async function portProcessStates(ctx) {
24496
- const handle = await findDaemon(ctx.config);
24497
- if (!handle) return /* @__PURE__ */ new Map();
24498
- const client = await connectDaemon(handle);
24499
- try {
24500
- return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
24501
- } finally {
24502
- client.dispose();
24503
- }
24504
- }
24505
- async function cmdPorts(ctx) {
24506
- const bad = unknownFlags(ctx.args.flags, [
24507
- "--all",
24508
- "--kill",
24509
- "--yes",
24510
- "--force"
24511
- ]);
24512
- if (bad) throw new CliExit(EXIT.usage, bad);
24513
- const pid = numericFlag(ctx.args.flags, "--kill");
24514
- if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
24515
- for (const flag of [
24516
- "--yes",
24517
- "--force",
24518
- "--all"
24519
- ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
24520
- if (!pid && (ctx.args.flags.has("--force") || ctx.args.flags.has("--yes"))) throw new CliExit(EXIT.usage, "--force/--yes require --kill PID");
24521
- const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
24522
- const inspector = createPortInspector({
24523
- config: () => ctx.config,
24524
- states: () => portProcessStates(ctx),
24525
- protectedPids: async () => {
24526
- const daemon = await findDaemon(ctx.config);
24527
- return daemon ? [daemon.record.pid] : [];
24528
- }
24529
- });
24530
- const report = await inspector.run({ ids });
24531
- const print = (result) => {
24532
- if (ctx.out.json) {
24533
- ctx.out.printJson(result);
24534
- return;
24535
- }
24536
- ctx.out.print(ctx.out.table([
24537
- "PROCESS",
24538
- "ENDPOINT",
24539
- "PID",
24540
- "PARENT",
24541
- "COMMAND",
24542
- "CWD",
24543
- "IDENTITY",
24544
- "STOP"
24545
- ], result.listeners.map((l) => [
24546
- l.id,
24547
- `${l.host}:${l.port}`,
24548
- String(l.pid),
24549
- String(l.ppid ?? "unknown"),
24550
- l.command,
24551
- l.cwd ?? "unavailable",
24552
- l.startStamp ?? "unknown",
24553
- l.refusal ?? "available"
24554
- ])));
24555
- if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
24556
- for (const warning of result.warnings) ctx.out.warn(warning);
24557
- };
24558
- if (!pid) {
24559
- print(report);
24560
- return report.warnings.length ? EXIT.failure : EXIT.ok;
24561
- }
24562
- const target = report.listeners.find((l) => l.pid === pid);
24563
- if (!target?.token) {
24564
- print(report);
24565
- throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
24566
- }
24567
- if (!ctx.args.flags.has("--yes")) {
24568
- print(report);
24569
- if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes with --kill PID");
24570
- const rl = createInterface({
24571
- input: process.stdin,
24572
- output: process.stdout
24573
- });
24574
- try {
24575
- const answer = await rl.question(`${ctx.args.flags.has("--force") ? "Force kill" : "Stop"} PID ${pid} (${target.command}) on ${target.host}:${target.port}? [y/N] `);
24576
- if (!/^y(es)?$/i.test(answer.trim())) return EXIT.ok;
24577
- } finally {
24578
- rl.close();
24579
- }
24580
- }
24581
- const result = await inspector.run({
24582
- ids,
24583
- token: target.token,
24584
- force: ctx.args.flags.has("--force")
24585
- });
24586
- print(result);
24587
- return result.warnings.length ? EXIT.failure : EXIT.ok;
24588
- }
24589
- //#endregion
24590
- //#region src/daemon/envOverrides.ts
24591
- const STORE_VERSION = 1;
24592
- /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
24593
- const MAX_VALUE_LENGTH = 4096;
24594
- const EMPTY_ENV_OVERRIDES = Object.freeze({});
24595
- function readable(value) {
24596
- if (value == null || typeof value !== "object") return null;
24597
- const processes = value.processes;
24598
- if (processes == null || typeof processes !== "object" || Array.isArray(processes)) return null;
24599
- const clean = {};
24600
- for (const [id, values] of Object.entries(processes)) {
24601
- if (values == null || typeof values !== "object" || Array.isArray(values)) continue;
24602
- const entries = {};
24603
- for (const [name, entry] of Object.entries(values)) if (typeof entry === "string" && entry.length <= MAX_VALUE_LENGTH) entries[name] = entry;
24604
- if (Object.keys(entries).length > 0) clean[id] = entries;
24605
- }
24606
- return clean;
24607
- }
24608
- /**
24609
- * Missing, unreadable or corrupt all read as "no overrides". A bad file must never block a start:
24610
- * the config alone is always enough to run, and the surfaces that report overrides say when the
24611
- * store could not be read.
24612
- */
24613
- async function readEnvOverrides(path) {
24614
- try {
24615
- return readable(JSON.parse(await readFile(path, "utf8"))) ?? EMPTY_ENV_OVERRIDES;
24616
- } catch {
24617
- return EMPTY_ENV_OVERRIDES;
24618
- }
24619
- }
24620
- /** 0600 and atomic — it can hold a token, and a half-written file must never be read as empty. */
24621
- async function writeEnvOverrides(path, overrides) {
24622
- await mkdir(dirname(path), {
24623
- recursive: true,
24624
- mode: 448
24625
- });
24626
- const store = {
24627
- version: STORE_VERSION,
24628
- processes: Object.fromEntries(Object.entries(overrides).filter(([, values]) => Object.keys(values).length > 0).map(([id, values]) => [id, { ...values }]))
24629
- };
24630
- const temp = `${path}.${process.pid}.tmp`;
24631
- await writeFile(temp, `${JSON.stringify(store, null, 2)}\n`, {
24632
- encoding: "utf8",
24633
- mode: 384
24634
- });
24635
- await rename(temp, path);
24636
- }
24637
- /** Pure: the store that results from applying `change`. Empty processes are pruned. */
24638
- function mutateEnvOverrides(current, change) {
24639
- const next = {};
24640
- for (const [id, values] of Object.entries(current)) next[id] = { ...values };
24641
- for (const id of change.clear ?? []) delete next[id];
24642
- for (const [id, values] of Object.entries(change.mutations ?? {})) {
24643
- const entries = next[id] ?? {};
24644
- for (const [name, value] of Object.entries(values)) if (value == null) delete entries[name];
24645
- else entries[name] = value;
24646
- if (Object.keys(entries).length > 0) next[id] = entries;
24647
- else delete next[id];
24648
- }
24649
- return next;
24650
- }
24651
- /**
24652
- * Read → check against the config → mutate → write, atomically enough for a file two surfaces
24653
- * touch. The one implementation behind both writers, so the daemon's `setEnv` and the CLI's
24654
- * no-daemon path can never diverge on what they accept.
24655
- */
24656
- async function applyEnvMutation(path, config, input) {
24657
- const checked = checkEnvMutations(config, input);
24658
- const next = mutateEnvOverrides(await readEnvOverrides(path), checked);
24659
- await writeEnvOverrides(path, next);
24660
- return {
24661
- overrides: next,
24662
- warnings: checked.warnings
24663
- };
24664
- }
24665
- function countOverrides(overrides) {
24666
- return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);
24667
- }
24668
- //#endregion
24669
24928
  //#region src/cli/commands/doctor.ts
24670
24929
  function formatAge(ms) {
24671
24930
  if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
@@ -24999,12 +25258,10 @@ async function cmdList(ctx) {
24999
25258
  dependsOn: proc.dependsOn,
25000
25259
  endpoints: proc.endpoints,
25001
25260
  url: proc.url ?? null,
25002
- envVars: proc.envVars
25261
+ envVars: proc.envVars,
25262
+ optIn: proc.optIn
25003
25263
  })),
25004
- groups: Object.fromEntries(Object.entries(config.groups).map(([name, group]) => [name, {
25005
- ids: group.ids,
25006
- staggerMs: group.staggerMs
25007
- }])),
25264
+ suites: Object.fromEntries(Object.entries(config.suites).map(([name, { name: _name, ...suite }]) => [name, suite])),
25008
25265
  warnings: config.warnings
25009
25266
  });
25010
25267
  return EXIT.ok;
@@ -25018,31 +25275,31 @@ async function cmdList(ctx) {
25018
25275
  ], config.processes.map((proc) => [
25019
25276
  proc.id,
25020
25277
  proc.kind,
25021
- Object.entries(proc.tags).map(([key, value]) => `${key}=${value}`).join(" "),
25278
+ [...tagTermsOf(proc.tags), ...proc.optIn ? ["(opt-in)"] : []].join(" "),
25022
25279
  proc.dependsOn.join(" "),
25023
25280
  proc.endpoints.map((endpoint) => `${endpoint.name}:${endpoint.port}`).join(" ")
25024
25281
  ])));
25025
- const groupRows = Object.entries(config.groups).map(([name, group]) => [
25026
- name,
25027
- String(group.ids.length),
25028
- group.ids.join(" "),
25029
- group.staggerMs > 0 ? `${group.staggerMs}ms` : "-"
25282
+ const suiteRows = Object.values(config.suites).map((suite) => [
25283
+ suite.name,
25284
+ String(suite.ids.length),
25285
+ `parallel ${suite.parallel}${suite.failFast ? " · fail-fast" : ""}`,
25286
+ suite.ids.join(" ")
25030
25287
  ]);
25031
- if (groupRows.length > 0) {
25288
+ if (suiteRows.length > 0) {
25032
25289
  out.print("");
25033
25290
  out.print(out.table([
25034
- "GROUP",
25291
+ "SUITE",
25035
25292
  "N",
25036
- "IDS",
25037
- "STAGGER"
25038
- ], groupRows));
25293
+ "POLICY",
25294
+ "IDS"
25295
+ ], suiteRows));
25039
25296
  }
25040
25297
  if (config.defaultSelection != null) out.print(out.paint("gray", `\ndefaultSelection: ${config.defaultSelection}`));
25041
25298
  for (const warning of config.warnings) out.warn(`${out.paint("yellow", "⚠")} ${warning}`);
25042
25299
  return EXIT.ok;
25043
25300
  }
25044
25301
  async function cmdExplain(ctx) {
25045
- const bad = unknownFlags(ctx.args.flags, ["--all"]);
25302
+ const bad = unknownFlags(ctx.args.flags, ["--all", "--any"]);
25046
25303
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25047
25304
  const selection = selectOrExit(ctx, { bare: "default" });
25048
25305
  const { out } = ctx;
@@ -25052,6 +25309,9 @@ async function cmdExplain(ctx) {
25052
25309
  }
25053
25310
  out.print(`direct: ${selection.direct.join(", ") || "(none)"}`);
25054
25311
  out.print(`auto-included: ${selection.autoIncluded.length > 0 ? selection.autoIncluded.join(", ") : "(none)"}`);
25312
+ const [onlyTerm] = ctx.args.positionals.length === 1 ? ctx.args.positionals : [];
25313
+ const suite = onlyTerm == null ? void 0 : ctx.config.suites[onlyTerm];
25314
+ if (suite != null) out.print(`suite policy: parallel ${suite.parallel}, fail-fast ${suite.failFast ? "on" : "off"}, stagger ${suite.staggerMs}ms`);
25055
25315
  out.print(`DAG order:`);
25056
25316
  selection.ordered.forEach((id, index) => {
25057
25317
  out.print(` ${index + 1}. ${id}`);
@@ -25239,6 +25499,7 @@ function printLine(out, entry) {
25239
25499
  }
25240
25500
  async function cmdLogs(ctx) {
25241
25501
  const bad = unknownFlags(ctx.args.flags, [
25502
+ "--any",
25242
25503
  "-f",
25243
25504
  "--follow",
25244
25505
  "--all"
@@ -25303,6 +25564,159 @@ async function cmdLogs(ctx) {
25303
25564
  }
25304
25565
  }
25305
25566
  //#endregion
25567
+ //#region src/cli/commands/ports.ts
25568
+ async function portProcessStates(ctx) {
25569
+ const handle = await findDaemon(ctx.config);
25570
+ if (!handle) return /* @__PURE__ */ new Map();
25571
+ const client = await connectDaemon(handle);
25572
+ try {
25573
+ return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
25574
+ } finally {
25575
+ client.dispose();
25576
+ }
25577
+ }
25578
+ async function cmdPorts(ctx) {
25579
+ const bad = unknownFlags(ctx.args.flags, [
25580
+ "--all",
25581
+ "--kill",
25582
+ "--yes",
25583
+ "--force"
25584
+ ]);
25585
+ if (bad) throw new CliExit(EXIT.usage, bad);
25586
+ const pid = numericFlag(ctx.args.flags, "--kill");
25587
+ if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
25588
+ for (const flag of [
25589
+ "--yes",
25590
+ "--force",
25591
+ "--all"
25592
+ ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
25593
+ if (!pid && (ctx.args.flags.has("--force") || ctx.args.flags.has("--yes"))) throw new CliExit(EXIT.usage, "--force/--yes require --kill PID");
25594
+ const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
25595
+ const inspector = createPortInspector({
25596
+ config: () => ctx.config,
25597
+ states: () => portProcessStates(ctx),
25598
+ protectedPids: async () => {
25599
+ const daemon = await findDaemon(ctx.config);
25600
+ return daemon ? [daemon.record.pid] : [];
25601
+ }
25602
+ });
25603
+ const report = await inspector.run({ ids });
25604
+ const print = (result) => {
25605
+ if (ctx.out.json) {
25606
+ ctx.out.printJson(result);
25607
+ return;
25608
+ }
25609
+ ctx.out.print(ctx.out.table([
25610
+ "PROCESS",
25611
+ "ENDPOINT",
25612
+ "PID",
25613
+ "PARENT",
25614
+ "COMMAND",
25615
+ "CWD",
25616
+ "IDENTITY",
25617
+ "STOP"
25618
+ ], result.listeners.map((l) => [
25619
+ l.id,
25620
+ `${l.host}:${l.port}`,
25621
+ String(l.pid),
25622
+ String(l.ppid ?? "unknown"),
25623
+ l.command,
25624
+ l.cwd ?? "unavailable",
25625
+ l.startStamp ?? "unknown",
25626
+ l.refusal ?? "available"
25627
+ ])));
25628
+ if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
25629
+ for (const warning of result.warnings) ctx.out.warn(warning);
25630
+ };
25631
+ if (!pid) {
25632
+ print(report);
25633
+ return report.warnings.length ? EXIT.failure : EXIT.ok;
25634
+ }
25635
+ const target = report.listeners.find((l) => l.pid === pid);
25636
+ if (!target?.token) {
25637
+ print(report);
25638
+ throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
25639
+ }
25640
+ if (!ctx.args.flags.has("--yes")) {
25641
+ print(report);
25642
+ if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes with --kill PID");
25643
+ const rl = createInterface({
25644
+ input: process.stdin,
25645
+ output: process.stdout
25646
+ });
25647
+ try {
25648
+ const answer = await rl.question(`${ctx.args.flags.has("--force") ? "Force kill" : "Stop"} PID ${pid} (${target.command}) on ${target.host}:${target.port}? [y/N] `);
25649
+ if (!/^y(es)?$/i.test(answer.trim())) return EXIT.ok;
25650
+ } finally {
25651
+ rl.close();
25652
+ }
25653
+ }
25654
+ const result = await inspector.run({
25655
+ ids,
25656
+ token: target.token,
25657
+ force: ctx.args.flags.has("--force")
25658
+ });
25659
+ print(result);
25660
+ return result.warnings.length ? EXIT.failure : EXIT.ok;
25661
+ }
25662
+ //#endregion
25663
+ //#region src/run/scheduler.ts
25664
+ async function runTaskPool(options) {
25665
+ const { failFast } = options;
25666
+ const pending = [...options.tasks];
25667
+ const succeeded = /* @__PURE__ */ new Set();
25668
+ const failed = /* @__PURE__ */ new Set();
25669
+ const running = /* @__PURE__ */ new Set();
25670
+ const selected = new Set(options.tasks.map((task) => task.id));
25671
+ const depsOf = (task) => task.dependsOn.filter((id) => selected.has(id));
25672
+ let cut = false;
25673
+ let waiters = [];
25674
+ const settled = () => new Promise((resolve) => {
25675
+ waiters.push(resolve);
25676
+ });
25677
+ const wake = () => {
25678
+ const current = waiters;
25679
+ waiters = [];
25680
+ for (const resolve of current) resolve();
25681
+ };
25682
+ const workers = Array.from({ length: Math.min(Math.max(1, options.parallel), pending.length) }, async () => {
25683
+ for (;;) {
25684
+ if (cut) return;
25685
+ const index = pending.findIndex((task) => depsOf(task).every((id) => succeeded.has(id) || failed.has(id)));
25686
+ if (index < 0) {
25687
+ if (running.size === 0) return;
25688
+ await settled();
25689
+ continue;
25690
+ }
25691
+ const [task] = pending.splice(index, 1);
25692
+ if (task == null) return;
25693
+ const blockedBy = depsOf(task).find((id) => failed.has(id));
25694
+ if (blockedBy != null) {
25695
+ failed.add(task.id);
25696
+ options.onBlocked(task, blockedBy);
25697
+ wake();
25698
+ continue;
25699
+ }
25700
+ running.add(task.id);
25701
+ const ok = await options.run(task);
25702
+ running.delete(task.id);
25703
+ (ok ? succeeded : failed).add(task.id);
25704
+ if (!ok && failFast && !cut) {
25705
+ cut = true;
25706
+ options.onFailFast?.();
25707
+ }
25708
+ wake();
25709
+ if (cut) return;
25710
+ }
25711
+ });
25712
+ await Promise.all(workers);
25713
+ return {
25714
+ succeeded,
25715
+ failed,
25716
+ leftover: pending
25717
+ };
25718
+ }
25719
+ //#endregion
25306
25720
  //#region src/cli/commands/run.ts
25307
25721
  const ACTIVE_STATES$1 = new Set([
25308
25722
  "starting",
@@ -25367,14 +25781,17 @@ async function cmdRun(ctx) {
25367
25781
  const bad = unknownFlags(ctx.args.flags, [
25368
25782
  "--parallel",
25369
25783
  "--fail-fast",
25370
- "--all"
25784
+ "--all",
25785
+ "--any"
25371
25786
  ]);
25372
25787
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25373
25788
  const parallel = numericFlag(ctx.args.flags, "--parallel");
25374
25789
  if (parallel != null && typeof parallel === "object") throw new CliExit(EXIT.usage, parallel.error);
25375
- const failFast = ctx.args.flags.has("--fail-fast");
25376
25790
  const selection = selectOrExit(ctx, { bare: "required" });
25377
25791
  const { out, config } = ctx;
25792
+ const [onlyTerm] = ctx.args.positionals.length === 1 ? ctx.args.positionals : [];
25793
+ const suitePolicy = onlyTerm == null ? void 0 : config.suites[onlyTerm];
25794
+ const failFast = ctx.args.flags.has("--fail-fast") || suitePolicy?.failFast === true;
25378
25795
  const byId = new Map(config.processes.map((proc) => [proc.id, proc]));
25379
25796
  const defs = selection.ordered.flatMap((id) => {
25380
25797
  const def = byId.get(id);
@@ -25535,60 +25952,30 @@ async function cmdRun(ctx) {
25535
25952
  try {
25536
25953
  const pumps = single ? [] : procs.map((proc) => startPump(out, proc));
25537
25954
  if (tasks.length > 0 && services.length === 0) {
25538
- const pending = [...tasks];
25539
- const succeeded = /* @__PURE__ */ new Set();
25540
- const failed = /* @__PURE__ */ new Set();
25541
- const running = /* @__PURE__ */ new Set();
25542
- const selected = new Set(tasks.map((def) => def.id));
25543
- const depsOf = (def) => def.dependsOn.filter((id) => selected.has(id));
25544
- let waiters = [];
25545
- const settled = () => new Promise((resolve) => {
25546
- waiters.push(resolve);
25547
- });
25548
- const wake = () => {
25549
- const current = waiters;
25550
- waiters = [];
25551
- for (const resolve of current) resolve();
25552
- };
25553
- const workers = Array.from({ length: Math.min(parallel ?? 1, pending.length) }, async () => {
25554
- for (;;) {
25555
- if (failFast && failures.length > 0) return;
25556
- const index = pending.findIndex((def) => depsOf(def).every((id) => succeeded.has(id) || failed.has(id)));
25557
- if (index < 0) {
25558
- if (running.size === 0) return;
25559
- await settled();
25560
- continue;
25561
- }
25562
- const [def] = pending.splice(index, 1);
25563
- const blockedBy = depsOf(def).find((id) => failed.has(id));
25564
- if (blockedBy != null) {
25565
- out.print(`${out.paint("yellow", "⊘")} ${out.accent(def.id, def.id)} blocked: "${blockedBy}" failed`);
25566
- failed.add(def.id);
25567
- recordFailure({
25568
- id: def.id,
25569
- code: 1,
25570
- failed: true
25571
- });
25572
- wake();
25573
- continue;
25574
- }
25575
- running.add(def.id);
25955
+ const pool = await runTaskPool({
25956
+ tasks,
25957
+ parallel: parallel ?? suitePolicy?.parallel ?? 1,
25958
+ failFast,
25959
+ run: async (def) => {
25576
25960
  const result = await runTask(def);
25577
- running.delete(def.id);
25578
- (result.failed ? failed : succeeded).add(def.id);
25579
- wake();
25580
- if (result.failed) {
25581
- recordFailure(result);
25582
- if (failFast) {
25583
- for (const proc of procs) if (!TERMINAL_STATES.has(proc.state)) proc.stop();
25584
- return;
25585
- }
25586
- }
25961
+ if (result.failed) recordFailure(result);
25962
+ return !result.failed;
25963
+ },
25964
+ onBlocked: (def, blockedBy) => {
25965
+ out.print(`${out.paint("yellow", "⊘")} ${out.accent(def.id, def.id)} blocked: "${blockedBy}" failed`);
25966
+ recordFailure({
25967
+ id: def.id,
25968
+ code: 1,
25969
+ failed: true
25970
+ });
25971
+ },
25972
+ onFailFast: () => {
25973
+ for (const proc of procs) if (!TERMINAL_STATES.has(proc.state)) proc.stop();
25587
25974
  }
25588
25975
  });
25589
- await Promise.all(workers);
25590
- for (const def of pending) {
25591
- const blockedBy = depsOf(def).find((id) => !succeeded.has(id)) ?? "a dependency";
25976
+ const { succeeded } = pool;
25977
+ for (const def of pool.leftover) {
25978
+ const blockedBy = def.dependsOn.find((id) => tasks.some((t) => t.id === id) && !succeeded.has(id)) ?? "a dependency";
25592
25979
  out.print(`${out.paint("yellow", "⊘")} ${out.accent(def.id, def.id)} blocked: "${blockedBy}" did not succeed`);
25593
25980
  recordFailure({
25594
25981
  id: def.id,
@@ -25866,6 +26253,82 @@ async function cmdUi(ctx) {
25866
26253
  return EXIT.ok;
25867
26254
  }
25868
26255
  //#endregion
26256
+ //#region src/daemon/savedFilters.ts
26257
+ const STORE_VERSION = 1;
26258
+ function readable(value) {
26259
+ const filters = value?.filters;
26260
+ if (!Array.isArray(filters)) return [];
26261
+ const clean = [];
26262
+ for (const entry of filters) {
26263
+ const query = checkSavedFilterQuery(entry);
26264
+ if (typeof query === "string") continue;
26265
+ const record = { ...entry };
26266
+ const name = record["name"];
26267
+ const lastRunAt = record["lastRunAt"];
26268
+ clean.push({
26269
+ id: savedFilterId(query),
26270
+ ...query,
26271
+ pinned: record["pinned"] === true,
26272
+ ...typeof name === "string" && name !== "" ? { name: name.slice(0, 48) } : {},
26273
+ ...typeof lastRunAt === "number" ? { lastRunAt } : {}
26274
+ });
26275
+ }
26276
+ return bounded(clean);
26277
+ }
26278
+ /** Pins are kept (newest-first cap); recents are a small ring, most recently run first. */
26279
+ function bounded(filters) {
26280
+ const pins = filters.filter((filter) => filter.pinned).slice(0, 24);
26281
+ const recents = filters.filter((filter) => !filter.pinned).sort((a, b) => (b.lastRunAt ?? 0) - (a.lastRunAt ?? 0)).slice(0, 8);
26282
+ return [...pins, ...recents];
26283
+ }
26284
+ /** Missing, unreadable or corrupt all read as "nothing saved" — never a reason to fail a boot. */
26285
+ async function readSavedFilters(path) {
26286
+ try {
26287
+ return readable(JSON.parse(await readFile(path, "utf8")));
26288
+ } catch {
26289
+ return [];
26290
+ }
26291
+ }
26292
+ async function writeSavedFilters(path, filters) {
26293
+ await mkdir(dirname(path), {
26294
+ recursive: true,
26295
+ mode: 448
26296
+ });
26297
+ const temp = `${path}.${process.pid}.tmp`;
26298
+ await writeFile(temp, `${JSON.stringify({
26299
+ version: STORE_VERSION,
26300
+ filters
26301
+ }, null, 2)}\n`, {
26302
+ encoding: "utf8",
26303
+ mode: 384
26304
+ });
26305
+ await rename(temp, path);
26306
+ }
26307
+ /** Pure: the list that results from `change`. */
26308
+ function mutateSavedFilters(current, change) {
26309
+ if (change.kind === "remove") return current.filter((filter) => filter.id !== change.id);
26310
+ const id = savedFilterId(change.query);
26311
+ const existing = current.find((filter) => filter.id === id);
26312
+ const rest = current.filter((filter) => filter.id !== id);
26313
+ if (change.kind === "pin") {
26314
+ const name = change.name.trim().slice(0, 48);
26315
+ return bounded([{
26316
+ ...existing,
26317
+ id,
26318
+ ...change.query,
26319
+ pinned: true,
26320
+ ...name !== "" ? { name } : {}
26321
+ }, ...rest]);
26322
+ }
26323
+ return bounded([{
26324
+ ...existing,
26325
+ id,
26326
+ ...change.query,
26327
+ pinned: existing?.pinned === true,
26328
+ lastRunAt: change.at
26329
+ }, ...rest]);
26330
+ }
26331
+ //#endregion
25869
26332
  //#region src/cli.ts
25870
26333
  const HELP = `nice-commander — one typed config, one control surface, for dev environments.
25871
26334
 
@@ -25873,8 +26336,9 @@ usage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] [
25873
26336
 
25874
26337
  With NO command, "ui" runs: the daemon is ensured and the browser opened. --help prints this text.
25875
26338
 
25876
- selection: process ids, group names, tag=val (AND across terms), or --all.
25877
- Bare up/explain use the config's defaultSelection (or print the groups and exit);
26339
+ selection: process ids, suite names, @pin names, tag=val, or --all. Several tag=val terms AND
26340
+ together; --any ORs them instead. A tag selection and --all never start an optIn process.
26341
+ Bare up/explain use the config's defaultSelection (or print the suites and exit);
25878
26342
  bare down/restart/logs/run always require a selection — omission never means --all.
25879
26343
 
25880
26344
  commands:
@@ -25883,12 +26347,13 @@ commands:
25883
26347
  restart <sel> [--no-wait] stop + start
25884
26348
  status [--watch] table from the live status realm
25885
26349
  logs <sel> [-f] merged interleaved tail with colored id prefixes
25886
- list config introspection (processes, groups, warnings)
25887
- explain [sel] expanded ids, auto-included deps, DAG order
26350
+ list config introspection (processes, suites, warnings)
26351
+ explain [sel] expanded ids, auto-included deps, DAG order, suite policy
25888
26352
  env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
25889
26353
  overrides. A set value is STICKY: it applies to every
25890
26354
  later start until cleared, and never restarts anything.
25891
- run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape,
26355
+ run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape
26356
+ (a suite supplies its own parallel/fail-fast),
25892
26357
  a single id gets raw inherited stdio (interactive).
25893
26358
  --fail-fast = stop at the FIRST failure and stop the
25894
26359
  survivors; without it every task still runs, every
@@ -25956,7 +26421,7 @@ async function withTimeout(ctx, run) {
25956
26421
  async function main() {
25957
26422
  const argv = process.argv.slice(2);
25958
26423
  if (argv[0] === "daemon") {
25959
- const { runCommanderDaemon } = await import("./main-BlAdEbVt.mjs");
26424
+ const { runCommanderDaemon } = await import("./main-DrNJc_xN.mjs");
25960
26425
  return runCommanderDaemon(argv.slice(1));
25961
26426
  }
25962
26427
  const parsed = parseCliArgs(argv);
@@ -25981,6 +26446,7 @@ async function main() {
25981
26446
  out: createOut(parsed),
25982
26447
  config
25983
26448
  };
26449
+ if (parsed.positionals.some((term) => term.startsWith("@"))) ctx.pins = await readSavedFilters(commanderStatePaths(resolveCommanderDataDir(), config.configKey).savedFiltersPath);
25984
26450
  const code = await withTimeout(ctx, command(ctx));
25985
26451
  if (ctx.spawnedDaemon === true) process.exit(code);
25986
26452
  return code;
@@ -26000,6 +26466,6 @@ main().then((code) => {
26000
26466
  process.exitCode = EXIT.failure;
26001
26467
  });
26002
26468
  //#endregion
26003
- export { effectiveEnv as A, wsAcceptorCarrier as C, RuntimeCoordinate as D, ActionRuntime as E, withDependencies as F, readInstanceRecord as I, recordDaemonAlive as L, overrideFingerprint as M, loadCommanderConfigFile as N, createMemoryStorageAdapter_json as O, orderByDependency as P, removeInstanceRecord as R, httpAcceptorCarrier as S, createDefaultServeLogger as T, commanderStatePaths as _, createPortInspector as a, createRealmAcceptor as b, COMMANDER_BOOTSTRAP_PATH as c, COMMANDER_TICKET_PATH as d, COMMANDER_TICKET_PROTOCOL_PREFIX as f, commanderPackageVersion as g, commanderRuntimeError as h, readEnvOverrides as i, envVarViews as j, validateCommanderConfig as k, COMMANDER_HEALTH_PATH as l, commanderStatusRealm as m, applyEnvMutation as n, commanderChannel as o, COMMANDER_WS_PATH as p, countOverrides as r, commanderControlDomain as s, parseLogsClientMessage as t, COMMANDER_LOGS_PATH as u, ensureStateDir as v, serveChannel as w, createRealmServerEngine as x, resolveCommanderDataDir as y, writeInstanceRecord as z };
26469
+ export { ActionRuntime as A, withDependencies as B, resolveCommanderDataDir as C, wsAcceptorCarrier as D, httpAcceptorCarrier as E, envVarViews as F, writeInstanceRecord as G, readInstanceRecord as H, overrideFingerprint as I, hashCanonical as L, createMemoryStorageAdapter_json as M, validateCommanderConfig as N, serveChannel as O, effectiveEnv as P, loadCommanderConfigFile as R, ensureStateDir as S, createRealmServerEngine as T, recordDaemonAlive as U, savedFilterId as V, removeInstanceRecord as W, COMMANDER_WS_PATH as _, parseLogsClientMessage as a, commanderPackageVersion as b, countOverrides as c, commanderControlDomain as d, COMMANDER_BOOTSTRAP_PATH as f, COMMANDER_TICKET_PROTOCOL_PREFIX as g, COMMANDER_TICKET_PATH as h, runTaskPool as i, RuntimeCoordinate as j, createDefaultServeLogger as k, readEnvOverrides as l, COMMANDER_LOGS_PATH as m, readSavedFilters as n, createPortInspector as o, COMMANDER_HEALTH_PATH as p, writeSavedFilters as r, applyEnvMutation as s, mutateSavedFilters as t, commanderChannel as u, commanderStatusRealm as v, createRealmAcceptor as w, commanderStatePaths as x, commanderRuntimeError as y, orderByDependency as z };
26004
26470
 
26005
26471
  //# sourceMappingURL=cli.mjs.map