mandrel 2.124.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 (54) hide show
  1. package/.agents/docs/agentrc-reference.json +1 -0
  2. package/.agents/docs/configuration.md +2 -0
  3. package/.agents/docs/runbooks/dispatch-board.md +174 -0
  4. package/.agents/docs/runbooks/dispatch.md +219 -0
  5. package/.agents/docs/runbooks/session-titles.md +52 -0
  6. package/.agents/schemas/agentrc.schema.json +60 -0
  7. package/.agents/scripts/acceptance-eval.js +11 -2
  8. package/.agents/scripts/dispatch.js +400 -0
  9. package/.agents/scripts/lib/child-detached.js +48 -0
  10. package/.agents/scripts/lib/child-exec.js +11 -0
  11. package/.agents/scripts/lib/config/delivery-routing.js +15 -12
  12. package/.agents/scripts/lib/config/temp-paths.js +26 -0
  13. package/.agents/scripts/lib/config-settings-schema-delivery.js +45 -0
  14. package/.agents/scripts/lib/dispatch/environments.js +135 -0
  15. package/.agents/scripts/lib/dispatch/launch-cloud.js +164 -0
  16. package/.agents/scripts/lib/dispatch/launch-local.js +77 -0
  17. package/.agents/scripts/lib/dispatch/liveness.js +21 -0
  18. package/.agents/scripts/lib/dispatch/record.js +54 -0
  19. package/.agents/scripts/lib/dispatch/status.js +285 -0
  20. package/.agents/scripts/lib/dispatch/targets.js +101 -0
  21. package/.agents/scripts/lib/dispatch/verdict.js +207 -0
  22. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  23. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  24. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +2 -0
  25. package/.agents/scripts/lib/orchestration/story-handoff.js +6 -0
  26. package/.agents/scripts/lib/orchestration/story-stage-publish.js +147 -0
  27. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  28. package/.agents/scripts/session-title.js +187 -0
  29. package/.agents/scripts/single-story-confirm-merge.js +7 -0
  30. package/.agents/scripts/single-story-init.js +3 -0
  31. package/.agents/workflows/helpers/audit-lens-core.md +4 -0
  32. package/.agents/workflows/helpers/deliver-light.md +4 -1
  33. package/.agents/workflows/helpers/qa-core.md +2 -0
  34. package/.agents/workflows/mandrel-deliver.md +7 -3
  35. package/.agents/workflows/mandrel-orchestrate.md +2 -0
  36. package/.agents/workflows/mandrel-plan.md +4 -0
  37. package/README.md +8 -0
  38. package/bin/mandrel.js +35 -13
  39. package/docs/CHANGELOG.md +14 -0
  40. package/lib/cli/dispatch.js +27 -0
  41. package/lib/cli/ui/accounts.js +81 -0
  42. package/lib/cli/ui/board-model.js +372 -0
  43. package/lib/cli/ui/board.css +525 -0
  44. package/lib/cli/ui/board.html +80 -0
  45. package/lib/cli/ui/board.js +676 -0
  46. package/lib/cli/ui/log-tail.js +89 -0
  47. package/lib/cli/ui/panel-model.js +100 -0
  48. package/lib/cli/ui/preferences.js +136 -0
  49. package/lib/cli/ui/request-guard.js +108 -0
  50. package/lib/cli/ui/server.js +211 -0
  51. package/lib/cli/ui/sources.js +202 -0
  52. package/lib/cli/ui/story-detail.js +92 -0
  53. package/lib/cli/ui.js +114 -0
  54. package/package.json +1 -1
package/bin/mandrel.js CHANGED
@@ -13,7 +13,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
13
13
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
14
 
15
15
  /**
16
- * @typedef {{ description: string, knownFlags: Set<string> }} SubcommandMeta
16
+ * @typedef {{ description: string, knownFlags: string[] }} SubcommandMeta
17
17
  * @type {Map<string, SubcommandMeta>}
18
18
  */
