@nice-code/commander 0.95.0 → 0.97.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.cjs CHANGED
@@ -15,10 +15,10 @@ let module$1 = require("module");
15
15
  let ws = require("ws");
16
16
  let node_os = require("node:os");
17
17
  let node_child_process = require("node:child_process");
18
- let node_readline_promises = require("node:readline/promises");
18
+ let node_net = require("node:net");
19
19
  let node_dns_promises = require("node:dns/promises");
20
20
  let node_util = require("node:util");
21
- let node_net = require("node:net");
21
+ let node_readline_promises = require("node:readline/promises");
22
22
  //#region src/cli/args.ts
23
23
  const GLOBAL_VALUE_FLAGS = new Set(["--config", "--timeout"]);
24
24
  /**
@@ -151,7 +151,7 @@ function validStartStamp(value) {
151
151
  function isInstanceRecord(value) {
152
152
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
153
153
  const record = value;
154
- 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;
154
+ 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;
155
155
  }
156
156
  async function writeInstanceRecord(path, record) {
157
157
  await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), {
@@ -201,7 +201,7 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
201
201
  if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
202
202
  if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
203
203
  if (!boundedInt(record["port"], 1, 65535)) return null;
204
- const sameProtocol = record["protocolVersion"] === 5;
204
+ const sameProtocol = record["protocolVersion"] === 6;
205
205
  const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
206
206
  if (sameProtocol && sameRealm) return null;
207
207
  return {
@@ -298,6 +298,102 @@ async function pingDaemon(record, timeoutMs = 2e3) {
298
298
  }
299
299
  }
300
300
  //#endregion
301
+ //#region src/config/tags.ts
302
+ /** `key=value` → `[key, value]`, or null when the term is not tag-shaped. */
303
+ function parseTagTerm(term) {
304
+ const eq = term.indexOf("=");
305
+ return eq > 0 ? [term.slice(0, eq), term.slice(eq + 1)] : null;
306
+ }
307
+ function hasTag(tags, key, value) {
308
+ return tags[key]?.includes(value) === true;
309
+ }
310
+ /** Every entry must match (AND). */
311
+ function matchesTagQuery(tags, query) {
312
+ return Object.entries(query).every(([key, value]) => hasTag(tags, key, value));
313
+ }
314
+ /** Every `key=value` a process carries, in key order. */
315
+ function tagTermsOf(tags) {
316
+ return Object.entries(tags).flatMap(([key, values]) => values.map((value) => `${key}=${value}`));
317
+ }
318
+ //#endregion
319
+ //#region src/config/tagGroups.ts
320
+ /** Which of `terms` these tags carry, in `terms` order. */
321
+ function tagSignature(tags, terms) {
322
+ return terms.filter((term) => {
323
+ const parsed = parseTagTerm(term);
324
+ return parsed != null && tags[parsed[0]]?.includes(parsed[1]) === true;
325
+ });
326
+ }
327
+ /**
328
+ * Bucket by signature: most matched terms first, then by where the signature's terms sit in the
329
+ * filter — never by anything live, so buckets hold still while processes change state. In `any`
330
+ * mode the first bucket is the `all` result whenever anything matches every term.
331
+ */
332
+ function tagGroupsFor(items, terms, mode) {
333
+ const buckets = /* @__PURE__ */ new Map();
334
+ for (const item of items) {
335
+ const signature = tagSignature(item.tags, terms);
336
+ if (signature.length === 0 || mode === "all" && signature.length < terms.length) continue;
337
+ const key = signature.join(",");
338
+ const bucket = buckets.get(key) ?? {
339
+ signature,
340
+ members: []
341
+ };
342
+ bucket.members.push(item);
343
+ buckets.set(key, bucket);
344
+ }
345
+ const rank = (group) => group.signature.map((term) => terms.indexOf(term));
346
+ return [...buckets.values()].sort((a, b) => {
347
+ if (a.signature.length !== b.signature.length) return b.signature.length - a.signature.length;
348
+ const [ra, rb] = [rank(a), rank(b)];
349
+ for (let i = 0; i < ra.length; i += 1) if (ra[i] !== rb[i]) return (ra[i] ?? 0) - (rb[i] ?? 0);
350
+ return 0;
351
+ });
352
+ }
353
+ function sameSignature(a, b) {
354
+ return a.length === b.length && a.every((term) => b.includes(term));
355
+ }
356
+ function savedFilterId(query) {
357
+ const terms = [...query.terms].sort();
358
+ const bucket = query.bucket == null ? "" : `|${[...query.bucket].sort().join(",")}`;
359
+ return `${query.mode}:${terms.join(",")}${bucket}`;
360
+ }
361
+ /** The members a saved filter selects right now. `optIn` processes are never bulk members. */
362
+ function savedFilterMembers(query, items) {
363
+ const groups = tagGroupsFor(items.filter((item) => !item.optIn), [...query.terms].sort(), query.mode);
364
+ const bucket = query.bucket;
365
+ return (bucket == null ? groups : groups.filter((group) => sameSignature(group.signature, bucket))).flatMap((group) => group.members);
366
+ }
367
+ function asTerms(value) {
368
+ if (!Array.isArray(value) || value.length === 0 || value.length > 16) return null;
369
+ const terms = [];
370
+ for (const entry of value) {
371
+ if (typeof entry !== "string" || entry.length > 512 || parseTagTerm(entry) == null) return null;
372
+ if (!terms.includes(entry)) terms.push(entry);
373
+ }
374
+ return terms.sort();
375
+ }
376
+ /** The one place an untrusted value (the wire, or the file) becomes a query. */
377
+ function checkSavedFilterQuery(value) {
378
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return "expected an object";
379
+ const record = { ...value };
380
+ const mode = record["mode"];
381
+ if (mode !== "all" && mode !== "any") return "mode: expected \"all\" | \"any\"";
382
+ const terms = asTerms(record["terms"]);
383
+ if (terms == null) return `terms: expected 1–16 tag=value strings`;
384
+ if (record["bucket"] == null) return {
385
+ mode,
386
+ terms
387
+ };
388
+ const bucket = asTerms(record["bucket"]);
389
+ if (bucket == null || !bucket.every((term) => terms.includes(term))) return "bucket: expected a subset of terms";
390
+ return {
391
+ mode,
392
+ terms,
393
+ bucket
394
+ };
395
+ }
396
+ //#endregion
301
397
  //#region src/config/resolve.ts
302
398
  /** Topological order of the given id set over the dependsOn graph; config order breaks ties. */
