mandrel 2.123.0 → 2.125.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.
Files changed (105) hide show
  1. package/.agents/README.md +1 -1
  2. package/.agents/docs/agentrc-reference.json +2 -0
  3. package/.agents/docs/configuration.md +6 -3
  4. package/.agents/docs/runbooks/dispatch-board.md +174 -0
  5. package/.agents/docs/runbooks/dispatch.md +219 -0
  6. package/.agents/docs/runbooks/session-titles.md +52 -0
  7. package/.agents/runtime-deps.json +2 -2
  8. package/.agents/schemas/agentrc.schema.json +85 -3
  9. package/.agents/schemas/audit-rules.schema.json +1 -1
  10. package/.agents/schemas/story-deliver-terminal.schema.json +7 -2
  11. package/.agents/scripts/acceptance-eval.js +11 -2
  12. package/.agents/scripts/check-doc-links.js +4 -4
  13. package/.agents/scripts/dispatch.js +400 -0
  14. package/.agents/scripts/lib/audit-baselines/surface-entry.js +2 -2
  15. package/.agents/scripts/lib/audit-exceptions/globs.js +2 -2
  16. package/.agents/scripts/lib/audit-exceptions/scope.js +2 -2
  17. package/.agents/scripts/lib/audit-suite/selector.js +3 -3
  18. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +3 -3
  19. package/.agents/scripts/lib/baselines/components.js +2 -2
  20. package/.agents/scripts/lib/baselines/kinds/_crap-new-method-gate.js +2 -2
  21. package/.agents/scripts/lib/bdd-runner-detect.js +3 -4
  22. package/.agents/scripts/lib/child-detached.js +48 -0
  23. package/.agents/scripts/lib/child-exec.js +11 -0
  24. package/.agents/scripts/lib/close-validation/base-sync-revalidation.js +2 -2
  25. package/.agents/scripts/lib/config/delivery-routing.js +15 -12
  26. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  27. package/.agents/scripts/lib/config/handoff.js +21 -6
  28. package/.agents/scripts/lib/config/temp-paths.js +26 -0
  29. package/.agents/scripts/lib/config-settings-schema-delivery.js +64 -10
  30. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  31. package/.agents/scripts/lib/coverage-baseline.js +3 -3
  32. package/.agents/scripts/lib/coverage-capture-delta.js +2 -2
  33. package/.agents/scripts/lib/coverage-capture-own-fix.js +2 -2
  34. package/.agents/scripts/lib/dispatch/environments.js +135 -0
  35. package/.agents/scripts/lib/dispatch/launch-cloud.js +164 -0
  36. package/.agents/scripts/lib/dispatch/launch-local.js +77 -0
  37. package/.agents/scripts/lib/dispatch/liveness.js +21 -0
  38. package/.agents/scripts/lib/dispatch/record.js +54 -0
  39. package/.agents/scripts/lib/dispatch/status.js +285 -0
  40. package/.agents/scripts/lib/dispatch/targets.js +101 -0
  41. package/.agents/scripts/lib/dispatch/verdict.js +207 -0
  42. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  43. package/.agents/scripts/lib/git-test-guard.js +119 -0
  44. package/.agents/scripts/lib/git-utils.js +3 -0
  45. package/.agents/scripts/lib/maintainability-utils.js +4 -4
  46. package/.agents/scripts/lib/observability/handoff-telemetry.js +2 -0
  47. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  48. package/.agents/scripts/lib/orchestration/acceptance-eval-decision.js +3 -2
  49. package/.agents/scripts/lib/orchestration/block-class-recovery.js +44 -0
  50. package/.agents/scripts/lib/orchestration/code-review.js +35 -19
  51. package/.agents/scripts/lib/orchestration/diff-magnitude.js +1 -1
  52. package/.agents/scripts/lib/orchestration/git-cleanup/phases/filters.js +3 -3
  53. package/.agents/scripts/lib/orchestration/plan-persist/audit-attribution.js +3 -4
  54. package/.agents/scripts/lib/orchestration/review-history.js +9 -10
  55. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +9 -2
  56. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +8 -5
  57. package/.agents/scripts/lib/orchestration/review-providers/codex.js +3 -11
  58. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  59. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +22 -0
  60. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +10 -2
  61. package/.agents/scripts/lib/orchestration/review-providers/types.js +2 -0
  62. package/.agents/scripts/lib/orchestration/review-providers/ultrareview.js +13 -2
  63. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +40 -15
  64. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +2 -0
  65. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +8 -1
  66. package/.agents/scripts/lib/orchestration/story-handoff.js +222 -54
  67. package/.agents/scripts/lib/orchestration/story-stage-publish.js +147 -0
  68. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  69. package/.agents/scripts/lib/test-temp.js +5 -5
  70. package/.agents/scripts/lib/test-tiers.js +3 -3
  71. package/.agents/scripts/lib/util/glob-match.js +64 -0
  72. package/.agents/scripts/lib/wave-runner/footprint.js +3 -3
  73. package/.agents/scripts/run-tests.js +2 -1
  74. package/.agents/scripts/session-title.js +187 -0
  75. package/.agents/scripts/single-story-confirm-merge.js +7 -0
  76. package/.agents/scripts/single-story-init.js +6 -3
  77. package/.agents/workflows/helpers/audit-lens-core.md +4 -0
  78. package/.agents/workflows/helpers/code-review.md +8 -1
  79. package/.agents/workflows/helpers/deliver-digest.md +22 -23
  80. package/.agents/workflows/helpers/deliver-light.md +4 -1
  81. package/.agents/workflows/helpers/deliver-reference.md +55 -24
  82. package/.agents/workflows/helpers/deliver-story-reference.md +10 -3
  83. package/.agents/workflows/helpers/deliver-story.md +27 -7
  84. package/.agents/workflows/helpers/qa-core.md +2 -0
  85. package/.agents/workflows/mandrel-deliver.md +14 -4
  86. package/.agents/workflows/mandrel-orchestrate.md +2 -0
  87. package/.agents/workflows/mandrel-plan.md +4 -0
  88. package/README.md +8 -0
  89. package/bin/mandrel.js +35 -13
  90. package/docs/CHANGELOG.md +29 -0
  91. package/lib/cli/dispatch.js +27 -0
  92. package/lib/cli/ui/accounts.js +81 -0
  93. package/lib/cli/ui/board-model.js +372 -0
  94. package/lib/cli/ui/board.css +525 -0
  95. package/lib/cli/ui/board.html +80 -0
  96. package/lib/cli/ui/board.js +676 -0
  97. package/lib/cli/ui/log-tail.js +89 -0
  98. package/lib/cli/ui/panel-model.js +100 -0
  99. package/lib/cli/ui/preferences.js +136 -0
  100. package/lib/cli/ui/request-guard.js +108 -0
  101. package/lib/cli/ui/server.js +211 -0
  102. package/lib/cli/ui/sources.js +202 -0
  103. package/lib/cli/ui/story-detail.js +92 -0
  104. package/lib/cli/ui.js +114 -0
  105. package/package.json +2 -2
