@detergent-software/conductor 1.0.0-dev.3 → 1.0.0-dev.31

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 (114) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/README.md +391 -10
  3. package/build/brief-cli.js +68 -0
  4. package/build/brief-cli.js.map +1 -0
  5. package/build/brief.js +211 -0
  6. package/build/brief.js.map +1 -0
  7. package/build/broker-cli.js +126 -0
  8. package/build/broker-cli.js.map +1 -0
  9. package/build/broker.js +154 -0
  10. package/build/broker.js.map +1 -0
  11. package/build/cli.js +621 -99
  12. package/build/cli.js.map +1 -1
  13. package/build/clock.js +17 -0
  14. package/build/clock.js.map +1 -0
  15. package/build/conditions.js +20 -14
  16. package/build/conditions.js.map +1 -1
  17. package/build/config.js +95 -1
  18. package/build/config.js.map +1 -1
  19. package/build/console.js +176 -0
  20. package/build/console.js.map +1 -0
  21. package/build/credential.js +52 -0
  22. package/build/credential.js.map +1 -0
  23. package/build/daemon.js +168 -3
  24. package/build/daemon.js.map +1 -1
  25. package/build/events.js +107 -0
  26. package/build/events.js.map +1 -0
  27. package/build/help.js +447 -0
  28. package/build/help.js.map +1 -0
  29. package/build/history.js +634 -0
  30. package/build/history.js.map +1 -0
  31. package/build/inbox.js +408 -0
  32. package/build/inbox.js.map +1 -0
  33. package/build/manager.js +132 -34
  34. package/build/manager.js.map +1 -1
  35. package/build/mod.js +51 -0
  36. package/build/mod.js.map +1 -0
  37. package/build/note.js +71 -0
  38. package/build/note.js.map +1 -0
  39. package/build/notes.js +172 -0
  40. package/build/notes.js.map +1 -0
  41. package/build/notify.js +422 -0
  42. package/build/notify.js.map +1 -0
  43. package/build/overrides.js +83 -0
  44. package/build/overrides.js.map +1 -0
  45. package/build/paths.js +10 -1
  46. package/build/paths.js.map +1 -1
  47. package/build/profile.js +68 -2
  48. package/build/profile.js.map +1 -1
  49. package/build/pushover.js +67 -0
  50. package/build/pushover.js.map +1 -0
  51. package/build/queue.js +183 -0
  52. package/build/queue.js.map +1 -0
  53. package/build/registry.js +17 -10
  54. package/build/registry.js.map +1 -1
  55. package/build/rule-actions.js +444 -0
  56. package/build/rule-actions.js.map +1 -0
  57. package/build/rule-input.js +17 -0
  58. package/build/rule-input.js.map +1 -0
  59. package/build/rules-service.js +402 -0
  60. package/build/rules-service.js.map +1 -0
  61. package/build/rules.js +850 -0
  62. package/build/rules.js.map +1 -0
  63. package/build/scheduler.js +293 -0
  64. package/build/scheduler.js.map +1 -0
  65. package/build/serve.js +51 -0
  66. package/build/serve.js.map +1 -0
  67. package/build/server.js +329 -0
  68. package/build/server.js.map +1 -1
  69. package/build/spend.js +50 -0
  70. package/build/spend.js.map +1 -1
  71. package/build/store.js +452 -4
  72. package/build/store.js.map +1 -1
  73. package/build/trackers.js +15 -0
  74. package/build/trackers.js.map +1 -0
  75. package/build/upgrade.js +18 -14
  76. package/build/upgrade.js.map +1 -1
  77. package/build/wait.js +35 -41
  78. package/build/wait.js.map +1 -1
  79. package/build/watchers/ado-api.js +55 -0
  80. package/build/watchers/ado-api.js.map +1 -0
  81. package/build/watchers/ado.js +37 -49
  82. package/build/watchers/ado.js.map +1 -1
  83. package/build/watchers/boards-brief.js +63 -0
  84. package/build/watchers/boards-brief.js.map +1 -0
  85. package/build/watchers/boards-queue.js +120 -0
  86. package/build/watchers/boards-queue.js.map +1 -0
  87. package/build/watchers/boards-writes.js +83 -0
  88. package/build/watchers/boards-writes.js.map +1 -0
  89. package/build/watchers/boards.js +271 -0
  90. package/build/watchers/boards.js.map +1 -0
  91. package/build/watchers/github.js +5 -2
  92. package/build/watchers/github.js.map +1 -1
  93. package/build/watchers/index.js +1 -0
  94. package/build/watchers/index.js.map +1 -1
  95. package/build/watchers/linear-api.js +55 -0
  96. package/build/watchers/linear-api.js.map +1 -0
  97. package/build/watchers/linear-key.js +6 -45
  98. package/build/watchers/linear-key.js.map +1 -1
  99. package/build/watchers/linear-labels.js +43 -0
  100. package/build/watchers/linear-labels.js.map +1 -0
  101. package/build/watchers/linear-queue.js +96 -0
  102. package/build/watchers/linear-queue.js.map +1 -0
  103. package/build/watchers/linear.js +29 -18
  104. package/build/watchers/linear.js.map +1 -1
  105. package/build/why.js +78 -0
  106. package/build/why.js.map +1 -0
  107. package/mod/.claude-plugin/marketplace.json +6 -0
  108. package/mod/.claude-plugin/plugin.json +7 -0
  109. package/mod/README.md +17 -0
  110. package/mod/hooks/hooks.json +1 -0
  111. package/mod/hooks/model.ts +457 -0
  112. package/mod/hooks/register.tsx +542 -0
  113. package/mod/types/index.d.ts +57 -0
  114. package/package.json +4 -1
package/build/cli.js CHANGED
@@ -5,49 +5,37 @@ import { resolve, sep } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { parseArgs } from 'node:util';
7
7
  import { z } from 'zod';
8
+ import { briefCommand } from "./brief-cli.js";
9
+ import { heldLocks, lockCommand, lockLine, portsCommand } from "./broker-cli.js";
8
10
  import { callApi, NotRunningError, ping, readEndpoint } from "./client.js";
9
- import { startDaemon } from "./daemon.js";
11
+ import { loadConfig } from "./config.js";
12
+ import { CONSOLE_ARGS, CONSOLE_WINDOW, consoleProject, consoleTabArgs, escalationLines, escalationSchema, handledSchema } from "./console.js";
13
+ import { logCrashes, startDaemon } from "./daemon.js";
10
14
  import { ConductorError } from "./errors.js";
15
+ import { eventsCommand } from "./events.js";
16
+ import { commandHelp, isCommand, listing, unknownCommand, usageError } from "./help.js";
17
+ import { flagWindow, historyLines, historyReport, historySchema, parseRange, retroMarkdown } from "./history.js";
18
+ import { inboxLines } from "./inbox.js";
19
+ import { parseJsonc } from "./jsonc.js";
11
20
  import { processAlive, readPid } from "./lock.js";
12
- import { fleetWorkerSchema } from "./manager.js";
21
+ import { fleetWorkerSchema, storedFleet } from "./manager.js";
22
+ import { installMod, removeMod } from "./mod.js";
23
+ import { noteCommand } from "./note.js";
24
+ import { notifyLines, notifyStatusSchema, parseUntil, testResultSchema } from "./notify.js";
25
+ import { overrideViewSchema, PAUSE } from "./overrides.js";
13
26
  import { conductorPaths } from "./paths.js";
14
27
  import { registerProject } from "./registry.js";