19
19
  const SUBCOMMANDS = new Map([
@@ -21,7 +21,7 @@ const SUBCOMMANDS = new Map([
21
21
  'init',
22
22
  {
23
23
  description: 'install and configure mandrel in the current project',
24
- knownFlags: new Set([
24
+ knownFlags: [
25
25
  '--assume-yes',
26
26
  '--skip-github',
27
27
  '--owner',
@@ -30,14 +30,14 @@ const SUBCOMMANDS = new Map([
30
30
  '--project-number',
31
31
  '--operator-handle',
32
32
  '--dry-run',
33
- ]),
33
+ ],
34
34
  },
35
35
  ],
36
36
  [
37
37
  'sync',
38
38
  {
39
39
  description: 'materialize .agents/ payload from installed package',
40
- knownFlags: new Set(['--dry-run']),
40
+ knownFlags: ['--dry-run'],
41
41
  },
42
42
  ],
43
43
  [
@@ -47,7 +47,7 @@ const SUBCOMMANDS = new Map([
47
47
  // No --dry-run: the projection scripts have no preview mode, and
48
48
  // accepting the flag while syncing for real overwrote .claude/ on an
49
49
  // operator who asked for a preview. Reject it at the dispatcher.
50
- knownFlags: new Set([]),
50
+ knownFlags: [],
51
51
  },
52
52
  ],
53
53
  [
@@ -55,42 +55,64 @@ const SUBCOMMANDS = new Map([
55
55
  {
56
56
  description: 'regenerate .claude/agents/ from .agents/agents/',
57
57
  // Same contract as sync-commands: no preview mode, so no --dry-run.
58
- knownFlags: new Set([]),
58
+ knownFlags: [],
59
59
  },
60
60
  ],
61
61
  [
62
62
  'doctor',
63
63
  {
64
64
  description: 'run readiness checks and report remedies',
65
- knownFlags: new Set([]),
65
+ knownFlags: [],
66
66
  },
67
67
  ],
68
68
  [
69
69
  'update',
70
70
  {
71
71
  description: 'upgrade mandrel to the newest published version',
72
- knownFlags: new Set(['--dry-run', '--install-cmd']),
72
+ knownFlags: ['--dry-run', '--install-cmd'],
73
73
  },
74
74
  ],
75
75
  [
76
76
  'migrate',
77
77
  {
78
78
  description: 'apply version-keyed migrations for a version range',
79
- knownFlags: new Set(['--from', '--to', '--dry-run']),
79
+ knownFlags: ['--from', '--to', '--dry-run'],
80
80
  },
81
81
  ],
82
82
  [
83
83
  'explain',
84
84
  {
85
85
  description: 'print resolved config values and their sources',
86
- knownFlags: new Set(['--json']),
86
+ knownFlags: ['--json'],
87
+ },
88
+ ],
89
+ [
90
+ 'dispatch',
91
+ {
92
+ description: 'start, resume or stop a Story in a named environment',
93
+ knownFlags: [
94
+ '--env',
95
+ '--resume',
96
+ '--stop',
97
+ '--status',
98
+ '--json',
99
+ '--done-limit',
100
+ '--dry-run',
101
+ ],
102
+ },
103
+ ],
104
+ [
105
+ 'ui',
106
+ {
107
+ description: 'serve the local dispatch board on 127.0.0.1',
108
+ knownFlags: ['--port'],
87
109
  },
88
110
  ],
89
111
  [
90
112
  'uninstall',
91
113
  {
92
114
  description: 'reverse a recorded install using the install ledger',
93
- knownFlags: new Set(['--include-github', '--dry-run']),
115
+ knownFlags: ['--include-github', '--dry-run'],
94
116
  },
95
117
  ],
96
118
  ]);
@@ -165,7 +187,7 @@ const UNIVERSAL_FLAGS = new Set(['--help', '-h']);
165
187
  * Only flag names are checked (`--flag=value` is split).
166
188
  *
167
189
  * @param {string} subName
168
- * @param {Set<string>} knownFlags
190
+ * @param {string[]} knownFlags
169
191
  * @param {string[]} argv
170
192
  * @returns {string | null}
171
193
  */
@@ -174,7 +196,7 @@ function findUnknownFlag(subName, knownFlags, argv) {
174
196
  if (!arg.startsWith('-')) continue;
175
197
  const flagName = arg.includes('=') ? arg.slice(0, arg.indexOf('=')) : arg;
176
198
  if (UNIVERSAL_FLAGS.has(flagName)) continue;
177
- if (!knownFlags.has(flagName)) {
199
+ if (!knownFlags.includes(flagName)) {
178
200
  const names = [...knownFlags].sort().join(', ');
179
201
  const hint = names.length > 0 ? ` Known flags: ${names}\n` : '';
180
202
  return (
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,20 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.125.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.124.0...mandrel-v2.125.0) (2026-11-19)
19
+
20
+
21
+ ### Added
22
+
23
+ * add `mandrel ui`: a local board that shows every Story and dispatches by drag ([#6111](https://github.com/dsj1984/mandrel/issues/6111)) ([#6118](https://github.com/dsj1984/mandrel/issues/6118)) ([94cfb12](https://github.com/dsj1984/mandrel/commit/94cfb12f2ddf88f38fe63462532c9607788241d7))
24
+ * dispatch a Story to a named environment with `mandrel dispatch` (local launch) ([#6108](https://github.com/dsj1984/mandrel/issues/6108)) ([#6116](https://github.com/dsj1984/mandrel/issues/6116)) ([90f0576](https://github.com/dsj1984/mandrel/commit/90f05766e57a6371ae1aec6a06d86a3e6af9805c))
25
+ * dispatch a Story to an Anthropic cloud environment by firing a Claude routine ([#6110](https://github.com/dsj1984/mandrel/issues/6110)) ([#6117](https://github.com/dsj1984/mandrel/issues/6117)) ([d3d286c](https://github.com/dsj1984/mandrel/commit/d3d286cf24f253cd96645858b8d131820d4d37f3))
26
+ * dispatch board Settings: a gear icon opens per-browser board preferences, including how many Done Stories to show ([#6123](https://github.com/dsj1984/mandrel/issues/6123)) ([#6126](https://github.com/dsj1984/mandrel/issues/6126)) ([6ea0360](https://github.com/dsj1984/mandrel/commit/6ea0360e64dc9407e4929d1f8046be713e0c2772))
27
+ * dispatch board shows which GitHub and Claude accounts it uses, and opens Environments and Connections in the side panel from header icons ([#6122](https://github.com/dsj1984/mandrel/issues/6122)) ([#6125](https://github.com/dsj1984/mandrel/issues/6125)) ([4aecdca](https://github.com/dsj1984/mandrel/commit/4aecdca2fcd01bbac2447e4acea3e21d1e6f4acb))
28
+ * publish a Story's delivery stage to GitHub so remote runs show their progress ([#6109](https://github.com/dsj1984/mandrel/issues/6109)) ([#6114](https://github.com/dsj1984/mandrel/issues/6114)) ([430c8ec](https://github.com/dsj1984/mandrel/commit/430c8eca1e989cd01cc30ad02d785a80ee57b1c3))
29
+ * show on each dispatch-board card whether its delivery is alive and where it stands, with a detail popout per Story ([#6121](https://github.com/dsj1984/mandrel/issues/6121)) ([#6124](https://github.com/dsj1984/mandrel/issues/6124)) ([8c6e2dd](https://github.com/dsj1984/mandrel/commit/8c6e2dd1150b50985841bbd0119307330ddf0b74))
30
+ * title the host session with a state glyph as plan, deliver, orchestrate, audit and QA runs progress ([#6119](https://github.com/dsj1984/mandrel/issues/6119)) ([#6120](https://github.com/dsj1984/mandrel/issues/6120)) ([a0ebec9](https://github.com/dsj1984/mandrel/commit/a0ebec92ebb9364a26f98446633f2e6e603ad191))
31
+
18
32
  ## [2.124.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.123.0...mandrel-v2.124.0) (2026-11-17)
19
33
 
20
34
 
@@ -0,0 +1,27 @@
1
+ // lib/cli/dispatch.js
2
+ /**
3
+ * `mandrel dispatch` subcommand: the operator-facing face of
4
+ * `.agents/scripts/dispatch.js`. Both call `runDispatch`, so they share one
5
+ * envelope and one set of exit codes; this module only maps the code onto
6
+ * the process.
7
+ *
8
+ * Injectable seams (used by tests): `exit` replaces setting
9
+ * `process.exitCode`; every other key is passed to `runDispatch`.
10
+ */
11
+
12
+ import { runDispatch } from '../../.agents/scripts/dispatch.js';
13
+
14
+ /**
15
+ * @param {string[]} argv
16
+ * @param {{ exit?: (code: number) => void } & Parameters<typeof runDispatch>[1]} [deps]
17
+ * @returns {Promise<void>}
18
+ */
19
+ export default async function run(argv, deps = {}) {
20
+ const {
21
+ exit = (code) => {
22
+ process.exitCode = code;
23
+ },
24
+ ...rest
25
+ } = deps;
26
+ exit(await runDispatch(argv, rest));
27
+ }
@@ -0,0 +1,81 @@
1
+ // lib/cli/ui/accounts.js
2
+ /**
3
+ * Which GitHub login and Claude account the board and its local launches
4
+ * act as. Both probes run in parallel, the result is reused for `ttlMs`, and
5
+ * nothing here logs a value: account fields leave only in the response.
6
+ *
7
+ * @module cli/ui/accounts
8
+ */
9
+
10
+ import { runGh } from '../../../.agents/scripts/lib/gh-exec.js';
11
+
12
+ const TIMEOUT_MS = 10_000;
13
+ const LOGIN_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
14
+ const ACCOUNT_FIELDS = ['email', 'orgName', 'subscriptionType', 'authMethod'];
15
+ const FIRST_PARTY = 'firstParty';
16
+
17
+ async function githubLogin(env, runner) {
18
+ const r = await runGh(
19
+ ['api', 'user', '--jq', '.login'],
20
+ { env, timeout: TIMEOUT_MS },
21
+ runner,
22
+ );
23
+ const login = !r.error && r.status === 0 ? (r.stdout ?? '').trim() : '';
24
+ return LOGIN_RE.test(login)
25
+ ? { login }
26
+ : { login: null, reason: 'login-unavailable' };
27
+ }
28
+
29
+ function parseJson(text) {
30
+ try {
31
+ return JSON.parse(text);
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ /** The whitelisted account summary from `claude auth status --json`, or `null`. */
38
+ function accountOf(status) {
39
+ if (status?.loggedIn !== true) return null;
40
+ const account = {};
41
+ for (const field of ACCOUNT_FIELDS) {
42
+ if (typeof status[field] === 'string') account[field] = status[field];
43
+ }
44
+ const provider = status.apiProvider;
45
+ if (typeof provider === 'string' && provider !== FIRST_PARTY) {
46
+ account.apiProvider = provider;
47
+ }
48
+ return account;
49
+ }
50
+
51
+ async function claudeAccount(runner) {
52
+ const r = await runner('claude', ['auth', 'status', '--json'], {
53
+ shell: process.platform === 'win32',
54
+ timeout: TIMEOUT_MS,
55
+ });
56
+ return !r.error && r.status === 0 ? accountOf(parseJson(r.stdout)) : null;
57
+ }
58
+
59
+ /**
60
+ * @param {{ env: Record<string, string|undefined>, runner: Function,
61
+ * ttlMs?: number, now?: () => number }} deps
62
+ * @returns {() => Promise<{ github: { login: string|null, reason?: string },
63
+ * claude: object|null }>}
64
+ */
65
+ export function createAccountProbe({
66
+ env,
67
+ runner,
68
+ ttlMs = 60_000,
69
+ now = Date.now,
70
+ }) {
71
+ let cached = null;
72
+ return () => {
73
+ if (cached && now() - cached.at < ttlMs) return cached.promise;
74
+ const promise = Promise.all([
75
+ githubLogin(env, runner),
76
+ claudeAccount(runner),
77
+ ]).then(([github, claude]) => ({ github, claude }));
78
+ cached = { at: now(), promise };
79
+ return promise;
80
+ };
81
+ }
@@ -0,0 +1,372 @@
1
+ // lib/cli/ui/board-model.js
2
+ /**
3
+ * The `mandrel ui` view model: pure functions from the dispatch status read
4
+ * model to columns, lanes, cards and drop-zone verdict text. It runs in the
5
+ * browser (served as a module) and under `node --test`, so it imports
6
+ * nothing. It evaluates no dispatch rule: every verdict it shows is one the
7
+ * read model already computed into the Story's `drops`.
8
+ *
9
+ * @module cli/ui/board-model
10
+ */
11
+
12
+ const COLUMNS = Object.freeze([
13
+ { id: 'backlog', title: 'Backlog' },
14
+ { id: 'planning', title: 'Planning' },
15
+ { id: 'ready', title: 'Ready' },
16
+ { id: 'delivering', title: 'Delivering' },
17
+ { id: 'blocked', title: 'Blocked' },
18
+ { id: 'done', title: 'Done' },
19
+ ]);
20
+
21
+ /** The Delivering lane for in-flight Stories that name no environment. */
22
+ const UNTRACKED = 'untracked';
23
+
24
+ /** The published delivery stages, in order. */
25
+ const STAGES = Object.freeze(['build', 'check', 'handoff', 'close', 'merge']);
26
+
27
+ /** A step before, at and after the current stage. */
28
+ const STEP_STATES = ['done', 'current', 'todo'];
29
+
30
+ /** Columns whose cards show the delivery status row. */
31
+ const IN_FLIGHT = new Set(['delivering', 'blocked']);
32
+
33
+ const LIVENESS_TEXT = {
34
+ working: 'working',
35
+ exited: 'process exited',
36
+ unknown: 'unknown',
37
+ };
38
+
39
+ const ACTION_TEXT = {
40
+ dispatch: (env) => `Dispatch to ${env}`,
41
+ resume: (env) => `Resume in ${env}`,
42
+ stop: () => 'Stop and return to Ready',
43
+ };
44
+
45
+ /**
46
+ * @param {{ total: number, passed: number, failed: number, pending: number }|null|undefined} checks
47
+ * @returns {string}
48
+ */
49
+ function checksText(checks) {
50
+ if (!checks || checks.total === 0) return 'no checks';
51
+ const parts = [`${checks.passed}/${checks.total} passed`];
52
+ if (checks.failed > 0) parts.push(`${checks.failed} failed`);
53
+ if (checks.pending > 0) parts.push(`${checks.pending} pending`);
54
+ return parts.join(', ');
55
+ }
56
+
57
+ /** `url` when it is a GitHub page, else `null`: no other link is rendered. */
58
+ function githubUrl(url) {
59
+ return typeof url === 'string' && url.startsWith('https://github.com/')
60
+ ? url
61
+ : null;
62
+ }
63
+
64
+ function prView(pr) {
65
+ if (!pr) return null;
66
+ return {
67
+ number: pr.number,
68
+ url: githubUrl(pr.url),
69
+ checks: checksText(pr.checks),
70
+ };
71
+ }
72
+
73
+ /**
74
+ * Time from `iso` to `now` as `Nm` or `Nh Mm`; `null` when `iso` is not a date.
75
+ *
76
+ * @param {string|null|undefined} iso
77
+ * @param {number} now Epoch milliseconds.
78
+ * @returns {string|null}
79
+ */
80
+ function elapsed(iso, now) {
81
+ const ms = now - Date.parse(iso ?? '');
82
+ return Number.isFinite(ms) ? minutesText(Math.floor(ms / 60_000)) : null;
83
+ }
84
+
85
+ function minutesText(minutes) {
86
+ if (minutes < 60) return `${Math.max(0, minutes)}m`;
87
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
88
+ }
89
+
90
+ /** Each stage marked `done`, `current` or `todo` against `stage`. */
91
+ function stepper(stage) {
92
+ const at = STAGES.indexOf(stage);
93
+ return STAGES.map((name, i) => ({
94
+ name,
95
+ state: STEP_STATES[Math.sign(i - at) + 1],
96
+ }));
97
+ }
98
+
99
+ /**
100
+ * The liveness badge; `warning` flags a process gone while the Story still
101
+ * reads as executing.
102
+ *
103
+ * @param {{ state?: string }|null|undefined} proc
104
+ * @param {string|null|undefined} agentState
105
+ */
106
+ function livenessView(proc, agentState) {
107
+ const state = LIVENESS_TEXT[proc?.state] ? proc.state : 'unknown';
108
+ return {
109
+ state,
110
+ text: LIVENESS_TEXT[state],
111
+ warning: state === 'exited' && agentState === 'agent::executing',
112
+ };
113
+ }
114
+
115
+ /** `<label> <elapsed><suffix>`, or `null` when `iso` is not a date. */
116
+ function since(label, iso, now, suffix = '') {
117
+ const time = elapsed(iso, now);
118
+ return time && `${label} ${time}${suffix}`;
119
+ }
120
+
121
+ /** The in-flight status row, or `null` for a card that is not in flight. */
122
+ function statusView(story, now) {
123
+ if (!IN_FLIGHT.has(story.column)) return null;
124
+ return {
125
+ stage: story.stage ?? 'no stage yet',
126
+ steps: stepper(story.stage),
127
+ liveness: livenessView(story.process, story.state),
128
+ running: since('running', story.process?.startedAt, now),
129
+ updated: since('updated', story.stageUpdatedAt, now, ' ago'),
130
+ };
131
+ }
132
+
133
+ /**
134
+ * Dependencies still open on the board: named by the Story and present in a
135
+ * column other than Done.
136
+ *
137
+ * @param {{ dependsOn?: number[] }} story
138
+ * @param {Set<number>} openIds
139
+ * @returns {number[]}
140
+ */
141
+ function unmetOf(story, openIds) {
142
+ return (story.dependsOn ?? []).filter((id) => openIds.has(id));
143
+ }
144
+
145
+ /**
146
+ * The fields a card shows.
147
+ *
148
+ * @param {object} story A read-model Story row.
149
+ * @param {Set<number>} openIds
150
+ * @param {number} now Epoch milliseconds.
151
+ */
152
+ function cardView(story, openIds, now) {
153
+ return {
154
+ id: story.id,
155
+ title: story.title ?? '',
156
+ stage: story.stage ?? null,
157
+ environment: story.environment ?? null,
158
+ pr: prView(story.pr),
159
+ unmet: unmetOf(story, openIds),
160
+ status: statusView(story, now),
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Online state per environment name from `/api/connections`; an
166
+ * environment the connections report does not name is taken as online.
167
+ */
168
+ function onlineMap(connections) {
169
+ const map = new Map();
170
+ for (const env of connections?.environments ?? []) {
171
+ map.set(env.name, { online: env.online, reason: env.reason ?? null });
172
+ }
173
+ return map;
174
+ }
175
+
176
+ function laneOf(env, online) {
177
+ const status = online.get(env.name) ?? { online: true, reason: null };
178
+ return {
179
+ name: env.name,
180
+ target: env.target,
181
+ load: env.load,
182
+ capacity: env.capacity,
183
+ online: status.online,
184
+ reason: status.reason,
185
+ header: status.online ? `${env.load}/${env.capacity}` : 'offline',
186
+ cards: [],
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Columns with their cards; Delivering also carries one lane per
192
+ * environment plus the `untracked` lane.
193
+ *
194
+ * @param {{ environments?: object[], stories?: object[] }} state
195
+ * @param {{ environments?: object[] }|null} [connections]
196
+ * @param {number} [now] Epoch milliseconds the relative times count to.
197
+ */
198
+ export function buildBoard(state, connections = null, now = Date.now()) {
199
+ const stories = state?.stories ?? [];
200
+ const openIds = new Set(
201
+ stories.filter((s) => s.column !== 'done').map((s) => s.id),
202
+ );
203
+ const online = onlineMap(connections);
204
+ const lanes = (state?.environments ?? []).map((e) => laneOf(e, online));
205
+ const untracked = {
206
+ name: UNTRACKED,
207
+ target: null,
208
+ load: null,
209
+ capacity: null,
210
+ online: true,
211
+ reason: null,
212
+ header: '',
213
+ cards: [],
214
+ };
215
+ const columns = COLUMNS.map((c) => ({ ...c, cards: [], lanes: null }));
216
+ const byId = new Map(columns.map((c) => [c.id, c]));
217
+ byId.get('delivering').lanes = [...lanes, untracked];
218
+ for (const story of stories) {
219
+ const column = byId.get(story.column);
220
+ if (!column) continue;
221
+ const card = cardView(story, openIds, now);
222
+ if (column.lanes) {
223
+ const lane =
224
+ column.lanes.find((l) => l.name === story.environment) ?? untracked;
225
+ lane.cards.push(card);
226
+ } else {
227
+ column.cards.push(card);
228
+ }
229
+ }
230
+ return { columns, offline: lanes.filter((l) => !l.online).length };
231
+ }
232
+
233
+ const stamp = (iso) => `${String(iso).replace('T', ' ').slice(0, 16)} UTC`;
234
+
235
+ function recordRows(record) {
236
+ if (!record) return [];
237
+ return [
238
+ ['pid', record.pid],
239
+ ['Started', record.startedAt && stamp(record.startedAt)],
240
+ ['Session', record.sessionId],
241
+ ['Session URL', record.sessionUrl],
242
+ ['Command', record.argv?.join(' ')],
243
+ ].filter(([, value]) => value !== null && value !== undefined);
244
+ }
245
+
246
+ function timelineLine(entry, now) {
247
+ return `${entry.stage}: ${stamp(entry.at)} (${elapsed(entry.at, now) ?? '?'} ago)`;
248
+ }
249
+
250
+ function processText(proc, now) {
251
+ const { text } = livenessView(proc, null);
252
+ const running = since('running', proc?.startedAt, now);
253
+ return running ? `${text}, ${running}` : text;
254
+ }
255
+
256
+ function factRows(detail, now) {
257
+ return [
258
+ ['Column', detail.column],
259
+ ['Environment', detail.environment ?? 'none'],
260
+ ['Stage', detail.stage ?? 'none'],
261
+ ['Process', processText(detail.process, now)],
262
+ ['Labels', (detail.labels ?? []).join(', ') || 'none'],
263
+ ];
264
+ }
265
+
266
+ /**
267
+ * The Story detail view's sections from a `/api/story` response.
268
+ *
269
+ * @param {object} detail
270
+ * @param {number} [now] Epoch milliseconds.
271
+ */
272
+ export function storyDetailView(detail, now = Date.now()) {
273
+ return {
274
+ heading: `#${detail.id} ${detail.title ?? ''}`.trim(),
275
+ issueUrl: githubUrl(detail.issueUrl),
276
+ pr: prView(detail.pr),
277
+ facts: factRows(detail, now),
278
+ timeline: (detail.history ?? []).map((entry) => timelineLine(entry, now)),
279
+ record: recordRows(detail.record),
280
+ resumeCommand: detail.resumeCommand ?? null,
281
+ log: (detail.logTail ?? []).join('\n') || 'No log output yet.',
282
+ };
283
+ }
284
+
285
+ /**
286
+ * The text a verdict reads as: what the drop would do, or why not.
287
+ *
288
+ * @param {{ ok: boolean, action: string, environment?: string, reason?: string, detail?: string }} verdict
289
+ * @returns {string}
290
+ */
291
+ function verdictText(verdict) {
292
+ if (!verdict.ok) return verdict.detail || verdict.reason || 'Refused';
293
+ return ACTION_TEXT[verdict.action](verdict.environment);
294
+ }
295
+
296
+ /**
297
+ * What dropping `story` on `zone` (a column id or an environment name)
298
+ * would do. `kind` is `action` (run it), `confirm` (ask first, then run),
299
+ * `copy` (copy `text`'s command), `refused` or `none`.
300
+ *
301
+ * @param {object} story A read-model Story row.
302
+ * @param {string} zone
303
+ * @returns {{ kind: string, text: string, action?: string, environment?: string }}
304
+ */
305
+ export function zoneVerdict(story, zone) {
306
+ if (zone === story.column || zone === UNTRACKED) {
307
+ return { kind: 'none', text: 'No change' };
308
+ }
309
+ if (zone === 'planning' && story.column === 'backlog') {
310
+ return { kind: 'copy', text: `/mandrel-plan ${story.id}` };
311
+ }
312
+ const verdict = story.drops?.[zone] ?? null;
313
+ if (!verdict) return { kind: 'none', text: 'No action here' };
314
+ if (!verdict.ok) return { kind: 'refused', text: verdictText(verdict) };
315
+ return {
316
+ kind: verdict.action === 'stop' ? 'confirm' : 'action',
317
+ text: verdictText(verdict),
318
+ action: verdict.action,
319
+ environment: verdict.environment,
320
+ };
321
+ }
322
+
323
+ /**
324
+ * Every allowed move for a Story — the Move menu, so no action needs a drag.
325
+ *
326
+ * @param {object} story
327
+ * @param {string[]} zones Column ids and environment names, in board order.
328
+ */
329
+ export function moveOptions(story, zones) {
330
+ return zones
331
+ .map((zone) => ({ zone, ...zoneVerdict(story, zone) }))
332
+ .filter((v) => ['action', 'confirm', 'copy'].includes(v.kind));
333
+ }
334
+
335
+ /**
336
+ * Every drop zone in board order: the columns, then each environment lane.
337
+ *
338
+ * @param {{ environments?: object[] }} state
339
+ * @returns {string[]}
340
+ */
341
+ export function dropZones(state) {
342
+ return [
343
+ ...COLUMNS.map((c) => c.id),
344
+ ...(state?.environments ?? []).map((e) => e.name),
345
+ ];
346
+ }
347
+
348
+ /**
349
+ * The Environments panel view: one card per environment.
350
+ *
351
+ * @param {{ environments?: object[], stories?: object[] }} state
352
+ * @param {{ environments?: object[] }|null} [connections]
353
+ */
354
+ export function environmentCards(state, connections = null) {
355
+ const details = new Map(
356
+ (connections?.environments ?? []).map((e) => [e.name, e]),
357
+ );
358
+ return (state?.environments ?? []).map((env) => {
359
+ const detail = details.get(env.name);
360
+ return {
361
+ name: env.name,
362
+ target: env.target,
363
+ load: `${env.load}/${env.capacity}`,
364
+ online: detail ? detail.online : true,
365
+ reason: detail?.reason ?? null,
366
+ definedIn: detail?.definedIn ?? 'unknown',
367
+ stories: (state.stories ?? [])
368
+ .filter((s) => s.environment === env.name && s.column !== 'done')
369
+ .map((s) => s.id),
370
+ };
371
+ });
372
+ }