@@ -776,7 +776,7 @@
776
776
  },
777
777
  "minLength": 1
778
778
  },
779
- "description": "Repo-relative picomatch globs naming paths no test reads. A matching path is dropped from both sides of the coverage delta-refresh overlap check and from the re-measured set — a delta of only matching, baseline and coverage-directory paths restamps without a run — and from the overlap check of close's `test` delta re-credit (its incoming count and emptiness test are unchanged). It never changes the suite-input filter, the tree digest or stamp freshness. Default `[]`: nothing is built in, so Markdown counts as an input unless declared here.",
779
+ "description": "Repo-relative globs naming paths no test reads. A matching path is dropped from both sides of the coverage delta-refresh overlap check and from the re-measured set — a delta of only matching, baseline and coverage-directory paths restamps without a run — and from the overlap check of close's `test` delta re-credit (its incoming count and emptiness test are unchanged). It never changes the suite-input filter, the tree digest or stamp freshness. Default `[]`: nothing is built in, so Markdown counts as an input unless declared here.",
780
780
  "default": []
781
781
  },
782
782
  "captureHandlesConfigChanges": {
@@ -1467,7 +1467,7 @@
1467
1467
  "type": "string",
1468
1468
  "minLength": 1
1469
1469
  },
1470
- "description": "Globs (picomatch, dotfiles included) for whole-repo invariants: a base merge bringing in any matching path always re-runs every gate under `revalidateAfterBaseSync: \"ci\"`."
1470
+ "description": "Globs (dotfiles included) for whole-repo invariants: a base merge bringing in any matching path always re-runs every gate under `revalidateAfterBaseSync: \"ci\"`."
1471
1471
  }
1472
1472
  },
1473
1473
  "additionalProperties": false
@@ -1556,7 +1556,7 @@
1556
1556
  },