28
+ import { rulesLines, rulesService, rulesTestResultSchema, rulesViewSchema, testLines } from "./rules-service.js";
29
+ import { resolveUntil } from "./rules.js";
15
30
  import { outputOf, run } from "./run.js";
31
+ import { queueLines, queueViewSchema } from "./scheduler.js";
32
+ import { awaitStart, serveDetached, ServeStartError } from "./serve.js";
33
+ import { formatTokens, localDay } from "./spend.js";
16
34
  import { installStartup, removeStartup, runStartup, startupRunsCli, TASK_NAME } from "./startup.js";
17
- import { openStore, projectSchema, workerSchema } from "./store.js";
18
- import { parseTag, upgrade } from "./upgrade.js";
35
+ import { inboxItemSchema, openStore, projectSchema, waitSchema, workerSchema } from "./store.js";
36
+ import { parseTag, restartDaemon, upgrade } from "./upgrade.js";
19
37
  import { waitCommand } from "./wait.js";
20
- const USAGE = `Usage: conduct <command>
21
-
22
- serve run the daemon in this process (one per machine)
23
- stop stop the running daemon
24
- status [--json] the daemon's pid, port, projects and workers
25
- project add <path> register the project whose checkout holds .claude/conductor.json
26
- project list [--json] the registered projects
27
- launch <item> start a worker: its worktree, a background session, a tab
28
- [--project <name>] [--probe] [--prompt <text>] [--conductor <name>]
29
- retire <worker> [--force] stop a worker, remove its worktree and session; refuses unfinished work
30
- attach <worker> wake a parked worker (no event text) and open it in a tab
31
- wait <condition> wait for an outside event: in a worker's worktree with the daemon
32
- running, register it and end the turn (the daemon resumes the session);
33
- otherwise check it here and block (exit 0 when it holds, 2 at --timeout)
34
- pr <n> merged|checks|comment [--repo <owner>/<repo>]
35
- run <pipeline> <run id> [done]
36
- npm <version> [--tag <dist-tag>] [--package <name>]
37
- health <env> --version <x> | --commit <sha>
38
- approval [<item>] an approve / revise: comment after the item's newest Plan note
39
- item <item> <state> | item <item> label|note <value>
40
- time <when> such as 2026-10-10T09:00 (local)
41
- <full form> such as pr:ado:Emergent.AgenticToolkit#1850:merged
42
- [--local] [--timeout <minutes, local only; 29>] [--worker <worker>] [--item <item>]
43
- install-startup start the daemon at logon (Windows Task Scheduler)
44
- install-startup --remove remove that logon task
45
- upgrade [--tag dev|latest] stop the daemon, npm install the newest version on the tag (default:
46
- the tag the installed version came from), start the daemon again
47
- [--allow-downgrade] install the tag's version even when it is older than the installed one
48
-
49
- A <worker> is its item (ATK-309) or its name (probe-ATK-309).
50
- Files live in ~/.conductor (CONDUCTOR_HOME overrides it).`;
38
+ import { whyLines, whySchema } from "./why.js";
51
39
  const STOP_WAIT_MS = 10_000;
52
40
  // A restarted daemon opens its store and binds the port; under the logon task node starts cold.
53
41
  const START_WAIT_MS = 30_000;
@@ -59,6 +47,8 @@ const LAUNCH_WAIT_MS = 15 * 60_000;
59
47
  // attach waits out the settle time (up to 5 min), resumes (120 s) and opens the tab (60 s).
60
48
  const RETIRE_TIMEOUT_MS = 12 * 60_000;
61
49
  const ATTACH_TIMEOUT_MS = 9 * 60_000;
50
+ // Approve and revise ask Linear twice (the issue, then the comment), each within 20 s.
51
+ const ANSWER_TIMEOUT_MS = 60_000;
62
52
  const projectsBody = z.object({ projects: z.array(projectSchema) });
63
53
  const addBody = z.object({ created: z.boolean(), project: projectSchema });
64
54
  const errorBody = z.object({ details: z.array(z.string()).optional(), error: z.string() });
@@ -78,6 +68,13 @@ const retireBody = z.object({
78
68
  worker: workerSchema,
79
69
  });
80
70
  const attachBody = z.object({ resumed: z.boolean(), tab: z.string().nullable(), worker: workerSchema });
71
+ const inboxBody = z.object({ items: z.array(inboxItemSchema) });
72
+ const answerBody = z.object({
73
+ comment: z.object({ id: z.string(), url: z.string().nullable() }).nullable(),
74
+ item: inboxItemSchema,
75
+ waits: z.array(waitSchema),
76
+ });
77
+ const answerRefusal = z.object({ details: z.array(z.string()).optional(), error: z.string(), posted: z.enum(['no', 'unknown']).optional() });
81
78
  async function addProject(paths, path) {
82
79
  const absolute = resolve(path);
83
80
  let result;
@@ -88,10 +85,38 @@ async function addProject(paths, path) {
88
85
  if (!(error instanceof NotRunningError))
89
86
  throw error;
90
87
  // No daemon: write the store directly. The daemon reads it when it starts.
91
- result = withStore(paths, (store) => registerProject(store, absolute));
88
+ // Its rules are checked against config.json here too, as the daemon would.
89
+ const check = rulesService({ config: loadConfig(paths.config), listProjects: () => [], paths }).checkProfile;
90
+ result = withStore(paths, (store) => registerProject(store, absolute, check));
92
91
  }
93
92
  out(`${result.created ? 'registered' : 'updated'} ${projectLine(result.project).trim()}`);
94
93
  }