303
399
  function orderByDependency(processes, ids) {
@@ -348,43 +444,79 @@ function withDependencies(processes, ids) {
348
444
  return closed;
349
445
  }
350
446
  /**
447
+ * What stopping `direct` AND its dependencies may take down. A dependency is kept when a live
448
+ * process outside the stop set still needs it — and keeping one keeps what IT needs, hence the
449
+ * loop. Dependencies that simply are not running are not reported either way.
450
+ */
451
+ function stopSetWithDependencies(processes, direct, isLive) {
452
+ const stop = withDependencies(processes, direct);
453
+ const kept = [];
454
+ for (let changed = true; changed;) {
455
+ changed = false;
456
+ const needed = withDependencies(processes, processes.filter((proc) => !stop.has(proc.id) && isLive(proc.id)).map((proc) => proc.id));
457
+ for (const id of [...stop]) {
458
+ if (direct.includes(id) || !needed.has(id)) continue;
459
+ stop.delete(id);
460
+ if (isLive(id)) kept.push(id);
461
+ changed = true;
462
+ }
463
+ }
464
+ return {
465
+ stop: orderByDependency(processes, stop),
466
+ kept
467
+ };
468
+ }
469
+ /**
351
470
  * Resolve CLI/UI selection terms against the model. An empty `terms` is the caller's problem
352
471
  * (bare `up` consults `defaultSelection` before ever reaching here).
353
472
  */
354
- function resolveSelection(config, terms, extraIds = []) {
473
+ function resolveSelection(config, terms, options = {}) {
474
+ const extraIds = options.extraIds ?? [];
475
+ const bulk = (id) => options.purpose === "address" || config.processes.find((proc) => proc.id === id)?.optIn !== true;
355
476
  const errors = [];
356
477
  const selectors = /* @__PURE__ */ new Set();
357
478
  const tagTerms = [];
358
479
  for (const term of terms) {
359
- const eq = term.indexOf("=");
360
- if (eq > 0) {
361
- tagTerms.push([term.slice(0, eq), term.slice(eq + 1)]);
480
+ if (term.startsWith("@")) {
481
+ const pin = options.pins?.find((candidate) => candidate.name === term.slice(1));
482
+ if (pin == null) {
483
+ errors.push(`unknown pin "${term}" (pins are saved from the web UI)`);
484
+ continue;
485
+ }
486
+ for (const proc of savedFilterMembers(pin, config.processes)) selectors.add(proc.id);
487
+ continue;
488
+ }
489
+ const tagTerm = parseTagTerm(term);
490
+ if (tagTerm != null) {
491
+ tagTerms.push(tagTerm);
362
492
  continue;
363
493
  }
364
494
  if (term === "all") {
365
- for (const proc of config.processes) selectors.add(proc.id);
495
+ for (const proc of config.processes) if (bulk(proc.id)) selectors.add(proc.id);
366
496
  for (const id of extraIds) selectors.add(id);
367
497
  continue;
368
498
  }
369
- if (config.groups[term] != null) {
370
- for (const id of config.groups[term].ids) selectors.add(id);
499
+ if (config.suites[term] != null) {
500
+ for (const id of config.suites[term].ids) selectors.add(id);
371
501
  continue;
372
502
  }
373
503
  if (config.processes.some((proc) => proc.id === term) || extraIds.includes(term)) {
374
504
  selectors.add(term);
375
505
  continue;
376
506
  }
377
- errors.push(`unknown selection "${term}" (not a process id, group, tag=value, or "all")`);
507
+ errors.push(`unknown selection "${term}" (not a process id, suite, @pin, tag=value, or "all")`);
378
508
  }
379
509
  if (errors.length > 0) return {
380
510
  ok: false,
381
511
  errors
382
512
  };
383
513
  let direct = [...selectors];
384
- if (selectors.size === 0 && tagTerms.length > 0) direct = config.processes.map((proc) => proc.id);
514
+ if (selectors.size === 0 && tagTerms.length > 0) direct = config.processes.filter((proc) => bulk(proc.id)).map((proc) => proc.id);
385
515
  if (tagTerms.length > 0) direct = direct.filter((id) => {
386
516
  const proc = config.processes.find((candidate) => candidate.id === id);
387
- return proc != null && tagTerms.every(([key, value]) => proc.tags[key] === value);
517
+ if (proc == null) return false;
518
+ const matches = ([key, value]) => hasTag(proc.tags, key, value);
519
+ return options.any === true ? tagTerms.some(matches) : tagTerms.every(matches);
388
520
  });
389
521
  const closed = withDependencies(config.processes, direct);
390
522
  const ordered = orderByDependency(config.processes, closed);
@@ -651,6 +783,8 @@ function staleOverrides(config, overrides) {
651
783
  }
652
784
  return stale;
653
785
  }
786
+ const SUITE_PARALLEL_DEFAULT = 4;
787
+ const SUITE_STAGGER_DEFAULT_MS = 100;
654
788
  /** C0/DEL/C1 control characters have no business in tag keys/values or env keys. */
655
789
  function hasControlChars(value) {
656
790
  for (let i = 0; i < value.length; i += 1) {
@@ -660,6 +794,7 @@ function hasControlChars(value) {
660
794
  return false;
661
795
  }
662
796
  const MAX_TAGS = 32;
797
+ const MAX_TAG_VALUES = 16;
663
798
  function isRecord(value) {
664
799
  return typeof value === "object" && value != null && !Array.isArray(value);
665
800
  }
@@ -748,8 +883,52 @@ function findCycle(graph) {
748
883
  }
749
884
  return null;
750
885
  }
751
- function matchesTags(tags, query) {
752
- return Object.entries(query).every(([key, value]) => tags[key] === value);
886
+ /**
887
+ * Expand `include`/`where`/`exclude` over a set of sibling definitions. A `where` never picks up
888
+ * an `optIn` process; an explicit `include` does. Callers guarantee the reference graph is
889
+ * acyclic; `seen` only keeps a malformed one from recursing forever.
890
+ */
891
+ function expandSelection(name, inputs, byId, seen = /* @__PURE__ */ new Set()) {
892
+ const out = /* @__PURE__ */ new Set();
893
+ const input = inputs[name];
894
+ if (seen.has(name) || !isRecord(input)) return out;
895
+ seen.add(name);
896
+ const selection = input;
897
+ for (const entry of selection.include ?? []) if (byId.has(entry)) out.add(entry);
898
+ else if (typeof entry === "string" && entry in inputs) for (const id of expandSelection(entry, inputs, byId, seen)) out.add(id);
899
+ for (const query of normalizeTagQueryOr(selection.where) ?? []) for (const proc of byId.values()) if (!proc.optIn && matchesTagQuery(proc.tags, query)) out.add(proc.id);
900
+ const { ids: excludedIds, queries } = normalizeExcludes(selection.exclude);
901
+ for (const id of excludedIds) out.delete(id);
902
+ for (const id of [...out]) {
903
+ const proc = byId.get(id);
904
+ if (proc != null && queries.some((query) => matchesTagQuery(proc.tags, query))) out.delete(id);
905
+ }
906
+ seen.delete(name);
907
+ return out;
908
+ }
909
+ /** The tag selection that picks out exactly `ids`, if one exists — smallest first. */
910
+ function equivalentTagSelection(ids, byId) {
911
+ const [first, ...rest] = [...ids].flatMap((id) => byId.get(id) ?? []);
912
+ if (first == null) return null;
913
+ const common = tagTermsOf(first.tags).filter((term) => rest.every((proc) => tagTermsOf(proc.tags).includes(term)));
914
+ const selects = (terms) => {
915
+ const matched = [...byId.values()].filter((proc) => !proc.optIn && terms.every((term) => tagTermsOf(proc.tags).includes(term)));
916
+ return matched.length === ids.size && matched.every((proc) => ids.has(proc.id));
917
+ };
918
+ for (const term of common) if (selects([term])) return [term];
919
+ return common.length > 1 && selects(common) ? common : null;
920
+ }
921
+ /** `groups` was removed — say what each one becomes instead of just refusing the key. */
922
+ function groupMigrationErrors(groupsInput, byId) {
923
+ const errors = ["groups: removed — processes are organised by tags, and a run-unit is a `suite`. Per group:"];
924
+ for (const name of Object.keys(groupsInput)) {
925
+ const ids = expandSelection(name, groupsInput, byId);
926
+ const tagSelection = equivalentTagSelection(ids, byId);
927
+ if (ids.size < 2) errors.push(`groups.${name}: one member — delete it and use the id "${[...ids][0] ?? "?"}" directly`);
928
+ 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`);
929
+ else errors.push(`groups.${name}: move it under \`suites\` unchanged`);
930
+ }
931
+ return errors;
753
932
  }
754
933
  /**
755
934
  * Validate a raw loaded config and build the resolved model. `configDir`/`configPath` are the
@@ -831,16 +1010,25 @@ function validateCommanderConfig(raw, anchor) {
831
1010
  if (resolved != null) envVars.push(resolved);
832
1011
  }
833
1012
  for (const declared of envVars) if (declared.default != null) env[declared.name] = declared.default;
834
- const tags = {
1013
+ const tagEntries = Object.entries({
835
1014
  ...config.defaults?.tags,
836
1015
  ...proc.tags
837
- };
838
- const tagEntries = Object.entries(tags);
1016
+ });
839
1017
  if (tagEntries.length > MAX_TAGS) errors.push(`${at}.tags: ${tagEntries.length} entries exceeds the ${MAX_TAGS} bound`);
1018
+ const tags = {};
840
1019
  for (const [key, value] of tagEntries) {
841
- if (key === "" || key.length > 64 || hasControlChars(key)) errors.push(`${at}.tags: invalid key ${JSON.stringify(key)}`);
842
- if (typeof value !== "string" || value.length > 256 || hasControlChars(value)) errors.push(`${at}.tags[${JSON.stringify(key)}]: invalid value`);
1020
+ if (key === "" || key.length > 64 || key.includes("=") || hasControlChars(key)) errors.push(`${at}.tags: invalid key ${JSON.stringify(key)}`);
1021
+ const values = typeof value === "string" ? [value] : value;
1022
+ if (!Array.isArray(values) || values.length === 0 || values.length > MAX_TAG_VALUES) {
1023
+ errors.push(`${at}.tags[${JSON.stringify(key)}]: expected a string or 1–${MAX_TAG_VALUES} strings`);
1024
+ continue;
1025
+ }
1026
+ const clean = [];
1027
+ 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`);
1028
+ else if (!clean.includes(entry)) clean.push(entry);
1029
+ tags[key] = clean;
843
1030
  }
1031
+ if (proc.optIn != null && typeof proc.optIn !== "boolean") errors.push(`${at}.optIn: expected a boolean`);
844
1032
  const endpoints = [];
845
1033
  const endpointNames = /* @__PURE__ */ new Set();
846
1034
  for (const [endpointIndex, endpoint] of (proc.endpoints ?? []).entries()) {
@@ -925,6 +1113,7 @@ function validateCommanderConfig(raw, anchor) {
925
1113
  envVars,
926
1114
  stdin,
927
1115
  tags,
1116
+ optIn: proc.optIn === true,
928
1117
  dependsOn,
929
1118
  endpoints,
930
1119
  ...proc.url != null ? { url: proc.url } : {},
@@ -942,60 +1131,57 @@ function validateCommanderConfig(raw, anchor) {
942
1131
  for (const [id, deps] of dependsGraph) for (const dep of deps) if (!byId.has(dep)) errors.push(`process "${id}" dependsOn: unknown id "${dep}"`);
943
1132
  const processCycle = findCycle(dependsGraph);
944
1133
  if (processCycle != null) errors.push(`dependsOn cycle: ${processCycle.join(" → ")}`);
945
- const groupsInput = config.groups ?? {};
946
- const groupRefs = /* @__PURE__ */ new Map();
947
- for (const [name, group] of Object.entries(groupsInput)) {
948
- if (!require_types.COMMANDER_ID_PATTERN.test(name)) errors.push(`groups.${JSON.stringify(name)}: must match ${require_types.COMMANDER_ID_PATTERN}`);
949
- if (name === "all") errors.push(`groups.${name}: "all" is the built-in selector`);
950
- if (byId.has(name)) errors.push(`groups.${name}: collides with a process id`);
951
- if (typeof group !== "object" || group == null || Array.isArray(group)) {
952
- errors.push(`groups.${name}: expected an object`);
1134
+ const removedGroups = raw.groups;
1135
+ if (removedGroups != null) errors.push(...groupMigrationErrors(isRecord(removedGroups) ? removedGroups : {}, byId));
1136
+ const suitesInput = isRecord(config.suites) ? config.suites : {};
1137
+ if (config.suites != null && !isRecord(config.suites)) errors.push("suites: expected an object keyed by suite name");
1138
+ const suiteRefs = /* @__PURE__ */ new Map();
1139
+ for (const [name, suite] of Object.entries(suitesInput)) {
1140
+ const at = `suites.${name}`;
1141
+ if (!require_types.COMMANDER_ID_PATTERN.test(name)) errors.push(`suites.${JSON.stringify(name)}: must match ${require_types.COMMANDER_ID_PATTERN}`);
1142
+ if (name === "all") errors.push(`${at}: "all" is the built-in selector`);
1143
+ if (byId.has(name)) errors.push(`${at}: collides with a process id`);
1144
+ if (!isRecord(suite)) {
1145
+ errors.push(`${at}: expected an object`);
953
1146
  continue;
954
1147
  }
955
- for (const entry of group.include ?? []) if (typeof entry !== "string") errors.push(`groups.${name}.include: expected id/group strings`);
956
- else if (!byId.has(entry) && !(entry in groupsInput)) errors.push(`groups.${name}.include: unknown id or group "${entry}"`);
957
- const { ids: excludedIds, queries: excludeQueries } = normalizeExcludes(group.exclude);
958
- for (const id of excludedIds) if (!byId.has(id)) errors.push(`groups.${name}.exclude: unknown id "${id}"`);
959
- for (const query of [...normalizeTagQueryOr(group.where) ?? [], ...excludeQueries]) {
960
- if (Object.keys(query).length === 0) warnings.push(`groups.${name}: an empty tag query matches everything`);
961
- 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`);
962
- }
963
- groupRefs.set(name, (group.include ?? []).filter((entry) => typeof entry === "string" && entry in groupsInput));
964
- }
965
- const groupCycle = findCycle(groupRefs);
966
- if (groupCycle != null) errors.push(`group include cycle: ${groupCycle.join(" → ")}`);
967
- const groups = {};
968
- if (groupCycle == null) {
969
- const expand = (name, seen) => {
970
- if (seen.has(name)) return /* @__PURE__ */ new Set();
971
- seen.add(name);
972
- const group = groupsInput[name];
973
- const out = /* @__PURE__ */ new Set();
974
- if (typeof group === "object" && group != null && !Array.isArray(group)) {
975
- for (const entry of group.include ?? []) if (byId.has(entry)) out.add(entry);
976
- else if (typeof entry === "string" && entry in groupsInput) for (const id of expand(entry, seen)) out.add(id);
977
- for (const query of normalizeTagQueryOr(group.where) ?? []) for (const proc of byId.values()) if (matchesTags(proc.tags, query)) out.add(proc.id);
978
- const { ids: excludedIds, queries } = normalizeExcludes(group.exclude);
979
- for (const id of excludedIds) out.delete(id);
980
- if (queries.length > 0) for (const id of out) {
981
- const proc = byId.get(id);
982
- if (proc != null && queries.some((query) => matchesTags(proc.tags, query))) out.delete(id);
983
- }
984
- }
985
- seen.delete(name);
986
- return out;
987
- };
988
- for (const name of Object.keys(groupsInput)) {
989
- const expanded = expand(name, /* @__PURE__ */ new Set());
990
- const ordered = [...byId.keys()].filter((id) => expanded.has(id));
991
- if (ordered.length === 0) warnings.push(`groups.${name}: expands to zero processes`);
992
- const staggerMs = groupsInput[name]?.staggerMs;
993
- groups[name] = {
994
- name,
995
- ids: ordered,
996
- staggerMs: typeof staggerMs === "number" ? staggerMs : 100
997
- };
1148
+ const definition = suite;
1149
+ if (definition.description != null && typeof definition.description !== "string") errors.push(`${at}.description: expected a string`);
1150
+ if (definition.parallel != null && (!Number.isInteger(definition.parallel) || definition.parallel < 1)) errors.push(`${at}.parallel: expected an integer ≥ 1`);
1151
+ if (definition.failFast != null && typeof definition.failFast !== "boolean") errors.push(`${at}.failFast: expected a boolean`);
1152
+ if (definition.staggerMs != null && (typeof definition.staggerMs !== "number" || definition.staggerMs < 0)) errors.push(`${at}.staggerMs: expected a non-negative number`);
1153
+ for (const entry of definition.include ?? []) if (typeof entry !== "string") errors.push(`${at}.include: expected id/suite strings`);
1154
+ else if (!byId.has(entry) && !(entry in suitesInput)) errors.push(`${at}.include: unknown id or suite "${entry}"`);
1155
+ const { ids: excludedIds, queries: excludeQueries } = normalizeExcludes(definition.exclude);
1156
+ for (const id of excludedIds) if (!byId.has(id)) errors.push(`${at}.exclude: unknown id "${id}"`);
1157
+ for (const query of [...normalizeTagQueryOr(definition.where) ?? [], ...excludeQueries]) {
1158
+ if (Object.keys(query).length === 0) warnings.push(`${at}: an empty tag query matches everything`);
1159
+ 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`);
1160
+ }
1161
+ suiteRefs.set(name, (definition.include ?? []).filter((entry) => typeof entry === "string" && entry in suitesInput));
1162
+ }
1163
+ const suiteCycle = findCycle(suiteRefs);
1164
+ if (suiteCycle != null) errors.push(`suite include cycle: ${suiteCycle.join(" → ")}`);
1165
+ const suites = {};
1166
+ if (suiteCycle == null) for (const [name, suite] of Object.entries(suitesInput)) {
1167
+ if (!isRecord(suite)) continue;
1168
+ const definition = suite;
1169
+ const expanded = expandSelection(name, suitesInput, byId);
1170
+ const ordered = [...byId.keys()].filter((id) => expanded.has(id));
1171
+ if (ordered.length < 2) {
1172
+ 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`);
1173
+ continue;
998
1174
  }
1175
+ const tagSelection = Object.keys(definition).every((key) => key === "where") ? equivalentTagSelection(expanded, byId) : null;
1176
+ 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`);
1177
+ suites[name] = {
1178
+ name,
1179
+ ...typeof definition.description === "string" ? { description: definition.description } : {},
1180
+ ids: ordered,
1181
+ parallel: definition.parallel ?? SUITE_PARALLEL_DEFAULT,
1182
+ failFast: definition.failFast === true,
1183
+ staggerMs: definition.staggerMs ?? SUITE_STAGGER_DEFAULT_MS
1184
+ };
999
1185
  }
1000
1186
  const portClaims = /* @__PURE__ */ new Map();
1001
1187
  for (const proc of byId.values()) for (const ep of proc.endpoints) {
@@ -1016,7 +1202,7 @@ function validateCommanderConfig(raw, anchor) {
1016
1202
  }
1017
1203
  if (config.defaultSelection != null) {
1018
1204
  const selection = config.defaultSelection;
1019
- if (!byId.has(selection) && !(selection in groups)) errors.push(`defaultSelection: unknown id or group "${selection}"`);
1205
+ 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`);
1020
1206
  }
1021
1207
  const watchFiles = [anchor.configPath];
1022
1208
  for (const file of config.watchFiles ?? []) {
@@ -1036,7 +1222,7 @@ function validateCommanderConfig(raw, anchor) {
1036
1222
  const resolvedBase = {
1037
1223
  name,
1038
1224
  processes,
1039
- groups,
1225
+ suites,
1040
1226
  defaultSelection: config.defaultSelection,
1041
1227
  daemon: { port: typeof config.daemon?.port === "number" ? config.daemon.port : 4900 }
1042
1228
  };
@@ -1096,7 +1282,7 @@ async function loadConfigOrExit(configPath) {
1096
1282
  */
1097
1283
  function requireSelectionTerms(ctx) {
1098
1284
  if (ctx.args.positionals.length > 0 || ctx.args.flags.get("--all") === true) return;
1099
- throw new CliExit(EXIT.usage, `${ctx.args.command} requires a selection (ids, group, tag=val) or --all`);
1285
+ throw new CliExit(EXIT.usage, `${ctx.args.command} requires a selection (ids, suite, @pin, tag=val) or --all`);
1100
1286
  }
1101
1287
  function selectOrExit(ctx, options) {
1102
1288
  const { args, config } = ctx;
@@ -1104,19 +1290,24 @@ function selectOrExit(ctx, options) {
1104
1290
  if (args.flags.get("--all") === true) terms = [...terms, "all"];
1105
1291
  if (terms.length === 0) if (options.bare === "default" && config.defaultSelection != null) terms = [config.defaultSelection];
1106
1292
  else if (options.bare === "default") {
1107
- const groups = Object.keys(config.groups);
1108
- 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`);
1293
+ const suites = Object.keys(config.suites);
1294
+ 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`);
1109
1295
  } else requireSelectionTerms(ctx);
1110
- const result = resolveSelection(config, terms, options.extraIds ?? []);
1296
+ const result = resolveSelection(config, terms, {
1297
+ extraIds: options.extraIds ?? [],
1298
+ any: args.flags.get("--any") === true,
1299
+ purpose: args.command === "down" || args.command === "logs" ? "address" : "start",
1300
+ pins: ctx.pins ?? []
1301
+ });
1111
1302
  if (!result.ok) throw new CliExit(EXIT.usage, result.errors.join("\n"));
1112
1303
  return result.selection;
1113
1304
  }
1114
- /** Group stagger for a start: the widest stagger among the groups named in the terms. */
1305
+ /** Suite stagger for a start: the widest stagger among the suites named in the terms. */
1115
1306
  function staggerFor(config, terms) {
1116
1307
  let stagger = 0;
1117
1308
  for (const term of terms) {
1118
- const group = config.groups[term];
1119
- if (group != null) stagger = Math.max(stagger, group.staggerMs);
1309
+ const suite = config.suites[term];
1310
+ if (suite != null) stagger = Math.max(stagger, suite.staggerMs);
1120
1311
  }
1121
1312
  return stagger;
1122
1313
  }
@@ -5162,7 +5353,7 @@ function reject(reason, id) {
5162
5353
  /**
5163
5354
  * The machine-readable reject id an untrusted verify key produces: the presented key differs from
5164
5355
  * the one pinned for this client identity (trust-on-first-use). Carried on the reject frame's `id`
5165
- * and surfaced to the dialing side as `err_nice_wire_connect.identity_pin_mismatch`, so an app can
5356
+ * and surfaced to the dialing side as `err_wire_connect` id `identity_pin_mismatch`, so an app can
5166
5357
  * branch on it (`err.hasId("identity_pin_mismatch")`) — the obvious recovery being "this identity
5167
5358
  * is unusable with this key: clear the client's identity storage / mint a new persistent id".
5168
5359
  */
@@ -5832,6 +6023,9 @@ dropLink: async (opts) => {
5832
6023
  * Close any live long-lived connection (e.g. a WebSocket) before dropping it, so a teardown
5833
6024
  * actually releases the socket instead of leaving it open until GC. HTTP/stateless transports
5834
6025
  * don't implement `disconnect`, so they're simply forgotten.
6026
+ *
6027
+ * @internal Bare cache drop with no redial suppression. Apps call {@link clearTransportCache} or
6028
+ * {@link releaseLink} instead.
5835
6029
  */
5836
6030
  clearCache() {
5837
6031
  for (const entry of this._cache.values()) if (entry instanceof Promise) entry.then((ready) => ready.methods.disconnect?.()).catch(() => {});
@@ -10201,6 +10395,34 @@ var ReliableLog = class {
10201
10395
  }
10202
10396
  return prefix;
10203
10397
  }
10398
+ /**
10399
+ * {@link contiguousPrefix} with each payload's `seq` attached, optionally only the entries after
10400
+ * `afterSeq`. Pruned or compacted seqs are absent, so the first entry's `seq` says where the stored
10401
+ * history now starts.
10402
+ */
10403
+ contiguousEntries(streamId, afterSeq = -1) {
10404
+ const highWater = this._store.getHighWater(streamId);
10405
+ const entries = [];
10406
+ for (let seq = Math.max(afterSeq + 1, 0); seq <= highWater; seq++) {
10407
+ const raw = this._store.getPayload(streamId, seq);
10408
+ if (raw != null) entries.push({
10409
+ seq,
10410
+ payload: this._deserialize(raw)
10411
+ });
10412
+ }
10413
+ return entries;
10414
+ }
10415
+ /**
10416
+ * Delete a stream's stored frames with `seq <= through` (the replay recipe's prune, once the consumer
10417
+ * confirmed them). Clamped to the high-water, so a too-large `through` never touches undelivered frames.
10418
+ * Returns `false` when the store has no `deleteThrough` and nothing was pruned.
10419
+ */
10420
+ pruneThrough(streamId, through) {
10421
+ if (this._store.deleteThrough == null) return false;
10422
+ const clamped = Math.min(through, this._store.getHighWater(streamId));
10423
+ if (clamped >= 0) this._store.deleteThrough(streamId, clamped);
10424
+ return true;
10425
+ }
10204
10426
  };
10205
10427
  /**
10206
10428
  * An in-memory {@link IReliableLogStore} — used by tests to stand in for a Durable Object's SQL storage. It
@@ -10211,7 +10433,7 @@ var ReliableLog = class {
10211
10433
  function createMemoryReliableLogStore() {
10212
10434
  const frames = /* @__PURE__ */ new Map();
10213
10435
  const highWater = /* @__PURE__ */ new Map();
10214
- const key = (streamId, seq) => `${streamId}${seq}`;
10436
+ const key = (streamId, seq) => `${streamId}\u0000${seq}`;
10215
10437
  return {
10216
10438
  insertIgnore: (streamId, seq, payload) => {
10217
10439
  const k = key(streamId, seq);
@@ -10225,7 +10447,7 @@ function createMemoryReliableLogStore() {
10225
10447
  for (let seq = 0; seq <= through; seq++) frames.delete(key(streamId, seq));
10226
10448
  },
10227
10449
  deleteStream: (streamId) => {
10228
- const prefix = `${streamId} `;
10450
+ const prefix = `${streamId}\u0000`;
10229
10451
  for (const k of frames.keys()) if (k.startsWith(prefix)) frames.delete(k);
10230
10452
  highWater.delete(streamId);
10231
10453
  }
@@ -15112,7 +15334,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15112
15334
  this._sendPayload(connection, action, runtime.coordinate);
15113
15335
  runningAction._completeWithResult(action.successResult(void 0));
15114
15336
  } catch (err) {
15115
- runningAction._abort(err);
15337
+ runningAction._abort(this._pushSendError(action.id, err));
15116
15338
  }
15117
15339
  return runningAction;
15118
15340
  }
@@ -15125,10 +15347,19 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15125
15347
  try {
15126
15348
  this._sendPayload(connection, action, runtime.coordinate);
15127
15349
  } catch (err) {
15128
- runningAction._abort(err);
15350
+ runningAction._abort(this._pushSendError(action.id, err));
15129
15351
  }
15130
15352
  return runningAction;
15131
15353
  }
15354
+ /** A failed push send as a typed `send_failed`, keeping the carrier's error as the origin. */
15355
+ _pushSendError(actionId, cause) {
15356
+ if (err_nice_transport.isExact(cause)) return cause;
15357
+ return err_nice_transport.fromId("send_failed", {
15358
+ actionId,
15359
+ actionState: "request",
15360
+ message: cause instanceof Error ? cause.message : String(cause)
15361
+ }).withOriginError(cause);
15362
+ }
15132
15363
  /** Encode + send one payload; returns the encoded frame's size so a logger can report it. */
15133
15364
  _sendPayload(connection, payload, localClient, reliability) {
15134
15365
  const encoding = this._connEncoding.get(connection) ?? "binary";
@@ -16005,8 +16236,10 @@ function deriveDictionaryVersion(domains) {
16005
16236
  * Declare a transport-agnostic channel by role — the single source of truth both peers share. Each end
16006
16237
  * MUST call this with the same domains in the same order (the binary wire dictionary is positional); the
16007
16238
  * `dictionaryVersion` is derived from those domains unless you pin an explicit one. The wire dictionary
16008
- * spans `[...toAcceptor, ...toConnector]` in that order, so add new domains to the end of their list to
16009
- * keep older peers compatible.
16239
+ * spans `[...toAcceptor, ...toConnector]` in that order. Any change to the domains or their actions moves
16240
+ * the derived version, and the handshake rejects a peer whose version differs, so deploy both ends
16241
+ * together. Appending stays compatible with older peers only under a hand-pinned `dictionaryVersion`
16242
+ * you leave unchanged, and only when the additions come last in the whole dictionary.
16010
16243
  *
16011
16244
  * Declare the domains *by role* — `toAcceptor` (connector→acceptor requests) and `toConnector`
16012
16245
  * (acceptor→connector pushes) — so the routing for both ends is derived from the channel (see
@@ -16709,7 +16942,7 @@ function serveChannel(runtime, channel, options) {
16709
16942
  const pushToClient = (target, request, pushOptions) => {
16710
16943
  if (disposed) throw new Error("serveChannel: server disposed");
16711
16944
  const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
16712
- if (owner == null) throw new Error("serveChannel: no duplex carrier holds a connection for the push target");
16945
+ if (owner == null) throw err_nice_transport.fromId("not_found", { actionId: target instanceof RuntimeCoordinate ? target.stringId : "push-target-connection" });
16713
16946
  return owner.pushToClient(runtime, target, request, pushOptions);
16714
16947
  };
16715
16948
  const broadcast = (makeRequest, broadcastOptions) => {
@@ -18671,11 +18904,11 @@ const err_realm = err_nice.createChildDomain({
18671
18904
  message: ({ lastKnownVersion, oldestReplayable }) => `Version ${lastKnownVersion} is behind the replayable window (oldest ${oldestReplayable}) — full rehydration required.`,
18672
18905
  context: { required: true }
18673
18906
  }),
18674
- /** A `realm.update()` ran before the first hydrate (PLAN-FEATURE-COMPLETE §1.1): the
18675
- * projection is still `{}`, so the draft has nothing to write into. Await
18676
- * `realm.whenLive()` first — or use `assertOnAttach` for state that must exist on attach. */
18907
+ /** A write or intent made before the first hydrate is queued for it; this is the queued
18908
+ * handle's rejection when that hydrate never came (the realm detached, or `pendingExpiryMs`
18909
+ * passed first). Definite: nothing was sent. A refused attach rejects with the attach error. */
18677
18910
  write_before_hydrate: err({
18678
- 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).`,
18911
+ 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.`,
18679
18912
  context: { required: true }
18680
18913
  }),
18681
18914
  /**
@@ -19836,7 +20069,7 @@ const DEFAULT_PROBE_REPLY_TIMEOUT_MS = 1e4;
19836
20069
  function connectRealm(realm, options) {
19837
20070
  const coordinate = options.connection.coordinate;
19838
20071
  const persistentId = options.avatar.persistentId ?? coordinate?.perId;
19839
- 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).");
20072
+ 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.");
19840
20073
  const avatar = {
19841
20074
  type: options.avatar.type,
19842
20075
  persistentId,
@@ -19877,8 +20110,10 @@ function connectRealm(realm, options) {
19877
20110
  if (next === "live") hasBeenLive = true;
19878
20111
  for (const listener of [...statusListeners]) listener(next, { hasBeenLive });
19879
20112
  devtools?.onStatus?.(next, { hasBeenLive });
20113
+ if (next === "detached") rejectHydrateQueue();
19880
20114
  };
19881
20115
  let pending = [];
20116
+ const hydrateQueue = [];
19882
20117
  let nextSeq = 0;
19883
20118
  let flushScheduled = false;
19884
20119
  let projecting = false;
@@ -20340,8 +20575,7 @@ function connectRealm(realm, options) {
20340
20575
  if (coalesceWindowMs > 0) unrefTimer(setTimeout(flushOutbox, coalesceWindowMs));
20341
20576
  else queueMicrotask(flushOutbox);
20342
20577
  };
20343
- const rejectImmediately = (kind, error, intentName) => {
20344
- const controller = createWriteHandle();
20578
+ const rejectUnsent = (controller, kind, error, intentName) => {
20345
20579
  controller.reject(error);
20346
20580
  emitRejection({
20347
20581
  error,
@@ -20359,6 +20593,56 @@ function connectRealm(realm, options) {
20359
20593
  });
20360
20594
  return controller.handle;
20361
20595
  };
20596
+ const rejectImmediately = (kind, error, intentName) => rejectUnsent(createWriteHandle(), kind, error, intentName);
20597
+ const neverHydratedError = () => attachError ?? err_realm.fromId("write_before_hydrate", { realmId: realm.id });
20598
+ const rejectQueued = (queued, error) => {
20599
+ if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
20600
+ rejectUnsent(queued.controller, queued.kind, error, queued.intentName);
20601
+ };
20602
+ const mustQueueUntilHydrate = () => confirmedVersion === -1 || hydrateQueue.length > 0;
20603
+ const queueUntilHydrate = (queuedWrite, durability) => {
20604
+ const controller = createWriteHandle();
20605
+ if (status === "detached") return rejectUnsent(controller, queuedWrite.kind, neverHydratedError(), queuedWrite.intentName);
20606
+ const queued = {
20607
+ ...queuedWrite,
20608
+ controller,
20609
+ expiryTimer: void 0
20610
+ };
20611
+ if (durability !== "reassert") {
20612
+ queued.expiryTimer = setTimeout(() => {
20613
+ const index = hydrateQueue.indexOf(queued);
20614
+ if (index < 0) return;
20615
+ hydrateQueue.splice(index, 1);
20616
+ rejectQueued(queued, neverHydratedError());
20617
+ notifyPending();
20618
+ }, expiryMs);
20619
+ unrefTimer(queued.expiryTimer);
20620
+ }
20621
+ hydrateQueue.push(queued);
20622
+ notifyPending();
20623
+ return controller.handle;
20624
+ };
20625
+ const drainHydrateQueue = () => {
20626
+ for (let queued = hydrateQueue.shift(); queued != null; queued = hydrateQueue.shift()) {
20627
+ if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
20628
+ const { controller } = queued;
20629
+ let sent;
20630
+ try {
20631
+ sent = queued.run();
20632
+ } catch (cause) {
20633
+ console.error(`${warnTag()} a write queued before the first hydrate threw`, cause);
20634
+ rejectQueued(queued, castNiceError(cause));
20635
+ continue;
20636
+ }
20637
+ const settled = sent;
20638
+ settled.then(controller.confirm, () => {
20639
+ if (settled.error != null) controller.reject(settled.error);
20640
+ });
20641
+ }
20642
+ };
20643
+ const rejectHydrateQueue = () => {
20644
+ for (const queued of hydrateQueue.splice(0)) rejectQueued(queued, neverHydratedError());
20645
+ };
20362
20646
  const enqueueWrite = (patches, writeOptions) => {
20363
20647
  const durability = writeOptions?.durability;
20364
20648
  const immediate = writeOptions?.flush === "immediate";
@@ -20411,19 +20695,8 @@ function connectRealm(realm, options) {
20411
20695
  } else scheduleFlush();
20412
20696
  return controller.handle;
20413
20697
  };
20414
- const update = (fn, updateOptions) => {
20698
+ const applyUpdate = (fn, updateOptions) => {
20415
20699
  const projected = store.state;
20416
- if (confirmedVersion === -1) {
20417
- const error = err_realm.fromId("write_before_hydrate", { realmId: realm.id });
20418
- try {
20419
- produceWithPatches(projected, (draft) => {
20420
- fn(draft);
20421
- });
20422
- } catch (cause) {
20423
- throw new Error(error.message, { cause });
20424
- }
20425
- return rejectImmediately("write", error);
20426
- }
20427
20700
  let returned;
20428
20701
  const [next, patches] = produceWithPatches(projected, (draft) => {
20429
20702
  returned = fn(draft);
@@ -20445,7 +20718,16 @@ function connectRealm(realm, options) {
20445
20718
  if (verdict !== true) return rejectImmediately("write", verdict);
20446
20719
  return enqueueWrite(canonical, updateOptions);
20447
20720
  };
20448
- const runIntent = (name, input) => {
20721
+ const update = (fn, updateOptions) => mustQueueUntilHydrate() ? queueUntilHydrate({
20722
+ kind: "write",
20723
+ run: () => applyUpdate(fn, updateOptions)
20724
+ }, updateOptions?.durability) : applyUpdate(fn, updateOptions);
20725
+ const runIntent = (name, input) => mustQueueUntilHydrate() ? queueUntilHydrate({
20726
+ kind: "intent",
20727
+ intentName: name,
20728
+ run: () => sendIntent(name, input)
20729
+ }) : sendIntent(name, input);
20730
+ const sendIntent = (name, input) => {
20449
20731
  const def = realm.intents[name];
20450
20732
  if (def == null) return rejectImmediately("intent", err_realm.fromId("intent_unknown", { intent: name }), name);
20451
20733
  const invalid = validateValue(def.input, input);
@@ -20626,7 +20908,8 @@ function connectRealm(realm, options) {
20626
20908
  if (!isFirstHydrate && realm.transient.length > 0 && options.assertOnAttach != null && !hasPendingSystemAssert()) enqueueSystemAssert(confirmed);
20627
20909
  revalidateAndResendPending();
20628
20910
  project({ fullReplace: true });
20629
- if (options.assertOnAttach != null && !hasPendingSystemAssert()) update(options.assertOnAttach);
20911
+ if (options.assertOnAttach != null && !hasPendingSystemAssert()) applyUpdate(options.assertOnAttach);
20912
+ drainHydrateQueue();
20630
20913
  checkReownWatch();
20631
20914
  return;
20632
20915
  }
@@ -20933,11 +21216,12 @@ function connectRealm(realm, options) {
20933
21216
  }
20934
21217
  const handle = {
20935
21218
  store,
21219
+ avatar,
20936
21220
  update,
20937
21221
  intents: Object.fromEntries(realm.intentNames.map((name) => [name, (input) => runIntent(name, input)])),
20938
21222
  pending: {
20939
21223
  get count() {
20940
- return pending.reduce((n, frame) => frame.isSystemAssert ? n : n + 1, 0);
21224
+ return pending.reduce((n, frame) => frame.isSystemAssert ? n : n + 1, 0) + hydrateQueue.length;
20941
21225
  },
20942
21226
  has(pathPrefix) {
20943
21227
  return pending.some((frame) => !frame.isSystemAssert && frame.patches.some((patch) => patch.path.join(".").startsWith(pathPrefix)));
@@ -23313,7 +23597,8 @@ function commanderStatePaths(dataDir, configKey) {
23313
23597
  upLockPath: (0, node_path.join)(stateDir, "up.lock"),
23314
23598
  bootLogPath: (0, node_path.join)(stateDir, "daemon-boot.log"),
23315
23599
  ingestSeqPath: (0, node_path.join)(stateDir, "ingest-seq"),
23316
- envOverridesPath: (0, node_path.join)(stateDir, "env-overrides.json")
23600
+ envOverridesPath: (0, node_path.join)(stateDir, "env-overrides.json"),
23601
+ savedFiltersPath: (0, node_path.join)(stateDir, "saved-filters.json")
23317
23602
  };
23318
23603
  }
23319
23604
  async function ensureStateDir(paths) {
@@ -23407,7 +23692,8 @@ const commanderStatusRealm = defineRealm({
23407
23692
  degraded: t.boolean(),
23408
23693
  notes: t.array(t.string())
23409
23694
  })),
23410
- tags: t.record(t.id("tag"), t.string()),
23695
+ tags: t.record(t.id("tag"), t.array(t.string())),
23696
+ optIn: t.boolean(),
23411
23697
  detail: t.object({
23412
23698
  command: t.string(),
23413
23699
  cwd: t.string(),
@@ -23433,7 +23719,30 @@ const commanderStatusRealm = defineRealm({
23433
23719
  }))
23434
23720
  })
23435
23721
  })),
23436
- groups: t.record(t.id("groupName"), t.object({ members: t.array(t.string()) }))
23722
+ suites: t.record(t.id("suiteName"), t.object({
23723
+ description: t.optional(t.string()),
23724
+ members: t.array(t.string()),
23725
+ parallel: t.number(),
23726
+ failFast: t.boolean()
23727
+ })),
23728
+ runs: t.record(t.id("runKey"), t.object({
23729
+ suite: t.optional(t.string()),
23730
+ filterId: t.optional(t.string()),
23731
+ startedAt: t.number(),
23732
+ endedAt: t.optional(t.number()),
23733
+ outcome: t.optional(t.union(t.literal("passed"), t.literal("failed"))),
23734
+ previousDurationMs: t.optional(t.number()),
23735
+ 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")))
23736
+ })),
23737
+ savedFilters: t.array(t.object({
23738
+ id: t.string(),
23739
+ name: t.optional(t.string()),
23740
+ mode: t.union(t.literal("all"), t.literal("any")),
23741
+ terms: t.array(t.string()),
23742
+ bucket: t.optional(t.array(t.string())),
23743
+ pinned: t.boolean(),
23744
+ lastRunAt: t.optional(t.number())
23745
+ }))
23437
23746
  },
23438
23747
  rules: (r) => [r.path("**").view(r.everyone).alter(r.serverOnly)]
23439
23748
  });
@@ -23566,7 +23875,7 @@ var CommanderDaemonBootError = class extends Error {
23566
23875
  * a live dev environment, and an upgrade must never be the thing that kills one.
23567
23876
  */
23568
23877
  async function replaceSkewedDaemon(paths, skewed) {
23569
- 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" : ""})`;
23878
+ 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" : ""})`;
23570
23879
  let liveIds = [];
23571
23880
  try {
23572
23881
  liveIds = (await (0, _nice_code_process.openProcessLedger)({
@@ -23811,11 +24120,78 @@ function checkEnvReport(value) {
23811
24120
  warnings
23812
24121
  };
23813
24122
  }
23814
- function checkIds(value) {
24123
+ function checkStop(value) {
23815
24124
  const record = asRecord(value);
23816
24125
  if (record == null) return "expected an object";
23817
24126
  const ids = asIdList(record["ids"]);
23818
- return ids == null ? "ids: expected an array of process ids" : { ids };
24127
+ if (ids == null) return "ids: expected an array of process ids";
24128
+ const withDependencies = record["withDependencies"];
24129
+ if (withDependencies != null && typeof withDependencies !== "boolean") return "withDependencies: expected a boolean";
24130
+ return withDependencies === true ? {
24131
+ ids,
24132
+ withDependencies
24133
+ } : { ids };
24134
+ }
24135
+ function checkRunSuite(value) {
24136
+ const record = asRecord(value);
24137
+ if (record == null) return "expected an object";
24138
+ const input = {};
24139
+ const suite = record["suite"];
24140
+ if (suite != null) {
24141
+ if (typeof suite !== "string" || suite === "") return "suite: expected a suite name";
24142
+ input.suite = suite;
24143
+ }
24144
+ if (record["ids"] != null) {
24145
+ const ids = asIdList(record["ids"]);
24146
+ if (ids == null) return "ids: expected an array of process ids";
24147
+ input.ids = ids;
24148
+ }
24149
+ if (input.suite == null === (input.ids == null)) return "expected exactly one of suite | ids";
24150
+ const parallel = record["parallel"];
24151
+ if (parallel != null) {
24152
+ if (typeof parallel !== "number" || !Number.isInteger(parallel) || parallel < 1) return "parallel: expected an integer ≥ 1";
24153
+ input.parallel = parallel;
24154
+ }
24155
+ const failFast = record["failFast"];
24156
+ if (failFast != null) {
24157
+ if (typeof failFast !== "boolean") return "failFast: expected a boolean";
24158
+ input.failFast = failFast;
24159
+ }
24160
+ if (record["filter"] != null) {
24161
+ const filter = checkSavedFilterQuery(record["filter"]);
24162
+ if (typeof filter === "string") return `filter.${filter}`;
24163
+ input.filter = filter;
24164
+ }
24165
+ return input;
24166
+ }
24167
+ function checkRunSuiteReport(value) {
24168
+ const record = asRecord(value);
24169
+ if (record == null || typeof record["accepted"] !== "boolean") return "expected { accepted }";
24170
+ const { runKey, reason } = record;
24171
+ return {
24172
+ accepted: record["accepted"],
24173
+ ...typeof runKey === "string" ? { runKey } : {},
24174
+ ...typeof reason === "string" ? { reason } : {}
24175
+ };
24176
+ }
24177
+ function checkSaveFilter(value) {
24178
+ const record = asRecord(value);
24179
+ if (record == null) return "expected an object";
24180
+ const filter = checkSavedFilterQuery(record["filter"]);
24181
+ if (typeof filter === "string") return `filter.${filter}`;
24182
+ const name = record["name"];
24183
+ if (typeof name !== "string") return "name: expected a string";
24184
+ return {
24185
+ filter,
24186
+ name
24187
+ };
24188
+ }
24189
+ function checkRemoveFilter(value) {
24190
+ const id = asRecord(value)?.["id"];
24191
+ return typeof id === "string" && id !== "" ? { id } : "id: expected a saved filter id";
24192
+ }
24193
+ function checkOk(value) {
24194
+ return asRecord(value)?.["ok"] === true ? { ok: true } : "expected { ok: true }";
23819
24195
  }
23820
24196
  function checkEmpty(value) {
23821
24197
  return asRecord(value) == null ? "expected an object" : {};
@@ -23895,11 +24271,14 @@ const commanderControlDomain = createActionRootDomain({ domain: "commander" }).c
23895
24271
  actions: {
23896
24272
  ports: actionSchema().input({ schema: handSchema(checkPortsInput) }).output({ schema: handSchema(checkPortsReport) }),
23897
24273
  start: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
23898
- stop: actionSchema().input({ schema: handSchema(checkIds) }).output({ schema: handSchema(checkReport) }),
24274
+ stop: actionSchema().input({ schema: handSchema(checkStop) }).output({ schema: handSchema(checkReport) }),
23899
24275
  restart: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
24276
+ runSuite: actionSchema().input({ schema: handSchema(checkRunSuite) }).output({ schema: handSchema(checkRunSuiteReport) }),
24277
+ saveFilter: actionSchema().input({ schema: handSchema(checkSaveFilter) }).output({ schema: handSchema(checkOk) }),
24278
+ removeFilter: actionSchema().input({ schema: handSchema(checkRemoveFilter) }).output({ schema: handSchema(checkOk) }),
23900
24279
  setEnv: actionSchema().input({ schema: handSchema(checkSetEnv) }).output({ schema: handSchema(checkEnvReport) }),
23901
24280
  reloadConfig: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkReloadResult) }),
23902
- shutdown: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema((value) => value != null && value.ok === true ? { ok: true } : "expected { ok: true }") })
24281
+ shutdown: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkOk) })
23903
24282
  }
23904
24283
  });
23905
24284
  /** One socket carries control actions (toAcceptor) + the status realm (a mux protocol, D1). */
@@ -23943,7 +24322,7 @@ async function findDaemon(config) {
23943
24322
  async function findSkewedDaemon(config) {
23944
24323
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
23945
24324
  if (skewed == null || !pidAlive$1(skewed.pid)) return null;
23946
- const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v5` : "was started before an upgrade changed the status schema";
24325
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v6` : "was started before an upgrade changed the status schema";
23947
24326
  return {
23948
24327
  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.`,
23949
24328
  pid: skewed.pid,
@@ -24041,7 +24420,7 @@ async function connectDaemon(handle) {
24041
24420
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
24042
24421
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
24043
24422
  const report = parseActionReport(payload.result.output);
24044
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 5`);
24423
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 6`);
24045
24424
  return report;
24046
24425
  },
24047
24426
  setEnv: async (input) => {
@@ -24128,7 +24507,8 @@ async function cmdUp(ctx) {
24128
24507
  const bad = unknownFlags(ctx.args.flags, [
24129
24508
  "--no-wait",
24130
24509
  "--dry-run",
24131
- "--all"
24510
+ "--all",
24511
+ "--any"
24132
24512
  ]);
24133
24513
  if (bad != null) throw new CliExit(EXIT.usage, bad);
24134
24514
  const selection = selectOrExit(ctx, { bare: "default" });
@@ -24162,7 +24542,11 @@ async function cmdUp(ctx) {
24162
24542
  }
24163
24543
  }
24164
24544
  async function controlVerb(ctx, verb) {
24165
- const known = verb === "restart" ? ["--no-wait", "--all"] : ["--all"];
24545
+ const known = verb === "restart" ? [
24546
+ "--no-wait",
24547
+ "--all",
24548
+ "--any"
24549
+ ] : ["--all", "--any"];
24166
24550
  const bad = unknownFlags(ctx.args.flags, known);
24167
24551
  if (bad != null) throw new CliExit(EXIT.usage, bad);
24168
24552
  requireSelectionTerms(ctx);
@@ -24257,6 +24641,85 @@ function reportSignalShutdown(ctx, result) {
24257
24641
  }
24258
24642
  }
24259
24643
  //#endregion
24644
+ //#region src/daemon/envOverrides.ts
24645
+ const STORE_VERSION$1 = 1;
24646
+ /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
24647
+ const MAX_VALUE_LENGTH = 4096;
24648
+ const EMPTY_ENV_OVERRIDES = Object.freeze({});
24649
+ function readable$1(value) {
24650
+ if (value == null || typeof value !== "object") return null;
24651
+ const processes = value.processes;
24652
+ if (processes == null || typeof processes !== "object" || Array.isArray(processes)) return null;
24653
+ const clean = {};
24654
+ for (const [id, values] of Object.entries(processes)) {
24655
+ if (values == null || typeof values !== "object" || Array.isArray(values)) continue;
24656
+ const entries = {};
24657
+ for (const [name, entry] of Object.entries(values)) if (typeof entry === "string" && entry.length <= MAX_VALUE_LENGTH) entries[name] = entry;
24658
+ if (Object.keys(entries).length > 0) clean[id] = entries;
24659
+ }
24660
+ return clean;
24661
+ }
24662
+ /**
24663
+ * Missing, unreadable or corrupt all read as "no overrides". A bad file must never block a start:
24664
+ * the config alone is always enough to run, and the surfaces that report overrides say when the
24665
+ * store could not be read.
24666
+ */
24667
+ async function readEnvOverrides(path) {
24668
+ try {
24669
+ return readable$1(JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8"))) ?? EMPTY_ENV_OVERRIDES;
24670
+ } catch {
24671
+ return EMPTY_ENV_OVERRIDES;
24672
+ }
24673
+ }
24674
+ /** 0600 and atomic — it can hold a token, and a half-written file must never be read as empty. */
24675
+ async function writeEnvOverrides(path, overrides) {
24676
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), {
24677
+ recursive: true,
24678
+ mode: 448
24679
+ });
24680
+ const store = {
24681
+ version: STORE_VERSION$1,
24682
+ processes: Object.fromEntries(Object.entries(overrides).filter(([, values]) => Object.keys(values).length > 0).map(([id, values]) => [id, { ...values }]))
24683
+ };
24684
+ const temp = `${path}.${process.pid}.tmp`;
24685
+ await (0, node_fs_promises.writeFile)(temp, `${JSON.stringify(store, null, 2)}\n`, {
24686
+ encoding: "utf8",
24687
+ mode: 384
24688
+ });
24689
+ await (0, node_fs_promises.rename)(temp, path);
24690
+ }
24691
+ /** Pure: the store that results from applying `change`. Empty processes are pruned. */
24692
+ function mutateEnvOverrides(current, change) {
24693
+ const next = {};
24694
+ for (const [id, values] of Object.entries(current)) next[id] = { ...values };
24695
+ for (const id of change.clear ?? []) delete next[id];
24696
+ for (const [id, values] of Object.entries(change.mutations ?? {})) {
24697
+ const entries = next[id] ?? {};
24698
+ for (const [name, value] of Object.entries(values)) if (value == null) delete entries[name];
24699
+ else entries[name] = value;
24700
+ if (Object.keys(entries).length > 0) next[id] = entries;
24701
+ else delete next[id];
24702
+ }
24703
+ return next;
24704
+ }
24705
+ /**
24706
+ * Read → check against the config → mutate → write, atomically enough for a file two surfaces
24707
+ * touch. The one implementation behind both writers, so the daemon's `setEnv` and the CLI's
24708
+ * no-daemon path can never diverge on what they accept.
24709
+ */
24710
+ async function applyEnvMutation(path, config, input) {
24711
+ const checked = checkEnvMutations(config, input);
24712
+ const next = mutateEnvOverrides(await readEnvOverrides(path), checked);
24713
+ await writeEnvOverrides(path, next);
24714
+ return {
24715
+ overrides: next,
24716
+ warnings: checked.warnings
24717
+ };
24718
+ }
24719
+ function countOverrides(overrides) {
24720
+ return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);
24721
+ }
24722
+ //#endregion
24260
24723
  //#region src/ports/listeners.ts
24261
24724
  const exec = (0, node_util.promisify)(node_child_process.execFile);
24262
24725
  const ACTIVE = new Set([
@@ -24490,206 +24953,31 @@ function createPortInspector(options) {
24490
24953
  return { run };
24491
24954
  }
24492
24955
  //#endregion
24493
- //#region src/cli/commands/ports.ts
24494
- async function portProcessStates(ctx) {
24495
- const handle = await findDaemon(ctx.config);
24496
- if (!handle) return /* @__PURE__ */ new Map();
24497
- const client = await connectDaemon(handle);
24956
+ //#region src/cli/commands/doctor.ts
24957
+ function formatAge(ms) {
24958
+ if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
24959
+ if (ms < 36e5) return `${Math.round(ms / 6e4)}m`;
24960
+ return `${(ms / 36e5).toFixed(1)}h`;
24961
+ }
24962
+ let cachedWsl = null;
24963
+ /** WSL detection (fs.watch is flaky on /mnt/c; also drives the browser ladder). */
24964
+ async function isWsl() {
24965
+ if (cachedWsl != null) return cachedWsl;
24966
+ if (process.platform !== "linux") {
24967
+ cachedWsl = false;
24968
+ return false;
24969
+ }
24970
+ if (process.env["WSL_DISTRO_NAME"] != null) {
24971
+ cachedWsl = true;
24972
+ return true;
24973
+ }
24498
24974
  try {
24499
- return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
24500
- } finally {
24501
- client.dispose();
24502
- }
24503
- }
24504
- async function cmdPorts(ctx) {
24505
- const bad = unknownFlags(ctx.args.flags, [
24506
- "--all",
24507
- "--kill",
24508
- "--yes",
24509
- "--force"
24510
- ]);
24511
- if (bad) throw new CliExit(EXIT.usage, bad);
24512
- const pid = numericFlag(ctx.args.flags, "--kill");
24513
- if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
24514
- for (const flag of [
24515
- "--yes",
24516
- "--force",
24517
- "--all"
24518
- ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
24519
- if (!pid && (ctx.args.flags.has("--force") || ctx.args.flags.has("--yes"))) throw new CliExit(EXIT.usage, "--force/--yes require --kill PID");
24520
- const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
24521
- const inspector = createPortInspector({
24522
- config: () => ctx.config,
24523
- states: () => portProcessStates(ctx),
24524
- protectedPids: async () => {
24525
- const daemon = await findDaemon(ctx.config);
24526
- return daemon ? [daemon.record.pid] : [];
24527
- }
24528
- });
24529
- const report = await inspector.run({ ids });
24530
- const print = (result) => {
24531
- if (ctx.out.json) {
24532
- ctx.out.printJson(result);
24533
- return;
24534
- }
24535
- ctx.out.print(ctx.out.table([
24536
- "PROCESS",
24537
- "ENDPOINT",
24538
- "PID",
24539
- "PARENT",
24540
- "COMMAND",
24541
- "CWD",
24542
- "IDENTITY",
24543
- "STOP"
24544
- ], result.listeners.map((l) => [
24545
- l.id,
24546
- `${l.host}:${l.port}`,
24547
- String(l.pid),
24548
- String(l.ppid ?? "unknown"),
24549
- l.command,
24550
- l.cwd ?? "unavailable",
24551
- l.startStamp ?? "unknown",
24552
- l.refusal ?? "available"
24553
- ])));
24554
- if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
24555
- for (const warning of result.warnings) ctx.out.warn(warning);
24556
- };
24557
- if (!pid) {
24558
- print(report);
24559
- return report.warnings.length ? EXIT.failure : EXIT.ok;
24560
- }
24561
- const target = report.listeners.find((l) => l.pid === pid);
24562
- if (!target?.token) {
24563
- print(report);
24564
- throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
24565
- }
24566
- if (!ctx.args.flags.has("--yes")) {
24567
- print(report);
24568
- if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes with --kill PID");
24569
- const rl = (0, node_readline_promises.createInterface)({
24570
- input: process.stdin,
24571
- output: process.stdout
24572
- });
24573
- try {
24574
- const answer = await rl.question(`${ctx.args.flags.has("--force") ? "Force kill" : "Stop"} PID ${pid} (${target.command}) on ${target.host}:${target.port}? [y/N] `);
24575
- if (!/^y(es)?$/i.test(answer.trim())) return EXIT.ok;
24576
- } finally {
24577
- rl.close();
24578
- }
24579
- }
24580
- const result = await inspector.run({
24581
- ids,
24582
- token: target.token,
24583
- force: ctx.args.flags.has("--force")
24584
- });
24585
- print(result);
24586
- return result.warnings.length ? EXIT.failure : EXIT.ok;
24587
- }
24588
- //#endregion
24589
- //#region src/daemon/envOverrides.ts
24590
- const STORE_VERSION = 1;
24591
- /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
24592
- const MAX_VALUE_LENGTH = 4096;
24593
- const EMPTY_ENV_OVERRIDES = Object.freeze({});
24594
- function readable(value) {
24595
- if (value == null || typeof value !== "object") return null;
24596
- const processes = value.processes;
24597
- if (processes == null || typeof processes !== "object" || Array.isArray(processes)) return null;
24598
- const clean = {};
24599
- for (const [id, values] of Object.entries(processes)) {
24600
- if (values == null || typeof values !== "object" || Array.isArray(values)) continue;
24601
- const entries = {};
24602
- for (const [name, entry] of Object.entries(values)) if (typeof entry === "string" && entry.length <= MAX_VALUE_LENGTH) entries[name] = entry;
24603
- if (Object.keys(entries).length > 0) clean[id] = entries;
24604
- }
24605
- return clean;
24606
- }
24607
- /**
24608
- * Missing, unreadable or corrupt all read as "no overrides". A bad file must never block a start:
24609
- * the config alone is always enough to run, and the surfaces that report overrides say when the
24610
- * store could not be read.
24611
- */
24612
- async function readEnvOverrides(path) {
24613
- try {
24614
- return readable(JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8"))) ?? EMPTY_ENV_OVERRIDES;
24615
- } catch {
24616
- return EMPTY_ENV_OVERRIDES;
24617
- }
24618
- }
24619
- /** 0600 and atomic — it can hold a token, and a half-written file must never be read as empty. */
24620
- async function writeEnvOverrides(path, overrides) {
24621
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), {
24622
- recursive: true,
24623
- mode: 448
24624
- });
24625
- const store = {
24626
- version: STORE_VERSION,
24627
- processes: Object.fromEntries(Object.entries(overrides).filter(([, values]) => Object.keys(values).length > 0).map(([id, values]) => [id, { ...values }]))
24628
- };
24629
- const temp = `${path}.${process.pid}.tmp`;
24630
- await (0, node_fs_promises.writeFile)(temp, `${JSON.stringify(store, null, 2)}\n`, {
24631
- encoding: "utf8",
24632
- mode: 384
24633
- });
24634
- await (0, node_fs_promises.rename)(temp, path);
24635
- }
24636
- /** Pure: the store that results from applying `change`. Empty processes are pruned. */
24637
- function mutateEnvOverrides(current, change) {
24638
- const next = {};
24639
- for (const [id, values] of Object.entries(current)) next[id] = { ...values };
24640
- for (const id of change.clear ?? []) delete next[id];
24641
- for (const [id, values] of Object.entries(change.mutations ?? {})) {
24642
- const entries = next[id] ?? {};
24643
- for (const [name, value] of Object.entries(values)) if (value == null) delete entries[name];
24644
- else entries[name] = value;
24645
- if (Object.keys(entries).length > 0) next[id] = entries;
24646
- else delete next[id];
24647
- }
24648
- return next;
24649
- }
24650
- /**
24651
- * Read → check against the config → mutate → write, atomically enough for a file two surfaces
24652
- * touch. The one implementation behind both writers, so the daemon's `setEnv` and the CLI's
24653
- * no-daemon path can never diverge on what they accept.
24654
- */
24655
- async function applyEnvMutation(path, config, input) {
24656
- const checked = checkEnvMutations(config, input);
24657
- const next = mutateEnvOverrides(await readEnvOverrides(path), checked);
24658
- await writeEnvOverrides(path, next);
24659
- return {
24660
- overrides: next,
24661
- warnings: checked.warnings
24662
- };
24663
- }
24664
- function countOverrides(overrides) {
24665
- return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);
24666
- }
24667
- //#endregion
24668
- //#region src/cli/commands/doctor.ts
24669
- function formatAge(ms) {
24670
- if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
24671
- if (ms < 36e5) return `${Math.round(ms / 6e4)}m`;
24672
- return `${(ms / 36e5).toFixed(1)}h`;
24673
- }
24674
- let cachedWsl = null;
24675
- /** WSL detection (fs.watch is flaky on /mnt/c; also drives the browser ladder). */
24676
- async function isWsl() {
24677
- if (cachedWsl != null) return cachedWsl;
24678
- if (process.platform !== "linux") {
24679
- cachedWsl = false;
24680
- return false;
24681
- }
24682
- if (process.env["WSL_DISTRO_NAME"] != null) {
24683
- cachedWsl = true;
24684
- return true;
24685
- }
24686
- try {
24687
- const release = await (0, node_fs_promises.readFile)("/proc/sys/kernel/osrelease", "utf8");
24688
- cachedWsl = /microsoft/i.test(release);
24689
- return cachedWsl;
24690
- } catch {
24691
- cachedWsl = false;
24692
- return false;
24975
+ const release = await (0, node_fs_promises.readFile)("/proc/sys/kernel/osrelease", "utf8");
24976
+ cachedWsl = /microsoft/i.test(release);
24977
+ return cachedWsl;
24978
+ } catch {
24979
+ cachedWsl = false;
24980
+ return false;
24693
24981
  }
24694
24982
  }
24695
24983
  function tryConnectTcp(host, port, timeoutMs = 600) {
@@ -24998,12 +25286,10 @@ async function cmdList(ctx) {
24998
25286
  dependsOn: proc.dependsOn,
24999
25287
  endpoints: proc.endpoints,
25000
25288
  url: proc.url ?? null,
25001
- envVars: proc.envVars
25289
+ envVars: proc.envVars,
25290
+ optIn: proc.optIn
25002
25291
  })),
25003
- groups: Object.fromEntries(Object.entries(config.groups).map(([name, group]) => [name, {
25004
- ids: group.ids,
25005
- staggerMs: group.staggerMs
25006
- }])),
25292
+ suites: Object.fromEntries(Object.entries(config.suites).map(([name, { name: _name, ...suite }]) => [name, suite])),
25007
25293
  warnings: config.warnings
25008
25294
  });
25009
25295
  return EXIT.ok;
@@ -25017,31 +25303,31 @@ async function cmdList(ctx) {
25017
25303
  ], config.processes.map((proc) => [
25018
25304
  proc.id,
25019
25305
  proc.kind,
25020
- Object.entries(proc.tags).map(([key, value]) => `${key}=${value}`).join(" "),
25306
+ [...tagTermsOf(proc.tags), ...proc.optIn ? ["(opt-in)"] : []].join(" "),
25021
25307
  proc.dependsOn.join(" "),
25022
25308
  proc.endpoints.map((endpoint) => `${endpoint.name}:${endpoint.port}`).join(" ")
25023
25309
  ])));
25024
- const groupRows = Object.entries(config.groups).map(([name, group]) => [
25025
- name,
25026
- String(group.ids.length),
25027
- group.ids.join(" "),
25028
- group.staggerMs > 0 ? `${group.staggerMs}ms` : "-"
25310
+ const suiteRows = Object.values(config.suites).map((suite) => [
25311
+ suite.name,
25312
+ String(suite.ids.length),
25313
+ `parallel ${suite.parallel}${suite.failFast ? " · fail-fast" : ""}`,
25314
+ suite.ids.join(" ")
25029
25315
  ]);
25030
- if (groupRows.length > 0) {
25316
+ if (suiteRows.length > 0) {
25031
25317
  out.print("");
25032
25318
  out.print(out.table([
25033
- "GROUP",
25319
+ "SUITE",
25034
25320
  "N",
25035
- "IDS",
25036
- "STAGGER"
25037
- ], groupRows));
25321
+ "POLICY",
25322
+ "IDS"
25323
+ ], suiteRows));
25038
25324
  }
25039
25325
  if (config.defaultSelection != null) out.print(out.paint("gray", `\ndefaultSelection: ${config.defaultSelection}`));
25040
25326
  for (const warning of config.warnings) out.warn(`${out.paint("yellow", "⚠")} ${warning}`);
25041
25327
  return EXIT.ok;
25042
25328
  }
25043
25329
  async function cmdExplain(ctx) {
25044
- const bad = unknownFlags(ctx.args.flags, ["--all"]);
25330
+ const bad = unknownFlags(ctx.args.flags, ["--all", "--any"]);
25045
25331
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25046
25332
  const selection = selectOrExit(ctx, { bare: "default" });
25047
25333
  const { out } = ctx;
@@ -25051,6 +25337,9 @@ async function cmdExplain(ctx) {
25051
25337
  }
25052
25338
  out.print(`direct: ${selection.direct.join(", ") || "(none)"}`);
25053
25339
  out.print(`auto-included: ${selection.autoIncluded.length > 0 ? selection.autoIncluded.join(", ") : "(none)"}`);
25340
+ const [onlyTerm] = ctx.args.positionals.length === 1 ? ctx.args.positionals : [];
25341
+ const suite = onlyTerm == null ? void 0 : ctx.config.suites[onlyTerm];
25342
+ if (suite != null) out.print(`suite policy: parallel ${suite.parallel}, fail-fast ${suite.failFast ? "on" : "off"}, stagger ${suite.staggerMs}ms`);
25054
25343
  out.print(`DAG order:`);
25055
25344
  selection.ordered.forEach((id, index) => {
25056
25345
  out.print(` ${index + 1}. ${id}`);
@@ -25238,6 +25527,7 @@ function printLine(out, entry) {
25238
25527
  }
25239
25528
  async function cmdLogs(ctx) {
25240
25529
  const bad = unknownFlags(ctx.args.flags, [
25530
+ "--any",
25241
25531
  "-f",
25242
25532
  "--follow",
25243
25533
  "--all"
@@ -25302,6 +25592,159 @@ async function cmdLogs(ctx) {
25302
25592
  }
25303
25593
  }
25304
25594
  //#endregion
25595
+ //#region src/cli/commands/ports.ts
25596
+ async function portProcessStates(ctx) {
25597
+ const handle = await findDaemon(ctx.config);
25598
+ if (!handle) return /* @__PURE__ */ new Map();
25599
+ const client = await connectDaemon(handle);
25600
+ try {
25601
+ return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
25602
+ } finally {
25603
+ client.dispose();
25604
+ }
25605
+ }
25606
+ async function cmdPorts(ctx) {
25607
+ const bad = unknownFlags(ctx.args.flags, [
25608
+ "--all",
25609
+ "--kill",
25610
+ "--yes",
25611
+ "--force"
25612
+ ]);
25613
+ if (bad) throw new CliExit(EXIT.usage, bad);
25614
+ const pid = numericFlag(ctx.args.flags, "--kill");
25615
+ if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
25616
+ for (const flag of [
25617
+ "--yes",
25618
+ "--force",
25619
+ "--all"
25620
+ ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
25621
+ if (!pid && (ctx.args.flags.has("--force") || ctx.args.flags.has("--yes"))) throw new CliExit(EXIT.usage, "--force/--yes require --kill PID");
25622
+ const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
25623
+ const inspector = createPortInspector({
25624
+ config: () => ctx.config,
25625
+ states: () => portProcessStates(ctx),
25626
+ protectedPids: async () => {
25627
+ const daemon = await findDaemon(ctx.config);
25628
+ return daemon ? [daemon.record.pid] : [];
25629
+ }
25630
+ });
25631
+ const report = await inspector.run({ ids });
25632
+ const print = (result) => {
25633
+ if (ctx.out.json) {
25634
+ ctx.out.printJson(result);
25635
+ return;
25636
+ }
25637
+ ctx.out.print(ctx.out.table([
25638
+ "PROCESS",
25639
+ "ENDPOINT",
25640
+ "PID",
25641
+ "PARENT",
25642
+ "COMMAND",
25643
+ "CWD",
25644
+ "IDENTITY",
25645
+ "STOP"
25646
+ ], result.listeners.map((l) => [
25647
+ l.id,
25648
+ `${l.host}:${l.port}`,
25649
+ String(l.pid),
25650
+ String(l.ppid ?? "unknown"),
25651
+ l.command,
25652
+ l.cwd ?? "unavailable",
25653
+ l.startStamp ?? "unknown",
25654
+ l.refusal ?? "available"
25655
+ ])));
25656
+ if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
25657
+ for (const warning of result.warnings) ctx.out.warn(warning);
25658
+ };
25659
+ if (!pid) {
25660
+ print(report);
25661
+ return report.warnings.length ? EXIT.failure : EXIT.ok;
25662
+ }
25663
+ const target = report.listeners.find((l) => l.pid === pid);
25664
+ if (!target?.token) {
25665
+ print(report);
25666
+ throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
25667
+ }
25668
+ if (!ctx.args.flags.has("--yes")) {
25669
+ print(report);
25670
+ if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes with --kill PID");
25671
+ const rl = (0, node_readline_promises.createInterface)({
25672
+ input: process.stdin,
25673
+ output: process.stdout
25674
+ });
25675
+ try {
25676
+ const answer = await rl.question(`${ctx.args.flags.has("--force") ? "Force kill" : "Stop"} PID ${pid} (${target.command}) on ${target.host}:${target.port}? [y/N] `);
25677
+ if (!/^y(es)?$/i.test(answer.trim())) return EXIT.ok;
25678
+ } finally {
25679
+ rl.close();
25680
+ }
25681
+ }
25682
+ const result = await inspector.run({
25683
+ ids,
25684
+ token: target.token,
25685
+ force: ctx.args.flags.has("--force")
25686
+ });
25687
+ print(result);
25688
+ return result.warnings.length ? EXIT.failure : EXIT.ok;
25689
+ }
25690
+ //#endregion
25691
+ //#region src/run/scheduler.ts
25692
+ async function runTaskPool(options) {
25693
+ const { failFast } = options;
25694
+ const pending = [...options.tasks];
25695
+ const succeeded = /* @__PURE__ */ new Set();
25696
+ const failed = /* @__PURE__ */ new Set();
25697
+ const running = /* @__PURE__ */ new Set();
25698
+ const selected = new Set(options.tasks.map((task) => task.id));
25699
+ const depsOf = (task) => task.dependsOn.filter((id) => selected.has(id));
25700
+ let cut = false;
25701
+ let waiters = [];
25702
+ const settled = () => new Promise((resolve) => {
25703
+ waiters.push(resolve);
25704
+ });
25705
+ const wake = () => {
25706
+ const current = waiters;
25707
+ waiters = [];
25708
+ for (const resolve of current) resolve();
25709
+ };
25710
+ const workers = Array.from({ length: Math.min(Math.max(1, options.parallel), pending.length) }, async () => {
25711
+ for (;;) {
25712
+ if (cut) return;
25713
+ const index = pending.findIndex((task) => depsOf(task).every((id) => succeeded.has(id) || failed.has(id)));
25714
+ if (index < 0) {
25715
+ if (running.size === 0) return;
25716
+ await settled();
25717
+ continue;
25718
+ }
25719
+ const [task] = pending.splice(index, 1);
25720
+ if (task == null) return;
25721
+ const blockedBy = depsOf(task).find((id) => failed.has(id));
25722
+ if (blockedBy != null) {
25723
+ failed.add(task.id);
25724
+ options.onBlocked(task, blockedBy);
25725
+ wake();
25726
+ continue;
25727
+ }
25728
+ running.add(task.id);
25729
+ const ok = await options.run(task);
25730
+ running.delete(task.id);
25731
+ (ok ? succeeded : failed).add(task.id);
25732
+ if (!ok && failFast && !cut) {
25733
+ cut = true;
25734
+ options.onFailFast?.();
25735
+ }
25736
+ wake();
25737
+ if (cut) return;
25738
+ }
25739
+ });
25740
+ await Promise.all(workers);
25741
+ return {
25742
+ succeeded,
25743
+ failed,
25744
+ leftover: pending
25745
+ };
25746
+ }
25747
+ //#endregion
25305
25748
  //#region src/cli/commands/run.ts
25306
25749
  const ACTIVE_STATES$1 = new Set([
25307
25750
  "starting",
@@ -25366,14 +25809,17 @@ async function cmdRun(ctx) {
25366
25809
  const bad = unknownFlags(ctx.args.flags, [
25367
25810
  "--parallel",
25368
25811
  "--fail-fast",
25369
- "--all"
25812
+ "--all",
25813
+ "--any"
25370
25814
  ]);
25371
25815
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25372
25816
  const parallel = numericFlag(ctx.args.flags, "--parallel");
25373
25817
  if (parallel != null && typeof parallel === "object") throw new CliExit(EXIT.usage, parallel.error);
25374
- const failFast = ctx.args.flags.has("--fail-fast");
25375
25818
  const selection = selectOrExit(ctx, { bare: "required" });
25376
25819
  const { out, config } = ctx;
25820
+ const [onlyTerm] = ctx.args.positionals.length === 1 ? ctx.args.positionals : [];
25821
+ const suitePolicy = onlyTerm == null ? void 0 : config.suites[onlyTerm];
25822
+ const failFast = ctx.args.flags.has("--fail-fast") || suitePolicy?.failFast === true;
25377
25823
  const byId = new Map(config.processes.map((proc) => [proc.id, proc]));
25378
25824
  const defs = selection.ordered.flatMap((id) => {
25379
25825
  const def = byId.get(id);
@@ -25534,60 +25980,30 @@ async function cmdRun(ctx) {
25534
25980
  try {
25535
25981
  const pumps = single ? [] : procs.map((proc) => startPump(out, proc));
25536
25982
  if (tasks.length > 0 && services.length === 0) {
25537
- const pending = [...tasks];
25538
- const succeeded = /* @__PURE__ */ new Set();
25539
- const failed = /* @__PURE__ */ new Set();
25540
- const running = /* @__PURE__ */ new Set();
25541
- const selected = new Set(tasks.map((def) => def.id));
25542
- const depsOf = (def) => def.dependsOn.filter((id) => selected.has(id));
25543
- let waiters = [];
25544
- const settled = () => new Promise((resolve) => {
25545
- waiters.push(resolve);
25546
- });
25547
- const wake = () => {
25548
- const current = waiters;
25549
- waiters = [];
25550
- for (const resolve of current) resolve();
25551
- };
25552
- const workers = Array.from({ length: Math.min(parallel ?? 1, pending.length) }, async () => {
25553
- for (;;) {
25554
- if (failFast && failures.length > 0) return;
25555
- const index = pending.findIndex((def) => depsOf(def).every((id) => succeeded.has(id) || failed.has(id)));
25556
- if (index < 0) {
25557
- if (running.size === 0) return;
25558
- await settled();
25559
- continue;
25560
- }
25561
- const [def] = pending.splice(index, 1);
25562
- const blockedBy = depsOf(def).find((id) => failed.has(id));
25563
- if (blockedBy != null) {
25564
- out.print(`${out.paint("yellow", "⊘")} ${out.accent(def.id, def.id)} blocked: "${blockedBy}" failed`);
25565
- failed.add(def.id);
25566
- recordFailure({
25567
- id: def.id,
25568
- code: 1,
25569
- failed: true
25570
- });
25571
- wake();
25572
- continue;
25573
- }
25574
- running.add(def.id);
25983
+ const pool = await runTaskPool({
25984
+ tasks,
25985
+ parallel: parallel ?? suitePolicy?.parallel ?? 1,
25986
+ failFast,
25987
+ run: async (def) => {
25575
25988
  const result = await runTask(def);
25576
- running.delete(def.id);
25577
- (result.failed ? failed : succeeded).add(def.id);
25578
- wake();
25579
- if (result.failed) {
25580
- recordFailure(result);
25581
- if (failFast) {
25582
- for (const proc of procs) if (!TERMINAL_STATES.has(proc.state)) proc.stop();
25583
- return;
25584
- }
25585
- }
25989
+ if (result.failed) recordFailure(result);
25990
+ return !result.failed;
25991
+ },
25992
+ onBlocked: (def, blockedBy) => {
25993
+ out.print(`${out.paint("yellow", "⊘")} ${out.accent(def.id, def.id)} blocked: "${blockedBy}" failed`);
25994
+ recordFailure({
25995
+ id: def.id,
25996
+ code: 1,
25997
+ failed: true
25998
+ });
25999
+ },
26000
+ onFailFast: () => {
26001
+ for (const proc of procs) if (!TERMINAL_STATES.has(proc.state)) proc.stop();
25586
26002
  }
25587
26003
  });
25588
- await Promise.all(workers);
25589
- for (const def of pending) {
25590
- const blockedBy = depsOf(def).find((id) => !succeeded.has(id)) ?? "a dependency";
26004
+ const { succeeded } = pool;
26005
+ for (const def of pool.leftover) {
26006
+ const blockedBy = def.dependsOn.find((id) => tasks.some((t) => t.id === id) && !succeeded.has(id)) ?? "a dependency";
25591
26007
  out.print(`${out.paint("yellow", "⊘")} ${out.accent(def.id, def.id)} blocked: "${blockedBy}" did not succeed`);
25592
26008
  recordFailure({
25593
26009
  id: def.id,
@@ -25865,6 +26281,82 @@ async function cmdUi(ctx) {
25865
26281
  return EXIT.ok;
25866
26282
  }
25867
26283
  //#endregion
26284
+ //#region src/daemon/savedFilters.ts
26285
+ const STORE_VERSION = 1;
26286
+ function readable(value) {
26287
+ const filters = value?.filters;
26288
+ if (!Array.isArray(filters)) return [];
26289
+ const clean = [];
26290
+ for (const entry of filters) {
26291
+ const query = checkSavedFilterQuery(entry);
26292
+ if (typeof query === "string") continue;
26293
+ const record = { ...entry };
26294
+ const name = record["name"];
26295
+ const lastRunAt = record["lastRunAt"];
26296
+ clean.push({
26297
+ id: savedFilterId(query),
26298
+ ...query,
26299
+ pinned: record["pinned"] === true,
26300
+ ...typeof name === "string" && name !== "" ? { name: name.slice(0, 48) } : {},
26301
+ ...typeof lastRunAt === "number" ? { lastRunAt } : {}
26302
+ });
26303
+ }
26304
+ return bounded(clean);
26305
+ }
26306
+ /** Pins are kept (newest-first cap); recents are a small ring, most recently run first. */
26307
+ function bounded(filters) {
26308
+ const pins = filters.filter((filter) => filter.pinned).slice(0, 24);
26309
+ const recents = filters.filter((filter) => !filter.pinned).sort((a, b) => (b.lastRunAt ?? 0) - (a.lastRunAt ?? 0)).slice(0, 8);
26310
+ return [...pins, ...recents];
26311
+ }
26312
+ /** Missing, unreadable or corrupt all read as "nothing saved" — never a reason to fail a boot. */
26313
+ async function readSavedFilters(path) {
26314
+ try {
26315
+ return readable(JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8")));
26316
+ } catch {
26317
+ return [];
26318
+ }
26319
+ }
26320
+ async function writeSavedFilters(path, filters) {
26321
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), {
26322
+ recursive: true,
26323
+ mode: 448
26324
+ });
26325
+ const temp = `${path}.${process.pid}.tmp`;
26326
+ await (0, node_fs_promises.writeFile)(temp, `${JSON.stringify({
26327
+ version: STORE_VERSION,
26328
+ filters
26329
+ }, null, 2)}\n`, {
26330
+ encoding: "utf8",
26331
+ mode: 384
26332
+ });
26333
+ await (0, node_fs_promises.rename)(temp, path);
26334
+ }
26335
+ /** Pure: the list that results from `change`. */
26336
+ function mutateSavedFilters(current, change) {
26337
+ if (change.kind === "remove") return current.filter((filter) => filter.id !== change.id);
26338
+ const id = savedFilterId(change.query);
26339
+ const existing = current.find((filter) => filter.id === id);
26340
+ const rest = current.filter((filter) => filter.id !== id);
26341
+ if (change.kind === "pin") {
26342
+ const name = change.name.trim().slice(0, 48);
26343
+ return bounded([{
26344
+ ...existing,
26345
+ id,
26346
+ ...change.query,
26347
+ pinned: true,
26348
+ ...name !== "" ? { name } : {}
26349
+ }, ...rest]);
26350
+ }
26351
+ return bounded([{
26352
+ ...existing,
26353
+ id,
26354
+ ...change.query,
26355
+ pinned: existing?.pinned === true,
26356
+ lastRunAt: change.at
26357
+ }, ...rest]);
26358
+ }
26359
+ //#endregion
25868
26360
  //#region src/cli.ts
25869
26361
  const HELP = `nice-commander — one typed config, one control surface, for dev environments.
25870
26362
 
@@ -25872,8 +26364,9 @@ usage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] [
25872
26364
 
25873
26365
  With NO command, "ui" runs: the daemon is ensured and the browser opened. --help prints this text.
25874
26366
 
25875
- selection: process ids, group names, tag=val (AND across terms), or --all.
25876
- Bare up/explain use the config's defaultSelection (or print the groups and exit);
26367
+ selection: process ids, suite names, @pin names, tag=val, or --all. Several tag=val terms AND
26368
+ together; --any ORs them instead. A tag selection and --all never start an optIn process.
26369
+ Bare up/explain use the config's defaultSelection (or print the suites and exit);
25877
26370
  bare down/restart/logs/run always require a selection — omission never means --all.
25878
26371
 
25879
26372
  commands:
@@ -25882,12 +26375,13 @@ commands:
25882
26375
  restart <sel> [--no-wait] stop + start
25883
26376
  status [--watch] table from the live status realm
25884
26377
  logs <sel> [-f] merged interleaved tail with colored id prefixes
25885
- list config introspection (processes, groups, warnings)
25886
- explain [sel] expanded ids, auto-included deps, DAG order
26378
+ list config introspection (processes, suites, warnings)
26379
+ explain [sel] expanded ids, auto-included deps, DAG order, suite policy
25887
26380
  env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
25888
26381
  overrides. A set value is STICKY: it applies to every
25889
26382
  later start until cleared, and never restarts anything.
25890
- run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape,
26383
+ run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape
26384
+ (a suite supplies its own parallel/fail-fast),
25891
26385
  a single id gets raw inherited stdio (interactive).
25892
26386
  --fail-fast = stop at the FIRST failure and stop the
25893
26387
  survivors; without it every task still runs, every
@@ -25955,7 +26449,7 @@ async function withTimeout(ctx, run) {
25955
26449
  async function main() {
25956
26450
  const argv = process.argv.slice(2);
25957
26451
  if (argv[0] === "daemon") {
25958
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-B7EwREFQ.cjs"));
26452
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-Xo-6rWk6.cjs"));
25959
26453
  return runCommanderDaemon(argv.slice(1));
25960
26454
  }
25961
26455
  const parsed = parseCliArgs(argv);
@@ -25980,6 +26474,7 @@ async function main() {
25980
26474
  out: createOut(parsed),
25981
26475
  config
25982
26476
  };
26477
+ if (parsed.positionals.some((term) => term.startsWith("@"))) ctx.pins = await readSavedFilters(commanderStatePaths(resolveCommanderDataDir(), config.configKey).savedFiltersPath);
25983
26478
  const code = await withTimeout(ctx, command(ctx));
25984
26479
  if (ctx.spawnedDaemon === true) process.exit(code);
25985
26480
  return code;
@@ -26023,20 +26518,27 @@ exports.createRealmServerEngine = createRealmServerEngine;
26023
26518
  exports.effectiveEnv = effectiveEnv;
26024
26519
  exports.ensureStateDir = ensureStateDir;
26025
26520
  exports.envVarViews = envVarViews;
26521
+ exports.hashCanonical = hashCanonical;
26026
26522
  exports.httpAcceptorCarrier = httpAcceptorCarrier;
26027
26523
  exports.loadCommanderConfigFile = loadCommanderConfigFile;
26524
+ exports.mutateSavedFilters = mutateSavedFilters;
26028
26525
  exports.orderByDependency = orderByDependency;
26029
26526
  exports.overrideFingerprint = overrideFingerprint;
26030
26527
  exports.parseLogsClientMessage = parseLogsClientMessage;
26031
26528
  exports.readEnvOverrides = readEnvOverrides;
26032
26529
  exports.readInstanceRecord = readInstanceRecord;
26530
+ exports.readSavedFilters = readSavedFilters;
26033
26531
  exports.recordDaemonAlive = recordDaemonAlive;
26034
26532
  exports.removeInstanceRecord = removeInstanceRecord;
26035
26533
  exports.resolveCommanderDataDir = resolveCommanderDataDir;
26534
+ exports.runTaskPool = runTaskPool;
26535
+ exports.savedFilterId = savedFilterId;
26036
26536
  exports.serveChannel = serveChannel;
26537
+ exports.stopSetWithDependencies = stopSetWithDependencies;
26037
26538
  exports.validateCommanderConfig = validateCommanderConfig;
26038
26539
  exports.withDependencies = withDependencies;
26039
26540
  exports.writeInstanceRecord = writeInstanceRecord;
26541
+ exports.writeSavedFilters = writeSavedFilters;
26040
26542
  exports.wsAcceptorCarrier = wsAcceptorCarrier;
26041
26543
 
26042
26544
  //# sourceMappingURL=cli.cjs.map