1557
1557
  "sensitivePaths": {
1558
1558
  "type": "object",
1559
- "description": "The project's own sensitive-path classes, merged additively over the shipped `audit-rules.json` `sensitivePaths`: a class named like a shipped one appends its patterns to it, a new name adds a class, and no shipped class or pattern can be removed or narrowed. A changed file matching any class derives a `high` change level, which drives both code-review depth (`deep`, never `light`) and plan-time routing. Patterns are picomatch globs matched with `dot: true`.",
1559
+ "description": "The project's own sensitive-path classes, merged additively over the shipped `audit-rules.json` `sensitivePaths`: a class named like a shipped one appends its patterns to it, a new name adds a class, and no shipped class or pattern can be removed or narrowed. A changed file matching any class derives a `high` change level, which drives both code-review depth (`deep`, never `light`) and plan-time routing. Patterns are globs matched with `dot: true`.",
1560
1560
  "propertyNames": {
1561
1561
  "pattern": "^[a-z0-9][a-z0-9-]*$"
1562
1562
  },
@@ -1707,6 +1707,28 @@
1707
1707
  "type": "object",
1708
1708
  "description": "Story #5960. What `story-handoff.js` runs beyond close's own gates.",
1709
1709
  "properties": {
1710
+ "firstChecks": {
1711
+ "type": "array",
1712
+ "items": {
1713
+ "type": "object",
1714
+ "properties": {
1715
+ "cmd": {
1716
+ "type": "string",
1717
+ "minLength": 1
1718
+ },
1719
+ "args": {
1720
+ "type": "array",
1721
+ "items": {
1722
+ "type": "string"
1723
+ }
1724
+ }
1725
+ },
1726
+ "required": ["cmd"],
1727
+ "additionalProperties": false
1728
+ },
1729
+ "description": "Story #6099. Cheap consumer checks the handoff preflight runs first, in order, beside close's independent baseline compare: each `{ cmd, args? }` runs in the worktree without a shell, with `MANDREL_HANDOFF_STEP=preflight`. A non-zero exit settles `fix-required` naming the check and quoting its failure rows, before typecheck, lint, format, quality-preview, the ratchets or the held review start; under `--report-all` the rest still run. Default [] runs only the compare first.",
1730
+ "default": []
1731
+ },
1710
1732
  "postSeatChecks": {
1711
1733
  "type": "array",
1712
1734
  "items": {
@@ -1799,6 +1821,11 @@
1799
1821
  "description": "When true (default), single-story-close lands through merge in one close. Opt out per-run with --no-wait-merge.",
1800
1822
  "default": true
1801
1823
  },
1824
+ "sessionTitles": {
1825
+ "type": "boolean",
1826
+ "description": "When true (default), plan, deliver, orchestrate, audit and QA runs retitle the top-level host session with a state glyph (○ planning, ◐ in progress, ● done, ⊗ blocked) via session-title.js, on hosts that expose a session-title tool. False makes session-title.js answer apply: false, so no step renames anything.",
1827
+ "default": true
1828
+ },
1802
1829
  "agentModels": {
1803
1830
  "type": "object",
1804
1831
  "description": "Per-role model override for the role-scoped agents, keyed by role name (`story-worker`, `acceptance-critic`, `plan-critic`, `auditor`; any other key is a validation error). A value is a Claude Code agent model: an alias (`sonnet`, `opus`, `haiku`), a full model id, or `inherit` (the operator's session model). It replaces the role file's `model:` frontmatter default when `sync-claude-agents` projects `.claude/agents/<role>.md`. Defaults: story-worker, acceptance-critic and plan-critic `inherit` (a checker runs at least as strong as the maker); auditor `sonnet` (a read-heavy lens sweep). Nothing here selects or changes the operator's session model, and a one-Story run stays inline in that session. A multi-Story close records the dispatched story-worker's resolved model as `telemetry.workerModel` beside `workerTokens` (null for an inline close), so opting workers down, e.g. `{ \"story-worker\": \"sonnet\" }`, is decided from measured outcomes.",
@@ -1818,6 +1845,61 @@
1818
1845
  }
1819
1846
  },
1820
1847
  "additionalProperties": false
1848
+ },
1849
+ "environments": {
1850
+ "type": "object",
1851
+ "description": "Named delivery environments for `mandrel dispatch`, keyed by name (lowercase letters, digits and hyphens, at most 31 characters). `target` is where the delivery runs and `capacity` how many Stories may hold the environment at once (default 1). A `local` entry may set `command`, the argv started for a Story with `{id}` replaced by the Story id and `{sessionId}` by a fresh UUID per launch (default `[\"claude\", \"-p\", \"/mandrel-deliver {id}\", \"--session-id\", \"{sessionId}\", \"--name\", \"◐ Delivery #{id}\", \"--output-format\", \"stream-json\", \"--verbose\"]`), spawned without a shell. A `claude-cloud` entry fires a Claude Code routine instead: it requires `routine` (the routine id, `trig_…`) and `tokenEnv` (the NAME of the environment variable holding the routine token, never the token) and takes no `command`. Unset, one implicit `local` environment with capacity 1 is used. `.agentrc.local.json` adds or overrides an entry through the usual merge.",
1852
+ "propertyNames": {
1853
+ "pattern": "^[a-z0-9][a-z0-9-]{0,30}$"
1854
+ },
1855
+ "additionalProperties": {
1856
+ "oneOf": [
1857
+ {
1858
+ "type": "object",
1859
+ "properties": {
1860
+ "target": {
1861
+ "const": "local"
1862
+ },
1863
+ "capacity": {
1864
+ "type": "integer",
1865
+ "minimum": 1
1866
+ },
1867
+ "command": {
1868
+ "type": "array",
1869
+ "minItems": 1,
1870
+ "items": {
1871
+ "type": "string",
1872
+ "minLength": 1
1873
+ }
1874
+ }
1875
+ },
1876
+ "required": ["target"],
1877
+ "additionalProperties": false
1878
+ },
1879
+ {
1880
+ "type": "object",
1881
+ "properties": {
1882
+ "target": {
1883
+ "const": "claude-cloud"
1884
+ },
1885
+ "capacity": {
1886
+ "type": "integer",
1887
+ "minimum": 1
1888
+ },
1889
+ "routine": {
1890
+ "type": "string",
1891
+ "pattern": "^trig_[A-Za-z0-9_]+$"
1892
+ },
1893
+ "tokenEnv": {
1894
+ "type": "string",
1895
+ "pattern": "^[A-Z][A-Z0-9_]*$"
1896
+ }
1897
+ },
1898
+ "required": ["target", "routine", "tokenEnv"],
1899
+ "additionalProperties": false
1900
+ }
1901
+ ]
1902
+ }
1821
1903
  }
1822
1904
  },