94
+ // `conduct approve|revise|done`: Jason's answer to an inbox item, by id, or for approve and revise
95
+ // by the item whose plan waits.
96
+ async function answer(paths, ref, request) {
97
+ const target = request.action === 'done' ? inboxId(ref) : await planItem(paths, ref);
98
+ const { body, status } = await callApi(paths, { body: request, method: 'POST', path: `/inbox/${target}/resolve`, timeoutMs: ANSWER_TIMEOUT_MS });
99
+ if (status !== 200) {
100
+ const refusal = answerRefusal.safeParse(body).data;
101
+ const details = [...(refusal?.details ?? [])];
102
+ if (status === 502 && refusal?.posted === 'unknown')
103
+ details.push('the comment may be on the item already: look before answering again');
104
+ if (status === 404) {
105
+ if ((await openItems(paths)) === null)
106
+ throw noInbox();
107
+ throw new ConductorError(`no inbox item #${target}`, ['`conduct inbox` lists the open ones']);
108
+ }
109
+ throw new ConductorError(refusal?.error ?? `the API answered ${status}`, details);
110
+ }
111
+ const result = answerBody.parse(body);
112
+ const { item } = result;
113
+ if (request.action === 'done')
114
+ return out(`done: #${item.id} (${item.kind}${item.item ? ` ${item.item}` : ''})`);
115
+ out(`${request.action === 'approve' ? 'approved' : 'asked for a revision of'} ${item.item ?? `#${item.id}`}: ${result.comment?.url ?? result.comment?.id ?? 'comment posted'}`);
116
+ out(result.waits.length > 0
117
+ ? `its worker's approval wait resolved; the conductor resumes it`
118
+ : 'no worker waits on its approval here: the worker reads the comment when it next looks');
119
+ }
95
120
  async function attach(paths, ref) {
96
121
  const worker = await findWorker(paths, ref);
97
122
  const result = attachBody.parse(await expectOk(callApi(paths, { method: 'POST', path: `/workers/${worker.id}/attach`, timeoutMs: ATTACH_TIMEOUT_MS })));
@@ -99,16 +124,94 @@ async function attach(paths, ref) {
99
124
  if (result.tab)
100
125
  out(`no tab (${result.tab}); open it yourself: claude attach ${result.worker.handle ?? worker.name}`);
101
126
  }
102
- // The pid of the daemon once it answers /health, for upgrade's restart.
103
- async function awaitDaemon(paths) {
104
- const deadline = Date.now() + START_WAIT_MS;
105
- while (Date.now() < deadline) {
106
- const pid = readPid(paths.pid);
107
- if (pid !== null && (await ping(paths, pid)))
108
- return pid;
109
- await sleep(250);
127
+ // The pid of the daemon once it answers /health, for upgrade's restart. failure: the detached
128
+ // serve's spawn error, which ends the wait early.
129
+ async function awaitDaemon(paths, failure) {
130
+ return awaitStart({
131
+ answer: async () => {
132
+ const pid = readPid(paths.pid);
133
+ return pid !== null && (await ping(paths, pid)) ? pid : null;
134
+ },
135
+ failure,
136
+ log: paths.log,
137
+ timeoutMs: START_WAIT_MS,
138
+ });
139
+ }
140
+ // What `conduct ports` and `conduct lock` print to and run in.
141
+ function brokerIo() {
142
+ return { cwd: process.cwd(), err: (line) => process.stderr.write(`${line}\n`), out };
143
+ }
144
+ // `conduct console`: the console (design note, section 11), the Claude session the conductor mod
145
+ // serves, started with CONDUCTOR_CONSOLE=1 in the project's main checkout, where the console skill
146
+ // is installed. It keeps no state of its own, so a new one after a close loses nothing.
147
+ async function consoleCommand(paths, options) {
148
+ const project = consoleProject(await projectsNow(paths), options.project);
149
+ if (options.here) {
150
+ const child = spawn('claude', CONSOLE_ARGS, { cwd: project.root, env: { ...process.env, CONDUCTOR_CONSOLE: '1' }, stdio: 'inherit' });
151
+ // Ctrl+C belongs to the session; this process only waits for it to end.
152
+ process.on('SIGINT', () => { });
153
+ process.exitCode = await new Promise((done, fail) => {
154
+ child.on('error', (error) => fail(new ConductorError('could not start claude', [error.message])));
155
+ child.on('exit', (code) => done(code ?? 1));
156
+ });
157
+ return;
158
+ }
159
+ if (process.platform !== 'win32') {
160
+ throw new ConductorError('conduct console opens a Windows Terminal tab', ['run `conduct console --here` in a terminal of your own']);
161
+ }
162
+ // A tab starts with Windows Terminal's environment, not this one's.
163
+ if (process.env.CONDUCTOR_HOME) {
164
+ throw new ConductorError('a console tab would not see CONDUCTOR_HOME', ['run `conduct console --here` in a terminal where it is set']);
110
165
  }
111
- throw new ConductorError(`the conductor did not answer within ${START_WAIT_MS / 1000} s`, [`see ${paths.log}`]);
166
+ const args = consoleTabArgs(project, process.execPath, realpathSync(fileURLToPath(import.meta.url)));
167
+ const result = await run('wt.exe', args, { cwd: project.root, timeoutMs: 60_000 });
168
+ if (result.code !== 0)
169
+ throw new ConductorError('could not open the console tab', [outputOf(result, 500), 'run `conduct console --here` in a terminal instead']);
170
+ out(`opened the console in ${project.root} (Windows Terminal window "${CONSOLE_WINDOW}")`);
171
+ }
172
+ // How `conduct start` and upgrade's restart start the daemon detached from this process.
173
+ function daemonStarter(paths, cliPath) {
174
+ let failure = () => undefined;
175
+ return {
176
+ awaitDaemon: () => awaitDaemon(paths, failure),
177
+ runTask: runStartup,
178
+ serveDetached: () => {
179
+ failure = serveDetached(paths.home, process.execPath, [cliPath, 'serve']);
180
+ },
181
+ // The logon task's daemon uses ~/.conductor, so it can't start one kept in CONDUCTOR_HOME.
182
+ taskRunsCli: () => !process.env.CONDUCTOR_HOME && startupRunsCli(cliPath),
183
+ };
184
+ }
185
+ // `conduct escalations done`: the console reports back on an escalation.
186
+ async function escalationDone(paths, ref, finding) {
187
+ const id = /^#?(\d+)$/.exec(ref)?.[1];
188
+ if (id === undefined)
189
+ throw new ConductorError(`"${ref}" is not an escalation id`, ['`conduct escalations` lists them as #<id>']);
190
+ const answer = await callApi(paths, { body: finding, method: 'POST', path: `/console/escalations/${id}` });
191
+ if (answer.status === 404 && !errorBody.safeParse(answer.body).data?.details)
192
+ throw olderDaemon('no console escalations');
193
+ const { escalation, event, inbox: raised } = handledSchema.parse(await expectOk(Promise.resolve(answer)));
194
+ out(`handled escalation #${escalation.id}${escalation.item ? ` on ${escalation.item}` : ''} (event #${event})`);
195
+ if (raised)
196
+ out(`and raised inbox item #${raised.id} (console) for you`);
197
+ }
198
+ async function escalations(paths, json) {
199
+ const answer = await callApi(paths, { method: 'GET', path: '/console/escalations' });
200
+ if (answer.status === 404)
201
+ throw olderDaemon('no console escalations');
202
+ const { escalations: open } = z.object({ escalations: z.array(escalationSchema) }).parse(await expectOk(Promise.resolve(answer)));
203
+ if (json)
204
+ return out(JSON.stringify(open, null, 2));
205
+ escalationLines(open, new Date()).forEach((line) => out(line));
206
+ }
207
+ // `conduct events`: until Ctrl+C with --follow.
208
+ async function events(paths, follow, since, isConsole) {
209
+ if (since !== undefined && !/^\d+$/.test(since))
210
+ throw new ConductorError('--since takes an event id, such as --since 120');
211
+ const stop = new AbortController();
212
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGBREAK'])
213
+ process.once(signal, () => stop.abort());
214
+ await eventsCommand(paths, { console: isConsole, follow, since: since === undefined ? undefined : Number(since) }, { out, signal: stop.signal });
112
215
  }
113
216
  async function expectOk(call) {
114
217
  const { body, status } = await call;
@@ -128,13 +231,71 @@ async function findWorker(paths, ref) {
128
231
  throw new ConductorError(`no worker "${ref}" in flight`, ['`conduct status` lists them']);
129
232
  throw new ConductorError(`"${ref}" names several workers`, matches.map((w) => `${w.name} in ${w.project}`));
130
233
  }
131
- // 1234 → 1.2k, 3_400_000 → 3.4M.
132
- function formatTokens(tokens) {
133
- if (tokens >= 1_000_000)
134
- return `${(tokens / 1_000_000).toFixed(1)}M`;
135
- if (tokens >= 1_000)
136
- return `${(tokens / 1_000).toFixed(1)}k`;
137
- return String(tokens);
234
+ // `conduct help <name>`; `conduct help help` is the listing.
235
+ function helpOf(name) {
236
+ if (name === 'help')
237
+ return listing();
238
+ if (!isCommand(name))
239
+ throw unknownCommand(name);
240
+ return commandHelp(name);
241
+ }
242
+ // `conduct history` and `retro`: from the daemon, or straight from conductor.db when none runs or
243
+ // it is older than /history. Reading needs no daemon: the report is a query over the store.
244
+ async function history(paths, command, range, options) {
245
+ const flags = options.since !== undefined || options.until !== undefined;
246
+ if (flags && range !== undefined)
247
+ throw new ConductorError(`conduct ${command} takes a <range> or --since/--until, not both`);
248
+ const now = new Date();
249
+ const window = flags ? flagWindow(options.since, options.until, now) : parseRange(range, now);
250
+ const request = { project: options.project ?? null, since: window.since.toISOString(), until: window.until.toISOString() };
251
+ // Read-only: a daemon older than this build may be running, and a migration would strand it.
252
+ const local = () => {
253
+ try {
254
+ return withStore(paths, (store) => historyReport(store, request), { readOnly: true });
255
+ }
256
+ catch (error) {
257
+ if (error instanceof ConductorError)
258
+ throw error;
259
+ throw new ConductorError(`could not read ${paths.db}`, [
260
+ error instanceof Error ? error.message : String(error),
261
+ 'a schema older than this conduct, or a log left by a crash: start the conductor once (conduct serve, or conduct upgrade), then try again',
262
+ ]);
263
+ }
264
+ };
265
+ let report;
266
+ try {
267
+ const query = new URLSearchParams({ since: request.since, until: request.until, ...(options.project ? { project: options.project } : {}) });
268
+ const answer = await callApi(paths, { method: 'GET', path: `/history?${query.toString()}`, timeoutMs: 60_000 });
269
+ report = answer.status === 404 ? local() : historySchema.parse(await expectOk(Promise.resolve(answer)));
270
+ }
271
+ catch (error) {
272
+ if (!(error instanceof NotRunningError))
273
+ throw error;
274
+ report = local();
275
+ }
276
+ if (options.json)
277
+ return out(JSON.stringify(report, null, 2));
278
+ if (command === 'retro')
279
+ process.stdout.write(retroMarkdown(report));
280
+ else
281
+ historyLines(report).forEach((line) => out(line));
282
+ }
283
+ async function inbox(paths, json) {
284
+ const items = await openItems(paths);
285
+ if (items === null)
286
+ throw noInbox();
287
+ if (json)
288
+ return out(JSON.stringify(items, null, 2));
289
+ if (items.length === 0)
290
+ return out('the inbox is empty');
291
+ inboxLines(items, new Date()).forEach((line) => out(line));
292
+ }
293
+ // An inbox id as `conduct inbox` prints it (#12), or bare (12).
294
+ function inboxId(ref) {
295
+ const id = /^#?(\d+)$/.exec(ref)?.[1];
296
+ if (id === undefined)
297
+ throw new ConductorError(`"${ref}" is not an inbox item id`, ['`conduct inbox` lists them as #<id>']);
298
+ return Number(id);
138
299
  }
139
300
  function install() {
140
301
  const cliPath = realpathSync(fileURLToPath(import.meta.url));
@@ -144,6 +305,9 @@ function install() {
144
305
  out('warning: that build is in a worktree, which goes away; run install-startup from the main checkout');
145
306
  }
146
307
  }
308
+ function isHelpFlag(word) {
309
+ return word === '--help' || word === '-h';
310
+ }
147
311
  async function launch(paths, item, options) {
148
312
  const { worker } = workerBody.parse(await expectOk(callApi(paths, { body: { item, ...options }, method: 'POST', path: '/workers' })));
149
313
  out(`launching ${worker.name} in ${worker.project} (worker ${worker.id}): worktree, then session`);
@@ -168,15 +332,7 @@ async function launch(paths, item, options) {
168
332
  ]);
169
333
  }
170
334
  async function listProjects(paths, json) {
171
- let projects;
172
- try {
173
- projects = projectsBody.parse(await expectOk(callApi(paths, { method: 'GET', path: '/projects' }))).projects;
174
- }
175
- catch (error) {
176
- if (!(error instanceof NotRunningError))
177
- throw error;
178
- projects = withStore(paths, (store) => store.listProjects());
179
- }
335
+ const projects = await projectsNow(paths);
180
336
  if (json)
181
337
  return out(JSON.stringify(projects, null, 2));
182
338
  if (projects.length === 0)
@@ -186,81 +342,353 @@ async function listProjects(paths, json) {
186
342
  async function main(argv) {
187
343
  // `wait` has options of its own: its --version is a value, not this CLI's version.
188
344
  if (argv[0] === 'wait')
189
- return wait(argv.slice(1));
190
- const { positionals, values } = parseArgs({
345
+ return argv.slice(1).some(isHelpFlag) ? out(commandHelp('wait')) : wait(argv.slice(1));
346
+ // `revise` takes free text, which option parsing would cut at a word such as --force. Every word
347
+ // after the item is the text, quoted or not: a cut-off instruction would be posted as Jason's.
348
+ if (argv[0] === 'revise') {
349
+ // A lone help flag as the text is a call for help: posted, it would be a revision of "--help".
350
+ if (isHelpFlag(argv[1]) || (argv.length === 3 && isHelpFlag(argv[2])))
351
+ return out(commandHelp('revise'));
352
+ const [ref, ...words] = argv.slice(1);
353
+ const text = words.join(' ').trim();
354
+ if (ref === undefined || ref.startsWith('-') || !text)
355
+ throw usageError('revise');
356
+ return answer(conductorPaths(), ref, { action: 'revise', text });
357
+ }
358
+ // The same for a finding: free text after the id, with --ask as a word of its own anywhere.
359
+ if (argv[0] === 'escalations' && argv[1] === 'done') {
360
+ if (isHelpFlag(argv[2]) || (argv.length === 4 && isHelpFlag(argv[3])))
361
+ return out(commandHelp('escalations'));
362
+ const [ref, ...rest] = argv.slice(2);
363
+ const ask = rest.includes('--ask');
364
+ const text = rest.filter((word) => word !== '--ask').join(' ').trim();
365
+ if (ref === undefined || !text)
366
+ throw usageError('escalations');
367
+ return escalationDone(conductorPaths(), ref, { ask, text });
368
+ }
369
+ // The first word that names a command: an option's value (--project atk) comes before it at times.
370
+ const { positionals, values } = parsing(argv.find((word) => isCommand(word)), () => parseArgs({
191
371
  allowPositionals: true,
192
372
  args: argv,
193
373
  options: {
194
374
  'allow-downgrade': { type: 'boolean' },
375
+ channel: { type: 'string' },
195
376
  conductor: { type: 'string' },
377
+ console: { type: 'boolean' },
378
+ follow: { type: 'boolean' },
196
379
  force: { type: 'boolean' },
380
+ fresh: { type: 'boolean' },
197
381
  help: { short: 'h', type: 'boolean' },
382
+ here: { type: 'boolean' },
198
383
  json: { type: 'boolean' },
384
+ kind: { type: 'string' },
385
+ owner: { type: 'string' },
386
+ prefer: { type: 'string' },
199
387
  probe: { type: 'boolean' },
200
388
  project: { type: 'string' },
201
389
  prompt: { type: 'string' },
390
+ raise: { type: 'boolean' },
202
391
  remove: { type: 'boolean' },
392
+ since: { type: 'string' },
393
+ slots: { type: 'string' },
203
394
  tag: { type: 'string' },
395
+ text: { type: 'string' },
396
+ until: { type: 'string' },
204
397
  version: { short: 'v', type: 'boolean' },
398
+ wait: { type: 'string' },
399
+ weight: { type: 'string' },
400
+ worker: { type: 'string' },
205
401
  },
206
- });
402
+ }));
207
403
  const paths = conductorPaths();
208
404
  const [command, sub, arg] = positionals;
209
405
  if (values.version)
210
406
  return out(version());
211
- if (values.help || command === undefined || command === 'help')
212
- return out(USAGE);
407
+ if (command === undefined || command === 'help')
408
+ return out(sub === undefined ? listing() : helpOf(sub));
409
+ if (!isCommand(command))
410
+ throw unknownCommand(command);
411
+ if (values.help)
412
+ return out(commandHelp(command));
213
413
  switch (command) {
414
+ case 'approve':
415
+ if (sub === undefined)
416
+ throw usageError('approve');
417
+ return answer(paths, sub, { action: 'approve', ...(values.text?.trim() ? { text: values.text.trim() } : {}) });
214
418
  case 'attach':
215
419
  if (sub === undefined)
216
- throw new ConductorError('usage: conduct attach <worker>');
420
+ throw usageError('attach');
217
421
  return attach(paths, sub);
422
+ case 'brief':
423
+ if (sub === undefined)
424
+ throw usageError('brief');
425
+ process.exitCode = await briefCommand(paths, sub, { fresh: values.fresh === true, json: values.json === true }, {
426
+ err: (line) => process.stderr.write(`${line}\n`),
427
+ out,
428
+ });
429
+ return;
430
+ case 'console':
431
+ return consoleCommand(paths, { here: values.here === true, project: values.project });
432
+ case 'done':
433
+ if (sub === undefined)
434
+ throw usageError('done');
435
+ return answer(paths, sub, { action: 'done' });
436
+ case 'escalations':
437
+ if (sub !== undefined)
438
+ throw usageError('escalations');
439
+ return escalations(paths, values.json === true);
440
+ case 'events':
441
+ // CONDUCTOR_CONSOLE as well: a console still running a mod from before --console (until
442
+ // /reload-plugins after an upgrade) starts this package's new build, in the console's env.
443
+ return events(paths, values.follow === true, values.since, values.console === true || process.env.CONDUCTOR_CONSOLE === '1');
444
+ case 'history':
445
+ case 'retro':
446
+ return history(paths, command, sub, { json: values.json === true, project: values.project, since: values.since, until: values.until });
447
+ case 'inbox':
448
+ return inbox(paths, values.json === true);
449
+ case 'install-mod':
450
+ return values.remove ? removeMod(modDeps()) : installMod(fileURLToPath(new URL('../mod', import.meta.url)), modDeps());
218
451
  case 'install-startup':
219
452
  return values.remove ? uninstall() : install();
220
453
  case 'launch':
221
454
  if (sub === undefined)
222
- throw new ConductorError('usage: conduct launch <item> [--project <name>] [--probe]');
455
+ throw usageError('launch');
223
456
  return launch(paths, sub, {
224
457
  conductor: values.conductor,
225
458
  probe: values.probe,
226
459
  project: values.project,
227
460
  prompt: values.prompt,
228
461
  });
462
+ case 'lock': {
463
+ if (sub === undefined || arg === undefined)
464
+ throw usageError('lock');
465
+ const waitMinutes = values.wait === undefined ? undefined : Number(values.wait);
466
+ if (waitMinutes !== undefined && !(waitMinutes >= 0))
467
+ throw new ConductorError('--wait takes minutes, such as --wait 30');
468
+ process.exitCode = await lockCommand(paths, sub, arg, { owner: values.owner, waitMinutes }, brokerIo());
469
+ return;
470
+ }
471
+ case 'note':
472
+ if (sub === undefined || arg === undefined)
473
+ throw usageError('note');
474
+ process.exitCode = await noteCommand(paths, sub, arg, { worker: values.worker }, {
475
+ cwd: process.cwd(),
476
+ err: (line) => process.stderr.write(`${line}\n`),
477
+ out,
478
+ });
479
+ return;
480
+ case 'notify':
481
+ if (sub === undefined)
482
+ return notifyStatus(paths, values.json === true);
483
+ if (sub === 'profile')
484
+ return notifyProfile(paths, arg, values.until);
485
+ if (sub === 'test')
486
+ return notifyTest(paths, { channel: values.channel, kind: values.kind, raise: values.raise === true });
487
+ throw usageError('notify');
229
488
  case 'project':
230
489
  if (sub === 'add' && arg !== undefined)
231
490
  return addProject(paths, arg);
232
491
  if (sub === 'list')
233
492
  return listProjects(paths, values.json === true);
234
- throw new ConductorError('usage: conduct project add <path> | conduct project list');
493
+ throw usageError('project');
494
+ case 'focus':
495
+ if (sub === undefined || values.until === undefined)
496
+ throw usageError('focus');
497
+ return override(paths, {
498
+ action: 'focus',
499
+ project: sub,
500
+ ...(values.slots === undefined ? {} : { slots: wholeNumber('--slots', values.slots) }),
501
+ until: untilOf(values.until),
502
+ ...(values.weight === undefined ? {} : { weight: wholeNumber('--weight', values.weight) }),
503
+ });
504
+ case 'pause':
505
+ return override(paths, { action: 'pause', ...(sub === undefined ? {} : { project: sub }), ...(values.until === undefined ? {} : { until: untilOf(values.until) }) });
506
+ case 'ports':
507
+ process.exitCode = await portsCommand(paths, sub, { json: values.json === true, ...(values.prefer === undefined ? {} : { prefer: wholeNumber('--prefer', values.prefer) }) }, brokerIo());
508
+ return;
509
+ case 'queue':
510
+ return queue(paths, values.json === true, values.fresh === true);
511
+ case 'rules':
512
+ if (sub === undefined)
513
+ return rules(paths, values.json === true);
514
+ if (sub === 'test' && arg !== undefined)
515
+ return rulesTest(paths, arg, values.json === true);
516
+ throw usageError('rules');
235
517
  case 'retire':
236
518
  if (sub === undefined)
237
- throw new ConductorError('usage: conduct retire <worker> [--force]');
519
+ throw usageError('retire');
238
520
  return retire(paths, sub, values.force === true);
239
521
  case 'serve':
240
522
  return serve(paths);
523
+ case 'start':
524
+ return start(paths);
241
525
  case 'status':
242
526
  return status(paths, values.json === true);
243
527
  case 'stop':
244
528
  await stopDaemon(paths);
245
529
  return;
530
+ case 'unpause':
531
+ return override(paths, { action: 'unpause', ...(sub === undefined ? {} : { project: sub }) });
246
532
  case 'upgrade':
247
533
  return upgradeCommand(paths, values.tag, values['allow-downgrade'] === true);
248
- default:
249
- throw new ConductorError(`unknown command "${command}"`, ['run `conduct help` for the commands']);
534
+ case 'why':
535
+ if (sub === undefined)
536
+ throw usageError('why');
537
+ return why(paths, sub, values.json === true);
538
+ // Only when an option comes first: as the first word they parse their own arguments, above.
539
+ case 'revise':
540
+ case 'wait':
541
+ throw usageError(command, `conduct ${command} takes its arguments right after the command`);
542
+ default: {
543
+ const unhandled = command;
544
+ throw unknownCommand(String(unhandled));
545
+ }
546
+ }
547
+ }
548
+ function modDeps() {
549
+ return { claude: (args) => run('claude', args, { timeoutMs: 120_000 }), out };
550
+ }
551
+ function noInbox() {
552
+ return olderDaemon('no inbox');
553
+ }
554
+ // GET /notify, or a ConductorError from a daemon older than the notifier.
555
+ async function notifyAnswer(paths, request) {
556
+ const answer = await callApi(paths, request);
557
+ if (answer.status === 404)
558
+ throw olderDaemon('no notifier');
559
+ return expectOk(Promise.resolve(answer));
560
+ }
561
+ // `conduct notify profile`: the active profile, or switch to <name>.
562
+ async function notifyProfile(paths, name, until) {
563
+ if (name === undefined) {
564
+ if (until !== undefined)
565
+ throw usageError('notify', '--until needs a profile: conduct notify profile <name> --until <when>');
566
+ return notifyStatus(paths, false);
567
+ }
568
+ const body = { name, ...(until === undefined ? {} : { until: parseUntil(until, new Date()).toISOString() }) };
569
+ const status = notifyStatusSchema.parse(await notifyAnswer(paths, { body, method: 'POST', path: '/notify/profile' }));
570
+ notifyLines(status).forEach((line) => out(line));
571
+ }
572
+ async function notifyStatus(paths, json) {
573
+ const status = notifyStatusSchema.parse(await notifyAnswer(paths, { method: 'GET', path: '/notify' }));
574
+ if (json)
575
+ return out(JSON.stringify(status, null, 2));
576
+ notifyLines(status).forEach((line) => out(line));
577
+ }
578
+ async function notifyTest(paths, options) {
579
+ if (options.raise && options.channel)
580
+ throw new ConductorError('--raise routes the item by the profile; it takes no --channel');
581
+ const body = { ...(options.channel ? { channel: options.channel } : {}), ...(options.kind ? { kind: options.kind } : {}), raise: options.raise };
582
+ // Pushover can take its 15 s, after a Credential Manager read.
583
+ const answer = await notifyAnswer(paths, { body, method: 'POST', path: '/notify/test', timeoutMs: 60_000 });
584
+ if (options.raise) {
585
+ const { item } = z.object({ item: inboxItemSchema }).parse(answer);
586
+ return out(`raised inbox item #${item.id} (${item.kind}); \`conduct done ${item.id}\` clears it`);
250
587
  }
588
+ const result = testResultSchema.parse(answer);
589
+ if (result.channels.length === 0)
590
+ return out(`profile ${result.profile} sends a ${body.kind ?? 'npm-otp'} item nowhere`);
591
+ out(`profile ${result.profile}${result.quietNow ? ' (quiet hours now: a real item would wait for the summary)' : ''}`);
592
+ result.results.forEach((r) => out(` ${r.channel}: ${r.ok ? 'ok' : 'failed'}: ${r.detail}`));
593
+ if (result.results.some((r) => !r.ok))
594
+ process.exitCode = 1;
251
595
  }
252
596
  // npm is a .cmd shim on Windows, which starts through a shell alone. The only argument from input is
253
597
  // the tag, which parseTag limits to dev or latest.
254
598
  function npm(args, timeoutMs) {
255
599
  return run('npm', args, { shell: process.platform === 'win32', timeoutMs });
256
600
  }
601
+ function olderDaemon(what) {
602
+ return new ConductorError(`the running conductor has ${what}: it is older than this conduct`, [
603
+ 'restart it on this build: conduct stop, then conduct serve (or conduct upgrade)',
604
+ ]);
605
+ }
606
+ // The open inbox items, or null from a daemon older than the inbox (a linked build ahead of it).
607
+ async function openItems(paths) {
608
+ const answer = await callApi(paths, { method: 'GET', path: '/inbox' });
609
+ if (answer.status === 404)
610
+ return null;
611
+ return inboxBody.parse(await expectOk(Promise.resolve(answer))).items;
612
+ }
257
613
  function out(line) {
258
614
  process.stdout.write(`${line}\n`);
259
615
  }
616
+ // `conduct pause|unpause|focus`: an override that ends on its own (unpause ends a pause).
617
+ async function override(paths, body) {
618
+ const answer = await callApi(paths, { body: { ...body, by: `conduct ${String(body.action)}` }, method: 'POST', path: '/overrides' });
619
+ if (answer.status === 404)
620
+ throw olderDaemon('no overrides');
621
+ const { overrides, set } = z.object({ overrides: z.array(overrideViewSchema), set: z.array(overrideViewSchema) }).parse(await expectOk(Promise.resolve(answer)));
622
+ const untilOfView = (o) => (o.until === null ? ' until you unpause' : ` until ${new Date(o.until).toLocaleString()}`);
623
+ for (const o of set) {
624
+ const who = o.project ?? 'every project';
625
+ if (o.kind === PAUSE)
626
+ out(o.value === 'on' ? `paused launches in ${who}${untilOfView(o)}` : `launches in ${who} are no longer paused`);
627
+ else
628
+ out(`${who}: ${o.kind.replace('focus.', '')} ${o.value}${untilOfView(o)}`);
629
+ }
630
+ // A pause of every project still holds a project unpaused on its own.
631
+ const all = overrides.find((o) => o.kind === PAUSE && o.project === null);
632
+ if (body.action === 'unpause' && body.project !== undefined && all)
633
+ out(`but all launches stay paused${untilOfView(all)}: conduct unpause ends that`);
634
+ }
635
+ // parseArgs' own errors (an unknown option, a missing value) with the command's usage, not every
636
+ // command's.
637
+ function parsing(command, parse) {
638
+ try {
639
+ return parse();
640
+ }
641
+ catch (error) {
642
+ if (!(error instanceof Error && 'code' in error && typeof error.code === 'string' && error.code.startsWith('ERR_PARSE_ARGS')))
643
+ throw error;
644
+ // Node's advice on `--` for a positional that starts with a dash is about the shell, not conduct.
645
+ const message = error.message.replace(/\. To specify a positional argument.*$/s, '');
646
+ throw isCommand(command) ? usageError(command, message) : new ConductorError(message, ['run `conduct help` for the commands']);
647
+ }
648
+ }
649
+ // The open plan item of `ref`: the item (ATK-312) whose plan waits, or an inbox id written #12. A
650
+ // bare number is refused: it could be an issue's number, and the answer is posted as Jason's.
651
+ async function planItem(paths, ref) {
652
+ if (ref.startsWith('#'))
653
+ return inboxId(ref);
654
+ if (/^\d+$/.test(ref)) {
655
+ throw new ConductorError(`"${ref}" is ambiguous`, [`name the item, such as ATK-${ref}, or the inbox id as #${ref}`]);
656
+ }
657
+ const items = await openItems(paths);
658
+ if (items === null)
659
+ throw noInbox();
660
+ const plans = items.filter((i) => i.kind === 'plan' && i.item?.toUpperCase() === ref.toUpperCase());
661
+ if (plans.length === 1 && plans[0])
662
+ return plans[0].id;
663
+ if (plans.length === 0)
664
+ throw new ConductorError(`no plan of ${ref} waits in the inbox`, ['`conduct inbox` lists what waits']);
665
+ throw new ConductorError(`several plans of ${ref} wait`, plans.map((p) => `#${p.id} in ${p.project ?? '?'}: pass #${p.id}`));
666
+ }
260
667
  function projectLine(p) {
261
668
  const state = p.problem ? `${p.problem}; run \`conduct project add\` again` : p.enabled ? 'enabled' : 'disabled';
262
669
  return ` ${p.name} ${p.root} (protocol ${p.protocol}, ${state})`;
263
670
  }
671
+ // The registered projects: from the daemon, or from the store when it isn't running.
672
+ async function projectsNow(paths) {
673
+ try {
674
+ return projectsBody.parse(await expectOk(callApi(paths, { method: 'GET', path: '/projects' }))).projects;
675
+ }
676
+ catch (error) {
677
+ if (!(error instanceof NotRunningError))
678
+ throw error;
679
+ return withStore(paths, (store) => store.listProjects());
680
+ }
681
+ }
682
+ async function queue(paths, json, fresh) {
683
+ // A fresh read asks every project's tracker, within the shared rate budget.
684
+ const answer = await callApi(paths, { method: 'GET', path: `/queue${fresh ? '?fresh=true' : ''}`, timeoutMs: 120_000 });
685
+ if (answer.status === 404)
686
+ throw olderDaemon('no scheduler');
687
+ const view = queueViewSchema.parse(await expectOk(Promise.resolve(answer)));
688
+ if (json)
689
+ return out(JSON.stringify(view, null, 2));
690
+ queueLines(view).forEach((line) => out(line));
691
+ }
264
692
  async function retire(paths, ref, force) {
265
693
  const worker = await findWorker(paths, ref);
266
694
  const { body, status } = await callApi(paths, {
@@ -288,23 +716,86 @@ async function retire(paths, ref, force) {
288
716
  out(`retired ${worker.name}`);
289
717
  steps.forEach((s) => out(` ${s}`));
290
718
  }
719
+ // `conduct rules`: from the daemon, or straight from the files when it isn't running.
720
+ async function rules(paths, json) {
721
+ const view = await rulesAnswer(paths, { method: 'GET', path: '/rules' }, (body) => rulesViewSchema.parse(body), (service) => service.view());
722
+ if (json)
723
+ return out(JSON.stringify(view, null, 2));
724
+ rulesLines(view).forEach((line) => out(line));
725
+ }
726
+ // The daemon's answer, or, when none runs, the same thing worked out here from the files.
727
+ async function rulesAnswer(paths, request, parse, local) {
728
+ let answer;
729
+ try {
730
+ answer = await callApi(paths, request);
731
+ }
732
+ catch (error) {
733
+ if (!(error instanceof NotRunningError))
734
+ throw error;
735
+ process.stderr.write('conduct: the conductor is not running; read from the files\n');
736
+ const config = loadConfig(paths.config);
737
+ return withStore(paths, (store) => {
738
+ const service = rulesService({ config, listProjects: () => store.listProjects(), paths });
739
+ service.reload();
740
+ return local(service);
741
+ });
742
+ }
743
+ if (answer.status === 404)
744
+ throw olderDaemon('no rules engine');
745
+ return parse(await expectOk(Promise.resolve(answer)));
746
+ }
747
+ async function rulesTest(paths, file, json) {
748
+ let text;
749
+ try {
750
+ text = readFileSync(file, 'utf8');
751
+ }
752
+ catch (error) {
753
+ throw new ConductorError(`could not read ${file}`, [String(error)]);
754
+ }
755
+ const sample = parseJsonc(text, z.unknown(), file);
756
+ const result = await rulesAnswer(paths, { body: sample, method: 'POST', path: '/rules/test' }, (body) => rulesTestResultSchema.parse(body), (service) => service.test(sample));
757
+ if (json)
758
+ return out(JSON.stringify(result, null, 2));
759
+ testLines(result).forEach((line) => out(line));
760
+ }
291
761
  async function serve(paths) {
292
762
  const daemon = await startDaemon(paths, { version: version() });
293
763
  out(`conductor listening on 127.0.0.1:${daemon.port} (pid ${process.pid}, home ${paths.home})`);
294
764
  for (const signal of ['SIGINT', 'SIGTERM', 'SIGBREAK']) {
295
765
  process.once(signal, () => void daemon.stop(signal));
296
766
  }
297
- // Under the logon task nobody sees stderr, so a crash goes to the log. The pid file it leaves
298
- // names a dead process, which the next start replaces.
299
- process.on('uncaughtException', (error) => {
300
- daemon.log.log('error', 'uncaught exception', { error: error.stack ?? String(error) });
301
- process.exit(1);
302
- });
767
+ logCrashes(daemon.log);
303
768
  await daemon.closed;
304
769
  }
305
770
  function sleep(ms) {
306
771
  return new Promise((done) => setTimeout(done, ms));
307
772
  }
773
+ // `conduct start`: the daemon, detached from this process, so it outlives the shell or the Claude
774
+ // session that started it (the console's start runs this). Nothing when one answers already.
775
+ async function start(paths) {
776
+ const pid = readPid(paths.pid);
777
+ if (pid !== null && (await ping(paths, pid)))
778
+ return out(`the conductor is running (pid ${pid})`);
779
+ // A daemon that is still starting (the logon task's, say) holds the lock: wait for it rather than
780
+ // start a second one, which would exit on that lock. A pid a reboot reused gets a start after.
781
+ if (pid !== null && processAlive(pid)) {
782
+ try {
783
+ return out(`the conductor is running (pid ${await awaitDaemon(paths)})`);
784
+ }
785
+ catch {
786
+ // Not a daemon that answers: start one, which replaces a stale lock (or says who holds it).
787
+ }
788
+ }
789
+ try {
790
+ out(`started the conductor ${await restartDaemon(daemonStarter(paths, realpathSync(fileURLToPath(import.meta.url))))}`);
791
+ }
792
+ catch (error) {
793
+ const holder = readPid(paths.pid);
794
+ if (error instanceof ServeStartError || holder === null || !processAlive(holder))
795
+ throw error;
796
+ throw new ConductorError(`process ${holder} holds the conductor's lock (${paths.pid}) but doesn't answer`, ['if it is a hung conductor, stop it, then run conduct start again', `see ${paths.log}`]);
797
+ }
798
+ }
308
799
  async function status(paths, json) {
309
800
  let projects;
310
801
  try {
@@ -313,21 +804,36 @@ async function status(paths, json) {
313
804
  catch (error) {
314
805
  if (!(json && error instanceof NotRunningError))
315
806
  throw error;
316
- // Scripts and the conductor mod read the answer, so "not running" is JSON too (exit 1).
317
- out(JSON.stringify({ home: paths.home, running: false }, null, 2));
807
+ // Scripts and the conductor mod read the answer, so "not running" is JSON too (exit 1), with the
808
+ // store's workers while the daemon restarts or upgrades.
809
+ const workers = storedFleet(paths.db, localDay(new Date()));
810
+ out(JSON.stringify({ home: paths.home, running: false, ...(workers ? { workers, workersFrom: 'store' } : {}) }, null, 2));
318
811
  process.exitCode = 1;
319
812
  return;
320
813
  }
321
814
  const { workers } = fleetBody.parse(await expectOk(callApi(paths, { method: 'GET', path: '/fleet' })));
815
+ // A linked build's CLI can be newer than the daemon still running, which has no inbox (null).
816
+ const items = await openItems(paths);
817
+ // Null from a daemon older than the broker.
818
+ const locks = await heldLocks(paths);
322
819
  const pid = readPid(paths.pid);
323
820
  const port = readEndpoint(paths)?.port ?? null;
324
821
  if (json)
325
- return out(JSON.stringify({ home: paths.home, pid, port, projects, running: true, workers }, null, 2));
822
+ return out(JSON.stringify({ home: paths.home, inbox: items, locks, pid, port, projects, running: true, workers, workersFrom: 'daemon' }, null, 2));
326
823
  out(`conductor running (pid ${pid ?? '?'}, port ${port ?? '?'}, home ${paths.home})`);
327
824
  out(projects.length === 0 ? 'no projects; add one with `conduct project add <path>`' : 'projects:');
328
825
  projects.forEach((p) => out(projectLine(p)));
329
826
  out(workers.length === 0 ? 'no workers' : 'workers:');
330
827
  workers.forEach((w) => out(workerLine(w)));
828
+ if (locks === null)
829
+ out('locks: not in this daemon (restart it to run this build)');
830
+ else
831
+ out(locks.length === 0 ? 'locks: none held' : 'locks:');
832
+ locks?.forEach((l) => out(lockLine(l)));
833
+ if (items === null)
834
+ out('inbox: not in this daemon (restart it to run this build)');
835
+ else
836
+ out(items.length === 0 ? 'inbox: empty' : `inbox: ${items.length} open (conduct inbox)`);
331
837
  }
332
838
  // True when it stopped a daemon, false when none ran.
333
839
  async function stopDaemon(paths) {
@@ -357,10 +863,14 @@ async function stopDaemon(paths) {
357
863
  function uninstall() {
358
864
  out(removeStartup() ? `removed the "${TASK_NAME}" logon task` : `no "${TASK_NAME}" logon task to remove`);
359
865
  }
866
+ // --until: 17:00 (the next one), tomorrow, a day such as monday, or a date and time.
867
+ function untilOf(text) {
868
+ return resolveUntil({ kind: 'at', text }, new Date()).toISOString();
869
+ }
360
870
  async function upgradeCommand(paths, tag, allowDowngrade) {
361
871
  const cliPath = realpathSync(fileURLToPath(import.meta.url));
362
872
  await upgrade({ allowDowngrade, tag: parseTag(tag) }, {
363
- awaitDaemon: () => awaitDaemon(paths),
873
+ ...daemonStarter(paths, cliPath),
364
874
  cliPath,
365
875
  installedVersion: version,
366
876
  npmInstall: (spec) => npm(['install', '--global', spec], NPM_INSTALL_TIMEOUT_MS),
@@ -378,15 +888,7 @@ async function upgradeCommand(paths, tag, allowDowngrade) {
378
888
  return found;
379
889
  },
380
890
  out,
381
- runTask: runStartup,
382
- // A failed start shows as awaitDaemon's timeout. The daemon runs in its home, not in the
383
- // caller's directory, which it would hold open (a worktree it may later remove, say).
384
- serveDetached: () => spawn(process.execPath, [cliPath, 'serve'], { cwd: paths.home, detached: true, stdio: 'ignore', windowsHide: true })
385
- .on('error', () => { })
386
- .unref(),
387
891
  stopDaemon: () => stopDaemon(paths),
388
- // The logon task's daemon uses ~/.conductor, so it can't restart one kept in CONDUCTOR_HOME.
389
- taskRunsCli: () => !process.env.CONDUCTOR_HOME && startupRunsCli(cliPath),
390
892
  });
391
893
  }
392
894
  // Read from disk each time: upgrade asks again after npm has replaced the package.
@@ -395,7 +897,7 @@ function version() {
395
897
  return z.object({ version: z.string() }).parse(JSON.parse(readFileSync(file, 'utf8'))).version;
396
898
  }
397
899
  async function wait(argv) {
398
- const { positionals, values } = parseArgs({
900
+ const { positionals, values } = parsing('wait', () => parseArgs({
399
901
  allowPositionals: true,
400
902
  args: argv,
401
903
  options: {
@@ -409,17 +911,39 @@ async function wait(argv) {
409
911
  version: { type: 'string' },
410
912
  worker: { type: 'string' },
411
913
  },
412
- });
914
+ }));
413
915
  const timeout = values.timeout === undefined ? undefined : Number(values.timeout);
414
916
  if (timeout !== undefined && !(timeout > 0))
415
917
  throw new ConductorError('--timeout takes minutes, such as --timeout 25');
416
918
  if (positionals.length === 0)
417
- throw new ConductorError('usage: conduct wait <condition>', ['run `conduct help` for the conditions']);
919
+ throw usageError('wait');
418
920
  process.exitCode = await waitCommand(conductorPaths(), positionals, { ...values, timeoutMinutes: timeout }, { cwd: process.cwd(), err: (line) => process.stderr.write(`${line}\n`), out });
419
921
  }
420
- function withStore(paths, use) {
922
+ function wholeNumber(flag, text) {
923
+ if (!/^-?\d+$/.test(text))
924
+ throw new ConductorError(`${flag} takes a whole number, not "${text}"`);
925
+ return Number(text);
926
+ }
927
+ // `conduct why <event id>`: the rule behind it and its causes. `conduct why <item>`: the same for
928
+ // each of the item's newest actions.
929
+ async function why(paths, ref, json) {
930
+ const byId = /^#?(\d+)$/.exec(ref)?.[1];
931
+ const answer = await callApi(paths, { method: 'GET', path: byId === undefined ? `/why?item=${encodeURIComponent(ref)}` : `/why/${byId}` });
932
+ if (answer.status === 404 && byId !== undefined) {
933
+ const body = errorBody.safeParse(answer.body);
934
+ throw body.success && body.data.error === 'not_found' ? new ConductorError(`no event ${byId}`) : olderDaemon('no conduct why');
935
+ }
936
+ const body = await expectOk(Promise.resolve(answer));
937
+ const whys = byId === undefined ? z.object({ items: z.array(whySchema) }).parse(body).items : [whySchema.parse(body)];
938
+ if (json)
939
+ return out(JSON.stringify(byId === undefined ? whys : whys[0], null, 2));
940
+ if (whys.length === 0)
941
+ return out(`no action on ${ref} was caused by a rule`);
942
+ whys.forEach((w, i) => [...(i > 0 ? [''] : []), ...whyLines(w)].forEach((line) => out(line)));
943
+ }
944
+ function withStore(paths, use, options = {}) {
421
945
  mkdirSync(paths.home, { recursive: true });
422
- const store = openStore(paths.db);
946
+ const store = openStore(paths.db, undefined, options);
423
947
  try {
424
948
  return use(store);
425
949
  }
@@ -427,12 +951,13 @@ function withStore(paths, use) {
427
951
  store.close();
428
952
  }
429
953
  }
430
- // One line per worker: name, project, status and session activity, its waits, then spend.
954
+ // One line per worker: name, project, status and session activity, its phase and waits, then spend.
431
955
  function workerLine(w) {
432
956
  const activity = w.status === 'running' ? `running, ${w.activity}` : w.status;
433
957
  const waits = w.waits.map((x) => (x.resolvedAt ? `${x.condition} (resolved)` : x.condition));
434
958
  return [
435
959
  ` ${w.name} ${w.project} ${activity}`,
960
+ ...(w.phase ? [`phase ${w.phase}`] : []),
436
961
  ...(waits.length > 0 ? [`waits: ${waits.join(', ')}`] : []),
437
962
  `spend ${formatTokens(w.spend.today)} today, ${formatTokens(w.spend.total)} total`,
438
963
  ].join(' · ');
@@ -441,9 +966,6 @@ main(process.argv.slice(2)).catch((error) => {
441
966
  if (error instanceof ConductorError) {
442
967
  process.stderr.write(`conduct: ${error.message}\n${error.details.map((d) => ` ${d}\n`).join('')}`);
443
968
  }
444
- else if (error instanceof Error && 'code' in error && typeof error.code === 'string' && error.code.startsWith('ERR_PARSE_ARGS')) {
445
- process.stderr.write(`conduct: ${error.message}\n${USAGE}\n`);
446
- }
447
969
  else {
448
970
  process.stderr.write(`conduct: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
449
971
  }