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
@@ -0,0 +1,285 @@
1
+ /**
2
+ * The `--status` read model: environments with their load, and every Story
3
+ * in a board column with the verdict each drop target would return. Drops
4
+ * come from the same `decide` the command calls, so a board can never offer
5
+ * a move the command refuses.
6
+ *
7
+ * @module lib/dispatch/status
8
+ */
9
+
10
+ import { parseBlockedBy } from '../dependency-parser.js';
11
+ import { AGENT_LABELS, TYPE_LABELS } from '../label-constants.js';
12
+ import { agentStateOf, computeLoads, environmentOf } from './environments.js';
13
+ import { decide } from './verdict.js';
14
+
15
+ const COLUMNS = ['backlog', 'planning', 'ready', 'delivering', 'blocked'];
16
+ /** The Done Stories `--done-limit` may ask for; the first default is 20. */
17
+ export const DONE_LIMITS = Object.freeze([10, 20, 50, 100]);
18
+ export const DEFAULT_DONE_LIMIT = 20;
19
+
20
+ const DELIVERING = new Set([AGENT_LABELS.EXECUTING, AGENT_LABELS.CLOSING]);
21
+
22
+ /**
23
+ * @param {{ state?: string, labels?: string[] }} ticket
24
+ * @returns {'backlog'|'planning'|'ready'|'delivering'|'blocked'|'done'|null}
25
+ * `null` for an open ticket no column shows (`agent::done` still open).
26
+ */
27
+ function columnOf(ticket) {
28
+ if (String(ticket.state ?? '').toLowerCase() === 'closed') return 'done';
29
+ const state = agentStateOf(ticket.labels);
30
+ if (state === null) return 'backlog';
31
+ if (state === AGENT_LABELS.REVIEW_SPEC) return 'planning';
32
+ if (state === AGENT_LABELS.BLOCKED) return 'blocked';
33
+ if (DELIVERING.has(state)) return 'delivering';
34
+ if (state === AGENT_LABELS.READY) {
35
+ return environmentOf(ticket.labels) ? 'delivering' : 'ready';
36
+ }
37
+ return null;
38
+ }
39
+
40
+ /**
41
+ * Counts over a `statusCheckRollup`.
42
+ *
43
+ * @param {Array<{ status?: string, conclusion?: string, state?: string }>} [rollup]
44
+ * @returns {{ total: number, passed: number, failed: number, pending: number }}
45
+ */
46
+ function checkSummary(rollup) {
47
+ const summary = { total: 0, passed: 0, failed: 0, pending: 0 };
48
+ for (const check of rollup ?? []) {
49
+ summary.total += 1;
50
+ const outcome = String(check.conclusion || check.state || '').toUpperCase();
51
+ if (['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(outcome)) {
52
+ summary.passed += 1;
53
+ } else if (
54
+ outcome === '' ||
55
+ outcome === 'PENDING' ||
56
+ outcome === 'EXPECTED'
57
+ ) {
58
+ summary.pending += 1;
59
+ } else {
60
+ summary.failed += 1;
61
+ }
62
+ }
63
+ return summary;
64
+ }
65
+
66
+ /**
67
+ * The action a drop of `story` onto environment `envName` would take: a
68
+ * blocked Story resumes there, anything else is dispatched there.
69
+ *
70
+ * @param {object} story
71
+ * @returns {'resume'|'dispatch'}
72
+ */
73
+ function environmentDropAction(story) {
74
+ return agentStateOf(story.labels) === AGENT_LABELS.BLOCKED
75
+ ? 'resume'
76
+ : 'dispatch';
77
+ }
78
+
79
+ /**
80
+ * Each column and each environment mapped to that Story's verdict. Only the
81
+ * `ready` column has a command behind it (`--stop`); the others are `null`.
82
+ */
83
+ function dropsFor(story, ctx) {
84
+ const base = {
85
+ story,
86
+ environments: ctx.environments,
87
+ loads: ctx.loads,
88
+ operator: ctx.operator,
89
+ unmetDependencies: parseBlockedBy(story.body ?? '').filter((id) =>
90
+ ctx.openIds.has(id),
91
+ ),
92
+ };
93
+ const drops = Object.fromEntries(
94
+ [...COLUMNS, 'done'].map((column) => [column, null]),
95
+ );
96
+ drops.ready = decide({ ...base, action: 'stop', envName: null });
97
+ for (const env of ctx.environments) {
98
+ drops[env.name] = decide({
99
+ ...base,
100
+ action: environmentDropAction(story),
101
+ envName: env.name,
102
+ });
103
+ }
104
+ return drops;
105
+ }
106
+
107
+ function prFor(storyId, prs) {
108
+ const pr = prs.find((p) => p.headRefName === `story-${storyId}`);
109
+ if (!pr) return null;
110
+ return {
111
+ number: pr.number,
112
+ url: pr.url,
113
+ checks: checkSummary(pr.statusCheckRollup),
114
+ };
115
+ }
116
+
117
+ function storyRow(ticket, column, ctx) {
118
+ return {
119
+ id: ticket.id,
120
+ title: ticket.title,
121
+ column,
122
+ state: agentStateOf(ticket.labels),
123
+ labels: ticket.labels ?? [],
124
+ environment: environmentOf(ticket.labels),
125
+ pr: prFor(ticket.id, ctx.prs),
126
+ dependsOn: parseBlockedBy(ticket.body ?? ''),
127
+ drops: dropsFor(ticket, ctx),
128
+ };
129
+ }
130
+
131
+ const isEpic = (ticket) => (ticket.labels ?? []).includes(TYPE_LABELS.EPIC);
132
+
133
+ /**
134
+ * @param {{
135
+ * environments: import('./environments.js').Environment[],
136
+ * openTickets: object[],
137
+ * closedStories: object[],
138
+ * prs: object[],
139
+ * operator?: string|null,
140
+ * doneLimit?: number,
141
+ * closedTotal?: number|null,
142
+ * }} board
143
+ * @returns {{ environments: object[], stories: object[], doneShown: number,
144
+ * doneTotal: number|null }}
145
+ */
146
+ export function buildStatus({
147
+ environments,
148
+ openTickets,
149
+ closedStories,
150
+ prs,
151
+ operator = null,
152
+ doneLimit = DEFAULT_DONE_LIMIT,
153
+ closedTotal = null,
154
+ }) {
155
+ const loads = computeLoads(environments, openTickets);
156
+ const ctx = {
157
+ environments,
158
+ loads,
159
+ operator,
160
+ prs: prs ?? [],
161
+ openIds: new Set(openTickets.map((t) => t.id)),
162
+ };
163
+ const open = openTickets
164
+ .filter((t) => !isEpic(t))
165
+ .map((t) => [t, columnOf(t)])
166
+ .filter(([, column]) => column !== null)
167
+ .map(([t, column]) => storyRow(t, column, ctx));
168
+ const done = [...closedStories]
169
+ .sort((a, b) => String(b.closedAt).localeCompare(String(a.closedAt)))
170
+ .slice(0, doneLimit)
171
+ .map((t) => storyRow(t, 'done', ctx));
172
+ return {
173
+ environments: environments.map(
174
+ ({ command, routine, tokenEnv, ...shown }) => ({
175
+ ...shown,
176
+ load: loads[shown.name],
177
+ }),
178
+ ),
179
+ stories: [...open, ...done],
180
+ doneShown: done.length,
181
+ doneTotal: closedTotal,
182
+ };
183
+ }
184
+
185
+ const closedStory = (issue) => ({
186
+ id: issue.number,
187
+ title: issue.title,
188
+ body: issue.body ?? '',
189
+ labels: (issue.labels ?? []).map((l) => l.name ?? l),
190
+ assignees: (issue.assignees ?? []).map((a) => a.login),
191
+ state: 'closed',
192
+ closedAt: issue.closed_at ?? null,
193
+ });
194
+
195
+ /** Sorted by update, not close, so it reads spare rows; a page holds at most 100. */
196
+ async function closedPage(gh, repoPath, doneLimit) {
197
+ const perPage = Math.min(100, Math.max(50, doneLimit * 2));
198
+ const raw = await gh.api({
199
+ endpoint:
200
+ `/repos/${repoPath}/issues?state=closed&labels=${encodeURIComponent(TYPE_LABELS.STORY)}` +
201
+ `&sort=updated&direction=desc&per_page=${perPage}`,
202
+ });
203
+ return JSON.parse(raw.stdout || '[]')
204
+ .filter((issue) => !issue.pull_request)
205
+ .map(closedStory);
206
+ }
207
+
208
+ const totalCount = (raw) => {
209
+ const total = JSON.parse(raw.stdout || '{}').total_count;
210
+ return Number.isInteger(total) ? total : null;
211
+ };
212
+
213
+ /** Every closed Story's count from one search request, or `null` when it fails. */
214
+ function closedStoryTotal(gh, repoPath) {
215
+ const query = encodeURIComponent(
216
+ `repo:${repoPath} is:issue is:closed label:"${TYPE_LABELS.STORY}"`,
217
+ );
218
+ return gh
219
+ .api({ endpoint: `/search/issues?q=${query}&per_page=1` })
220
+ .then(totalCount)
221
+ .catch(() => null);
222
+ }
223
+
224
+ /**
225
+ * Live board data: every open issue, the most recently updated closed
226
+ * Stories (one page of up to 100, sorted by `closedAt` in
227
+ * {@link buildStatus}), their total count, and the open pull requests with
228
+ * their checks.
229
+ *
230
+ * @param {{ provider: object, gh: object, config: object, doneLimit?: number }} deps
231
+ * @returns {Promise<{ openTickets: object[], closedStories: object[],
232
+ * closedTotal: number|null, prs: object[] }>}
233
+ */
234
+ export async function fetchBoard({
235
+ provider,
236
+ gh,
237
+ config,
238
+ doneLimit = DEFAULT_DONE_LIMIT,
239
+ }) {
240
+ const repoPath = `${config?.github?.owner ?? '{owner}'}/${config?.github?.repo ?? '{repo}'}`;
241
+ const [openTickets, closedStories, closedTotal, prs] = await Promise.all([
242
+ provider.listTicketsByLabel({ state: 'open' }),
243
+ closedPage(gh, repoPath, doneLimit),
244
+ closedStoryTotal(gh, repoPath),
245
+ gh.pr.list(
246
+ ['--state', 'open', '--limit', '100'],
247
+ ['number', 'url', 'headRefName', 'statusCheckRollup'],
248
+ ),
249
+ ]);
250
+ return {
251
+ openTickets,
252
+ closedStories,
253
+ closedTotal,
254
+ prs: Array.isArray(prs) ? prs : [],
255
+ };
256
+ }
257
+
258
+ const offlineNote = (env) =>
259
+ env.online ? '' : ` offline (${env.offlineReason})`;
260
+
261
+ /**
262
+ * A short human table of the same data `--status --json` returns.
263
+ *
264
+ * @param {{ environments: object[], stories: object[] }} status
265
+ * @returns {string}
266
+ */
267
+ export function renderStatus(status) {
268
+ const lines = ['Environments:'];
269
+ for (const env of status.environments) {
270
+ lines.push(
271
+ ` ${env.name.padEnd(16)} ${env.target.padEnd(12)} ${env.load}/${env.capacity}${offlineNote(env)}`,
272
+ );
273
+ }
274
+ for (const column of [...COLUMNS, 'done']) {
275
+ const rows = status.stories.filter((s) => s.column === column);
276
+ if (rows.length === 0) continue;
277
+ lines.push('', `${column} (${rows.length}):`);
278
+ for (const s of rows) {
279
+ const where = s.environment ? ` [${s.environment}]` : '';
280
+ const pr = s.pr ? ` PR #${s.pr.number}` : '';
281
+ lines.push(` #${s.id}${where}${pr} ${s.title}`);
282
+ }
283
+ }
284
+ return `${lines.join('\n')}\n`;
285
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * What differs between launch targets: how an environment entry resolves,
3
+ * which launcher starts it, and the envelope fields its launch, stop and
4
+ * dry-run report. `local` runs a process; `claude-cloud` fires a routine.
5
+ *
6
+ * @module lib/dispatch/targets
7
+ */
8
+
9
+ import {
10
+ CloudLaunchError,
11
+ cloudEnvelopeFields,
12
+ describeFireRequest,
13
+ } from './launch-cloud.js';
14
+
15
+ const CLOUD_TARGET = 'claude-cloud';
16
+
17
+ const DEFAULT_COMMAND = Object.freeze([
18
+ 'claude',
19
+ '-p',
20
+ '/mandrel-deliver {id}',
21
+ '--session-id',
22
+ '{sessionId}',
23
+ '--name',
24
+ '◐ Delivery #{id}',
25
+ '--output-format',
26
+ 'stream-json',
27
+ '--verbose',
28
+ ]);
29
+
30
+ const isCloud = (environment) => environment.target === CLOUD_TARGET;
31
+
32
+ /**
33
+ * One configured entry with its defaults; a cloud entry is online only when
34
+ * its token variable is set in `env`.
35
+ *
36
+ * @param {string} name
37
+ * @param {object} entry
38
+ * @param {Record<string, string|undefined>} env
39
+ * @returns {import('./environments.js').Environment}
40
+ */
41
+ export function resolveEntry(name, entry, env) {
42
+ const base = {
43
+ name,
44
+ target: entry?.target ?? 'local',
45
+ capacity: entry?.capacity ?? 1,
46
+ };
47
+ if (!isCloud(base)) {
48
+ return {
49
+ ...base,
50
+ online: true,
51
+ command: [...(entry?.command ?? DEFAULT_COMMAND)],
52
+ };
53
+ }
54
+ const cloud = { ...base, routine: entry.routine, tokenEnv: entry.tokenEnv };
55
+ return env[entry.tokenEnv]
56
+ ? { ...cloud, online: true }
57
+ : { ...cloud, online: false, offlineReason: 'missing-token' };
58
+ }
59
+
60
+ /** The launcher `deps` provides for the environment's target. */
61
+ export function launcherFor(environment, deps) {
62
+ return isCloud(environment) ? deps.launchCloudImpl : deps.launchImpl;
63
+ }
64
+
65
+ /** Whether a failed launch takes back the label it applied. */
66
+ export function releasesLabel(applied, err) {
67
+ return applied && !err?.keepLabel;
68
+ }
69
+
70
+ /**
71
+ * Envelope fields for a cloud fire that failed; any other launch error is
72
+ * rethrown as the command failing.
73
+ */
74
+ export function launchFailureFields(err) {
75
+ if (err instanceof CloudLaunchError) return cloudEnvelopeFields(err);
76
+ throw new Error(`launch failed: ${err?.message ?? err}`);
77
+ }
78
+
79
+ /** Where a launched delivery can be followed. */
80
+ export function launchedFields(record) {
81
+ return record.sessionUrl
82
+ ? { sessionUrl: record.sessionUrl, commentPosted: record.commentPosted }
83
+ : { pid: record.pid, logPath: record.logPath };
84
+ }
85
+
86
+ /** A stopped cloud Story's session is left for the operator to archive. */
87
+ export function stoppedFields(record) {
88
+ if (!record?.sessionUrl) return {};
89
+ return {
90
+ sessionUrl: record.sessionUrl,
91
+ remoteStop: 'manual',
92
+ detail: `No API stops a fired session; archive it at ${record.sessionUrl}.`,
93
+ };
94
+ }
95
+
96
+ /** What a dry run would start: the argv, or the redacted fire request. */
97
+ export function dryRunFields(environment, storyId, commandFor) {
98
+ return isCloud(environment)
99
+ ? { request: describeFireRequest(environment, storyId) }
100
+ : { argv: commandFor(environment.command, storyId) };
101
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * The one verdict function for `mandrel dispatch`: what an action on a Story
3
+ * in an environment would do. The command, `--dry-run` and the `--status`
4
+ * read model all call it, so a refusal never differs between them. Pure.
5
+ *
6
+ * @module lib/dispatch/verdict
7
+ */
8
+
9
+ import { AGENT_LABELS, TYPE_LABELS } from '../label-constants.js';
10
+ import {
11
+ agentStateOf,
12
+ environmentOf,
13
+ holdsEnvironment,
14
+ } from './environments.js';
15
+
16
+ /**
17
+ * @typedef {{ ok: true, action: string, environment: string, applyLabel: boolean }
18
+ * | { ok: false, action: string, reason: string, detail: string }} Verdict
19
+ */
20
+
21
+ const refuse = (action, reason, detail) => ({
22
+ ok: false,
23
+ action,
24
+ reason,
25
+ detail,
26
+ });
27
+
28
+ const ids = (list) => list.map((id) => `#${id}`).join(', ');
29
+
30
+ /** Any assignee other than the operator; with no operator, any assignee. */
31
+ function foreignOwner(assignees, operator) {
32
+ const owner = assignees?.[0] ?? null;
33
+ if (owner === null) return null;
34
+ if (operator && owner.toLowerCase() === operator.toLowerCase()) return null;
35
+ return owner;
36
+ }
37
+
38
+ /**
39
+ * Refusals every action shares once its environment is chosen.
40
+ *
41
+ * @returns {Verdict|null}
42
+ */
43
+ function sharedRefusal({ action, story, envName, environments, operator }) {
44
+ if (!environments.some((e) => e.name === envName)) {
45
+ const known = environments.map((e) => e.name).join(', ');
46
+ return refuse(
47
+ action,
48
+ 'unknown-environment',
49
+ `No environment named "${envName ?? ''}"; configured: ${known}.`,
50
+ );
51
+ }
52
+ const owner = foreignOwner(story.assignees, operator);
53
+ if (owner) {
54
+ return refuse(
55
+ action,
56
+ 'foreign-lease',
57
+ `#${story.id} is leased to @${owner}.`,
58
+ );
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /** An offline environment takes no new Story; capacity is checked after. */
64
+ function unavailable({ action, envName, environments, loads }) {
65
+ const env = environments.find((e) => e.name === envName);
66
+ if (env.online === false) {
67
+ return refuse(
68
+ action,
69
+ 'offline',
70
+ `Environment "${envName}" is offline (${env.offlineReason ?? 'unavailable'}).`,
71
+ );
72
+ }
73
+ const load = loads?.[envName] ?? 0;
74
+ if (load < env.capacity) return null;
75
+ return refuse(
76
+ action,
77
+ 'at-capacity',
78
+ `Environment "${envName}" holds ${load} of ${env.capacity}.`,
79
+ );
80
+ }
81
+
82
+ function decideDispatch(input) {
83
+ const { story, envName } = input;
84
+ const state = agentStateOf(story.labels);
85
+ if (holdsEnvironment(story)) {
86
+ return refuse(
87
+ 'dispatch',
88
+ 'already-dispatched',
89
+ `#${story.id} is already held by environment "${environmentOf(story.labels)}".`,
90
+ );
91
+ }
92
+ if (state !== AGENT_LABELS.READY) {
93
+ return refuse(
94
+ 'dispatch',
95
+ 'not-ready',
96
+ `#${story.id} is ${state ?? 'unlabelled'}, not ${AGENT_LABELS.READY}.`,
97
+ );
98
+ }
99
+ const shared = sharedRefusal({ ...input, action: 'dispatch' });
100
+ if (shared) return shared;
101
+ if (input.unmetDependencies?.length > 0) {
102
+ return refuse(
103
+ 'dispatch',
104
+ 'unmet-dependency',
105
+ `#${story.id} is blocked by open ${ids(input.unmetDependencies)}.`,
106
+ );
107
+ }
108
+ const full = unavailable({ ...input, action: 'dispatch' });
109
+ if (full) return full;
110
+ return {
111
+ ok: true,
112
+ action: 'dispatch',
113
+ environment: envName,
114
+ applyLabel: true,
115
+ };
116
+ }
117
+
118
+ function decideResume(input) {
119
+ const { story, envName } = input;
120
+ const state = agentStateOf(story.labels);
121
+ if (state !== AGENT_LABELS.BLOCKED) {
122
+ return refuse(
123
+ 'resume',
124
+ 'not-blocked',
125
+ `#${story.id} is ${state ?? 'unlabelled'}, not ${AGENT_LABELS.BLOCKED}.`,
126
+ );
127
+ }
128
+ const holder = environmentOf(story.labels);
129
+ if (envName && holder && envName !== holder) {
130
+ return refuse(
131
+ 'resume',
132
+ 'wrong-environment',
133
+ `#${story.id} is held by "${holder}", not "${envName}".`,
134
+ );
135
+ }
136
+ const target = holder ?? envName;
137
+ const shared = sharedRefusal({ ...input, envName: target, action: 'resume' });
138
+ if (shared) return shared;
139
+ const offline = unavailable({
140
+ ...input,
141
+ envName: target,
142
+ loads: holder ? {} : input.loads,
143
+ action: 'resume',
144
+ });
145
+ if (offline) return offline;
146
+ return {
147
+ ok: true,
148
+ action: 'resume',
149
+ environment: target,
150
+ applyLabel: !holder,
151
+ };
152
+ }
153
+
154
+ function decideStop(input) {
155
+ const { story, envName } = input;
156
+ if (agentStateOf(story.labels) === AGENT_LABELS.CLOSING) {
157
+ return refuse(
158
+ 'stop',
159
+ 'closing',
160
+ `#${story.id} is ${AGENT_LABELS.CLOSING}; let close land or recover it.`,
161
+ );
162
+ }
163
+ const holder = environmentOf(story.labels);
164
+ if (!holder || (envName && envName !== holder)) {
165
+ return refuse(
166
+ 'stop',
167
+ 'wrong-environment',
168
+ holder
169
+ ? `#${story.id} is held by "${holder}", not "${envName}".`
170
+ : `#${story.id} is not held by any environment.`,
171
+ );
172
+ }
173
+ const shared = sharedRefusal({ ...input, envName: holder, action: 'stop' });
174
+ if (shared) return shared;
175
+ return { ok: true, action: 'stop', environment: holder, applyLabel: false };
176
+ }
177
+
178
+ const DECIDERS = {
179
+ dispatch: decideDispatch,
180
+ resume: decideResume,
181
+ stop: decideStop,
182
+ };
183
+
184
+ /**
185
+ * @param {{
186
+ * action: 'dispatch'|'resume'|'stop',
187
+ * story: { id: number, labels: string[], assignees?: string[] },
188
+ * envName?: string|null,
189
+ * environments: import('./environments.js').Environment[],
190
+ * loads?: Record<string, number>,
191
+ * unmetDependencies?: number[],
192
+ * children?: number[],
193
+ * operator?: string|null,
194
+ * }} input
195
+ * @returns {Verdict}
196
+ */
197
+ export function decide(input) {
198
+ const { action, story } = input;
199
+ if ((story.labels ?? []).includes(TYPE_LABELS.EPIC)) {
200
+ return refuse(
201
+ action,
202
+ 'epic',
203
+ `#${story.id} is an Epic; dispatch its children: ${ids(input.children ?? []) || 'none'}.`,
204
+ );
205
+ }
206
+ return DECIDERS[action](input);
207
+ }