1823
1905
  "additionalProperties": false
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "sensitivePaths": {
24
24
  "type": "object",
25
- "description": "Map of sensitive-path class name to the globs that identify it. A change set touching any registered pattern derives a `high` change level, which resolves review depth to `deep` and the acceptance critic to `fresh` regardless of how narrow the diff is (deriveChangeLevel in lib/orchestration/review-depth.js). This is configuration, not code: an operator extends the classes or their globs here without editing a module, and the globs run through the same picomatch machinery as the audit-lens `filePatterns` triggers above. Those lens triggers are a SEPARATE block with a separate job — they select which lens runs, never the change level — so a path registered there is not sensitive here unless it is also registered in this block. An absent or empty block means no path is sensitive and depth falls back to diff width alone.",
25
+ "description": "Map of sensitive-path class name to the globs that identify it. A change set touching any registered pattern derives a `high` change level, which resolves review depth to `deep` and the acceptance critic to `fresh` regardless of how narrow the diff is (deriveChangeLevel in lib/orchestration/review-depth.js). This is configuration, not code: an operator extends the classes or their globs here without editing a module, and the globs run through the same glob machinery as the audit-lens `filePatterns` triggers above. Those lens triggers are a SEPARATE block with a separate job — they select which lens runs, never the change level — so a path registered there is not sensitive here unless it is also registered in this block. An absent or empty block means no path is sensitive and depth falls back to diff width alone.",
26
26
  "patternProperties": {
27
27
  "^[a-z][a-z0-9-]*$": { "$ref": "#/definitions/sensitivePathClass" }
28
28
  },
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "status": {
23
23
  "type": "string",
24
- "description": "landed — the PR merged, the Story is agent::done, and the post-land tail was attempted. pending — a bounded wait expired with the PR still in flight; NO label was mutated and no merge.unlanded event was emitted, so the run is resumable via nextCommand. blocked — a classified hard block; the Story carries agent::blocked and blocked.blockClass names the class. failed — a phase crashed; phase names which one. escalated — /deliver-light's suitability gate refused a prompt on an un-waivable risk rule or an un-ledgered verdict; nothing was created and the LIGHT PATH ends here, nextCommand naming the /mandrel-plan invocation that owns the work instead. Story #5344 narrowed what refuses (the predicted-shape ceilings are gone) and loosened what follows (that command may be run in the same session, seeded with escalation.reasons) without touching this shape.",
24
+ "description": "landed — the PR merged, the Story is agent::done, and the post-land tail was attempted. pending — a bounded wait expired with the PR still in flight; NO label was mutated and no merge.unlanded event was emitted, so the run is resumable via nextCommand. blocked — a classified hard block; blocked.blockClass names the class and blocked.recovery who clears it: with recovery agent an unlanded merge leaves the Story at agent::closing for the session to fix and resume, with recovery operator the Story carries agent::blocked. failed — a phase crashed; phase names which one. escalated — /deliver-light's suitability gate refused a prompt on an un-waivable risk rule or an un-ledgered verdict; nothing was created and the LIGHT PATH ends here, nextCommand naming the /mandrel-plan invocation that owns the work instead. Story #5344 narrowed what refuses (the predicted-shape ceilings are gone) and loosened what follows (that command may be run in the same session, seeded with escalation.reasons) without touching this shape.",
25
25
  "enum": ["landed", "pending", "blocked", "failed", "escalated"]
26
26
  },
27
27
  "phase": {
@@ -145,7 +145,7 @@
145
145
  "blocked": {
146
146
  "type": ["object", "null"],
147
147
  "description": "Present iff status === \"blocked\". blockClass comes from the shared classifier (merge-block-class.js) or the merged-flip-failed terminal, never an ad hoc string.",
148
- "required": ["blockClass", "reason"],
148
+ "required": ["blockClass", "reason", "recovery"],
149
149
  "properties": {
150
150
  "blockClass": {
151
151
  "type": "string",
@@ -167,6 +167,11 @@
167
167
  "frictionCommentId": {
168
168
  "type": ["string", "null"],
169
169
  "description": "Pointer to the friction comment carrying the operator-facing remediation."
170
+ },
171
+ "recovery": {
172
+ "type": "string",
173
+ "enum": ["agent", "operator"],
174
+ "description": "Who clears the block, from BLOCK_CLASS_RECOVERY in merge-block-class.js. agent: the delivering session fixes and resumes in the same turn, and an unlanded merge leaves the Story at agent::closing. operator: a human must act; the Story carries agent::blocked."
170
175
  }
171
176
  },
172
177
  "additionalProperties": false
@@ -37,6 +37,7 @@ import {
37
37
  resolveAcceptanceEvalRound,
38
38
  scoreVerifyRuns,
39
39
  } from './lib/orchestration/acceptance-eval-decision.js';
40
+ import { publishDeliveryStage } from './lib/orchestration/story-stage-publish.js';
40
41
  import {
41
42
  classifyVerifyEntries,
42
43
  FULL_SUITE_SHAPE_WARNING,
@@ -603,15 +604,22 @@ function requireStoryId(storyId) {
603
604
  /**
604
605
  * `--init`: write the skeleton and print its summary; scores nothing.
605
606
  *
606
- * @param {{ storyId: number, cwd: string|null, resolveConfigImpl: typeof resolveConfig, logger: { info: Function }, deps: { initSkeletonImpl?: typeof initVerdictSkeleton } }} args
607
+ * @param {{ storyId: number, cwd: string|null, resolveConfigImpl: typeof resolveConfig, logger: { info: Function }, deps: { initSkeletonImpl?: typeof initVerdictSkeleton, createProviderFn?: typeof createProvider } }} args
607
608
  * @returns {Promise<object>}
608
609
  */
609
610
  async function runInitCli({ storyId, cwd, resolveConfigImpl, logger, deps }) {
610
611
  const workCwd = path.resolve(cwd ?? process.cwd());
612
+ const config = resolveConfigImpl({ cwd: workCwd });
613
+ const createProviderFn = deps.createProviderFn ?? createProvider;
614
+ await publishDeliveryStage({
615
+ provider: () => createProviderFn(config),
616
+ storyId,
617
+ stage: 'check',
618
+ });
611
619
  const skeleton = await (deps.initSkeletonImpl ?? initVerdictSkeleton)({
612
620
  storyId,
613
621
  cwd: workCwd,
614
- config: resolveConfigImpl({ cwd: workCwd }),
622
+ config,
615
623
  });
616
624
  logger.info(JSON.stringify(skeleton));
617
625
  return skeleton;
@@ -631,6 +639,7 @@ async function runInitCli({ storyId, cwd, resolveConfigImpl, logger, deps }) {
631
639
  * runEntryImpl?: typeof runScopedVerifyEntry,
632
640
  * readHeadImpl?: typeof readHeadSha,
633
641
  * initSkeletonImpl?: typeof initVerdictSkeleton,
642
+ * createProviderFn?: typeof createProvider,
634
643
  * logger?: { info: Function, warn?: Function },
635
644
  * }} [deps]
636
645
  * @returns {Promise<object>} the emitted envelope (the skeleton summary under `--init`).
@@ -8,10 +8,10 @@
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
- import picomatch from 'picomatch';
12
11
  import { parseStandardCliArgs } from './lib/cli/standard-args.js';
13
12
  import { runAsCli } from './lib/cli-utils.js';
14
13
  import { Logger } from './lib/Logger.js';
14
+ import { isGlobMatch } from './lib/util/glob-match.js';
15
15
  import { toPosix } from './lib/util/paths.js';
16
16
 
17
17
  const __filename = fileURLToPath(import.meta.url);
@@ -156,7 +156,7 @@ function walkMarkdown(dirAbs, repoRoot, out) {
156
156
  /**
157
157
  * @param {string} rootAbs
158
158
  * @param {string[]} scanRoots
159
- * @param {string[]} [exclude] picomatch globs over repo-relative POSIX paths
159
+ * @param {string[]} [exclude] globs over repo-relative POSIX paths
160
160
  */
161
161
  export function discoverMarkdown(rootAbs, scanRoots, exclude = []) {
162
162
  const out = [];
@@ -167,7 +167,7 @@ export function discoverMarkdown(rootAbs, scanRoots, exclude = []) {
167
167
  const filtered = exclude.length
168
168
  ? out.filter((abs) => {
169
169
  const rel = toPosix(path.relative(rootAbs, abs));
170
- return !exclude.some((g) => picomatch.isMatch(rel, g, { dot: true }));
170
+ return !exclude.some((g) => isGlobMatch(rel, g, { dot: true }));
171
171
  })
172
172
  : out;
173
173
  filtered.sort();
@@ -457,7 +457,7 @@ runAsCli(import.meta.url, main, {
457
457
  ],
458
458
  [
459
459
  '--exclude <glob>',
460
- 'Repeatable. picomatch glob; matching files are dropped from the scan.',
460
+ 'Repeatable. glob; matching files are dropped from the scan.',
461
461
  ],
462
462
  ],
463
463
  notes: [
@@ -0,0 +1,400 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Dispatch a Story's delivery to a named environment, resume or stop it, or
5
+ * read the board. `mandrel dispatch` calls {@link runDispatch} too, so both
6
+ * share one implementation, one envelope and one set of exit codes.
7
+ *
8
+ * Exit codes: 0 success, 2 a refusal (`{ ok: false, reason, detail }`),
9
+ * 1 the command itself could not run.
10
+ */
11
+
12
+ import { parseArgs } from 'node:util';
13
+
14
+ import { runAsCli } from './lib/cli-utils.js';
15
+ import { resolveConfig } from './lib/config-resolver.js';
16
+ import { parseBlockedBy } from './lib/dependency-parser.js';
17
+ import {
18
+ agentStateOf,
19
+ commandFor,
20
+ computeLoads,
21
+ ENV_LABEL_COLOR,
22
+ environmentOf,
23
+ envLabel,
24
+ resolveEnvironments,
25
+ } from './lib/dispatch/environments.js';
26
+ import { launchCloud } from './lib/dispatch/launch-cloud.js';
27
+ import { launchLocal, stopLocal } from './lib/dispatch/launch-local.js';
28
+ import {
29
+ readRecord,
30
+ removeRecord,
31
+ writeRecord,
32
+ } from './lib/dispatch/record.js';
33
+ import {
34
+ buildStatus,
35
+ DEFAULT_DONE_LIMIT,
36
+ DONE_LIMITS,
37
+ fetchBoard,
38
+ renderStatus,
39
+ } from './lib/dispatch/status.js';
40
+ import {
41
+ dryRunFields,
42
+ launchedFields,
43
+ launcherFor,
44
+ launchFailureFields,
45
+ releasesLabel,
46
+ stoppedFields,
47
+ } from './lib/dispatch/targets.js';
48
+ import { decide } from './lib/dispatch/verdict.js';
49
+ import { gh as defaultGh } from './lib/gh-exec.js';
50
+ import { AGENT_LABELS, TYPE_LABELS } from './lib/label-constants.js';
51
+ import {
52
+ normalizeOperatorHandle,
53
+ releaseLease,
54
+ } from './lib/orchestration/ticket-lease.js';
55
+ import { transitionTicketState } from './lib/orchestration/ticketing.js';
56
+ import { PROJECT_ROOT } from './lib/project-root.js';
57
+ import { createProvider } from './lib/provider-factory.js';
58
+
59
+ const DISPATCH_USAGE = `Usage: mandrel dispatch --env <name> <storyId>
60
+ mandrel dispatch --resume [--env <name>] <storyId>
61
+ mandrel dispatch --stop <storyId>
62
+ mandrel dispatch --status [--json] [--done-limit <n>]
63
+ (or: node .agents/scripts/dispatch.js with the same flags)
64
+
65
+ Starts an agent::ready Story's delivery in a named environment
66
+ (delivery.environments; one implicit "local" environment when unset),
67
+ labelling the Story env::<name> as the claim. The launched command is the
68
+ environment's argv with {id} replaced by the Story id and {sessionId} by a
69
+ fresh UUID, started detached without a shell; its output goes to
70
+ <tempRoot>/dispatch/story-<id>.log.
71
+ A claude-cloud environment instead fires its Claude Code routine once with
72
+ the payload "mandrel-deliver <id>" and posts the session URL on the Story.
73
+
74
+ Flags:
75
+ --env <name> Environment to dispatch to (required for a dispatch).
76
+ --resume Relaunch an agent::blocked Story in the environment its
77
+ label names; changes no agent::* label.
78
+ --stop Stop the recorded process, release the lease, return the
79
+ Story to agent::ready and remove its env:: label. The
80
+ branch and worktree are kept. A cloud session is not
81
+ stopped: archive it at the printed session URL.
82
+ --status Print environments, load and every Story's column.
83
+ --json With --status, emit the read model as JSON.
84
+ --done-limit <n>
85
+ With --status, how many Done Stories to show, most
86
+ recently closed first: 10, 20 (default), 50 or 100.
87
+ Any other value exits 2.
88
+ --dry-run Print the verdict and the argv (or the cloud request,
89
+ Authorization redacted); write and start nothing.
90
+ --help Show this message.
91
+
92
+ stdout is one JSON envelope. Exit 0 on success, 2 on a refusal
93
+ ({ ok: false, reason, detail }), 1 when the command could not run or a
94
+ cloud fire failed (reason launch-failed, rate-limited or
95
+ launch-unconfirmed).
96
+ `;
97
+
98
+ /** A usage error that exits 2, like a refusal: its envelope is `{ ok, reason, detail }`. */
99
+ class UsageRefusal extends Error {
100
+ constructor(reason, detail) {
101
+ super(detail);
102
+ this.reason = reason;
103
+ }
104
+ }
105
+
106
+ /** A usage refusal exits 2; anything else means the command could not run. */
107
+ function failureResult(err) {
108
+ if (err instanceof UsageRefusal) {
109
+ return {
110
+ code: 2,
111
+ envelope: { ok: false, reason: err.reason, detail: err.message },
112
+ };
113
+ }
114
+ return {
115
+ code: 1,
116
+ envelope: { ok: false, error: err?.message ?? String(err) },
117
+ };
118
+ }
119
+
120
+ function doneLimitOf(raw) {
121
+ if (raw === undefined) return DEFAULT_DONE_LIMIT;
122
+ if (!DONE_LIMITS.map(String).includes(raw)) {
123
+ throw new UsageRefusal(
124
+ 'invalid-done-limit',
125
+ `--done-limit must be one of ${DONE_LIMITS.join(', ')} (see --help)`,
126
+ );
127
+ }
128
+ return Number(raw);
129
+ }
130
+
131
+ const STORY_ID_RE = /^[1-9]\d*$/;
132
+
133
+ function usageError(message) {
134
+ return new Error(`${message} (see --help)`);
135
+ }
136
+
137
+ /**
138
+ * @param {string[]} argv
139
+ * @returns {{ mode: 'dispatch'|'resume'|'stop'|'status', envName: string|null,
140
+ * storyId: number|null, json: boolean, dryRun: boolean, help: boolean,
141
+ * doneLimit: number }}
142
+ */
143
+ function parseDispatchArgv(argv) {
144
+ const { values, positionals } = parseArgs({
145
+ args: argv,
146
+ options: {
147
+ env: { type: 'string' },
148
+ resume: { type: 'boolean', default: false },
149
+ stop: { type: 'boolean', default: false },
150
+ status: { type: 'boolean', default: false },
151
+ json: { type: 'boolean', default: false },
152
+ 'done-limit': { type: 'string' },
153
+ 'dry-run': { type: 'boolean', default: false },
154
+ help: { type: 'boolean', short: 'h', default: false },
155
+ },
156
+ allowPositionals: true,
157
+ strict: true,
158
+ });
159
+ const base = {
160
+ envName: values.env ?? null,
161
+ json: values.json,
162
+ dryRun: values['dry-run'],
163
+ help: values.help,
164
+ };
165
+ if (values.help) return { ...base, mode: 'status', storyId: null };
166
+ base.doneLimit = doneLimitOf(values['done-limit']);
167
+ const modes = ['resume', 'stop', 'status'].filter((m) => values[m]);
168
+ if (modes.length > 1) {
169
+ throw usageError(`--${modes.join(' and --')} are mutually exclusive`);
170
+ }
171
+ const mode = modes[0] ?? 'dispatch';
172
+ if (mode === 'status') return { ...base, mode, storyId: null };
173
+ if (positionals.length !== 1 || !STORY_ID_RE.test(positionals[0])) {
174
+ throw usageError('exactly one positive integer Story id is required');
175
+ }
176
+ if (mode === 'dispatch' && !base.envName) {
177
+ throw usageError('--env <name> is required to dispatch');
178
+ }
179
+ return { ...base, mode, storyId: Number(positionals[0]) };
180
+ }
181
+
182
+ async function openDependencies(provider, body) {
183
+ const unmet = [];
184
+ for (const id of parseBlockedBy(body ?? '')) {
185
+ const dep = await provider.getTicket(id);
186
+ if (String(dep?.state ?? '').toLowerCase() === 'open') unmet.push(id);
187
+ }
188
+ return unmet;
189
+ }
190
+
191
+ /** Everything `decide` needs about one Story, read live. */
192
+ async function gatherVerdictInput({ ctx, mode, storyId, envName }) {
193
+ const { provider, environments } = ctx;
194
+ const story = await provider.getTicket(storyId);
195
+ const isEpic = (story.labels ?? []).includes(TYPE_LABELS.EPIC);
196
+ const children = isEpic
197
+ ? (await provider.getSubTickets(storyId)).map((c) => c.id)
198
+ : [];
199
+ const target = envName ?? environmentOf(story.labels);
200
+ const held = environments.some((e) => e.name === target)
201
+ ? await provider.listTicketsByLabel({
202
+ state: 'open',
203
+ labels: envLabel(target),
204
+ })
205
+ : [];
206
+ return {
207
+ action: mode,
208
+ story,
209
+ envName,
210
+ environments,
211
+ loads: computeLoads(environments, held),
212
+ unmetDependencies: await openDependencies(provider, story.body),
213
+ children,
214
+ operator: ctx.operator,
215
+ };
216
+ }
217
+
218
+ async function launch({ ctx, verdict, storyId }) {
219
+ const { provider, deps, config } = ctx;
220
+ const environment = ctx.environments.find(
221
+ (e) => e.name === verdict.environment,
222
+ );
223
+ const label = envLabel(environment.name);
224
+ if (verdict.applyLabel) {
225
+ await provider.ensureLabels([
226
+ {
227
+ name: label,
228
+ color: ENV_LABEL_COLOR,
229
+ description: `Held by delivery environment "${environment.name}".`,
230
+ },
231
+ ]);
232
+ await provider.updateTicket(storyId, { labels: { add: [label] } });
233
+ }
234
+ const head = {
235
+ action: verdict.action,
236
+ storyId,
237
+ environment: environment.name,
238
+ };
239
+ let record;
240
+ try {
241
+ record = await launcherFor(
242
+ environment,
243
+ deps,
244
+ )({
245
+ storyId,
246
+ environment,
247
+ cwd: ctx.cwd,
248
+ config,
249
+ provider,
250
+ });
251
+ } catch (err) {
252
+ if (releasesLabel(verdict.applyLabel, err)) {
253
+ await provider.updateTicket(storyId, { labels: { remove: [label] } });
254
+ }
255
+ return { ok: false, ...head, ...launchFailureFields(err) };
256
+ }
257
+ deps.writeRecordImpl(record, { config });
258
+ return { ok: true, ...head, ...launchedFields(record) };
259
+ }
260
+
261
+ async function stop({ ctx, verdict, storyId, story }) {
262
+ const { provider, deps, config, operator } = ctx;
263
+ const record = deps.readRecordImpl(storyId, { config });
264
+ if (record?.pid) deps.stopImpl(record.pid);
265
+ if (operator) {
266
+ await deps.releaseLeaseImpl({ provider, ticketId: storyId, operator });
267
+ }
268
+ if (agentStateOf(story.labels) !== AGENT_LABELS.READY) {
269
+ await deps.transitionImpl(provider, storyId, AGENT_LABELS.READY, {
270
+ config,
271
+ });
272
+ }
273
+ await provider.updateTicket(storyId, {
274
+ labels: { remove: [envLabel(verdict.environment)] },
275
+ });
276
+ deps.removeRecordImpl(storyId, { config });
277
+ return {
278
+ ok: true,
279
+ action: 'stop',
280
+ storyId,
281
+ environment: verdict.environment,
282
+ pid: record?.pid ?? null,
283
+ ...stoppedFields(record),
284
+ };
285
+ }
286
+
287
+ function dryRunEnvelope({ ctx, verdict, storyId }) {
288
+ const envelope = {
289
+ ok: true,
290
+ action: verdict.action,
291
+ storyId,
292
+ environment: verdict.environment,
293
+ dryRun: true,
294
+ };
295
+ if (verdict.action === 'stop') return envelope;
296
+ const environment = ctx.environments.find(
297
+ (e) => e.name === verdict.environment,
298
+ );
299
+ return { ...envelope, ...dryRunFields(environment, storyId, commandFor) };
300
+ }
301
+
302
+ async function act(ctx, args) {
303
+ const input = await gatherVerdictInput({ ctx, ...args });
304
+ const verdict = decide(input);
305
+ if (!verdict.ok) return { code: 2, envelope: verdict };
306
+ const step = { ctx, verdict, storyId: args.storyId, story: input.story };
307
+ if (args.dryRun) return { code: 0, envelope: dryRunEnvelope(step) };
308
+ const envelope = args.mode === 'stop' ? await stop(step) : await launch(step);
309
+ // A failed cloud fire is the command failing: exit 1.
310
+ return { code: Number(!envelope.ok), envelope };
311
+ }
312
+
313
+ async function status(ctx, { json, doneLimit }) {
314
+ const board = await ctx.deps.fetchBoardImpl({
315
+ provider: ctx.provider,
316
+ gh: ctx.deps.gh,
317
+ config: ctx.config,
318
+ doneLimit,
319
+ });
320
+ const model = buildStatus({
321
+ environments: ctx.environments,
322
+ ...board,
323
+ operator: ctx.operator,
324
+ doneLimit,
325
+ });
326
+ return json
327
+ ? { code: 0, envelope: model }
328
+ : { code: 0, text: renderStatus(model) };
329
+ }
330
+
331
+ /**
332
+ * The shared entry: parse, decide, act, and write one envelope to stdout.
333
+ *
334
+ * @param {string[]} argv
335
+ * @param {{
336
+ * config?: object, provider?: object, gh?: object, cwd?: string,
337
+ * write?: (s: string) => void,
338
+ * resolveConfigImpl?: typeof resolveConfig,
339
+ * createProviderImpl?: typeof createProvider,
340
+ * launchImpl?: typeof launchLocal, stopImpl?: typeof stopLocal,
341
+ * launchCloudImpl?: typeof launchCloud, fetchImpl?: typeof fetch,
342
+ * env?: Record<string, string|undefined>,
343
+ * fetchBoardImpl?: typeof fetchBoard,
344
+ * transitionImpl?: typeof transitionTicketState,
345
+ * releaseLeaseImpl?: typeof releaseLease,
346
+ * writeRecordImpl?: typeof writeRecord, readRecordImpl?: typeof readRecord,
347
+ * removeRecordImpl?: typeof removeRecord,
348
+ * }} [overrides]
349
+ * @returns {Promise<number>} The exit code.
350
+ */
351
+ export async function runDispatch(argv, overrides = {}) {
352
+ const deps = {
353
+ write: (s) => process.stdout.write(s),
354
+ resolveConfigImpl: resolveConfig,
355
+ createProviderImpl: createProvider,
356
+ launchImpl: launchLocal,
357
+ stopImpl: stopLocal,
358
+ launchCloudImpl: (args) =>
359
+ launchCloud(args, { fetchImpl: deps.fetchImpl, env: deps.env }),
360
+ env: process.env,
361
+ fetchBoardImpl: fetchBoard,
362
+ transitionImpl: transitionTicketState,
363
+ releaseLeaseImpl: releaseLease,
364
+ writeRecordImpl: writeRecord,
365
+ readRecordImpl: readRecord,
366
+ removeRecordImpl: removeRecord,
367
+ gh: defaultGh,
368
+ cwd: PROJECT_ROOT,
369
+ ...overrides,
370
+ };
371
+ let result;
372
+ try {
373
+ const args = parseDispatchArgv(argv);
374
+ if (args.help) {
375
+ deps.write(DISPATCH_USAGE);
376
+ return 0;
377
+ }
378
+ const config = deps.config ?? deps.resolveConfigImpl({ cwd: deps.cwd });
379
+ const ctx = {
380
+ deps,
381
+ config,
382
+ cwd: deps.cwd,
383
+ provider: deps.provider ?? deps.createProviderImpl(config),
384
+ environments: resolveEnvironments(config, deps.env),
385
+ operator: normalizeOperatorHandle(config?.github?.operatorHandle),
386
+ };
387
+ result =
388
+ args.mode === 'status' ? await status(ctx, args) : await act(ctx, args);
389
+ } catch (err) {
390
+ result = failureResult(err);
391
+ }
392
+ deps.write(result.text ?? `${JSON.stringify(result.envelope, null, 2)}\n`);
393
+ return result.code;
394
+ }
395
+
396
+ runAsCli(import.meta.url, () => runDispatch(process.argv.slice(2)), {
397
+ source: 'dispatch',
398
+ usage: DISPATCH_USAGE,
399
+ propagateExitCode: true,
400
+ });
@@ -5,8 +5,8 @@
5
5
  * @module lib/audit-baselines/surface-entry
6
6
  */
7
7
 
8
- import picomatch from 'picomatch';
9
8
  import { IGNORED_DIRS } from '../maintainability-utils.js';
9
+ import { globMatcher } from '../util/glob-match.js';
10
10
  import { GATE_KINDS, KIND_SPECS, measuredTotalOf, rollupOf } from './kinds.js';
11
11
  import { stalenessOf } from './staleness.js';
12
12
 
@@ -110,7 +110,7 @@ function isJudgeableGlob(glob, scannerSkipDirs) {
110
110
  * @returns {boolean}
111
111
  */
112
112
  function matchesNothing(glob, files) {
113
- const isMatch = picomatch(glob, { dot: true });
113
+ const isMatch = globMatcher(glob, { dot: true });
114
114
  return !files.some((f) => isMatch(f));
115
115
  }
116
116