@staff0rd/assist 0.1031.0 → 0.1032.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.
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { Command } from "commander";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@staff0rd/assist",
9
- version: "0.1031.0",
9
+ version: "0.1032.0",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -2756,11 +2756,11 @@ function attachSessions(item, rel, id) {
2756
2756
  // src/commands/backlog/sumPhaseUsage.ts
2757
2757
  function sumPhaseUsage(usage) {
2758
2758
  return usage.reduce(
2759
- (total2, u) => ({
2760
- tokensUp: total2.tokensUp + u.tokensUp,
2761
- tokensDown: total2.tokensDown + u.tokensDown,
2762
- activeMs: total2.activeMs + u.activeMs,
2763
- peakContextPct: Math.max(total2.peakContextPct, u.peakContextPct)
2759
+ (total3, u) => ({
2760
+ tokensUp: total3.tokensUp + u.tokensUp,
2761
+ tokensDown: total3.tokensDown + u.tokensDown,
2762
+ activeMs: total3.activeMs + u.activeMs,
2763
+ peakContextPct: Math.max(total3.peakContextPct, u.peakContextPct)
2764
2764
  }),
2765
2765
  { tokensUp: 0, tokensDown: 0, activeMs: 0, peakContextPct: 0 }
2766
2766
  );
@@ -3607,8 +3607,8 @@ async function assertMigrationsInSync(exec3) {
3607
3607
  // src/shared/db/migrations/MigrationExecutor.ts
3608
3608
  function pgExecutor(queryable) {
3609
3609
  return {
3610
- exec: (sql32) => queryable.query(sql32),
3611
- query: async (sql32, params) => (await queryable.query(sql32, params)).rows
3610
+ exec: (sql33) => queryable.query(sql33),
3611
+ query: async (sql33, params) => (await queryable.query(sql33, params)).rows
3612
3612
  };
3613
3613
  }
3614
3614
 
@@ -9898,11 +9898,11 @@ function listUsageHistory(req, res) {
9898
9898
  return respondPagedRows(req, res, async (range, params) => {
9899
9899
  const window = parseWindow(params.get("window"));
9900
9900
  const db = await getDb();
9901
- const [rows, total2] = await Promise.all([
9901
+ const [rows, total3] = await Promise.all([
9902
9902
  listUsagePeaks(db, { ...range, window }),
9903
9903
  countUsagePeaks(db, window)
9904
9904
  ]);
9905
- return { rows, total: total2 };
9905
+ return { rows, total: total3 };
9906
9906
  });
9907
9907
  }
9908
9908
 
@@ -10066,23 +10066,443 @@ function listUsageItems(req, res) {
10066
10066
  });
10067
10067
  }
10068
10068
 
10069
+ // src/shared/db/jobRunTotals.ts
10070
+ import { and as and12, desc as desc7, eq as eq28, gte as gte2, sql as sql24 } from "drizzle-orm";
10071
+ var total = (column) => sql24`coalesce(sum(${column}), 0)`.mapWith(Number);
10072
+ async function jobRunTotals(db, since) {
10073
+ const inWindow = gte2(jobRuns.startedAt, since);
10074
+ const [byKind, [sums], [lastFailure]] = await Promise.all([
10075
+ db.select({
10076
+ kind: jobRuns.kind,
10077
+ runs: sql24`count(*)`.mapWith(Number)
10078
+ }).from(jobRuns).where(inWindow).groupBy(jobRuns.kind),
10079
+ db.select({
10080
+ inputTokens: total(jobRuns.inputTokens),
10081
+ outputTokens: total(jobRuns.outputTokens),
10082
+ cacheReadTokens: total(jobRuns.cacheReadTokens),
10083
+ costUsd: sql24`sum(${jobRuns.costUsd})`.mapWith(Number),
10084
+ failed: sql24`count(*) filter (where ${jobRuns.status} = 'failed')`.mapWith(
10085
+ Number
10086
+ )
10087
+ }).from(jobRuns).where(inWindow),
10088
+ db.select({ kind: jobRuns.kind, startedAt: jobRuns.startedAt }).from(jobRuns).where(and12(inWindow, eq28(jobRuns.status, "failed"))).orderBy(desc7(jobRuns.startedAt)).limit(1)
10089
+ ]);
10090
+ return {
10091
+ runs: byKind.reduce((sum3, row3) => sum3 + row3.runs, 0),
10092
+ runsByKind: Object.fromEntries(byKind.map((row3) => [row3.kind, row3.runs])),
10093
+ ...sums,
10094
+ lastFailure: lastFailure ?? null
10095
+ };
10096
+ }
10097
+
10069
10098
  // src/shared/db/listJobRuns.ts
10070
- import { count as count3, desc as desc7 } from "drizzle-orm";
10071
- async function listJobRuns(db, range) {
10072
- const [rows, [{ total: total2 }]] = await Promise.all([
10073
- db.select().from(jobRuns).orderBy(desc7(jobRuns.startedAt), desc7(jobRuns.id)).limit(range.limit).offset(range.offset),
10074
- db.select({ total: count3() }).from(jobRuns)
10099
+ import { and as and13, count as count3, desc as desc8, eq as eq29 } from "drizzle-orm";
10100
+ async function listJobRuns(db, range, filters = {}) {
10101
+ const where = and13(
10102
+ filters.kind ? eq29(jobRuns.kind, filters.kind) : void 0,
10103
+ filters.trigger ? eq29(jobRuns.trigger, filters.trigger) : void 0
10104
+ );
10105
+ const [rows, [{ total: total3 }]] = await Promise.all([
10106
+ db.select().from(jobRuns).where(where).orderBy(desc8(jobRuns.startedAt), desc8(jobRuns.id)).limit(range.limit).offset(range.offset),
10107
+ db.select({ total: count3() }).from(jobRuns).where(where)
10075
10108
  ]);
10076
- return { rows, total: total2 };
10109
+ return { rows, total: total3 };
10110
+ }
10111
+
10112
+ // src/shared/db/failStaleJobRuns.ts
10113
+ import { and as and14, eq as eq30, lt } from "drizzle-orm";
10114
+ async function failStaleJobRuns(db, { startedBefore, detail }) {
10115
+ const failed3 = await db.update(jobRuns).set({ status: "failed", detail }).where(
10116
+ and14(eq30(jobRuns.status, "running"), lt(jobRuns.startedAt, startedBefore))
10117
+ ).returning({ id: jobRuns.id });
10118
+ return failed3.length;
10119
+ }
10120
+
10121
+ // src/commands/inbox/runInboxScanClaude.ts
10122
+ import { spawn as spawn2 } from "child_process";
10123
+ import { z as z11 } from "zod";
10124
+
10125
+ // src/commands/review/attachLineParser.ts
10126
+ function flushBuffer(buffer, onLine) {
10127
+ let remaining = buffer;
10128
+ while (true) {
10129
+ const idx = remaining.indexOf("\n");
10130
+ if (idx === -1) return remaining;
10131
+ const line = remaining.slice(0, idx);
10132
+ remaining = remaining.slice(idx + 1);
10133
+ if (line.trim()) onLine(line);
10134
+ }
10135
+ }
10136
+ function attachLineParser(child, onLine) {
10137
+ let buffer = "";
10138
+ child.stdout?.on("data", (chunk) => {
10139
+ buffer += chunk.toString("utf8");
10140
+ buffer = flushBuffer(buffer, onLine);
10141
+ });
10142
+ return () => {
10143
+ if (buffer.trim()) onLine(buffer);
10144
+ };
10145
+ }
10146
+
10147
+ // src/commands/review/attachStderrCollector.ts
10148
+ function attachStderrCollector(child) {
10149
+ const state = { value: "" };
10150
+ child.stderr?.on("data", (chunk) => {
10151
+ state.value += chunk.toString("utf8");
10152
+ });
10153
+ return state;
10154
+ }
10155
+
10156
+ // src/commands/inbox/buildInboxScanPrompt.ts
10157
+ function buildInboxScanPrompt(since) {
10158
+ const sinceUnix = Math.floor(since.getTime() / 1e3);
10159
+ return [
10160
+ "Triage my Gmail and Slack for messages a person wrote to me that look like they need my reply.",
10161
+ "You are read-only: never label, mark read, react to, reply to or otherwise change any message.",
10162
+ "",
10163
+ "Gmail:",
10164
+ '- Call search_threads with query "in:inbox is:unread" (page through all results).',
10165
+ "- Call get_thread with messageFormat PLAIN_TEXT on each thread.",
10166
+ "- Consider the latest unread message in each thread.",
10167
+ "",
10168
+ `Slack (only messages since ${since.toISOString()}, unix ${sinceUnix}):`,
10169
+ `- Call slack_search_public_and_private with filters "is:dm" and after "${sinceUnix}".`,
10170
+ `- Call slack_search_public_and_private with keywords ["<@MY_USER_ID>"] and after "${sinceUnix}", where MY_USER_ID is the logged-in user id from the tool description.`,
10171
+ "- Skip messages I wrote myself.",
10172
+ "- For a message in a thread, call slack_read_thread and skip it if I have replied in that thread after it.",
10173
+ "",
10174
+ "Do not flag anything from bots, apps, automated or notification systems (CI, calendars, ticketing, monitoring, no-reply addresses), newsletters or mailing lists.",
10175
+ "Flag only messages a human wrote that ask me something, request something of me, or otherwise expect my response.",
10176
+ "",
10177
+ "For each flagged message return:",
10178
+ '- source: "gmail" or "slack"',
10179
+ "- messageId: the Gmail message id, or for Slack <channel_id>:<message ts>",
10180
+ "- sender: the sender's name",
10181
+ "- summary: one sentence on what they need from me",
10182
+ "- link: the Gmail message viewUrl or the Slack permalink",
10183
+ "- receivedAt: when it was sent, as an ISO 8601 timestamp",
10184
+ "",
10185
+ "Return an empty messages array when nothing needs a reply."
10186
+ ].join("\n");
10187
+ }
10188
+
10189
+ // src/commands/inbox/describeInboxScanTool.ts
10190
+ function pick(input, keys) {
10191
+ return keys.map((key) => input[key]).filter(
10192
+ (value) => typeof value === "string" || typeof value === "number"
10193
+ ).map(String);
10194
+ }
10195
+ function toolLabel(name) {
10196
+ const match = name.match(/^mcp__claude_ai_([^_]+)__(?:slack_)?(.+)$/);
10197
+ return match ? `${match[1]} ${match[2]}` : name;
10198
+ }
10199
+ function describeInboxScanTool(name, input) {
10200
+ const record = input && typeof input === "object" ? input : {};
10201
+ const detail = pick(record, [
10202
+ "query",
10203
+ "thread_id",
10204
+ "threadId",
10205
+ "channel_id",
10206
+ "message_ts"
10207
+ ]).join(" ");
10208
+ return { label: toolLabel(name), detail };
10209
+ }
10210
+
10211
+ // src/commands/inbox/assistantScanEvents.ts
10212
+ var MAX_TEXT = 500;
10213
+ function truncate(text20) {
10214
+ const trimmed = text20.trim();
10215
+ return trimmed.length <= MAX_TEXT ? trimmed : `${trimmed.slice(0, MAX_TEXT - 1)}\u2026`;
10216
+ }
10217
+ function blockEvent(block) {
10218
+ if (block.type === "tool_use") {
10219
+ const name = typeof block.name === "string" ? block.name : "tool";
10220
+ return { kind: "tool", ...describeInboxScanTool(name, block.input) };
10221
+ }
10222
+ if (block.type === "text" && typeof block.text === "string" && block.text.trim())
10223
+ return { kind: "text", label: "Assistant", detail: truncate(block.text) };
10224
+ return void 0;
10225
+ }
10226
+ function assistantScanEvents(content) {
10227
+ if (!Array.isArray(content)) return [];
10228
+ const at2 = (/* @__PURE__ */ new Date()).toISOString();
10229
+ return content.map(blockEvent).filter((event) => event !== void 0).map((event) => ({ at: at2, ...event }));
10230
+ }
10231
+
10232
+ // src/commands/review/parseTokenUsage.ts
10233
+ function count4(value) {
10234
+ return typeof value === "number" ? value : 0;
10235
+ }
10236
+ function parseTokenUsage(usage, keys) {
10237
+ if (typeof usage !== "object" || usage === null) return void 0;
10238
+ const raw = usage;
10239
+ const parsed = {
10240
+ input: count4(raw.input_tokens),
10241
+ output: count4(raw.output_tokens),
10242
+ cacheRead: count4(raw[keys.cacheRead])
10243
+ };
10244
+ if (keys.cacheWrite) parsed.cacheWrite = count4(raw[keys.cacheWrite]);
10245
+ return parsed;
10246
+ }
10247
+
10248
+ // src/commands/review/parseClaudeUsage.ts
10249
+ function parseClaudeUsage(usage) {
10250
+ return parseTokenUsage(usage, {
10251
+ cacheRead: "cache_read_input_tokens",
10252
+ cacheWrite: "cache_creation_input_tokens"
10253
+ });
10254
+ }
10255
+
10256
+ // src/commands/inbox/emptyScanUsage.ts
10257
+ function emptyScanUsage() {
10258
+ return {
10259
+ input: 0,
10260
+ output: 0,
10261
+ cacheRead: 0,
10262
+ cacheWrite: 0,
10263
+ costUsd: null,
10264
+ durationMs: null
10265
+ };
10266
+ }
10267
+
10268
+ // src/commands/inbox/scanUsageTokens.ts
10269
+ function scanUsageTokens(usage) {
10270
+ return usage.input + usage.output + usage.cacheRead + (usage.cacheWrite ?? 0);
10271
+ }
10272
+
10273
+ // src/commands/inbox/createScanUsageTracker.ts
10274
+ var numberOrNull = (value) => typeof value === "number" ? value : null;
10275
+ function createScanUsageTracker() {
10276
+ const usage = emptyScanUsage();
10277
+ const turns = /* @__PURE__ */ new Map();
10278
+ let unsettled = 0;
10279
+ return {
10280
+ current: () => ({ ...usage }),
10281
+ // stream-json repeats a message's usage on every content-block line, so
10282
+ // each turn is counted once by message id, applying only the change.
10283
+ addTurn(id, raw) {
10284
+ const parsed = parseClaudeUsage(raw);
10285
+ if (!parsed) return false;
10286
+ const key = typeof id === "string" ? id : `turn-${turns.size}`;
10287
+ const previous = turns.get(key);
10288
+ turns.set(key, parsed);
10289
+ usage.input += parsed.input - (previous?.input ?? 0);
10290
+ usage.output += parsed.output - (previous?.output ?? 0);
10291
+ usage.cacheRead += parsed.cacheRead - (previous?.cacheRead ?? 0);
10292
+ usage.cacheWrite += (parsed.cacheWrite ?? 0) - (previous?.cacheWrite ?? 0);
10293
+ unsettled += scanUsageTokens(parsed) - (previous ? scanUsageTokens(previous) : 0);
10294
+ return true;
10295
+ },
10296
+ takeTurnTokens() {
10297
+ const tokens = unsettled;
10298
+ unsettled = 0;
10299
+ return tokens > 0 ? tokens : void 0;
10300
+ },
10301
+ finish(result) {
10302
+ usage.costUsd = numberOrNull(result.total_cost_usd);
10303
+ usage.durationMs = numberOrNull(result.duration_ms);
10304
+ }
10305
+ };
10306
+ }
10307
+
10308
+ // src/commands/inbox/inboxScanSchema.ts
10309
+ import { z as z10 } from "zod";
10310
+ var flaggedMessageSchema = z10.object({
10311
+ source: z10.enum(["gmail", "slack"]),
10312
+ messageId: z10.string().min(1),
10313
+ sender: z10.string().min(1),
10314
+ summary: z10.string().min(1),
10315
+ link: z10.string().min(1),
10316
+ receivedAt: z10.string().optional()
10317
+ });
10318
+ var inboxScanSchema = z10.object({
10319
+ messages: z10.array(flaggedMessageSchema)
10320
+ });
10321
+
10322
+ // src/commands/inbox/parseInboxScanOutput.ts
10323
+ function parseInboxScanOutput(stdout) {
10324
+ const result = JSON.parse(stdout);
10325
+ if (result.is_error)
10326
+ throw new Error(`Inbox scan failed: ${result.result ?? "unknown error"}`);
10327
+ return inboxScanSchema.parse(result.structured_output).messages;
10328
+ }
10329
+
10330
+ // src/commands/inbox/parseScanStreamLine.ts
10331
+ function parseScanStreamLine(line) {
10332
+ try {
10333
+ return JSON.parse(line);
10334
+ } catch {
10335
+ return void 0;
10336
+ }
10337
+ }
10338
+
10339
+ // src/commands/inbox/createInboxScanParser.ts
10340
+ function createInboxScanParser({
10341
+ onEvent = () => {
10342
+ },
10343
+ onUsage = () => {
10344
+ },
10345
+ onModel = () => {
10346
+ }
10347
+ } = {}) {
10348
+ const usage = createScanUsageTracker();
10349
+ let resultLine;
10350
+ const onAssistant = (message3) => {
10351
+ const counted = usage.addTurn(message3?.id, message3?.usage);
10352
+ for (const scanEvent of assistantScanEvents(message3?.content)) {
10353
+ const tokens = usage.takeTurnTokens();
10354
+ onEvent(tokens === void 0 ? scanEvent : { ...scanEvent, tokens });
10355
+ }
10356
+ if (counted) onUsage(usage.current());
10357
+ };
10358
+ return {
10359
+ onLine(line) {
10360
+ const event = parseScanStreamLine(line);
10361
+ if (!event) return;
10362
+ if (event.type === "system" && typeof event.model === "string")
10363
+ onModel(event.model);
10364
+ else if (event.type === "assistant") onAssistant(event.message);
10365
+ else if (event.type === "result") {
10366
+ resultLine = line;
10367
+ usage.finish(event);
10368
+ onUsage(usage.current());
10369
+ }
10370
+ },
10371
+ finish(failure) {
10372
+ if (!resultLine) throw new Error(`Inbox scan failed: ${failure}`);
10373
+ return {
10374
+ messages: parseInboxScanOutput(resultLine),
10375
+ usage: usage.current()
10376
+ };
10377
+ }
10378
+ };
10379
+ }
10380
+
10381
+ // src/commands/inbox/inboxScanTools.ts
10382
+ var gmail = (tool) => `mcp__claude_ai_Gmail__${tool}`;
10383
+ var slack = (tool) => `mcp__claude_ai_Slack__${tool}`;
10384
+ var inboxScanTools = {
10385
+ allowed: [
10386
+ gmail("search_threads"),
10387
+ gmail("get_thread"),
10388
+ slack("slack_search_public_and_private"),
10389
+ slack("slack_read_thread")
10390
+ ],
10391
+ denied: [
10392
+ ...[
10393
+ "apply_sensitive_message_label",
10394
+ "apply_sensitive_thread_label",
10395
+ "create_draft",
10396
+ "create_label",
10397
+ "delete_draft",
10398
+ "delete_label",
10399
+ "forward",
10400
+ "label_message",
10401
+ "label_thread",
10402
+ "mark_message_spam",
10403
+ "mark_thread_spam",
10404
+ "reply",
10405
+ "send_message",
10406
+ "trash_message",
10407
+ "trash_thread",
10408
+ "unlabel_message",
10409
+ "unlabel_thread",
10410
+ "unmark_message_spam",
10411
+ "unmark_thread_spam",
10412
+ "untrash_message",
10413
+ "untrash_thread",
10414
+ "update_draft",
10415
+ "update_label",
10416
+ "update_message_labels"
10417
+ ].map(gmail),
10418
+ ...[
10419
+ "slack_add_reaction",
10420
+ "slack_create_canvas",
10421
+ "slack_create_conversation",
10422
+ "slack_schedule_message",
10423
+ "slack_send_message",
10424
+ "slack_send_message_draft",
10425
+ "slack_update_canvas"
10426
+ ].map(slack)
10427
+ ]
10428
+ };
10429
+
10430
+ // src/commands/inbox/runInboxScanClaude.ts
10431
+ var INBOX_SCAN_TIMEOUT_MS = 20 * 6e4;
10432
+ function buildInboxScanArgs(since) {
10433
+ return [
10434
+ "-p",
10435
+ "--tools",
10436
+ "",
10437
+ "--permission-mode",
10438
+ "dontAsk",
10439
+ "--allowedTools",
10440
+ ...inboxScanTools.allowed,
10441
+ "--disallowedTools",
10442
+ ...inboxScanTools.denied,
10443
+ "--no-session-persistence",
10444
+ "--output-format",
10445
+ "stream-json",
10446
+ "--verbose",
10447
+ "--json-schema",
10448
+ JSON.stringify(z11.toJSONSchema(inboxScanSchema, { target: "draft-07" })),
10449
+ "--",
10450
+ buildInboxScanPrompt(since)
10451
+ ];
10452
+ }
10453
+ function describeExit(code, signal) {
10454
+ return signal ? `claude was killed (${signal})` : `claude exited ${code}`;
10455
+ }
10456
+ async function runInboxScanClaude(since, listener = {}) {
10457
+ const child = spawn2("claude", buildInboxScanArgs(since), {
10458
+ stdio: ["ignore", "pipe", "pipe"],
10459
+ windowsHide: true,
10460
+ timeout: INBOX_SCAN_TIMEOUT_MS
10461
+ });
10462
+ const parser = createInboxScanParser(listener);
10463
+ const flush = attachLineParser(child, parser.onLine);
10464
+ const stderr = attachStderrCollector(child);
10465
+ const exit = await new Promise((resolve32, reject) => {
10466
+ child.on("error", reject);
10467
+ child.on("close", (code, signal) => resolve32(describeExit(code, signal)));
10468
+ });
10469
+ flush();
10470
+ const tail = stderr.value.trim().slice(-500);
10471
+ return parser.finish(tail ? `${exit}: ${tail}` : exit);
10472
+ }
10473
+
10474
+ // src/commands/inbox/failTimedOutInboxScans.ts
10475
+ var GRACE_MS = 5 * 6e4;
10476
+ function failTimedOutInboxScans(db, now = /* @__PURE__ */ new Date()) {
10477
+ return failStaleJobRuns(db, {
10478
+ startedBefore: new Date(now.getTime() - INBOX_SCAN_TIMEOUT_MS - GRACE_MS),
10479
+ detail: `No result within ${INBOX_SCAN_TIMEOUT_MS / 6e4}m: the process running it likely exited`
10480
+ });
10077
10481
  }
10078
10482
 
10079
10483
  // src/commands/sessions/web/listUsageJobs.ts
10484
+ var TOTALS_WINDOW_MS = 30 * 24 * 60 * 6e4;
10485
+ var kinds = ["inbox-scan", "review"];
10486
+ var triggers = ["scheduled", "manual"];
10487
+ function pick2(allowed, value) {
10488
+ return allowed.find((option) => option === value);
10489
+ }
10490
+ function parseJobRunFilters(params) {
10491
+ return {
10492
+ kind: pick2(kinds, params.get("kind")),
10493
+ trigger: pick2(triggers, params.get("trigger"))
10494
+ };
10495
+ }
10080
10496
  function listUsageJobs(req, res) {
10081
- return respondPagedRows(
10082
- req,
10083
- res,
10084
- async (range) => listJobRuns(await getDb(), range)
10085
- );
10497
+ return respondPagedRows(req, res, async (range, params) => {
10498
+ const db = await getDb();
10499
+ await failTimedOutInboxScans(db);
10500
+ const [page, totals] = await Promise.all([
10501
+ listJobRuns(db, range, parseJobRunFilters(params)),
10502
+ jobRunTotals(db, new Date(Date.now() - TOTALS_WINDOW_MS))
10503
+ ]);
10504
+ return { ...page, totals };
10505
+ });
10086
10506
  }
10087
10507
 
10088
10508
  // src/commands/sessions/web/openInCode.ts
@@ -11020,7 +11440,7 @@ async function revertDiffFile(req, res) {
11020
11440
  }
11021
11441
 
11022
11442
  // src/commands/run/runCommandToCompletion.ts
11023
- import { spawn as spawn2 } from "child_process";
11443
+ import { spawn as spawn3 } from "child_process";
11024
11444
  import { existsSync as existsSync21 } from "fs";
11025
11445
 
11026
11446
  // src/shared/expandEnv.ts
@@ -11061,7 +11481,7 @@ function runCommandToCompletion(command, args, env, cwd, quiet) {
11061
11481
  });
11062
11482
  return;
11063
11483
  }
11064
- const child = spawn2(resolveCommand(command), args, {
11484
+ const child = spawn3(resolveCommand(command), args, {
11065
11485
  stdio: quiet ? "pipe" : "inherit",
11066
11486
  env: env ? { ...process.env, ...expandEnv(env) } : void 0,
11067
11487
  cwd
@@ -11847,10 +12267,10 @@ function currentRepoLabel(shared, origin) {
11847
12267
  }
11848
12268
 
11849
12269
  // src/shared/db/saveRepoConfig.ts
11850
- import { eq as eq28 } from "drizzle-orm";
12270
+ import { eq as eq31 } from "drizzle-orm";
11851
12271
  async function saveRepoConfig(orm, repoKey, config) {
11852
12272
  if (Object.keys(config).length === 0) {
11853
- await orm.delete(repoConfigs).where(eq28(repoConfigs.repoKey, repoKey));
12273
+ await orm.delete(repoConfigs).where(eq31(repoConfigs.repoKey, repoKey));
11854
12274
  return;
11855
12275
  }
11856
12276
  await orm.insert(repoConfigs).values({ repoKey, config }).onConflictDoUpdate({
@@ -11909,14 +12329,14 @@ async function applySharedRepoConfigSet(key, coerced, repoName, cwd = process.cw
11909
12329
  }
11910
12330
 
11911
12331
  // src/shared/db/updateUserConfig.ts
11912
- import { eq as eq29 } from "drizzle-orm";
12332
+ import { eq as eq32 } from "drizzle-orm";
11913
12333
  async function updateUserConfig(orm, update4) {
11914
12334
  return orm.transaction(async (tx) => {
11915
- const [row3] = await tx.select().from(userConfig).where(eq29(userConfig.id, 1)).for("update");
12335
+ const [row3] = await tx.select().from(userConfig).where(eq32(userConfig.id, 1)).for("update");
11916
12336
  const outcome = update4(row3?.config ?? {});
11917
12337
  if (!outcome.ok) return outcome;
11918
12338
  if (Object.keys(outcome.config).length === 0) {
11919
- await tx.delete(userConfig).where(eq29(userConfig.id, 1));
12339
+ await tx.delete(userConfig).where(eq32(userConfig.id, 1));
11920
12340
  return outcome;
11921
12341
  }
11922
12342
  await tx.insert(userConfig).values({ id: 1, config: outcome.config }).onConflictDoUpdate({
@@ -13628,8 +14048,8 @@ var options = [
13628
14048
  ];
13629
14049
 
13630
14050
  // src/commands/verify/init/getAvailableOptions.ts
13631
- function resolveDescription(desc8, setup) {
13632
- return typeof desc8 === "function" ? desc8(setup) : desc8;
14051
+ function resolveDescription(desc9, setup) {
14052
+ return typeof desc9 === "function" ? desc9(setup) : desc9;
13633
14053
  }
13634
14054
  function toVerifyOption(def, setup) {
13635
14055
  return {
@@ -14519,7 +14939,7 @@ function resolveEntries() {
14519
14939
  }
14520
14940
 
14521
14941
  // src/commands/verify/run/spawnCommand.ts
14522
- import { spawn as spawn3 } from "child_process";
14942
+ import { spawn as spawn4 } from "child_process";
14523
14943
  var verboseMode = false;
14524
14944
  function setVerbose(verbose) {
14525
14945
  verboseMode = verbose;
@@ -14529,7 +14949,7 @@ function shouldSuppress(quiet) {
14529
14949
  return !!quiet || !!process.env.CLAUDECODE;
14530
14950
  }
14531
14951
  function spawnCommand(fullCommand, cwd, env, quiet) {
14532
- return spawn3(fullCommand, [], {
14952
+ return spawn4(fullCommand, [], {
14533
14953
  stdio: shouldSuppress(quiet) ? "pipe" : "inherit",
14534
14954
  shell: true,
14535
14955
  cwd: cwd ?? process.cwd(),
@@ -14975,9 +15395,9 @@ async function activity(options2) {
14975
15395
  console.log("Not enough data points to chart.");
14976
15396
  return;
14977
15397
  }
14978
- const total2 = data.reduce((sum3, d) => sum3 + d.count, 0);
15398
+ const total3 = data.reduce((sum3, d) => sum3 + d.count, 0);
14979
15399
  const activeDays = data.filter((d) => d.count > 0).length;
14980
- console.log(`${total2} commits across ${activeDays} active days.`);
15400
+ console.log(`${total3} commits across ${activeDays} active days.`);
14981
15401
  const weekly = /* @__PURE__ */ new Map();
14982
15402
  for (const { date, count: count11 } of data) {
14983
15403
  const d = new Date(date);
@@ -15578,12 +15998,12 @@ function registerAsk(program) {
15578
15998
  import { randomUUID as randomUUID4 } from "crypto";
15579
15999
 
15580
16000
  // src/commands/sessions/shared/askCheckInputSchema.ts
15581
- import { z as z10 } from "zod";
15582
- var text17 = z10.string().trim().min(1);
15583
- var askCheckInputSchema = z10.object({
16001
+ import { z as z12 } from "zod";
16002
+ var text17 = z12.string().trim().min(1);
16003
+ var askCheckInputSchema = z12.object({
15584
16004
  title: text17,
15585
- steps: z10.array(text17).min(1, "Give at least 1 step"),
15586
- before: z10.array(text17).optional(),
16005
+ steps: z12.array(text17).min(1, "Give at least 1 step"),
16006
+ before: z12.array(text17).optional(),
15587
16007
  changed: text17.optional()
15588
16008
  });
15589
16009
  var CHECK_RESULT_KEY = "result";
@@ -15840,23 +16260,23 @@ function rejectLongQuestions(questions) {
15840
16260
  }
15841
16261
 
15842
16262
  // src/commands/sessions/shared/askQuestionInputSchema.ts
15843
- import { z as z11 } from "zod";
15844
- var askQuestionOptionSchema = z11.object({
15845
- label: z11.string().min(1),
15846
- description: z11.string(),
15847
- preview: z11.string().optional()
16263
+ import { z as z13 } from "zod";
16264
+ var askQuestionOptionSchema = z13.object({
16265
+ label: z13.string().min(1),
16266
+ description: z13.string(),
16267
+ preview: z13.string().optional()
15848
16268
  });
15849
- var askQuestionSchema = z11.object({
15850
- question: z11.string().min(1),
15851
- header: z11.string().min(1),
15852
- multiSelect: z11.boolean(),
15853
- options: z11.array(askQuestionOptionSchema).min(2, "Each question needs at least 2 options").max(4, "Each question allows at most 4 options").refine(
16269
+ var askQuestionSchema = z13.object({
16270
+ question: z13.string().min(1),
16271
+ header: z13.string().min(1),
16272
+ multiSelect: z13.boolean(),
16273
+ options: z13.array(askQuestionOptionSchema).min(2, "Each question needs at least 2 options").max(4, "Each question allows at most 4 options").refine(
15854
16274
  (options2) => new Set(options2.map((option) => option.label)).size === options2.length,
15855
16275
  "Option labels must be unique within a question"
15856
16276
  )
15857
16277
  });
15858
- var askQuestionInputSchema = z11.object({
15859
- questions: z11.array(askQuestionSchema).min(1, "Ask at least 1 question").max(4, "Ask at most 4 questions").refine(
16278
+ var askQuestionInputSchema = z13.object({
16279
+ questions: z13.array(askQuestionSchema).min(1, "Ask at least 1 question").max(4, "Ask at most 4 questions").refine(
15860
16280
  (questions) => new Set(questions.map((q) => q.question)).size === questions.length,
15861
16281
  "Question texts must be unique"
15862
16282
  )
@@ -16144,8 +16564,8 @@ async function buildDump(tables, copyOut) {
16144
16564
  // src/commands/backlog/dump/copyTableOut.ts
16145
16565
  import { to as copyTo } from "pg-copy-streams";
16146
16566
  async function copyTableOut(client, table) {
16147
- const sql32 = `COPY ${table.name} (${table.columns.join(", ")}) TO STDOUT`;
16148
- const stream = client.query(copyTo(sql32));
16567
+ const sql33 = `COPY ${table.name} (${table.columns.join(", ")}) TO STDOUT`;
16568
+ const stream = client.query(copyTo(sql33));
16149
16569
  const chunks = [];
16150
16570
  for await (const chunk of stream) {
16151
16571
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
@@ -16612,11 +17032,11 @@ function registerActivityCommands(cmd) {
16612
17032
 
16613
17033
  // src/commands/backlog/associateGithub.ts
16614
17034
  import chalk45 from "chalk";
16615
- import { eq as eq31 } from "drizzle-orm";
17035
+ import { eq as eq34 } from "drizzle-orm";
16616
17036
 
16617
17037
  // src/commands/backlog/beginAssociation.ts
16618
17038
  import chalk44 from "chalk";
16619
- import { eq as eq30 } from "drizzle-orm";
17039
+ import { eq as eq33 } from "drizzle-orm";
16620
17040
  async function beginAssociation(id, options2, clearPatch, label) {
16621
17041
  const found = await findOneItem(id);
16622
17042
  if (!found) {
@@ -16626,7 +17046,7 @@ async function beginAssociation(id, options2, clearPatch, label) {
16626
17046
  const { orm } = found;
16627
17047
  const itemId2 = found.item.id;
16628
17048
  if (options2.clear) {
16629
- await orm.update(items).set(clearPatch).where(eq30(items.id, itemId2));
17049
+ await orm.update(items).set(clearPatch).where(eq33(items.id, itemId2));
16630
17050
  console.log(
16631
17051
  chalk44.green(
16632
17052
  `Cleared ${label} association on item ${formatItemId(itemId2)}.`
@@ -16694,7 +17114,7 @@ async function associateGithub(id, issue, options2) {
16694
17114
  return;
16695
17115
  }
16696
17116
  const title = fetchGithubIssueTitle(normalized);
16697
- await orm.update(items).set({ githubIssue: normalized, jiraKey: null }).where(eq31(items.id, itemId2));
17117
+ await orm.update(items).set({ githubIssue: normalized, jiraKey: null }).where(eq34(items.id, itemId2));
16698
17118
  console.log(
16699
17119
  chalk45.green(`Associated ${normalized} with item ${formatItemId(itemId2)}.`),
16700
17120
  title ? chalk45.dim(`(${title})`) : ""
@@ -16708,7 +17128,7 @@ function registerAssociateGithubCommand(cmd) {
16708
17128
 
16709
17129
  // src/commands/backlog/associateJira.ts
16710
17130
  import chalk47 from "chalk";
16711
- import { eq as eq32 } from "drizzle-orm";
17131
+ import { eq as eq35 } from "drizzle-orm";
16712
17132
 
16713
17133
  // src/commands/jira/fetchIssue.ts
16714
17134
  import { execSync as execSync17 } from "child_process";
@@ -16773,7 +17193,7 @@ async function associateJira(id, key, options2) {
16773
17193
  const parsed = fetchIssue(normalized, "summary");
16774
17194
  const fields = parsed?.fields;
16775
17195
  const summary = fields?.summary;
16776
- await orm.update(items).set({ jiraKey: normalized, githubIssue: null }).where(eq32(items.id, itemId2));
17196
+ await orm.update(items).set({ jiraKey: normalized, githubIssue: null }).where(eq35(items.id, itemId2));
16777
17197
  console.log(
16778
17198
  chalk47.green(`Associated ${normalized} with item ${formatItemId(itemId2)}.`),
16779
17199
  summary ? chalk47.dim(`(${summary})`) : ""
@@ -17055,8 +17475,8 @@ async function confirmReplace(client, tables, incoming, fromStdin) {
17055
17475
  import { finished } from "stream/promises";
17056
17476
  import { from as copyFrom } from "pg-copy-streams";
17057
17477
  async function copyTableIn(client, table, data) {
17058
- const sql32 = `COPY ${table.name} (${table.columns.join(", ")}) FROM STDIN`;
17059
- const stream = client.query(copyFrom(sql32));
17478
+ const sql33 = `COPY ${table.name} (${table.columns.join(", ")}) FROM STDIN`;
17479
+ const stream = client.query(copyFrom(sql33));
17060
17480
  stream.end(data);
17061
17481
  await finished(stream);
17062
17482
  }
@@ -17131,10 +17551,10 @@ async function importBacklog(file, options2 = {}) {
17131
17551
  return;
17132
17552
  }
17133
17553
  await restore(client, parsed);
17134
- const total2 = incoming.reduce((sum3, n) => sum3 + n, 0);
17554
+ const total3 = incoming.reduce((sum3, n) => sum3 + n, 0);
17135
17555
  console.error(
17136
17556
  chalk54.green(
17137
- `Imported backlog: ${total2} rows restored across ${tables.length} tables.`
17557
+ `Imported backlog: ${total3} rows restored across ${tables.length} tables.`
17138
17558
  )
17139
17559
  );
17140
17560
  });
@@ -17304,9 +17724,9 @@ import chalk58 from "chalk";
17304
17724
 
17305
17725
  // src/commands/backlog/resolveInsertPosition.ts
17306
17726
  import chalk57 from "chalk";
17307
- import { count as count4, eq as eq33 } from "drizzle-orm";
17727
+ import { count as count5, eq as eq36 } from "drizzle-orm";
17308
17728
  async function resolveInsertPosition(orm, itemId2, position) {
17309
- const [row3] = await orm.select({ cnt: count4() }).from(planPhases).where(eq33(planPhases.itemId, itemId2));
17729
+ const [row3] = await orm.select({ cnt: count5() }).from(planPhases).where(eq36(planPhases.itemId, itemId2));
17310
17730
  const phaseCount = row3?.cnt ?? 0;
17311
17731
  if (position === void 0) return phaseCount;
17312
17732
  const pos = Number.parseInt(position, 10);
@@ -17489,21 +17909,21 @@ async function list(options2) {
17489
17909
  import chalk63 from "chalk";
17490
17910
 
17491
17911
  // src/commands/backlog/propose/proposedItemSchema.ts
17492
- import { z as z12 } from "zod";
17493
- var proposedPhaseSchema = z12.strictObject({
17494
- name: z12.string().trim().min(1, "phase name is required").refine(
17912
+ import { z as z14 } from "zod";
17913
+ var proposedPhaseSchema = z14.strictObject({
17914
+ name: z14.string().trim().min(1, "phase name is required").refine(
17495
17915
  (name) => name.toLowerCase() !== REVIEW_PHASE_NAME.toLowerCase(),
17496
17916
  `"${REVIEW_PHASE_NAME}" is owned by the runner and appended to every plan automatically \u2014 remove this phase`
17497
17917
  ),
17498
- tasks: z12.array(z12.string().trim().min(1)).min(1, "a phase needs at least one task"),
17499
- manualChecks: z12.array(z12.string().trim().min(1)).default([])
17918
+ tasks: z14.array(z14.string().trim().min(1)).min(1, "a phase needs at least one task"),
17919
+ manualChecks: z14.array(z14.string().trim().min(1)).default([])
17500
17920
  });
17501
- var proposedItemSchema = z12.strictObject({
17502
- name: z12.string().trim().min(1, "name is required"),
17503
- type: z12.enum(["story", "bug"]),
17504
- description: z12.string().optional(),
17505
- acceptanceCriteria: z12.array(z12.string().trim().min(1)).default([]),
17506
- phases: z12.array(proposedPhaseSchema).default([])
17921
+ var proposedItemSchema = z14.strictObject({
17922
+ name: z14.string().trim().min(1, "name is required"),
17923
+ type: z14.enum(["story", "bug"]),
17924
+ description: z14.string().optional(),
17925
+ acceptanceCriteria: z14.array(z14.string().trim().min(1)).default([]),
17926
+ phases: z14.array(proposedPhaseSchema).default([])
17507
17927
  });
17508
17928
 
17509
17929
  // src/commands/backlog/propose/readProposedItem.ts
@@ -17580,10 +18000,10 @@ async function reviewProposal(item, sessionId, confirmed, revises) {
17580
18000
  import chalk62 from "chalk";
17581
18001
 
17582
18002
  // src/commands/backlog/propose/reviseProposedItem.ts
17583
- import { eq as eq35 } from "drizzle-orm";
18003
+ import { eq as eq38 } from "drizzle-orm";
17584
18004
 
17585
18005
  // src/commands/backlog/updatePlan/replacePlan.ts
17586
- import { eq as eq34 } from "drizzle-orm";
18006
+ import { eq as eq37 } from "drizzle-orm";
17587
18007
 
17588
18008
  // src/commands/backlog/updatePlan/clampCurrentPhase.ts
17589
18009
  function clampCurrentPhase(currentPhase, phaseCount) {
@@ -17594,8 +18014,8 @@ function clampCurrentPhase(currentPhase, phaseCount) {
17594
18014
  // src/commands/backlog/updatePlan/replacePlan.ts
17595
18015
  async function replacePlan(orm, itemId2, phases, currentPhase) {
17596
18016
  await orm.transaction(async (tx) => {
17597
- await tx.delete(planTasks).where(eq34(planTasks.itemId, itemId2));
17598
- await tx.delete(planPhases).where(eq34(planPhases.itemId, itemId2));
18017
+ await tx.delete(planTasks).where(eq37(planTasks.itemId, itemId2));
18018
+ await tx.delete(planPhases).where(eq37(planPhases.itemId, itemId2));
17599
18019
  if (phases.length > 0) {
17600
18020
  await tx.insert(planPhases).values(
17601
18021
  phases.map((phase, idx) => ({
@@ -17613,7 +18033,7 @@ async function replacePlan(orm, itemId2, phases, currentPhase) {
17613
18033
  if (currentPhase === void 0) return;
17614
18034
  const clamped = clampCurrentPhase(currentPhase, phases.length);
17615
18035
  if (clamped === currentPhase) return;
17616
- await tx.update(items).set({ currentPhase: clamped }).where(eq34(items.id, itemId2));
18036
+ await tx.update(items).set({ currentPhase: clamped }).where(eq37(items.id, itemId2));
17617
18037
  });
17618
18038
  }
17619
18039
 
@@ -17623,14 +18043,14 @@ var BUG_DEFAULT_PLAN = [
17623
18043
  ];
17624
18044
  async function reviseProposedItem(itemId2, item) {
17625
18045
  const orm = await getDb();
17626
- const [existing] = await orm.select({ currentPhase: items.currentPhase }).from(items).where(eq35(items.id, itemId2));
18046
+ const [existing] = await orm.select({ currentPhase: items.currentPhase }).from(items).where(eq38(items.id, itemId2));
17627
18047
  if (!existing) return false;
17628
18048
  await orm.update(items).set({
17629
18049
  type: item.type,
17630
18050
  name: item.name,
17631
18051
  description: item.description || null,
17632
18052
  acceptanceCriteria: JSON.stringify(item.acceptanceCriteria)
17633
- }).where(eq35(items.id, itemId2));
18053
+ }).where(eq38(items.id, itemId2));
17634
18054
  const phases = item.phases.length > 0 || item.type !== "bug" ? item.phases : BUG_DEFAULT_PLAN;
17635
18055
  await replacePlan(orm, itemId2, phases, existing.currentPhase ?? void 0);
17636
18056
  return true;
@@ -17700,14 +18120,14 @@ function mutateLedger(path109, mutate) {
17700
18120
  }
17701
18121
 
17702
18122
  // src/commands/backlog/propose/findPredecessor.ts
17703
- var GRACE_MS = 5e3;
18123
+ var GRACE_MS2 = 5e3;
17704
18124
  var SIBLING_WAIT_MS = 5e3;
17705
18125
  var POLL_MS = 100;
17706
18126
  function knownPredecessor(path109, startedAt) {
17707
18127
  const { created } = readLedger(path109);
17708
18128
  if (!created) return void 0;
17709
18129
  if (created.startedAt > startedAt) return void 0;
17710
- if (created.at < startedAt - GRACE_MS) return void 0;
18130
+ if (created.at < startedAt - GRACE_MS2) return void 0;
17711
18131
  return created.itemId;
17712
18132
  }
17713
18133
  function hasOlderOpenSibling(path109, token, startedAt) {
@@ -17857,9 +18277,9 @@ function hasCycle(adjacency, fromId, toId) {
17857
18277
  }
17858
18278
 
17859
18279
  // src/commands/backlog/loadDependencyGraph.ts
17860
- import { eq as eq36 } from "drizzle-orm";
18280
+ import { eq as eq39 } from "drizzle-orm";
17861
18281
  async function loadDependencyGraph(orm) {
17862
- const rows = await orm.select({ itemId: links.itemId, targetId: links.targetId }).from(links).where(eq36(links.type, "depends-on"));
18282
+ const rows = await orm.select({ itemId: links.itemId, targetId: links.targetId }).from(links).where(eq39(links.type, "depends-on"));
17863
18283
  const graph = /* @__PURE__ */ new Map();
17864
18284
  for (const { itemId: itemId2, targetId } of rows) {
17865
18285
  const bucket = graph.get(itemId2);
@@ -17926,7 +18346,7 @@ async function link(fromId, toId, opts) {
17926
18346
 
17927
18347
  // src/commands/backlog/unlink.ts
17928
18348
  import chalk66 from "chalk";
17929
- import { and as and12, eq as eq37 } from "drizzle-orm";
18349
+ import { and as and15, eq as eq40 } from "drizzle-orm";
17930
18350
  async function unlink(fromId, toId) {
17931
18351
  const fromNum = parseItemId(fromId);
17932
18352
  const toNum = parseItemId(toId);
@@ -17950,7 +18370,7 @@ async function unlink(fromId, toId) {
17950
18370
  );
17951
18371
  return;
17952
18372
  }
17953
- await orm.delete(links).where(and12(eq37(links.itemId, fromNum), eq37(links.targetId, toNum)));
18373
+ await orm.delete(links).where(and15(eq40(links.itemId, fromNum), eq40(links.targetId, toNum)));
17954
18374
  console.log(
17955
18375
  chalk66.green(
17956
18376
  `Removed link from ${formatItemId(fromNum)} to ${formatItemId(toNum)}.`
@@ -17970,7 +18390,7 @@ function registerLinkCommands(cmd) {
17970
18390
 
17971
18391
  // src/commands/backlog/moveRepo.ts
17972
18392
  import chalk68 from "chalk";
17973
- import { eq as eq39 } from "drizzle-orm";
18393
+ import { eq as eq42 } from "drizzle-orm";
17974
18394
 
17975
18395
  // src/commands/backlog/move-repo/confirmMove.ts
17976
18396
  import chalk67 from "chalk";
@@ -17985,9 +18405,9 @@ async function confirmMove(cnt, oldOrigin, newOrigin) {
17985
18405
  }
17986
18406
 
17987
18407
  // src/commands/backlog/move-repo/countByOrigin.ts
17988
- import { count as count5, eq as eq38 } from "drizzle-orm";
18408
+ import { count as count6, eq as eq41 } from "drizzle-orm";
17989
18409
  async function countByOrigin(orm, origin) {
17990
- const [{ cnt }] = await orm.select({ cnt: count5() }).from(items).where(eq38(items.origin, origin));
18410
+ const [{ cnt }] = await orm.select({ cnt: count6() }).from(items).where(eq41(items.origin, origin));
17991
18411
  return cnt;
17992
18412
  }
17993
18413
 
@@ -18030,7 +18450,7 @@ async function moveRepo(oldOriginRaw, newOriginRaw, options2 = {}) {
18030
18450
  console.log(chalk68.yellow("Move cancelled; no changes made."));
18031
18451
  return;
18032
18452
  }
18033
- await orm.update(items).set({ origin: newOrigin }).where(eq39(items.origin, oldOrigin));
18453
+ await orm.update(items).set({ origin: newOrigin }).where(eq42(items.origin, oldOrigin));
18034
18454
  console.log(
18035
18455
  chalk68.green(
18036
18456
  `Moved ${pluralItems(cnt)} from "${oldOrigin}" to "${newOrigin}".`
@@ -18502,12 +18922,12 @@ function message(error) {
18502
18922
  import chalk72 from "chalk";
18503
18923
 
18504
18924
  // src/shared/db/findPhaseBySessionId.ts
18505
- import { and as and13, eq as eq40 } from "drizzle-orm";
18925
+ import { and as and16, eq as eq43 } from "drizzle-orm";
18506
18926
  async function findPhaseBySessionId(db, itemId2, claudeSessionId) {
18507
18927
  const rows = await db.select({ phaseIdx: phaseUsage.phaseIdx }).from(phaseUsage).where(
18508
- and13(
18509
- eq40(phaseUsage.itemId, itemId2),
18510
- eq40(phaseUsage.claudeSessionId, claudeSessionId)
18928
+ and16(
18929
+ eq43(phaseUsage.itemId, itemId2),
18930
+ eq43(phaseUsage.claudeSessionId, claudeSessionId)
18511
18931
  )
18512
18932
  ).limit(1);
18513
18933
  return rows[0]?.phaseIdx;
@@ -18645,14 +19065,14 @@ function ensureHooksSettings() {
18645
19065
  }
18646
19066
 
18647
19067
  // src/shared/spawnInherit.ts
18648
- import { spawn as spawn4 } from "child_process";
19068
+ import { spawn as spawn5 } from "child_process";
18649
19069
  function spawnInherit(command, args, options2 = {}) {
18650
19070
  const {
18651
19071
  ASSIST_ACTIVITY_ID: _activityId,
18652
19072
  CLAUDE_CODE_CHILD_SESSION: _childSession,
18653
19073
  ...env
18654
19074
  } = process.env;
18655
- const child = spawn4(command, args, {
19075
+ const child = spawn5(command, args, {
18656
19076
  stdio: "inherit",
18657
19077
  env: { ...env, ...options2.env },
18658
19078
  cwd: options2.cwd
@@ -19117,7 +19537,7 @@ import { randomUUID as randomUUID10 } from "crypto";
19117
19537
  import os4 from "os";
19118
19538
 
19119
19539
  // src/shared/db/recordPhaseSession.ts
19120
- import { sql as sql24 } from "drizzle-orm";
19540
+ import { sql as sql25 } from "drizzle-orm";
19121
19541
  async function recordPhaseSession(db, itemId2, phaseIdx, claudeSessionId, hostname2, osUser) {
19122
19542
  await db.insert(phaseSessions).values({ itemId: itemId2, phaseIdx, claudeSessionId, hostname: hostname2, osUser }).onConflictDoUpdate({
19123
19543
  target: [
@@ -19126,7 +19546,7 @@ async function recordPhaseSession(db, itemId2, phaseIdx, claudeSessionId, hostna
19126
19546
  phaseSessions.claudeSessionId
19127
19547
  ],
19128
19548
  set: { hostname: hostname2, osUser },
19129
- setWhere: sql24`${phaseSessions.hostname} = 'unknown'`
19549
+ setWhere: sql25`${phaseSessions.hostname} = 'unknown'`
19130
19550
  });
19131
19551
  }
19132
19552
 
@@ -19171,20 +19591,20 @@ async function persistPhaseSessionId(itemId2, phaseIdx, claudeSessionId) {
19171
19591
  import { mkdirSync as mkdirSync14, readFileSync as readFileSync27, rmSync as rmSync4, writeFileSync as writeFileSync23 } from "fs";
19172
19592
  import { homedir as homedir17 } from "os";
19173
19593
  import { dirname as dirname28, join as join51 } from "path";
19174
- import { z as z13 } from "zod";
19175
- var activitySchema = z13.object({
19176
- kind: z13.enum(["command", "backlog"]),
19177
- harness: z13.enum(["claude", "codex", "pi"]).optional(),
19178
- name: z13.string().optional(),
19179
- itemId: z13.number().optional(),
19180
- itemName: z13.string().optional(),
19181
- itemIds: z13.array(z13.number()).optional(),
19182
- phase: z13.number().optional(),
19183
- phaseName: z13.string().optional(),
19184
- totalPhases: z13.number().optional(),
19185
- claudeSessionId: z13.string().optional(),
19186
- watchState: z13.enum(["waiting", "updating"]).optional(),
19187
- startedAt: z13.number()
19594
+ import { z as z15 } from "zod";
19595
+ var activitySchema = z15.object({
19596
+ kind: z15.enum(["command", "backlog"]),
19597
+ harness: z15.enum(["claude", "codex", "pi"]).optional(),
19598
+ name: z15.string().optional(),
19599
+ itemId: z15.number().optional(),
19600
+ itemName: z15.string().optional(),
19601
+ itemIds: z15.array(z15.number()).optional(),
19602
+ phase: z15.number().optional(),
19603
+ phaseName: z15.string().optional(),
19604
+ totalPhases: z15.number().optional(),
19605
+ claudeSessionId: z15.string().optional(),
19606
+ watchState: z15.enum(["waiting", "updating"]).optional(),
19607
+ startedAt: z15.number()
19188
19608
  });
19189
19609
  function activityPath(sessionId) {
19190
19610
  return join51(homedir17(), ".assist", "activity", `activity-${sessionId}.json`);
@@ -20030,10 +20450,10 @@ async function start(id) {
20030
20450
 
20031
20451
  // src/commands/backlog/stop.ts
20032
20452
  import chalk96 from "chalk";
20033
- import { and as and14, eq as eq41 } from "drizzle-orm";
20453
+ import { and as and17, eq as eq44 } from "drizzle-orm";
20034
20454
  async function stop() {
20035
20455
  const { orm } = await getReady();
20036
- const stopped = await orm.update(items).set({ status: "todo", currentPhase: 1 }).where(and14(eq41(items.status, "in-progress"), eq41(items.origin, getOrigin()))).returning({ id: items.id, name: items.name });
20456
+ const stopped = await orm.update(items).set({ status: "todo", currentPhase: 1 }).where(and17(eq44(items.status, "in-progress"), eq44(items.origin, getOrigin()))).returning({ id: items.id, name: items.name });
20037
20457
  if (stopped.length === 0) {
20038
20458
  console.log(chalk96.yellow("No in-progress items to stop."));
20039
20459
  return;
@@ -20091,20 +20511,20 @@ function registerStatusCommands(cmd) {
20091
20511
 
20092
20512
  // src/commands/backlog/movePhase.ts
20093
20513
  import chalk99 from "chalk";
20094
- import { count as count7, eq as eq44 } from "drizzle-orm";
20514
+ import { count as count8, eq as eq47 } from "drizzle-orm";
20095
20515
 
20096
20516
  // src/commands/backlog/reorderPhaseRows.ts
20097
- import { and as and16, asc as asc11, eq as eq43 } from "drizzle-orm";
20517
+ import { and as and19, asc as asc11, eq as eq46 } from "drizzle-orm";
20098
20518
 
20099
20519
  // src/commands/backlog/reindexPhases.ts
20100
- import { and as and15, asc as asc10, count as count6, eq as eq42 } from "drizzle-orm";
20520
+ import { and as and18, asc as asc10, count as count7, eq as eq45 } from "drizzle-orm";
20101
20521
  async function reindexPhases(db, itemId2) {
20102
- const remaining = await db.select({ idx: planPhases.idx }).from(planPhases).where(eq42(planPhases.itemId, itemId2)).orderBy(asc10(planPhases.idx));
20522
+ const remaining = await db.select({ idx: planPhases.idx }).from(planPhases).where(eq45(planPhases.itemId, itemId2)).orderBy(asc10(planPhases.idx));
20103
20523
  for (let i = 0; i < remaining.length; i++) {
20104
20524
  const oldIdx = remaining[i].idx;
20105
20525
  if (oldIdx === i) continue;
20106
- await db.update(planTasks).set({ phaseIdx: i }).where(and15(eq42(planTasks.itemId, itemId2), eq42(planTasks.phaseIdx, oldIdx)));
20107
- await db.update(planPhases).set({ idx: i }).where(and15(eq42(planPhases.itemId, itemId2), eq42(planPhases.idx, oldIdx)));
20526
+ await db.update(planTasks).set({ phaseIdx: i }).where(and18(eq45(planTasks.itemId, itemId2), eq45(planTasks.phaseIdx, oldIdx)));
20527
+ await db.update(planPhases).set({ idx: i }).where(and18(eq45(planPhases.itemId, itemId2), eq45(planPhases.idx, oldIdx)));
20108
20528
  }
20109
20529
  }
20110
20530
  async function adjustCurrentPhase(db, item, removedIdx) {
@@ -20112,24 +20532,24 @@ async function adjustCurrentPhase(db, item, removedIdx) {
20112
20532
  if (currentPhase === void 0) return;
20113
20533
  const currentIdx = currentPhase - 1;
20114
20534
  if (removedIdx < currentIdx) {
20115
- await db.update(items).set({ currentPhase: currentPhase - 1 }).where(eq42(items.id, item.id));
20535
+ await db.update(items).set({ currentPhase: currentPhase - 1 }).where(eq45(items.id, item.id));
20116
20536
  return;
20117
20537
  }
20118
20538
  if (removedIdx !== currentIdx) return;
20119
- const [row3] = await db.select({ cnt: count6() }).from(planPhases).where(eq42(planPhases.itemId, item.id));
20539
+ const [row3] = await db.select({ cnt: count7() }).from(planPhases).where(eq45(planPhases.itemId, item.id));
20120
20540
  const cnt = row3?.cnt ?? 0;
20121
- await db.update(items).set({ currentPhase: cnt === 0 ? null : Math.min(currentPhase, cnt) }).where(eq42(items.id, item.id));
20541
+ await db.update(items).set({ currentPhase: cnt === 0 ? null : Math.min(currentPhase, cnt) }).where(eq45(items.id, item.id));
20122
20542
  }
20123
20543
 
20124
20544
  // src/commands/backlog/reorderPhaseRows.ts
20125
20545
  async function reorderPhaseRows(orm, itemId2, fromIdx, toIdx) {
20126
20546
  await orm.transaction(async (tx) => {
20127
- const [phaseRow] = await tx.select({ name: planPhases.name, manualChecks: planPhases.manualChecks }).from(planPhases).where(and16(eq43(planPhases.itemId, itemId2), eq43(planPhases.idx, fromIdx)));
20128
- const tasks = await tx.select({ idx: planTasks.idx, task: planTasks.task }).from(planTasks).where(and16(eq43(planTasks.itemId, itemId2), eq43(planTasks.phaseIdx, fromIdx))).orderBy(asc11(planTasks.idx));
20547
+ const [phaseRow] = await tx.select({ name: planPhases.name, manualChecks: planPhases.manualChecks }).from(planPhases).where(and19(eq46(planPhases.itemId, itemId2), eq46(planPhases.idx, fromIdx)));
20548
+ const tasks = await tx.select({ idx: planTasks.idx, task: planTasks.task }).from(planTasks).where(and19(eq46(planTasks.itemId, itemId2), eq46(planTasks.phaseIdx, fromIdx))).orderBy(asc11(planTasks.idx));
20129
20549
  await tx.delete(planTasks).where(
20130
- and16(eq43(planTasks.itemId, itemId2), eq43(planTasks.phaseIdx, fromIdx))
20550
+ and19(eq46(planTasks.itemId, itemId2), eq46(planTasks.phaseIdx, fromIdx))
20131
20551
  );
20132
- await tx.delete(planPhases).where(and16(eq43(planPhases.itemId, itemId2), eq43(planPhases.idx, fromIdx)));
20552
+ await tx.delete(planPhases).where(and19(eq46(planPhases.itemId, itemId2), eq46(planPhases.idx, fromIdx)));
20133
20553
  await reindexPhases(tx, itemId2);
20134
20554
  await shiftPhasesUp(tx, itemId2, toIdx);
20135
20555
  await tx.insert(planPhases).values({
@@ -20170,7 +20590,7 @@ async function movePhase(id, from, to) {
20170
20590
  if (!found) return;
20171
20591
  const { orm, item } = found;
20172
20592
  const itemId2 = item.id;
20173
- const [row3] = await orm.select({ cnt: count7() }).from(planPhases).where(eq44(planPhases.itemId, itemId2));
20593
+ const [row3] = await orm.select({ cnt: count8() }).from(planPhases).where(eq47(planPhases.itemId, itemId2));
20174
20594
  const phaseCount = row3?.cnt ?? 0;
20175
20595
  const fromIdx = toIndex2(from, phaseCount);
20176
20596
  if (fromIdx === void 0) return;
@@ -20186,22 +20606,22 @@ async function movePhase(id, from, to) {
20186
20606
  import chalk101 from "chalk";
20187
20607
 
20188
20608
  // src/commands/backlog/applyPhaseUpdate.ts
20189
- import { and as and17, eq as eq45 } from "drizzle-orm";
20609
+ import { and as and20, eq as eq48 } from "drizzle-orm";
20190
20610
  async function applyPhaseUpdate(orm, itemId2, phaseIdx, fields) {
20191
20611
  await orm.transaction(async (tx) => {
20192
20612
  if (fields.name) {
20193
20613
  await tx.update(planPhases).set({ name: fields.name }).where(
20194
- and17(eq45(planPhases.itemId, itemId2), eq45(planPhases.idx, phaseIdx))
20614
+ and20(eq48(planPhases.itemId, itemId2), eq48(planPhases.idx, phaseIdx))
20195
20615
  );
20196
20616
  }
20197
20617
  if (fields.manualCheck) {
20198
20618
  await tx.update(planPhases).set({ manualChecks: JSON.stringify(fields.manualCheck) }).where(
20199
- and17(eq45(planPhases.itemId, itemId2), eq45(planPhases.idx, phaseIdx))
20619
+ and20(eq48(planPhases.itemId, itemId2), eq48(planPhases.idx, phaseIdx))
20200
20620
  );
20201
20621
  }
20202
20622
  if (fields.task) {
20203
20623
  await tx.delete(planTasks).where(
20204
- and17(eq45(planTasks.itemId, itemId2), eq45(planTasks.phaseIdx, phaseIdx))
20624
+ and20(eq48(planTasks.itemId, itemId2), eq48(planTasks.phaseIdx, phaseIdx))
20205
20625
  );
20206
20626
  if (fields.task.length) {
20207
20627
  await tx.insert(planTasks).values(
@@ -20219,14 +20639,14 @@ async function applyPhaseUpdate(orm, itemId2, phaseIdx, fields) {
20219
20639
 
20220
20640
  // src/commands/backlog/findPhase.ts
20221
20641
  import chalk100 from "chalk";
20222
- import { and as and18, count as count8, eq as eq46 } from "drizzle-orm";
20642
+ import { and as and21, count as count9, eq as eq49 } from "drizzle-orm";
20223
20643
  async function findPhase(id, phase) {
20224
20644
  const found = await findOneItem(id);
20225
20645
  if (!found) return void 0;
20226
20646
  const { orm, item } = found;
20227
20647
  const itemId2 = item.id;
20228
20648
  const phaseIdx = Number.parseInt(phase, 10) - 1;
20229
- const [row3] = await orm.select({ cnt: count8() }).from(planPhases).where(and18(eq46(planPhases.itemId, itemId2), eq46(planPhases.idx, phaseIdx)));
20649
+ const [row3] = await orm.select({ cnt: count9() }).from(planPhases).where(and21(eq49(planPhases.itemId, itemId2), eq49(planPhases.idx, phaseIdx)));
20230
20650
  if (!row3 || row3.cnt === 0) {
20231
20651
  console.log(
20232
20652
  chalk100.red(
@@ -20399,16 +20819,16 @@ function registerUpdatePhaseCommand(cmd) {
20399
20819
 
20400
20820
  // src/commands/backlog/removePhase.ts
20401
20821
  import chalk102 from "chalk";
20402
- import { and as and19, eq as eq47 } from "drizzle-orm";
20822
+ import { and as and22, eq as eq50 } from "drizzle-orm";
20403
20823
  async function removePhase(id, phase) {
20404
20824
  const found = await findPhase(id, phase);
20405
20825
  if (!found) return;
20406
20826
  const { item, orm, itemId: itemId2, phaseIdx } = found;
20407
20827
  await orm.transaction(async (tx) => {
20408
20828
  await tx.delete(planTasks).where(
20409
- and19(eq47(planTasks.itemId, itemId2), eq47(planTasks.phaseIdx, phaseIdx))
20829
+ and22(eq50(planTasks.itemId, itemId2), eq50(planTasks.phaseIdx, phaseIdx))
20410
20830
  );
20411
- await tx.delete(planPhases).where(and19(eq47(planPhases.itemId, itemId2), eq47(planPhases.idx, phaseIdx)));
20831
+ await tx.delete(planPhases).where(and22(eq50(planPhases.itemId, itemId2), eq50(planPhases.idx, phaseIdx)));
20412
20832
  await reindexPhases(tx, itemId2);
20413
20833
  await adjustCurrentPhase(tx, item, phaseIdx);
20414
20834
  });
@@ -20421,13 +20841,13 @@ async function removePhase(id, phase) {
20421
20841
 
20422
20842
  // src/commands/backlog/update/update.ts
20423
20843
  import chalk106 from "chalk";
20424
- import { eq as eq48 } from "drizzle-orm";
20844
+ import { eq as eq51 } from "drizzle-orm";
20425
20845
 
20426
20846
  // src/commands/backlog/update/buildUpdateValues.ts
20427
20847
  import chalk103 from "chalk";
20428
20848
  function buildUpdateValues(options2) {
20429
- const { name, desc: desc8, type, ac, origin } = options2;
20430
- if (!name && !desc8 && !type && !ac && !origin) {
20849
+ const { name, desc: desc9, type, ac, origin } = options2;
20850
+ if (!name && !desc9 && !type && !ac && !origin) {
20431
20851
  console.log(chalk103.red("Nothing to update. Provide at least one flag."));
20432
20852
  process.exitCode = 1;
20433
20853
  return void 0;
@@ -20443,8 +20863,8 @@ function buildUpdateValues(options2) {
20443
20863
  set.name = name;
20444
20864
  fieldNames.push("name");
20445
20865
  }
20446
- if (desc8) {
20447
- set.description = desc8.replaceAll(String.raw`\n`, "\n");
20866
+ if (desc9) {
20867
+ set.description = desc9.replaceAll(String.raw`\n`, "\n");
20448
20868
  fieldNames.push("description");
20449
20869
  }
20450
20870
  if (type) {
@@ -20532,7 +20952,7 @@ async function update(id, options2) {
20532
20952
  if (!built) return;
20533
20953
  const { orm } = found;
20534
20954
  const itemId2 = found.item.id;
20535
- await orm.update(items).set(built.set).where(eq48(items.id, itemId2));
20955
+ await orm.update(items).set(built.set).where(eq51(items.id, itemId2));
20536
20956
  console.log(
20537
20957
  chalk106.green(`Updated ${built.fields} on item ${formatItemId(itemId2)}.`)
20538
20958
  );
@@ -20567,9 +20987,9 @@ function registerUpdateFieldCommand(cmd) {
20567
20987
  import chalk108 from "chalk";
20568
20988
 
20569
20989
  // src/commands/backlog/updatePlan/planUpdateSchema.ts
20570
- import { z as z14 } from "zod";
20571
- var planUpdateSchema = z14.strictObject({
20572
- phases: z14.array(proposedPhaseSchema).min(1, "a plan needs at least one phase")
20990
+ import { z as z16 } from "zod";
20991
+ var planUpdateSchema = z16.strictObject({
20992
+ phases: z16.array(proposedPhaseSchema).min(1, "a plan needs at least one phase")
20573
20993
  });
20574
20994
 
20575
20995
  // src/commands/backlog/updatePlan/readPlanUpdate.ts
@@ -21164,21 +21584,21 @@ function registerBranch(program) {
21164
21584
  import { basename as basename15 } from "path";
21165
21585
 
21166
21586
  // src/commands/backlog/isDocsLocked.ts
21167
- import { and as and20, eq as eq49, notInArray as notInArray2, sql as sql25 } from "drizzle-orm";
21587
+ import { and as and23, eq as eq52, notInArray as notInArray2, sql as sql26 } from "drizzle-orm";
21168
21588
  async function isDocsRefreshItem(itemId2) {
21169
21589
  const orm = await getDb();
21170
- const [row3] = await orm.select({ itemId: links.itemId }).from(links).where(and20(eq49(links.itemId, itemId2), eq49(links.type, "docs-refresh"))).limit(1);
21590
+ const [row3] = await orm.select({ itemId: links.itemId }).from(links).where(and23(eq52(links.itemId, itemId2), eq52(links.type, "docs-refresh"))).limit(1);
21171
21591
  return row3 !== void 0;
21172
21592
  }
21173
21593
  async function hasOpenDocsUnlock(itemId2) {
21174
21594
  const orm = await getDb();
21175
- const [row3] = await orm.select({ itemId: itemGitRefs.itemId }).from(itemGitRefs).innerJoin(items, eq49(items.id, itemGitRefs.itemId)).where(
21176
- and20(
21177
- eq49(itemGitRefs.itemId, itemId2),
21178
- eq49(itemGitRefs.kind, "docs-unlock"),
21179
- eq49(
21595
+ const [row3] = await orm.select({ itemId: itemGitRefs.itemId }).from(itemGitRefs).innerJoin(items, eq52(items.id, itemGitRefs.itemId)).where(
21596
+ and23(
21597
+ eq52(itemGitRefs.itemId, itemId2),
21598
+ eq52(itemGitRefs.kind, "docs-unlock"),
21599
+ eq52(
21180
21600
  itemGitRefs.ref,
21181
- sql25`'phase-' || coalesce(${items.currentPhase}, 1)`
21601
+ sql26`'phase-' || coalesce(${items.currentPhase}, 1)`
21182
21602
  ),
21183
21603
  notInArray2(items.status, ["done", "wontdo"])
21184
21604
  )
@@ -22842,7 +23262,7 @@ import { randomUUID as randomUUID13 } from "crypto";
22842
23262
  import notifier from "node-notifier";
22843
23263
 
22844
23264
  // src/commands/notify/showNotification/showWindowsNotificationFromWsl.ts
22845
- import { spawn as spawn5 } from "child_process";
23265
+ import { spawn as spawn6 } from "child_process";
22846
23266
  import fs15 from "fs";
22847
23267
  import { createRequire as createRequire2 } from "module";
22848
23268
  import path30 from "path";
@@ -22862,7 +23282,7 @@ function showWindowsNotificationFromWsl(options2) {
22862
23282
  if (sound) {
22863
23283
  args.push("-s", "ms-winsoundevent:Notification.Default");
22864
23284
  }
22865
- const child = spawn5(snoreToastPath, args, {
23285
+ const child = spawn6(snoreToastPath, args, {
22866
23286
  detached: true,
22867
23287
  stdio: "ignore"
22868
23288
  });
@@ -24138,10 +24558,10 @@ async function sloc(pattern2 = "**/*.ts", options2 = {}) {
24138
24558
  const color = exceedsThreshold ? chalk128.red : chalk128.white;
24139
24559
  console.log(`${color(file)} \u2192 ${chalk128.cyan(lines2)} lines`);
24140
24560
  }
24141
- const total2 = results.reduce((sum3, r) => sum3 + r.lines, 0);
24561
+ const total3 = results.reduce((sum3, r) => sum3 + r.lines, 0);
24142
24562
  console.log(
24143
24563
  chalk128.dim(`
24144
- Total: ${total2} lines across ${files.length} files`)
24564
+ Total: ${total3} lines across ${files.length} files`)
24145
24565
  );
24146
24566
  if (hasViolation) {
24147
24567
  process.exit(1);
@@ -24545,8 +24965,8 @@ function matching(filter) {
24545
24965
  const needle = filter.toLowerCase();
24546
24966
  return (leaf) => leaf.key.toLowerCase().includes(needle);
24547
24967
  }
24548
- function headline(shown, total2, filter) {
24549
- return filter ? chalk138.bold(`${shown} of ${total2} config keys matching "${filter}"`) : chalk138.bold(`${total2} config keys`);
24968
+ function headline(shown, total3, filter) {
24969
+ return filter ? chalk138.bold(`${shown} of ${total3} config keys matching "${filter}"`) : chalk138.bold(`${total3} config keys`);
24550
24970
  }
24551
24971
  function formatLeaf(leaf, help) {
24552
24972
  const meta = [typeText(leaf), `default: ${formatConfigDefault(leaf)}`];
@@ -24783,15 +25203,15 @@ function registerConfig(program) {
24783
25203
  import chalk146 from "chalk";
24784
25204
 
24785
25205
  // src/commands/browser/formatInspectMatches.ts
24786
- function formatInspectMatches({ matches, total: total2 }, query) {
24787
- if (total2 === 0) return [`no elements match ${query}`];
25206
+ function formatInspectMatches({ matches, total: total3 }, query) {
25207
+ if (total3 === 0) return [`no elements match ${query}`];
24788
25208
  const lines2 = matches.flatMap((match, index3) => [
24789
- `[${index3 + 1}/${total2}] ${match.width}\xD7${match.height} ${JSON.stringify(match.text)}`,
25209
+ `[${index3 + 1}/${total3}] ${match.width}\xD7${match.height} ${JSON.stringify(match.text)}`,
24790
25210
  ...match.chain.map((step3) => ` ${step3}`)
24791
25211
  ]);
24792
- if (total2 > matches.length)
25212
+ if (total3 > matches.length)
24793
25213
  lines2.push(
24794
- `showing the first ${matches.length} of ${total2} matches; narrow the query to see the rest`
25214
+ `showing the first ${matches.length} of ${total3} matches; narrow the query to see the rest`
24795
25215
  );
24796
25216
  return lines2;
24797
25217
  }
@@ -26020,30 +26440,30 @@ import { dirname as dirname31, join as join70 } from "path";
26020
26440
  import chalk163 from "chalk";
26021
26441
 
26022
26442
  // src/commands/devlog/write/devEntryInputSchema.ts
26023
- import { z as z15 } from "zod";
26024
- var oneLine = z15.string().trim().min(1).refine((value) => !value.includes("\n"), "must be a single line");
26025
- var isoDate = z15.string().regex(/^\d{4}-\d{2}-\d{2}$/, "must be a date like 2026-08-10");
26443
+ import { z as z17 } from "zod";
26444
+ var oneLine = z17.string().trim().min(1).refine((value) => !value.includes("\n"), "must be a single line");
26445
+ var isoDate = z17.string().regex(/^\d{4}-\d{2}-\d{2}$/, "must be a date like 2026-08-10");
26026
26446
  var MAX_ITEM_LENGTH = 80;
26027
26447
  var itemText = oneLine.refine(
26028
26448
  (value) => value.length <= MAX_ITEM_LENGTH,
26029
26449
  `must be a short changelog phrase (at most ${MAX_ITEM_LENGTH} characters)`
26030
26450
  );
26031
- var changeItems = z15.array(z15.object({ text: itemText, version: oneLine.optional() }).strict()).default([]);
26451
+ var changeItems = z17.array(z17.object({ text: itemText, version: oneLine.optional() }).strict()).default([]);
26032
26452
  function datesWithinWeek(week, dates) {
26033
26453
  if (!isValidWeek(week)) return true;
26034
26454
  const { start: start2, end } = isoWeekRange(week);
26035
26455
  return start2 <= dates.first && dates.first <= dates.last && dates.last <= end;
26036
26456
  }
26037
- var devEntryInputSchema = z15.object({
26038
- week: z15.string().refine(isValidWeek, "must be an ISO week like 2026-W33"),
26457
+ var devEntryInputSchema = z17.object({
26458
+ week: z17.string().refine(isValidWeek, "must be an ISO week like 2026-W33"),
26039
26459
  title: oneLine,
26040
- dates: z15.object({ first: isoDate, last: isoDate }).strict(),
26041
- versions: z15.object({ first: oneLine, last: oneLine }).strict().optional(),
26460
+ dates: z17.object({ first: isoDate, last: isoDate }).strict(),
26461
+ versions: z17.object({ first: oneLine, last: oneLine }).strict().optional(),
26042
26462
  aiGenerated: oneLine,
26043
26463
  added: changeItems,
26044
26464
  changed: changeItems,
26045
26465
  fixed: changeItems,
26046
- lede: z15.string().trim().min(1)
26466
+ lede: z17.string().trim().min(1)
26047
26467
  }).strict().refine((entry) => datesWithinWeek(entry.week, entry.dates), {
26048
26468
  message: "first and last must be in order and within the week",
26049
26469
  path: ["dates"]
@@ -28223,7 +28643,7 @@ function buildFixStructurePlan(issues, options2) {
28223
28643
  tooDeep,
28224
28644
  typeChangeCount: entries.filter((entry) => entry.typeChange).length,
28225
28645
  labelRemovalCount: entries.reduce(
28226
- (total2, entry) => total2 + entry.labelRemovals.length,
28646
+ (total3, entry) => total3 + entry.labelRemovals.length,
28227
28647
  0
28228
28648
  )
28229
28649
  };
@@ -29803,11 +30223,6 @@ function formatScanCost(costUsd) {
29803
30223
  return `$${costUsd.toFixed(2)}`;
29804
30224
  }
29805
30225
 
29806
- // src/commands/inbox/scanUsageTokens.ts
29807
- function scanUsageTokens(usage) {
29808
- return usage.input + usage.output + usage.cacheRead + (usage.cacheWrite ?? 0);
29809
- }
29810
-
29811
30226
  // src/commands/inbox/formatScanUsage.ts
29812
30227
  function formatScanUsage(usage) {
29813
30228
  const tokens = `${formatTokens(scanUsageTokens(usage))} tokens`;
@@ -29829,357 +30244,10 @@ async function writeInboxLastScan(orm, at2) {
29829
30244
  await orm.insert(metadata).values({ key: INBOX_LAST_SCAN_KEY, value }).onConflictDoUpdate({ target: metadata.key, set: { value } });
29830
30245
  }
29831
30246
 
29832
- // src/commands/inbox/runInboxScanClaude.ts
29833
- import { spawn as spawn6 } from "child_process";
29834
- import { z as z17 } from "zod";
29835
-
29836
- // src/commands/review/attachLineParser.ts
29837
- function flushBuffer(buffer, onLine) {
29838
- let remaining = buffer;
29839
- while (true) {
29840
- const idx = remaining.indexOf("\n");
29841
- if (idx === -1) return remaining;
29842
- const line = remaining.slice(0, idx);
29843
- remaining = remaining.slice(idx + 1);
29844
- if (line.trim()) onLine(line);
29845
- }
29846
- }
29847
- function attachLineParser(child, onLine) {
29848
- let buffer = "";
29849
- child.stdout?.on("data", (chunk) => {
29850
- buffer += chunk.toString("utf8");
29851
- buffer = flushBuffer(buffer, onLine);
29852
- });
29853
- return () => {
29854
- if (buffer.trim()) onLine(buffer);
29855
- };
29856
- }
29857
-
29858
- // src/commands/review/attachStderrCollector.ts
29859
- function attachStderrCollector(child) {
29860
- const state = { value: "" };
29861
- child.stderr?.on("data", (chunk) => {
29862
- state.value += chunk.toString("utf8");
29863
- });
29864
- return state;
29865
- }
29866
-
29867
- // src/commands/inbox/buildInboxScanPrompt.ts
29868
- function buildInboxScanPrompt(since) {
29869
- const sinceUnix = Math.floor(since.getTime() / 1e3);
29870
- return [
29871
- "Triage my Gmail and Slack for messages a person wrote to me that look like they need my reply.",
29872
- "You are read-only: never label, mark read, react to, reply to or otherwise change any message.",
29873
- "",
29874
- "Gmail:",
29875
- '- Call search_threads with query "in:inbox is:unread" (page through all results).',
29876
- "- Call get_thread with messageFormat PLAIN_TEXT on each thread.",
29877
- "- Consider the latest unread message in each thread.",
29878
- "",
29879
- `Slack (only messages since ${since.toISOString()}, unix ${sinceUnix}):`,
29880
- `- Call slack_search_public_and_private with filters "is:dm" and after "${sinceUnix}".`,
29881
- `- Call slack_search_public_and_private with keywords ["<@MY_USER_ID>"] and after "${sinceUnix}", where MY_USER_ID is the logged-in user id from the tool description.`,
29882
- "- Skip messages I wrote myself.",
29883
- "- For a message in a thread, call slack_read_thread and skip it if I have replied in that thread after it.",
29884
- "",
29885
- "Do not flag anything from bots, apps, automated or notification systems (CI, calendars, ticketing, monitoring, no-reply addresses), newsletters or mailing lists.",
29886
- "Flag only messages a human wrote that ask me something, request something of me, or otherwise expect my response.",
29887
- "",
29888
- "For each flagged message return:",
29889
- '- source: "gmail" or "slack"',
29890
- "- messageId: the Gmail message id, or for Slack <channel_id>:<message ts>",
29891
- "- sender: the sender's name",
29892
- "- summary: one sentence on what they need from me",
29893
- "- link: the Gmail message viewUrl or the Slack permalink",
29894
- "- receivedAt: when it was sent, as an ISO 8601 timestamp",
29895
- "",
29896
- "Return an empty messages array when nothing needs a reply."
29897
- ].join("\n");
29898
- }
29899
-
29900
- // src/commands/inbox/describeInboxScanTool.ts
29901
- function pick(input, keys) {
29902
- return keys.map((key) => input[key]).filter(
29903
- (value) => typeof value === "string" || typeof value === "number"
29904
- ).map(String);
29905
- }
29906
- function toolLabel(name) {
29907
- const match = name.match(/^mcp__claude_ai_([^_]+)__(?:slack_)?(.+)$/);
29908
- return match ? `${match[1]} ${match[2]}` : name;
29909
- }
29910
- function describeInboxScanTool(name, input) {
29911
- const record = input && typeof input === "object" ? input : {};
29912
- const detail = pick(record, [
29913
- "query",
29914
- "thread_id",
29915
- "threadId",
29916
- "channel_id",
29917
- "message_ts"
29918
- ]).join(" ");
29919
- return { label: toolLabel(name), detail };
29920
- }
29921
-
29922
- // src/commands/inbox/assistantScanEvents.ts
29923
- var MAX_TEXT = 500;
29924
- function truncate(text20) {
29925
- const trimmed = text20.trim();
29926
- return trimmed.length <= MAX_TEXT ? trimmed : `${trimmed.slice(0, MAX_TEXT - 1)}\u2026`;
29927
- }
29928
- function blockEvent(block) {
29929
- if (block.type === "tool_use") {
29930
- const name = typeof block.name === "string" ? block.name : "tool";
29931
- return { kind: "tool", ...describeInboxScanTool(name, block.input) };
29932
- }
29933
- if (block.type === "text" && typeof block.text === "string" && block.text.trim())
29934
- return { kind: "text", label: "Assistant", detail: truncate(block.text) };
29935
- return void 0;
29936
- }
29937
- function assistantScanEvents(content) {
29938
- if (!Array.isArray(content)) return [];
29939
- const at2 = (/* @__PURE__ */ new Date()).toISOString();
29940
- return content.map(blockEvent).filter((event) => event !== void 0).map((event) => ({ at: at2, ...event }));
29941
- }
29942
-
29943
- // src/commands/review/parseTokenUsage.ts
29944
- function count9(value) {
29945
- return typeof value === "number" ? value : 0;
29946
- }
29947
- function parseTokenUsage(usage, keys) {
29948
- if (typeof usage !== "object" || usage === null) return void 0;
29949
- const raw = usage;
29950
- const parsed = {
29951
- input: count9(raw.input_tokens),
29952
- output: count9(raw.output_tokens),
29953
- cacheRead: count9(raw[keys.cacheRead])
29954
- };
29955
- if (keys.cacheWrite) parsed.cacheWrite = count9(raw[keys.cacheWrite]);
29956
- return parsed;
29957
- }
29958
-
29959
- // src/commands/review/parseClaudeUsage.ts
29960
- function parseClaudeUsage(usage) {
29961
- return parseTokenUsage(usage, {
29962
- cacheRead: "cache_read_input_tokens",
29963
- cacheWrite: "cache_creation_input_tokens"
29964
- });
29965
- }
29966
-
29967
- // src/commands/inbox/emptyScanUsage.ts
29968
- function emptyScanUsage() {
29969
- return {
29970
- input: 0,
29971
- output: 0,
29972
- cacheRead: 0,
29973
- cacheWrite: 0,
29974
- costUsd: null,
29975
- durationMs: null
29976
- };
29977
- }
29978
-
29979
- // src/commands/inbox/createScanUsageTracker.ts
29980
- var numberOrNull = (value) => typeof value === "number" ? value : null;
29981
- function createScanUsageTracker() {
29982
- const usage = emptyScanUsage();
29983
- const turns = /* @__PURE__ */ new Map();
29984
- let unsettled = 0;
29985
- return {
29986
- current: () => ({ ...usage }),
29987
- // stream-json repeats a message's usage on every content-block line, so
29988
- // each turn is counted once by message id, applying only the change.
29989
- addTurn(id, raw) {
29990
- const parsed = parseClaudeUsage(raw);
29991
- if (!parsed) return false;
29992
- const key = typeof id === "string" ? id : `turn-${turns.size}`;
29993
- const previous = turns.get(key);
29994
- turns.set(key, parsed);
29995
- usage.input += parsed.input - (previous?.input ?? 0);
29996
- usage.output += parsed.output - (previous?.output ?? 0);
29997
- usage.cacheRead += parsed.cacheRead - (previous?.cacheRead ?? 0);
29998
- usage.cacheWrite += (parsed.cacheWrite ?? 0) - (previous?.cacheWrite ?? 0);
29999
- unsettled += scanUsageTokens(parsed) - (previous ? scanUsageTokens(previous) : 0);
30000
- return true;
30001
- },
30002
- takeTurnTokens() {
30003
- const tokens = unsettled;
30004
- unsettled = 0;
30005
- return tokens > 0 ? tokens : void 0;
30006
- },
30007
- finish(result) {
30008
- usage.costUsd = numberOrNull(result.total_cost_usd);
30009
- usage.durationMs = numberOrNull(result.duration_ms);
30010
- }
30011
- };
30012
- }
30013
-
30014
- // src/commands/inbox/inboxScanSchema.ts
30015
- import { z as z16 } from "zod";
30016
- var flaggedMessageSchema = z16.object({
30017
- source: z16.enum(["gmail", "slack"]),
30018
- messageId: z16.string().min(1),
30019
- sender: z16.string().min(1),
30020
- summary: z16.string().min(1),
30021
- link: z16.string().min(1),
30022
- receivedAt: z16.string().optional()
30023
- });
30024
- var inboxScanSchema = z16.object({
30025
- messages: z16.array(flaggedMessageSchema)
30026
- });
30027
-
30028
- // src/commands/inbox/parseInboxScanOutput.ts
30029
- function parseInboxScanOutput(stdout) {
30030
- const result = JSON.parse(stdout);
30031
- if (result.is_error)
30032
- throw new Error(`Inbox scan failed: ${result.result ?? "unknown error"}`);
30033
- return inboxScanSchema.parse(result.structured_output).messages;
30034
- }
30035
-
30036
- // src/commands/inbox/parseScanStreamLine.ts
30037
- function parseScanStreamLine(line) {
30038
- try {
30039
- return JSON.parse(line);
30040
- } catch {
30041
- return void 0;
30042
- }
30043
- }
30044
-
30045
- // src/commands/inbox/createInboxScanParser.ts
30046
- function createInboxScanParser({
30047
- onEvent = () => {
30048
- },
30049
- onUsage = () => {
30050
- },
30051
- onModel = () => {
30052
- }
30053
- } = {}) {
30054
- const usage = createScanUsageTracker();
30055
- let resultLine;
30056
- const onAssistant = (message3) => {
30057
- const counted = usage.addTurn(message3?.id, message3?.usage);
30058
- for (const scanEvent of assistantScanEvents(message3?.content)) {
30059
- const tokens = usage.takeTurnTokens();
30060
- onEvent(tokens === void 0 ? scanEvent : { ...scanEvent, tokens });
30061
- }
30062
- if (counted) onUsage(usage.current());
30063
- };
30064
- return {
30065
- onLine(line) {
30066
- const event = parseScanStreamLine(line);
30067
- if (!event) return;
30068
- if (event.type === "system" && typeof event.model === "string")
30069
- onModel(event.model);
30070
- else if (event.type === "assistant") onAssistant(event.message);
30071
- else if (event.type === "result") {
30072
- resultLine = line;
30073
- usage.finish(event);
30074
- onUsage(usage.current());
30075
- }
30076
- },
30077
- finish(failure) {
30078
- if (!resultLine) throw new Error(`Inbox scan failed: ${failure}`);
30079
- return {
30080
- messages: parseInboxScanOutput(resultLine),
30081
- usage: usage.current()
30082
- };
30083
- }
30084
- };
30085
- }
30086
-
30087
- // src/commands/inbox/inboxScanTools.ts
30088
- var gmail = (tool) => `mcp__claude_ai_Gmail__${tool}`;
30089
- var slack = (tool) => `mcp__claude_ai_Slack__${tool}`;
30090
- var inboxScanTools = {
30091
- allowed: [
30092
- gmail("search_threads"),
30093
- gmail("get_thread"),
30094
- slack("slack_search_public_and_private"),
30095
- slack("slack_read_thread")
30096
- ],
30097
- denied: [
30098
- ...[
30099
- "apply_sensitive_message_label",
30100
- "apply_sensitive_thread_label",
30101
- "create_draft",
30102
- "create_label",
30103
- "delete_draft",
30104
- "delete_label",
30105
- "forward",
30106
- "label_message",
30107
- "label_thread",
30108
- "mark_message_spam",
30109
- "mark_thread_spam",
30110
- "reply",
30111
- "send_message",
30112
- "trash_message",
30113
- "trash_thread",
30114
- "unlabel_message",
30115
- "unlabel_thread",
30116
- "unmark_message_spam",
30117
- "unmark_thread_spam",
30118
- "untrash_message",
30119
- "untrash_thread",
30120
- "update_draft",
30121
- "update_label",
30122
- "update_message_labels"
30123
- ].map(gmail),
30124
- ...[
30125
- "slack_add_reaction",
30126
- "slack_create_canvas",
30127
- "slack_create_conversation",
30128
- "slack_schedule_message",
30129
- "slack_send_message",
30130
- "slack_send_message_draft",
30131
- "slack_update_canvas"
30132
- ].map(slack)
30133
- ]
30134
- };
30135
-
30136
- // src/commands/inbox/runInboxScanClaude.ts
30137
- function buildInboxScanArgs(since) {
30138
- return [
30139
- "-p",
30140
- "--tools",
30141
- "",
30142
- "--permission-mode",
30143
- "dontAsk",
30144
- "--allowedTools",
30145
- ...inboxScanTools.allowed,
30146
- "--disallowedTools",
30147
- ...inboxScanTools.denied,
30148
- "--no-session-persistence",
30149
- "--output-format",
30150
- "stream-json",
30151
- "--verbose",
30152
- "--json-schema",
30153
- JSON.stringify(z17.toJSONSchema(inboxScanSchema, { target: "draft-07" })),
30154
- "--",
30155
- buildInboxScanPrompt(since)
30156
- ];
30157
- }
30158
- function describeExit(code, signal) {
30159
- return signal ? `claude was killed (${signal})` : `claude exited ${code}`;
30160
- }
30161
- async function runInboxScanClaude(since, listener = {}) {
30162
- const child = spawn6("claude", buildInboxScanArgs(since), {
30163
- stdio: ["ignore", "pipe", "pipe"],
30164
- windowsHide: true,
30165
- timeout: 20 * 6e4
30166
- });
30167
- const parser = createInboxScanParser(listener);
30168
- const flush = attachLineParser(child, parser.onLine);
30169
- const stderr = attachStderrCollector(child);
30170
- const exit = await new Promise((resolve32, reject) => {
30171
- child.on("error", reject);
30172
- child.on("close", (code, signal) => resolve32(describeExit(code, signal)));
30173
- });
30174
- flush();
30175
- const tail = stderr.value.trim().slice(-500);
30176
- return parser.finish(tail ? `${exit}: ${tail}` : exit);
30177
- }
30178
-
30179
30247
  // src/shared/db/finishJobRun.ts
30180
- import { eq as eq50 } from "drizzle-orm";
30248
+ import { eq as eq53 } from "drizzle-orm";
30181
30249
  async function finishJobRun(db, id, result) {
30182
- await db.update(jobRuns).set(result).where(eq50(jobRuns.id, id));
30250
+ await db.update(jobRuns).set(result).where(eq53(jobRuns.id, id));
30183
30251
  }
30184
30252
 
30185
30253
  // src/shared/db/startJobRun.ts
@@ -32831,9 +32899,9 @@ async function list4() {
32831
32899
  import chalk200 from "chalk";
32832
32900
 
32833
32901
  // src/commands/backlog/removeFeed.ts
32834
- import { eq as eq51 } from "drizzle-orm";
32902
+ import { eq as eq54 } from "drizzle-orm";
32835
32903
  async function removeFeed(db, url) {
32836
- const deleted = await db.delete(feeds).where(eq51(feeds.url, url)).returning({ id: feeds.id });
32904
+ const deleted = await db.delete(feeds).where(eq54(feeds.url, url)).returning({ id: feeds.id });
32837
32905
  return deleted.length > 0;
32838
32906
  }
32839
32907
 
@@ -32994,17 +33062,17 @@ function getPageSlice(pullRequests, page) {
32994
33062
  const start2 = page * PAGE_SIZE2;
32995
33063
  return pullRequests.slice(start2, start2 + PAGE_SIZE2);
32996
33064
  }
32997
- function pageHeader(page, totalPages, total2) {
33065
+ function pageHeader(page, totalPages, total3) {
32998
33066
  return `
32999
- Page ${page + 1} of ${totalPages} (${total2} total)
33067
+ Page ${page + 1} of ${totalPages} (${total3} total)
33000
33068
  `;
33001
33069
  }
33002
33070
  function displayPage(pullRequests, totalPages, page) {
33003
33071
  console.log(pageHeader(page, totalPages, pullRequests.length));
33004
33072
  for (const pr of getPageSlice(pullRequests, page)) printPr(pr);
33005
33073
  }
33006
- function hasNextPage(page, total2) {
33007
- return page < total2 - 1;
33074
+ function hasNextPage(page, total3) {
33075
+ return page < total3 - 1;
33008
33076
  }
33009
33077
  var NEXT_CHOICE = { name: "Next page", value: "next" };
33010
33078
  var PREV_CHOICE = { name: "Previous page", value: "prev" };
@@ -35212,11 +35280,11 @@ function parseReadBudget(value) {
35212
35280
  `Invalid budget "${value}". Use a duration like 45s, 1m30s or 2m.`
35213
35281
  );
35214
35282
  }
35215
- const total2 = Number(minutes ?? 0) * 60 + Number(seconds ?? 0);
35216
- if (total2 === 0) {
35283
+ const total3 = Number(minutes ?? 0) * 60 + Number(seconds ?? 0);
35284
+ if (total3 === 0) {
35217
35285
  throw new Error(`Invalid budget "${value}". Value must be at least 1s.`);
35218
35286
  }
35219
- return total2;
35287
+ return total3;
35220
35288
  }
35221
35289
 
35222
35290
  // src/commands/readTime/resolveReadTimeTarget.ts
@@ -39472,7 +39540,7 @@ function basename24(path109) {
39472
39540
  return path109.slice(path109.lastIndexOf("/") + 1);
39473
39541
  }
39474
39542
  function sum(nodes, key) {
39475
- return nodes.reduce((total2, node) => total2 + node[key], 0);
39543
+ return nodes.reduce((total3, node) => total3 + node[key], 0);
39476
39544
  }
39477
39545
  function byName(a, b) {
39478
39546
  return a.name.localeCompare(b.name);
@@ -39516,7 +39584,7 @@ function buildHighLevelTree(files) {
39516
39584
 
39517
39585
  // src/commands/review/highLevel/buildHighLevelStructure.ts
39518
39586
  function sum2(files, key) {
39519
- return files.reduce((total2, file) => total2 + file[key], 0);
39587
+ return files.reduce((total3, file) => total3 + file[key], 0);
39520
39588
  }
39521
39589
  function countOf(files, status2) {
39522
39590
  return files.filter((file) => file.status === status2).length;
@@ -39717,12 +39785,12 @@ function visitCase(call, context) {
39717
39785
  if (!context.changed) return [toCase(call, context)];
39718
39786
  const lines2 = changedLines(call, context.changed);
39719
39787
  if (lines2.length === 0) return [];
39720
- const total2 = call.getEndLineNumber() - call.getStartLineNumber() + 1;
39788
+ const total3 = call.getEndLineNumber() - call.getStartLineNumber() + 1;
39721
39789
  return [
39722
39790
  toCase(
39723
39791
  call,
39724
39792
  context,
39725
- lines2.length === total2 ? { change: "added" } : { change: "modified", changedLines: lines2 }
39793
+ lines2.length === total3 ? { change: "added" } : { change: "modified", changedLines: lines2 }
39726
39794
  )
39727
39795
  ];
39728
39796
  }
@@ -39891,7 +39959,7 @@ var EVIDENCE_PATTERNS = [
39891
39959
  ];
39892
39960
  function countEvidence(body) {
39893
39961
  return EVIDENCE_PATTERNS.reduce(
39894
- (total2, pattern2) => total2 + (body.match(pattern2)?.length ?? 0),
39962
+ (total3, pattern2) => total3 + (body.match(pattern2)?.length ?? 0),
39895
39963
  0
39896
39964
  );
39897
39965
  }
@@ -41132,11 +41200,11 @@ function cells(usage) {
41132
41200
  format(usage.cacheWrite)
41133
41201
  ];
41134
41202
  }
41135
- function sumOf(reported, pick2) {
41136
- const values = reported.map(pick2).filter((v) => v !== void 0);
41203
+ function sumOf(reported, pick3) {
41204
+ const values = reported.map(pick3).filter((v) => v !== void 0);
41137
41205
  return values.length === 0 ? void 0 : values.reduce((a, b) => a + b, 0);
41138
41206
  }
41139
- function total(usages) {
41207
+ function total2(usages) {
41140
41208
  const reported = usages.filter((u) => u !== void 0);
41141
41209
  return [
41142
41210
  format(sumOf(reported, (u) => u.input)),
@@ -41157,7 +41225,7 @@ function buildTokenUsageTable(usages) {
41157
41225
  ...usages.map(
41158
41226
  (usage, i) => row2(SLOT_LABELS[i] ?? `Slot ${i + 1}`, cells(usage))
41159
41227
  ),
41160
- row2("**Total**", total(usages))
41228
+ row2("**Total**", total2(usages))
41161
41229
  ].join("\n");
41162
41230
  }
41163
41231
 
@@ -42024,12 +42092,12 @@ function parseCodexEvent(line) {
42024
42092
  }
42025
42093
 
42026
42094
  // src/commands/review/createCodexLineHandler.ts
42027
- function addUsage(total2, turn) {
42028
- if (!total2) return turn;
42095
+ function addUsage(total3, turn) {
42096
+ if (!total3) return turn;
42029
42097
  return {
42030
- input: total2.input + turn.input,
42031
- output: total2.output + turn.output,
42032
- cacheRead: total2.cacheRead + turn.cacheRead
42098
+ input: total3.input + turn.input,
42099
+ output: total3.output + turn.output,
42100
+ cacheRead: total3.cacheRead + turn.cacheRead
42033
42101
  };
42034
42102
  }
42035
42103
  function createCodexLineHandler(name, spinner, model) {
@@ -43601,8 +43669,8 @@ function filterToSql(filter) {
43601
43669
  // src/commands/seq/fetchSeqData.ts
43602
43670
  function buildDataParams(filter, count11, from, to) {
43603
43671
  const sqlFilter = filterToSql(filter);
43604
- const sql32 = `select @Timestamp, @Level, @Exception, @Message from stream where ${sqlFilter} order by @Timestamp desc limit ${count11}`;
43605
- const params = new URLSearchParams({ q: sql32 });
43672
+ const sql33 = `select @Timestamp, @Level, @Exception, @Message from stream where ${sqlFilter} order by @Timestamp desc limit ${count11}`;
43673
+ const params = new URLSearchParams({ q: sql33 });
43606
43674
  if (from) params.set("rangeStartUtc", from);
43607
43675
  if (to) params.set("rangeEndUtc", to);
43608
43676
  return params;
@@ -44225,26 +44293,26 @@ import chalk271 from "chalk";
44225
44293
  // src/commands/sql/loadConnections.ts
44226
44294
  function loadConnections3() {
44227
44295
  const raw = loadGlobalConfigRaw();
44228
- const sql32 = raw.sql;
44229
- return sql32?.connections ?? [];
44296
+ const sql33 = raw.sql;
44297
+ return sql33?.connections ?? [];
44230
44298
  }
44231
44299
  function saveConnections3(connections) {
44232
44300
  const raw = loadGlobalConfigRaw();
44233
- const sql32 = raw.sql ?? {};
44234
- sql32.connections = connections;
44235
- raw.sql = sql32;
44301
+ const sql33 = raw.sql ?? {};
44302
+ sql33.connections = connections;
44303
+ raw.sql = sql33;
44236
44304
  saveGlobalConfig(raw);
44237
44305
  }
44238
44306
  function getDefaultConnection2() {
44239
44307
  const raw = loadGlobalConfigRaw();
44240
- const sql32 = raw.sql;
44241
- return sql32?.defaultConnection;
44308
+ const sql33 = raw.sql;
44309
+ return sql33?.defaultConnection;
44242
44310
  }
44243
44311
  function setDefaultConnection2(name) {
44244
44312
  const raw = loadGlobalConfigRaw();
44245
- const sql32 = raw.sql ?? {};
44246
- sql32.defaultConnection = name;
44247
- raw.sql = sql32;
44313
+ const sql33 = raw.sql ?? {};
44314
+ sql33.defaultConnection = name;
44315
+ raw.sql = sql33;
44248
44316
  saveGlobalConfig(raw);
44249
44317
  }
44250
44318
 
@@ -44315,9 +44383,9 @@ function resolveConnection3(name) {
44315
44383
  }
44316
44384
 
44317
44385
  // src/commands/sql/sqlConnect.ts
44318
- import sql26 from "mssql";
44386
+ import sql27 from "mssql";
44319
44387
  async function sqlConnect(conn) {
44320
- return await sql26.connect({
44388
+ return await sql27.connect({
44321
44389
  server: conn.server,
44322
44390
  port: conn.port,
44323
44391
  user: conn.user,
@@ -44380,11 +44448,11 @@ var MUTATION_PATTERN = new RegExp(
44380
44448
  `\\b(${MUTATION_KEYWORDS.join("|")})\\b`,
44381
44449
  "i"
44382
44450
  );
44383
- function stripComments(sql32) {
44384
- return sql32.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ");
44451
+ function stripComments(sql33) {
44452
+ return sql33.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ");
44385
44453
  }
44386
- function isMutation(sql32) {
44387
- const stripped = stripComments(sql32);
44454
+ function isMutation(sql33) {
44455
+ const stripped = stripComments(sql33);
44388
44456
  if (MUTATION_PATTERN.test(stripped)) return true;
44389
44457
  return /\bSELECT\b[\s\S]+\bINTO\s+\w/i.test(stripped);
44390
44458
  }
@@ -44735,13 +44803,13 @@ function syncCodexHooks(sourcePath) {
44735
44803
  // src/commands/sync/syncCodex.ts
44736
44804
  function syncCodex(claudeDir, options2) {
44737
44805
  if (!isHarnessAvailable("codex")) return;
44738
- const { total: total2, names } = installHarnessCommands(
44806
+ const { total: total3, names } = installHarnessCommands(
44739
44807
  claudeDir,
44740
44808
  harnesses.codex,
44741
44809
  commandToSkill
44742
44810
  );
44743
44811
  syncCodexHooks(path97.join(claudeDir, "..", "codex", "config.toml"));
44744
- console.log(`Synced ${total2} skill(s) to ~/.codex/skills`);
44812
+ console.log(`Synced ${total3} skill(s) to ~/.codex/skills`);
44745
44813
  if (!options2?.prune) return;
44746
44814
  const force = options2.force ?? false;
44747
44815
  reportPrune(
@@ -47457,12 +47525,12 @@ function parseEnvPairs(pairs) {
47457
47525
  if (pairs.length === 0) return void 0;
47458
47526
  const env = {};
47459
47527
  for (const pair of pairs) {
47460
- const eq55 = pair.indexOf("=");
47461
- if (eq55 <= 0) {
47528
+ const eq58 = pair.indexOf("=");
47529
+ if (eq58 <= 0) {
47462
47530
  console.error(`--env must be KEY=VALUE, got "${pair}"`);
47463
47531
  process.exit(1);
47464
47532
  }
47465
- env[pair.slice(0, eq55)] = pair.slice(eq55 + 1);
47533
+ env[pair.slice(0, eq58)] = pair.slice(eq58 + 1);
47466
47534
  }
47467
47535
  return env;
47468
47536
  }
@@ -47475,11 +47543,11 @@ function fail10(spec) {
47475
47543
  process.exit(1);
47476
47544
  }
47477
47545
  function parseParamSpec(spec) {
47478
- const eq55 = spec.indexOf("=");
47479
- const name = eq55 === -1 ? spec : spec.slice(0, eq55);
47480
- if (eq55 !== -1) {
47481
- if (eq55 === 0 || name.endsWith("!")) fail10(spec);
47482
- return { name, default: spec.slice(eq55 + 1) };
47546
+ const eq58 = spec.indexOf("=");
47547
+ const name = eq58 === -1 ? spec : spec.slice(0, eq58);
47548
+ if (eq58 !== -1) {
47549
+ if (eq58 === 0 || name.endsWith("!")) fail10(spec);
47550
+ return { name, default: spec.slice(eq58 + 1) };
47483
47551
  }
47484
47552
  if (name.endsWith("!")) {
47485
47553
  if (name.length === 1) fail10(spec);
@@ -48016,6 +48084,19 @@ function createAutoExit(exit, graceMs = DEFAULT_GRACE_MS) {
48016
48084
  };
48017
48085
  }
48018
48086
 
48087
+ // src/commands/sessions/daemon/failInterruptedJobRuns.ts
48088
+ async function failInterruptedJobRuns(startedBefore = /* @__PURE__ */ new Date()) {
48089
+ try {
48090
+ const failed3 = await failStaleJobRuns(await getDb(), {
48091
+ startedBefore,
48092
+ detail: "Interrupted: the daemon restarted before it finished"
48093
+ });
48094
+ daemonLog(`jobs: marked ${failed3} interrupted run(s) failed on start`);
48095
+ } catch (error) {
48096
+ daemonLog(`jobs: failing interrupted runs failed: ${String(error)}`);
48097
+ }
48098
+ }
48099
+
48019
48100
  // src/commands/sessions/daemon/inbox/createActivityThrottle.ts
48020
48101
  var ACTIVITY_THROTTLE_MS = 1e3;
48021
48102
  function createActivityThrottle(onActivity) {
@@ -48035,10 +48116,10 @@ function createActivityThrottle(onActivity) {
48035
48116
  }
48036
48117
 
48037
48118
  // src/shared/db/readInboxLastRun.ts
48038
- import { eq as eq52 } from "drizzle-orm";
48119
+ import { eq as eq55 } from "drizzle-orm";
48039
48120
  var INBOX_LAST_RUN_KEY = "inbox.lastRun";
48040
48121
  async function readInboxLastRun(orm) {
48041
- const [row3] = await orm.select().from(metadata).where(eq52(metadata.key, INBOX_LAST_RUN_KEY));
48122
+ const [row3] = await orm.select().from(metadata).where(eq55(metadata.key, INBOX_LAST_RUN_KEY));
48042
48123
  return row3 ? JSON.parse(row3.value) : void 0;
48043
48124
  }
48044
48125
 
@@ -50355,10 +50436,10 @@ function processCwd(link3) {
50355
50436
 
50356
50437
  // src/commands/sessions/daemon/worktree/awaitTreeVacated.ts
50357
50438
  var POLL_MS3 = 500;
50358
- var GRACE_MS2 = 5e3;
50439
+ var GRACE_MS3 = 5e3;
50359
50440
  function awaitTreeVacated(session, treePath) {
50360
50441
  return new Promise((resolve32) => {
50361
- let ticks = GRACE_MS2 / POLL_MS3;
50442
+ let ticks = GRACE_MS3 / POLL_MS3;
50362
50443
  const settle = (outcome) => {
50363
50444
  clearTimeout(timer);
50364
50445
  session.closeGrace = void 0;
@@ -50558,13 +50639,13 @@ function drainSessions(sessions, notify2) {
50558
50639
  }
50559
50640
 
50560
50641
  // src/shared/db/recordPhaseActiveMs.ts
50561
- import { sql as sql27 } from "drizzle-orm";
50642
+ import { sql as sql28 } from "drizzle-orm";
50562
50643
  async function recordPhaseActiveMs(db, itemId2, phaseIdx, activeMs) {
50563
50644
  if (activeMs <= 0) return;
50564
50645
  await db.insert(phaseUsage).values({ itemId: itemId2, phaseIdx, activeMs }).onConflictDoUpdate({
50565
50646
  target: [phaseUsage.itemId, phaseUsage.phaseIdx],
50566
50647
  set: {
50567
- activeMs: sql27`${phaseUsage.activeMs} + excluded.active_ms`
50648
+ activeMs: sql28`${phaseUsage.activeMs} + excluded.active_ms`
50568
50649
  }
50569
50650
  });
50570
50651
  }
@@ -51212,10 +51293,10 @@ function applyReviewPause(session, activity2) {
51212
51293
  }
51213
51294
 
51214
51295
  // src/shared/db/getPhaseActiveMs.ts
51215
- import { and as and21, eq as eq53 } from "drizzle-orm";
51296
+ import { and as and24, eq as eq56 } from "drizzle-orm";
51216
51297
  async function getPhaseActiveMs(db, itemId2, phaseIdx) {
51217
51298
  const [row3] = await db.select({ activeMs: phaseUsage.activeMs }).from(phaseUsage).where(
51218
- and21(eq53(phaseUsage.itemId, itemId2), eq53(phaseUsage.phaseIdx, phaseIdx))
51299
+ and24(eq56(phaseUsage.itemId, itemId2), eq56(phaseUsage.phaseIdx, phaseIdx))
51219
51300
  );
51220
51301
  return row3?.activeMs ?? 0;
51221
51302
  }
@@ -51971,7 +52052,7 @@ async function readTranscriptUsage(transcriptPath2) {
51971
52052
  }
51972
52053
 
51973
52054
  // src/shared/db/recordPhaseCycleContext.ts
51974
- import { sql as sql28 } from "drizzle-orm";
52055
+ import { sql as sql29 } from "drizzle-orm";
51975
52056
  async function recordPhaseCycleContext(db, itemId2, phaseIdx, window, resetsAt, pct) {
51976
52057
  if (pct <= 0) return;
51977
52058
  await db.insert(phaseCycleContext).values({ itemId: itemId2, phaseIdx, window, resetsAt, peakContextPct: pct }).onConflictDoUpdate({
@@ -51982,24 +52063,24 @@ async function recordPhaseCycleContext(db, itemId2, phaseIdx, window, resetsAt,
51982
52063
  phaseCycleContext.resetsAt
51983
52064
  ],
51984
52065
  set: {
51985
- peakContextPct: sql28`GREATEST(${phaseCycleContext.peakContextPct}, ${pct})`
52066
+ peakContextPct: sql29`GREATEST(${phaseCycleContext.peakContextPct}, ${pct})`
51986
52067
  }
51987
52068
  });
51988
52069
  }
51989
52070
 
51990
52071
  // src/shared/db/recordPhasePeakContext.ts
51991
- import { sql as sql29 } from "drizzle-orm";
52072
+ import { sql as sql30 } from "drizzle-orm";
51992
52073
  async function recordPhasePeakContext(db, itemId2, phaseIdx, pct) {
51993
52074
  await db.insert(phaseUsage).values({ itemId: itemId2, phaseIdx, peakContextPct: pct }).onConflictDoUpdate({
51994
52075
  target: [phaseUsage.itemId, phaseUsage.phaseIdx],
51995
52076
  set: {
51996
- peakContextPct: sql29`GREATEST(${phaseUsage.peakContextPct}, ${pct})`
52077
+ peakContextPct: sql30`GREATEST(${phaseUsage.peakContextPct}, ${pct})`
51997
52078
  }
51998
52079
  });
51999
52080
  }
52000
52081
 
52001
52082
  // src/shared/db/recordPhaseTranscriptUsage.ts
52002
- import { sql as sql30 } from "drizzle-orm";
52083
+ import { sql as sql31 } from "drizzle-orm";
52003
52084
  async function recordPhaseTranscriptUsage(db, itemId2, phaseIdx, responses) {
52004
52085
  const byId = /* @__PURE__ */ new Map();
52005
52086
  for (const r of responses) byId.set(r.messageId, r);
@@ -52019,8 +52100,8 @@ async function recordPhaseTranscriptUsage(db, itemId2, phaseIdx, responses) {
52019
52100
  await tx.insert(phaseUsage).values({ itemId: itemId2, phaseIdx, tokensUp, tokensDown }).onConflictDoUpdate({
52020
52101
  target: [phaseUsage.itemId, phaseUsage.phaseIdx],
52021
52102
  set: {
52022
- tokensUp: sql30`${phaseUsage.tokensUp} + ${tokensUp}`,
52023
- tokensDown: sql30`${phaseUsage.tokensDown} + ${tokensDown}`
52103
+ tokensUp: sql31`${phaseUsage.tokensUp} + ${tokensUp}`,
52104
+ tokensDown: sql31`${phaseUsage.tokensDown} + ${tokensDown}`
52024
52105
  }
52025
52106
  });
52026
52107
  return { tokensUp, tokensDown };
@@ -52028,17 +52109,17 @@ async function recordPhaseTranscriptUsage(db, itemId2, phaseIdx, responses) {
52028
52109
  }
52029
52110
 
52030
52111
  // src/shared/db/recordWindowTokens.ts
52031
- import { and as and22, eq as eq54, sql as sql31 } from "drizzle-orm";
52112
+ import { and as and25, eq as eq57, sql as sql32 } from "drizzle-orm";
52032
52113
  async function recordWindowTokens(db, window, resetsAt, tokensUp, tokensDown) {
52033
52114
  if (tokensUp <= 0 && tokensDown <= 0) return;
52034
52115
  await db.update(usagePeaks).set({
52035
- tokensUp: sql31`${usagePeaks.tokensUp} + ${tokensUp}`,
52036
- tokensDown: sql31`${usagePeaks.tokensDown} + ${tokensDown}`
52116
+ tokensUp: sql32`${usagePeaks.tokensUp} + ${tokensUp}`,
52117
+ tokensDown: sql32`${usagePeaks.tokensDown} + ${tokensDown}`
52037
52118
  }).where(
52038
- and22(
52039
- eq54(usagePeaks.window, window),
52040
- eq54(usagePeaks.resetsAt, resetsAt),
52041
- eq54(usagePeaks.segment, 0)
52119
+ and25(
52120
+ eq57(usagePeaks.window, window),
52121
+ eq57(usagePeaks.resetsAt, resetsAt),
52122
+ eq57(usagePeaks.segment, 0)
52042
52123
  )
52043
52124
  );
52044
52125
  }
@@ -56528,6 +56609,7 @@ async function runDaemon() {
56528
56609
  setDaemonLogSink(manager.clients.emitLog);
56529
56610
  startDaemonLogTrimmer();
56530
56611
  pollRepoConfigCache();
56612
+ void failInterruptedJobRuns();
56531
56613
  inboxScanner.start((type) => broadcast(manager.clients, { type }));
56532
56614
  await startDaemonServer(manager, checkAutoExit);
56533
56615
  await refreshRepoConfigCacheOnStart();