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
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The delivery-environment registry behind `mandrel dispatch`: the resolved
3
+ * `delivery.environments` map, the `env::<name>` label that records which
4
+ * environment holds a Story, and an environment's load. No I/O: a cloud
5
+ * entry is online when its token variable is set in the env map passed in.
6
+ *
7
+ * @module lib/dispatch/environments
8
+ */
9
+
10
+ import { AGENT_LABELS } from '../label-constants.js';
11
+ import { resolveEntry } from './targets.js';
12
+
13
+ /**
14
+ * `env::<name>` records which environment holds a Story; minted on demand.
15
+ * On a closed Story it is history only.
16
+ */
17
+ const ENV_LABEL_PREFIX = 'env::';
18
+
19
+ const SESSION_PLACEHOLDER = '{sessionId}';
20
+
21
+ /** The colour an `env::` label is created with. */
22
+ export const ENV_LABEL_COLOR = '#5319E7';
23
+
24
+ /** States in which a labelled open Story counts against its environment. */
25
+ const LOAD_STATES = new Set([
26
+ AGENT_LABELS.READY,
27
+ AGENT_LABELS.EXECUTING,
28
+ AGENT_LABELS.CLOSING,
29
+ AGENT_LABELS.BLOCKED,
30
+ ]);
31
+
32
+ /**
33
+ * @typedef {{ name: string, target: string, capacity: number, online: boolean,
34
+ * offlineReason?: string, command?: string[], routine?: string,
35
+ * tokenEnv?: string }} Environment
36
+ */
37
+
38
+ /**
39
+ * Every configured environment with its defaults applied; one implicit
40
+ * `local` environment (capacity 1) when none is configured.
41
+ *
42
+ * @param {object} [config]
43
+ * @param {Record<string, string|undefined>} [env] Where a cloud token is looked up.
44
+ * @returns {Environment[]}
45
+ */
46
+ export function resolveEnvironments(config, env = process.env) {
47
+ const map = config?.delivery?.environments;
48
+ const entries =
49
+ map && typeof map === 'object' && Object.keys(map).length > 0
50
+ ? Object.entries(map)
51
+ : [['local', { target: 'local' }]];
52
+ return entries.map(([name, entry]) => resolveEntry(name, entry, env));
53
+ }
54
+
55
+ /**
56
+ * @param {string} name
57
+ * @returns {string}
58
+ */
59
+ export function envLabel(name) {
60
+ return `${ENV_LABEL_PREFIX}${name}`;
61
+ }
62
+
63
+ /**
64
+ * The environment a Story's labels name, or `null`.
65
+ *
66
+ * @param {string[]} [labels]
67
+ * @returns {string|null}
68
+ */
69
+ export function environmentOf(labels) {
70
+ const label = (labels ?? []).find((l) => l.startsWith(ENV_LABEL_PREFIX));
71
+ return label ? label.slice(ENV_LABEL_PREFIX.length) : null;
72
+ }
73
+
74
+ /**
75
+ * The Story's `agent::*` state label, or `null`.
76
+ *
77
+ * @param {string[]} [labels]
78
+ * @returns {string|null}
79
+ */
80
+ export function agentStateOf(labels) {
81
+ const states = Object.values(AGENT_LABELS);
82
+ return (labels ?? []).find((l) => states.includes(l)) ?? null;
83
+ }
84
+
85
+ /**
86
+ * Whether a ticket holds an environment slot: open, labelled, and in a
87
+ * dispatched-or-delivering state. A label on a closed Story is history.
88
+ *
89
+ * @param {{ state?: string, labels?: string[] }} ticket
90
+ * @returns {boolean}
91
+ */
92
+ export function holdsEnvironment(ticket) {
93
+ if (String(ticket?.state ?? '').toLowerCase() !== 'open') return false;
94
+ if (environmentOf(ticket.labels) === null) return false;
95
+ return LOAD_STATES.has(agentStateOf(ticket.labels));
96
+ }
97
+
98
+ /**
99
+ * Load per environment name over a ticket list.
100
+ *
101
+ * @param {Environment[]} environments
102
+ * @param {Array<{ state?: string, labels?: string[] }>} tickets
103
+ * @returns {Record<string, number>}
104
+ */
105
+ export function computeLoads(environments, tickets) {
106
+ const loads = Object.fromEntries(environments.map((e) => [e.name, 0]));
107
+ for (const ticket of tickets ?? []) {
108
+ if (!holdsEnvironment(ticket)) continue;
109
+ const name = environmentOf(ticket.labels);
110
+ if (name in loads) loads[name] += 1;
111
+ }
112
+ return loads;
113
+ }
114
+
115
+ /**
116
+ * The argv for one Story: `{id}` and `{sessionId}` replaced in every
117
+ * element; a dry run keeps the session placeholder.
118
+ *
119
+ * @param {string[]} command
120
+ * @param {number} storyId A validated positive integer.
121
+ * @param {string} [sessionId]
122
+ * @returns {string[]}
123
+ */
124
+ export function commandFor(command, storyId, sessionId = SESSION_PLACEHOLDER) {
125
+ return command.map((part) =>
126
+ part
127
+ .replaceAll('{id}', String(storyId))
128
+ .replaceAll(SESSION_PLACEHOLDER, sessionId),
129
+ );
130
+ }
131
+
132
+ /** Whether a command asks for a session id. */
133
+ export function wantsSessionId(command) {
134
+ return command.some((part) => part.includes(SESSION_PLACEHOLDER));
135
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * The `claude-cloud` launch target: fire a Claude Code routine so a Story's
3
+ * delivery runs in an Anthropic-hosted session. The routine token is read
4
+ * from the environment variable the entry names and never leaves the request
5
+ * headers: every error, record and comment is built without it.
6
+ *
7
+ * @module lib/dispatch/launch-cloud
8
+ */
9
+
10
+ const ROUTINES_BASE = 'https://api.anthropic.com/v1/claude_code/routines';
11
+ const REDACTED = '[redacted]';
12
+
13
+ /** A refused or unconfirmed fire; `keepLabel` when the session may exist. */
14
+ export class CloudLaunchError extends Error {
15
+ /**
16
+ * @param {string} reason
17
+ * @param {string} detail
18
+ * @param {{ keepLabel?: boolean, status?: number, retryAfter?: string|null }} [extra]
19
+ */
20
+ constructor(reason, detail, { keepLabel = false, ...extra } = {}) {
21
+ super(detail);
22
+ this.reason = reason;
23
+ this.keepLabel = keepLabel;
24
+ Object.assign(this, extra);
25
+ }
26
+ }
27
+
28
+ /**
29
+ * The fire request for one Story.
30
+ *
31
+ * @param {{ routine: string }} environment
32
+ * @param {number} storyId
33
+ * @param {string} token
34
+ * @returns {{ url: string, method: string, headers: Record<string, string>, body: string }}
35
+ */
36
+ function fireRequest(environment, storyId, token) {
37
+ return {
38
+ url: `${ROUTINES_BASE}/${environment.routine}/fire`,
39
+ method: 'POST',
40
+ headers: {
41
+ Authorization: `Bearer ${token}`,
42
+ 'anthropic-version': '2023-06-01',
43
+ 'anthropic-beta': 'experimental-cc-routine-2026-04-01',
44
+ 'Content-Type': 'application/json',
45
+ },
46
+ body: JSON.stringify({ text: `mandrel-deliver ${storyId}` }),
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The envelope fields a failed fire reports.
52
+ *
53
+ * @param {CloudLaunchError} err
54
+ * @returns {{ reason: string, detail: string, status?: number, retryAfter?: string|null }}
55
+ */
56
+ export function cloudEnvelopeFields(err) {
57
+ const fields = { reason: err.reason, detail: err.message };
58
+ if (err.status !== undefined) fields.status = err.status;
59
+ if (err.reason === 'rate-limited') fields.retryAfter = err.retryAfter;
60
+ return fields;
61
+ }
62
+
63
+ /** The request `--dry-run` prints: the Authorization value redacted. */
64
+ export function describeFireRequest(environment, storyId) {
65
+ const request = fireRequest(environment, storyId, '');
66
+ return {
67
+ ...request,
68
+ headers: { ...request.headers, Authorization: REDACTED },
69
+ };
70
+ }
71
+
72
+ const scrub = (text, token) => String(text ?? '').replaceAll(token, REDACTED);
73
+
74
+ async function send(fetchImpl, request, token) {
75
+ const { url, ...init } = request;
76
+ try {
77
+ return await fetchImpl(url, init);
78
+ } catch (err) {
79
+ throw new CloudLaunchError(
80
+ 'launch-unconfirmed',
81
+ `The fire request got no response (${scrub(err?.message, token)}); ` +
82
+ 'check the routine for a new session before dispatching again.',
83
+ { keepLabel: true },
84
+ );
85
+ }
86
+ }
87
+
88
+ function refused(response) {
89
+ if (response.status === 429) {
90
+ const retryAfter = response.headers?.get?.('retry-after') ?? null;
91
+ return new CloudLaunchError(
92
+ 'rate-limited',
93
+ `The routine refused the fire (429); retry after ${retryAfter ?? 'an unstated delay'}.`,
94
+ { status: 429, retryAfter },
95
+ );
96
+ }
97
+ return new CloudLaunchError(
98
+ 'launch-failed',
99
+ `The routine refused the fire (HTTP ${response.status}).`,
100
+ { status: response.status },
101
+ );
102
+ }
103
+
104
+ async function sessionOf(response) {
105
+ try {
106
+ const json = await response.json();
107
+ if (json?.claude_code_session_url) return json;
108
+ } catch {
109
+ // An unreadable success body is handled below like a missing field.
110
+ }
111
+ throw new CloudLaunchError(
112
+ 'launch-unconfirmed',
113
+ 'The routine accepted the fire but returned no session URL; check its sessions.',
114
+ { keepLabel: true },
115
+ );
116
+ }
117
+
118
+ /**
119
+ * Fire the environment's routine for a Story, once (the endpoint has no
120
+ * idempotency key), and post the session URL on the Story.
121
+ *
122
+ * @param {{ storyId: number, environment: object,
123
+ * provider: { postComment: Function } }} args
124
+ * @param {{ fetchImpl?: typeof fetch, env?: Record<string, string|undefined>,
125
+ * now?: () => Date }} [deps]
126
+ * @returns {Promise<object>} The dispatch record.
127
+ * @throws {CloudLaunchError}
128
+ */
129
+ export async function launchCloud(
130
+ { storyId, environment, provider },
131
+ { fetchImpl = fetch, env = process.env, now = () => new Date() } = {},
132
+ ) {
133
+ const token = env[environment.tokenEnv];
134
+ if (!token) {
135
+ throw new CloudLaunchError(
136
+ 'offline',
137
+ `Environment variable ${environment.tokenEnv} is not set.`,
138
+ );
139
+ }
140
+ const response = await send(
141
+ fetchImpl,
142
+ fireRequest(environment, storyId, token),
143
+ token,
144
+ );
145
+ if (!response.ok) throw refused(response);
146
+ const session = await sessionOf(response);
147
+ // The session already exists: a failed comment must not undo the claim.
148
+ const commentPosted = await provider
149
+ .postComment(storyId, {
150
+ body: `Dispatched to environment \`${environment.name}\` (claude-cloud): ${session.claude_code_session_url}`,
151
+ })
152
+ .then(
153
+ () => true,
154
+ () => false,
155
+ );
156
+ return {
157
+ storyId,
158
+ environment: environment.name,
159
+ startedAt: now().toISOString(),
160
+ sessionId: session.claude_code_session_id ?? null,
161
+ sessionUrl: session.claude_code_session_url,
162
+ commentPosted,
163
+ };
164
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The `local` launch target: start a Story's delivery as a detached process
3
+ * on this machine and stop it again. The argv is spawned as an array, never
4
+ * through a shell.
5
+ *
6
+ * @module lib/dispatch/launch-local
7
+ */
8
+
9
+ import { randomUUID } from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ import { spawnDetached } from '../child-exec.js';
14
+ import { dispatchLogPath } from '../config/temp-paths.js';
15
+ import { commandFor, wantsSessionId } from './environments.js';
16
+
17
+ /** The argv with a fresh session id, plus that id when the command used it. */
18
+ function sessionLaunch(command, storyId, sessionId) {
19
+ const argv = commandFor(command, storyId, sessionId);
20
+ return wantsSessionId(command) ? { argv, sessionId } : { argv };
21
+ }
22
+
23
+ /**
24
+ * @param {{ storyId: number, environment: import('./environments.js').Environment,
25
+ * cwd: string, config?: object }} args
26
+ * @param {{ spawnImpl?: typeof spawnDetached, fsImpl?: typeof fs,
27
+ * now?: () => Date, uuid?: () => string }} [deps]
28
+ * @returns {Promise<import('./record.js').DispatchRecord>}
29
+ */
30
+ export async function launchLocal(
31
+ { storyId, environment, cwd, config },
32
+ {
33
+ spawnImpl = spawnDetached,
34
+ fsImpl = fs,
35
+ now = () => new Date(),
36
+ uuid = randomUUID,
37
+ } = {},
38
+ ) {
39
+ const session = sessionLaunch(environment.command, storyId, uuid());
40
+ const logPath = dispatchLogPath(storyId, config);
41
+ fsImpl.mkdirSync(path.dirname(logPath), { recursive: true });
42
+ const [file, ...args] = session.argv;
43
+ const { pid } = await spawnImpl(file, args, { logPath, cwd });
44
+ return {
45
+ storyId,
46
+ environment: environment.name,
47
+ pid,
48
+ startedAt: now().toISOString(),
49
+ logPath,
50
+ ...session,
51
+ };
52
+ }
53
+
54
+ /**
55
+ * Terminate a launched delivery: its process group where groups exist
56
+ * (detached children lead their own), else the pid. A process that is
57
+ * already gone counts as stopped.
58
+ *
59
+ * @param {number} pid
60
+ * @param {{ kill?: typeof process.kill, platform?: string }} [deps]
61
+ * @returns {boolean} Whether a live process was signalled.
62
+ */
63
+ export function stopLocal(
64
+ pid,
65
+ { kill = process.kill.bind(process), platform = process.platform } = {},
66
+ ) {
67
+ const targets = platform === 'win32' ? [pid] : [-pid, pid];
68
+ for (const target of targets) {
69
+ try {
70
+ kill(target, 'SIGTERM');
71
+ return true;
72
+ } catch (err) {
73
+ if (err?.code !== 'ESRCH') throw err;
74
+ }
75
+ }
76
+ return false;
77
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Whether a recorded delivery process still runs, probed with signal 0,
3
+ * which delivers nothing. A cloud or unrecorded Story is `unknown`.
4
+ */
5
+ export function processState(
6
+ record,
7
+ { kill = process.kill.bind(process) } = {},
8
+ ) {
9
+ const startedAt = record?.startedAt ?? null;
10
+ if (!record || record.sessionUrl || !Number.isInteger(record.pid)) {
11
+ return { state: 'unknown', startedAt };
12
+ }
13
+ try {
14
+ kill(record.pid, 0);
15
+ return { state: 'working', startedAt };
16
+ } catch (err) {
17
+ if (err?.code === 'EPERM') return { state: 'working', startedAt };
18
+ if (err?.code === 'ESRCH') return { state: 'exited', startedAt };
19
+ return { state: 'unknown', startedAt };
20
+ }
21
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The dispatch record: what `--stop` needs to find a launched delivery
3
+ * (`pid`) and what an operator needs to follow it (`logPath`). Written beside
4
+ * the log under the project temp root.
5
+ *
6
+ * @module lib/dispatch/record
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+
11
+ import { dispatchRecordPath } from '../config/temp-paths.js';
12
+
13
+ /**
14
+ * New fields are optional to readers; a cloud record has `sessionUrl`, no pid.
15
+ * @typedef {{ storyId: number, environment: string, pid?: number,
16
+ * startedAt: string, logPath?: string, argv?: string[],
17
+ * sessionId?: string, sessionUrl?: string }} DispatchRecord
18
+ */
19
+
20
+ /**
21
+ * @param {DispatchRecord} record
22
+ * @param {{ config?: object, fsImpl?: typeof fs }} [opts]
23
+ * @returns {string} The record path.
24
+ */
25
+ export function writeRecord(record, { config, fsImpl = fs } = {}) {
26
+ const file = dispatchRecordPath(record.storyId, config);
27
+ fsImpl.writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`);
28
+ return file;
29
+ }
30
+
31
+ /**
32
+ * The Story's record, or `null` when none was written or it is unreadable.
33
+ *
34
+ * @param {number} storyId
35
+ * @param {{ config?: object, fsImpl?: typeof fs }} [opts]
36
+ * @returns {DispatchRecord|null}
37
+ */
38
+ export function readRecord(storyId, { config, fsImpl = fs } = {}) {
39
+ try {
40
+ return JSON.parse(
41
+ fsImpl.readFileSync(dispatchRecordPath(storyId, config), 'utf8'),
42
+ );
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * @param {number} storyId
50
+ * @param {{ config?: object, fsImpl?: typeof fs }} [opts]
51
+ */
52
+ export function removeRecord(storyId, { config, fsImpl = fs } = {}) {
53
+ fsImpl.rmSync(dispatchRecordPath(storyId, config), { force: true });
54
+ }