@staff0rd/assist 0.1030.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.1030.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);
@@ -15519,6 +15939,19 @@ async function awaitPreviewApproval(subject, request, options2 = {}) {
15519
15939
  return outcome;
15520
15940
  }
15521
15941
 
15942
+ // src/commands/sessions/shared/printApprovedComments.ts
15943
+ function printApprovedComments(decision) {
15944
+ console.log("Approved.");
15945
+ const comments3 = decision.comments ?? [];
15946
+ if (comments3.length === 0) return;
15947
+ console.log(
15948
+ `
15949
+ The reviewer left ${comments3.length} comment${comments3.length === 1 ? "" : "s"} on the preview. Act on each one:
15950
+ `
15951
+ );
15952
+ for (const line of formatPreviewComments(comments3)) console.log(line);
15953
+ }
15954
+
15522
15955
  // src/commands/ask.ts
15523
15956
  async function ask(options2) {
15524
15957
  const body = await readBodyArgument(options2.body);
@@ -15545,15 +15978,7 @@ async function ask(options2) {
15545
15978
  rejectionAdvice: "Revise the update to address the reason and every comment above, then re-run `assist ask` with the revision."
15546
15979
  }
15547
15980
  );
15548
- console.log("Approved.");
15549
- const comments3 = decision.comments ?? [];
15550
- if (comments3.length === 0) return;
15551
- console.log(
15552
- `
15553
- The reviewer left ${comments3.length} comment${comments3.length === 1 ? "" : "s"} on the preview. Act on each one:
15554
- `
15555
- );
15556
- for (const line of formatPreviewComments(comments3)) console.log(line);
15981
+ printApprovedComments(decision);
15557
15982
  }
15558
15983
 
15559
15984
  // src/commands/registerAsk.ts
@@ -15573,12 +15998,12 @@ function registerAsk(program) {
15573
15998
  import { randomUUID as randomUUID4 } from "crypto";
15574
15999
 
15575
16000
  // src/commands/sessions/shared/askCheckInputSchema.ts
15576
- import { z as z10 } from "zod";
15577
- var text17 = z10.string().trim().min(1);
15578
- var askCheckInputSchema = z10.object({
16001
+ import { z as z12 } from "zod";
16002
+ var text17 = z12.string().trim().min(1);
16003
+ var askCheckInputSchema = z12.object({
15579
16004
  title: text17,
15580
- steps: z10.array(text17).min(1, "Give at least 1 step"),
15581
- before: z10.array(text17).optional(),
16005
+ steps: z12.array(text17).min(1, "Give at least 1 step"),
16006
+ before: z12.array(text17).optional(),
15582
16007
  changed: text17.optional()
15583
16008
  });
15584
16009
  var CHECK_RESULT_KEY = "result";
@@ -15737,9 +16162,79 @@ function registerAskCheck(program) {
15737
16162
  );
15738
16163
  }
15739
16164
 
15740
- // src/commands/askQuestion.ts
16165
+ // src/commands/askDesign.ts
15741
16166
  import { randomUUID as randomUUID5 } from "crypto";
15742
16167
 
16168
+ // src/commands/askDesign/designReviewSessionId.ts
16169
+ async function designReviewSessionId() {
16170
+ const sessionId = process.env.ASSIST_SESSION_ID;
16171
+ if (process.env.ASSIST_SESSION !== "1" || !sessionId) return void 0;
16172
+ return await isLiveDaemonSession(sessionId) ? sessionId : void 0;
16173
+ }
16174
+
16175
+ // src/commands/askDesign/isArtifactUrl.ts
16176
+ var ARTIFACT_PATH = /^\/(code\/)?artifact\/[\w-]+\/?$/;
16177
+ function isArtifactUrl(value) {
16178
+ let url;
16179
+ try {
16180
+ url = new URL(value);
16181
+ } catch {
16182
+ return false;
16183
+ }
16184
+ return url.protocol === "https:" && url.hostname === "claude.ai" && ARTIFACT_PATH.test(url.pathname);
16185
+ }
16186
+
16187
+ // src/commands/askDesign.ts
16188
+ var DEFAULT_BODY = "Open the design above, then approve or reject it.";
16189
+ async function askDesign(options2) {
16190
+ if (!isArtifactUrl(options2.url)) {
16191
+ console.error(
16192
+ `Error: --url must be a claude.ai artifact link (https://claude.ai/artifact/<id> or https://claude.ai/code/artifact/<id>), got: ${options2.url}`
16193
+ );
16194
+ process.exit(1);
16195
+ }
16196
+ const body = options2.body === void 0 ? "" : (await readBodyArgument(options2.body)).trim();
16197
+ const sessionId = await designReviewSessionId();
16198
+ if (!sessionId) {
16199
+ console.log(`Design: ${options2.url}`);
16200
+ if (body) console.log(`
16201
+ ${body}`);
16202
+ return;
16203
+ }
16204
+ const decision = await awaitPreviewApproval(
16205
+ options2.title,
16206
+ {
16207
+ sessionId,
16208
+ requestId: randomUUID5(),
16209
+ title: options2.title,
16210
+ body: body || DEFAULT_BODY,
16211
+ prNumber: null,
16212
+ kind: "design",
16213
+ metadata: [{ label: "Design", value: options2.url, url: options2.url }]
16214
+ },
16215
+ {
16216
+ rejectionAdvice: "Revise the design to address the reason and every comment above, republish it to the same artifact URL, then re-run `assist ask-design`."
16217
+ }
16218
+ );
16219
+ printApprovedComments(decision);
16220
+ }
16221
+
16222
+ // src/commands/registerAskDesign.ts
16223
+ function registerAskDesign(program) {
16224
+ internalCommand(
16225
+ program.command("ask-design").description(
16226
+ "Open a claude.ai design artifact in the session's web preview pane for the user to approve or reject, with inline comments, and wait for the decision; prints the link outside a web session"
16227
+ ).requiredOption(
16228
+ "--url <artifact-url>",
16229
+ "claude.ai artifact link of the design"
16230
+ ).requiredOption("--title <title>", "Pane title").option("--body <markdown|->", "Markdown summary, or - for stdin").action(askDesign),
16231
+ "/draft"
16232
+ );
16233
+ }
16234
+
16235
+ // src/commands/askQuestion.ts
16236
+ import { randomUUID as randomUUID6 } from "crypto";
16237
+
15743
16238
  // src/commands/askQuestion/formatAskQuestionAnswers.ts
15744
16239
  function formatAskQuestionAnswers(questions, answers) {
15745
16240
  const pairs = questions.map(({ question }) => `"${question}"="${answers[question] ?? ""}"`).join(", ");
@@ -15765,23 +16260,23 @@ function rejectLongQuestions(questions) {
15765
16260
  }
15766
16261
 
15767
16262
  // src/commands/sessions/shared/askQuestionInputSchema.ts
15768
- import { z as z11 } from "zod";
15769
- var askQuestionOptionSchema = z11.object({
15770
- label: z11.string().min(1),
15771
- description: z11.string(),
15772
- 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()
15773
16268
  });
15774
- var askQuestionSchema = z11.object({
15775
- question: z11.string().min(1),
15776
- header: z11.string().min(1),
15777
- multiSelect: z11.boolean(),
15778
- 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(
15779
16274
  (options2) => new Set(options2.map((option) => option.label)).size === options2.length,
15780
16275
  "Option labels must be unique within a question"
15781
16276
  )
15782
16277
  });
15783
- var askQuestionInputSchema = z11.object({
15784
- 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(
15785
16280
  (questions) => new Set(questions.map((q) => q.question)).size === questions.length,
15786
16281
  "Question texts must be unique"
15787
16282
  )
@@ -15813,7 +16308,7 @@ async function askQuestion(options2) {
15813
16308
  title,
15814
16309
  {
15815
16310
  sessionId,
15816
- requestId: randomUUID5(),
16311
+ requestId: randomUUID6(),
15817
16312
  title,
15818
16313
  body: JSON.stringify({ questions }),
15819
16314
  prNumber: null,
@@ -16069,8 +16564,8 @@ async function buildDump(tables, copyOut) {
16069
16564
  // src/commands/backlog/dump/copyTableOut.ts
16070
16565
  import { to as copyTo } from "pg-copy-streams";
16071
16566
  async function copyTableOut(client, table) {
16072
- const sql32 = `COPY ${table.name} (${table.columns.join(", ")}) TO STDOUT`;
16073
- const stream = client.query(copyTo(sql32));
16567
+ const sql33 = `COPY ${table.name} (${table.columns.join(", ")}) TO STDOUT`;
16568
+ const stream = client.query(copyTo(sql33));
16074
16569
  const chunks = [];
16075
16570
  for await (const chunk of stream) {
16076
16571
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
@@ -16537,11 +17032,11 @@ function registerActivityCommands(cmd) {
16537
17032
 
16538
17033
  // src/commands/backlog/associateGithub.ts
16539
17034
  import chalk45 from "chalk";
16540
- import { eq as eq31 } from "drizzle-orm";
17035
+ import { eq as eq34 } from "drizzle-orm";
16541
17036
 
16542
17037
  // src/commands/backlog/beginAssociation.ts
16543
17038
  import chalk44 from "chalk";
16544
- import { eq as eq30 } from "drizzle-orm";
17039
+ import { eq as eq33 } from "drizzle-orm";
16545
17040
  async function beginAssociation(id, options2, clearPatch, label) {
16546
17041
  const found = await findOneItem(id);
16547
17042
  if (!found) {
@@ -16551,7 +17046,7 @@ async function beginAssociation(id, options2, clearPatch, label) {
16551
17046
  const { orm } = found;
16552
17047
  const itemId2 = found.item.id;
16553
17048
  if (options2.clear) {
16554
- await orm.update(items).set(clearPatch).where(eq30(items.id, itemId2));
17049
+ await orm.update(items).set(clearPatch).where(eq33(items.id, itemId2));
16555
17050
  console.log(
16556
17051
  chalk44.green(
16557
17052
  `Cleared ${label} association on item ${formatItemId(itemId2)}.`
@@ -16619,7 +17114,7 @@ async function associateGithub(id, issue, options2) {
16619
17114
  return;
16620
17115
  }
16621
17116
  const title = fetchGithubIssueTitle(normalized);
16622
- 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));
16623
17118
  console.log(
16624
17119
  chalk45.green(`Associated ${normalized} with item ${formatItemId(itemId2)}.`),
16625
17120
  title ? chalk45.dim(`(${title})`) : ""
@@ -16633,7 +17128,7 @@ function registerAssociateGithubCommand(cmd) {
16633
17128
 
16634
17129
  // src/commands/backlog/associateJira.ts
16635
17130
  import chalk47 from "chalk";
16636
- import { eq as eq32 } from "drizzle-orm";
17131
+ import { eq as eq35 } from "drizzle-orm";
16637
17132
 
16638
17133
  // src/commands/jira/fetchIssue.ts
16639
17134
  import { execSync as execSync17 } from "child_process";
@@ -16698,7 +17193,7 @@ async function associateJira(id, key, options2) {
16698
17193
  const parsed = fetchIssue(normalized, "summary");
16699
17194
  const fields = parsed?.fields;
16700
17195
  const summary = fields?.summary;
16701
- 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));
16702
17197
  console.log(
16703
17198
  chalk47.green(`Associated ${normalized} with item ${formatItemId(itemId2)}.`),
16704
17199
  summary ? chalk47.dim(`(${summary})`) : ""
@@ -16980,8 +17475,8 @@ async function confirmReplace(client, tables, incoming, fromStdin) {
16980
17475
  import { finished } from "stream/promises";
16981
17476
  import { from as copyFrom } from "pg-copy-streams";
16982
17477
  async function copyTableIn(client, table, data) {
16983
- const sql32 = `COPY ${table.name} (${table.columns.join(", ")}) FROM STDIN`;
16984
- const stream = client.query(copyFrom(sql32));
17478
+ const sql33 = `COPY ${table.name} (${table.columns.join(", ")}) FROM STDIN`;
17479
+ const stream = client.query(copyFrom(sql33));
16985
17480
  stream.end(data);
16986
17481
  await finished(stream);
16987
17482
  }
@@ -17056,10 +17551,10 @@ async function importBacklog(file, options2 = {}) {
17056
17551
  return;
17057
17552
  }
17058
17553
  await restore(client, parsed);
17059
- const total2 = incoming.reduce((sum3, n) => sum3 + n, 0);
17554
+ const total3 = incoming.reduce((sum3, n) => sum3 + n, 0);
17060
17555
  console.error(
17061
17556
  chalk54.green(
17062
- `Imported backlog: ${total2} rows restored across ${tables.length} tables.`
17557
+ `Imported backlog: ${total3} rows restored across ${tables.length} tables.`
17063
17558
  )
17064
17559
  );
17065
17560
  });
@@ -17229,9 +17724,9 @@ import chalk58 from "chalk";
17229
17724
 
17230
17725
  // src/commands/backlog/resolveInsertPosition.ts
17231
17726
  import chalk57 from "chalk";
17232
- import { count as count4, eq as eq33 } from "drizzle-orm";
17727
+ import { count as count5, eq as eq36 } from "drizzle-orm";
17233
17728
  async function resolveInsertPosition(orm, itemId2, position) {
17234
- 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));
17235
17730
  const phaseCount = row3?.cnt ?? 0;
17236
17731
  if (position === void 0) return phaseCount;
17237
17732
  const pos = Number.parseInt(position, 10);
@@ -17248,7 +17743,7 @@ async function resolveInsertPosition(orm, itemId2, position) {
17248
17743
  }
17249
17744
 
17250
17745
  // src/commands/backlog/addPhase/reviewProposedPhase.ts
17251
- import { randomUUID as randomUUID6 } from "crypto";
17746
+ import { randomUUID as randomUUID7 } from "crypto";
17252
17747
 
17253
17748
  // src/commands/backlog/renderPhaseSection.ts
17254
17749
  function renderPhaseSection(phase, idx) {
@@ -17272,7 +17767,7 @@ async function reviewProposedPhase(item, phaseIdx, phase) {
17272
17767
  return;
17273
17768
  await awaitPreviewApproval("Backlog phase preview", {
17274
17769
  sessionId,
17275
- requestId: randomUUID6(),
17770
+ requestId: randomUUID7(),
17276
17771
  title: `Add a phase to ${formatItemId(item.id)}: ${item.name}`,
17277
17772
  body: renderPhaseSection(phase, phaseIdx),
17278
17773
  prNumber: null,
@@ -17414,21 +17909,21 @@ async function list(options2) {
17414
17909
  import chalk63 from "chalk";
17415
17910
 
17416
17911
  // src/commands/backlog/propose/proposedItemSchema.ts
17417
- import { z as z12 } from "zod";
17418
- var proposedPhaseSchema = z12.strictObject({
17419
- 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(
17420
17915
  (name) => name.toLowerCase() !== REVIEW_PHASE_NAME.toLowerCase(),
17421
17916
  `"${REVIEW_PHASE_NAME}" is owned by the runner and appended to every plan automatically \u2014 remove this phase`
17422
17917
  ),
17423
- tasks: z12.array(z12.string().trim().min(1)).min(1, "a phase needs at least one task"),
17424
- 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([])
17425
17920
  });
17426
- var proposedItemSchema = z12.strictObject({
17427
- name: z12.string().trim().min(1, "name is required"),
17428
- type: z12.enum(["story", "bug"]),
17429
- description: z12.string().optional(),
17430
- acceptanceCriteria: z12.array(z12.string().trim().min(1)).default([]),
17431
- 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([])
17432
17927
  });
17433
17928
 
17434
17929
  // src/commands/backlog/propose/readProposedItem.ts
@@ -17437,7 +17932,7 @@ function readProposedItem(source) {
17437
17932
  }
17438
17933
 
17439
17934
  // src/commands/backlog/propose/reviewProposal.ts
17440
- import { randomUUID as randomUUID7 } from "crypto";
17935
+ import { randomUUID as randomUUID8 } from "crypto";
17441
17936
  import chalk61 from "chalk";
17442
17937
 
17443
17938
  // src/shared/renderMarkdownTerminal.ts
@@ -17479,7 +17974,7 @@ async function reviewProposal(item, sessionId, confirmed, revises) {
17479
17974
  if (sessionId) {
17480
17975
  const decision = await awaitPreviewApproval("Backlog item preview", {
17481
17976
  sessionId,
17482
- requestId: randomUUID7(),
17977
+ requestId: randomUUID8(),
17483
17978
  title: revises === void 0 ? item.name : `Update ${formatItemId(revises)}: ${item.name}`,
17484
17979
  body,
17485
17980
  prNumber: null,
@@ -17505,10 +18000,10 @@ async function reviewProposal(item, sessionId, confirmed, revises) {
17505
18000
  import chalk62 from "chalk";
17506
18001
 
17507
18002
  // src/commands/backlog/propose/reviseProposedItem.ts
17508
- import { eq as eq35 } from "drizzle-orm";
18003
+ import { eq as eq38 } from "drizzle-orm";
17509
18004
 
17510
18005
  // src/commands/backlog/updatePlan/replacePlan.ts
17511
- import { eq as eq34 } from "drizzle-orm";
18006
+ import { eq as eq37 } from "drizzle-orm";
17512
18007
 
17513
18008
  // src/commands/backlog/updatePlan/clampCurrentPhase.ts
17514
18009
  function clampCurrentPhase(currentPhase, phaseCount) {
@@ -17519,8 +18014,8 @@ function clampCurrentPhase(currentPhase, phaseCount) {
17519
18014
  // src/commands/backlog/updatePlan/replacePlan.ts
17520
18015
  async function replacePlan(orm, itemId2, phases, currentPhase) {
17521
18016
  await orm.transaction(async (tx) => {
17522
- await tx.delete(planTasks).where(eq34(planTasks.itemId, itemId2));
17523
- 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));
17524
18019
  if (phases.length > 0) {
17525
18020
  await tx.insert(planPhases).values(
17526
18021
  phases.map((phase, idx) => ({
@@ -17538,7 +18033,7 @@ async function replacePlan(orm, itemId2, phases, currentPhase) {
17538
18033
  if (currentPhase === void 0) return;
17539
18034
  const clamped = clampCurrentPhase(currentPhase, phases.length);
17540
18035
  if (clamped === currentPhase) return;
17541
- 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));
17542
18037
  });
17543
18038
  }
17544
18039
 
@@ -17548,14 +18043,14 @@ var BUG_DEFAULT_PLAN = [
17548
18043
  ];
17549
18044
  async function reviseProposedItem(itemId2, item) {
17550
18045
  const orm = await getDb();
17551
- 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));
17552
18047
  if (!existing) return false;
17553
18048
  await orm.update(items).set({
17554
18049
  type: item.type,
17555
18050
  name: item.name,
17556
18051
  description: item.description || null,
17557
18052
  acceptanceCriteria: JSON.stringify(item.acceptanceCriteria)
17558
- }).where(eq35(items.id, itemId2));
18053
+ }).where(eq38(items.id, itemId2));
17559
18054
  const phases = item.phases.length > 0 || item.type !== "bug" ? item.phases : BUG_DEFAULT_PLAN;
17560
18055
  await replacePlan(orm, itemId2, phases, existing.currentPhase ?? void 0);
17561
18056
  return true;
@@ -17602,7 +18097,7 @@ function startProposedRun(id) {
17602
18097
  }
17603
18098
 
17604
18099
  // src/commands/backlog/propose/trackProposal.ts
17605
- import { randomUUID as randomUUID8 } from "crypto";
18100
+ import { randomUUID as randomUUID9 } from "crypto";
17606
18101
 
17607
18102
  // src/commands/backlog/propose/mutateLedger.ts
17608
18103
  import { mkdirSync as mkdirSync10, readFileSync as readFileSync23, renameSync as renameSync4, writeFileSync as writeFileSync19 } from "fs";
@@ -17625,14 +18120,14 @@ function mutateLedger(path109, mutate) {
17625
18120
  }
17626
18121
 
17627
18122
  // src/commands/backlog/propose/findPredecessor.ts
17628
- var GRACE_MS = 5e3;
18123
+ var GRACE_MS2 = 5e3;
17629
18124
  var SIBLING_WAIT_MS = 5e3;
17630
18125
  var POLL_MS = 100;
17631
18126
  function knownPredecessor(path109, startedAt) {
17632
18127
  const { created } = readLedger(path109);
17633
18128
  if (!created) return void 0;
17634
18129
  if (created.startedAt > startedAt) return void 0;
17635
- if (created.at < startedAt - GRACE_MS) return void 0;
18130
+ if (created.at < startedAt - GRACE_MS2) return void 0;
17636
18131
  return created.itemId;
17637
18132
  }
17638
18133
  function hasOlderOpenSibling(path109, token, startedAt) {
@@ -17658,7 +18153,7 @@ function proposalLedgerPath(sessionId) {
17658
18153
  var STALE_OPEN_MS = 60 * 6e4;
17659
18154
  function trackProposal(sessionId) {
17660
18155
  const path109 = proposalLedgerPath(sessionId);
17661
- const token = randomUUID8();
18156
+ const token = randomUUID9();
17662
18157
  const startedAt = Date.now();
17663
18158
  mutateLedger(path109, (ledger) => {
17664
18159
  ledger.open = ledger.open.filter(
@@ -17782,9 +18277,9 @@ function hasCycle(adjacency, fromId, toId) {
17782
18277
  }
17783
18278
 
17784
18279
  // src/commands/backlog/loadDependencyGraph.ts
17785
- import { eq as eq36 } from "drizzle-orm";
18280
+ import { eq as eq39 } from "drizzle-orm";
17786
18281
  async function loadDependencyGraph(orm) {
17787
- 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"));
17788
18283
  const graph = /* @__PURE__ */ new Map();
17789
18284
  for (const { itemId: itemId2, targetId } of rows) {
17790
18285
  const bucket = graph.get(itemId2);
@@ -17851,7 +18346,7 @@ async function link(fromId, toId, opts) {
17851
18346
 
17852
18347
  // src/commands/backlog/unlink.ts
17853
18348
  import chalk66 from "chalk";
17854
- import { and as and12, eq as eq37 } from "drizzle-orm";
18349
+ import { and as and15, eq as eq40 } from "drizzle-orm";
17855
18350
  async function unlink(fromId, toId) {
17856
18351
  const fromNum = parseItemId(fromId);
17857
18352
  const toNum = parseItemId(toId);
@@ -17875,7 +18370,7 @@ async function unlink(fromId, toId) {
17875
18370
  );
17876
18371
  return;
17877
18372
  }
17878
- 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)));
17879
18374
  console.log(
17880
18375
  chalk66.green(
17881
18376
  `Removed link from ${formatItemId(fromNum)} to ${formatItemId(toNum)}.`
@@ -17895,7 +18390,7 @@ function registerLinkCommands(cmd) {
17895
18390
 
17896
18391
  // src/commands/backlog/moveRepo.ts
17897
18392
  import chalk68 from "chalk";
17898
- import { eq as eq39 } from "drizzle-orm";
18393
+ import { eq as eq42 } from "drizzle-orm";
17899
18394
 
17900
18395
  // src/commands/backlog/move-repo/confirmMove.ts
17901
18396
  import chalk67 from "chalk";
@@ -17910,9 +18405,9 @@ async function confirmMove(cnt, oldOrigin, newOrigin) {
17910
18405
  }
17911
18406
 
17912
18407
  // src/commands/backlog/move-repo/countByOrigin.ts
17913
- import { count as count5, eq as eq38 } from "drizzle-orm";
18408
+ import { count as count6, eq as eq41 } from "drizzle-orm";
17914
18409
  async function countByOrigin(orm, origin) {
17915
- 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));
17916
18411
  return cnt;
17917
18412
  }
17918
18413
 
@@ -17955,7 +18450,7 @@ async function moveRepo(oldOriginRaw, newOriginRaw, options2 = {}) {
17955
18450
  console.log(chalk68.yellow("Move cancelled; no changes made."));
17956
18451
  return;
17957
18452
  }
17958
- 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));
17959
18454
  console.log(
17960
18455
  chalk68.green(
17961
18456
  `Moved ${pluralItems(cnt)} from "${oldOrigin}" to "${newOrigin}".`
@@ -18427,12 +18922,12 @@ function message(error) {
18427
18922
  import chalk72 from "chalk";
18428
18923
 
18429
18924
  // src/shared/db/findPhaseBySessionId.ts
18430
- import { and as and13, eq as eq40 } from "drizzle-orm";
18925
+ import { and as and16, eq as eq43 } from "drizzle-orm";
18431
18926
  async function findPhaseBySessionId(db, itemId2, claudeSessionId) {
18432
18927
  const rows = await db.select({ phaseIdx: phaseUsage.phaseIdx }).from(phaseUsage).where(
18433
- and13(
18434
- eq40(phaseUsage.itemId, itemId2),
18435
- eq40(phaseUsage.claudeSessionId, claudeSessionId)
18928
+ and16(
18929
+ eq43(phaseUsage.itemId, itemId2),
18930
+ eq43(phaseUsage.claudeSessionId, claudeSessionId)
18436
18931
  )
18437
18932
  ).limit(1);
18438
18933
  return rows[0]?.phaseIdx;
@@ -18570,14 +19065,14 @@ function ensureHooksSettings() {
18570
19065
  }
18571
19066
 
18572
19067
  // src/shared/spawnInherit.ts
18573
- import { spawn as spawn4 } from "child_process";
19068
+ import { spawn as spawn5 } from "child_process";
18574
19069
  function spawnInherit(command, args, options2 = {}) {
18575
19070
  const {
18576
19071
  ASSIST_ACTIVITY_ID: _activityId,
18577
19072
  CLAUDE_CODE_CHILD_SESSION: _childSession,
18578
19073
  ...env
18579
19074
  } = process.env;
18580
- const child = spawn4(command, args, {
19075
+ const child = spawn5(command, args, {
18581
19076
  stdio: "inherit",
18582
19077
  env: { ...env, ...options2.env },
18583
19078
  cwd: options2.cwd
@@ -19036,13 +19531,13 @@ Phase ${phaseNumber} completed.`));
19036
19531
  }
19037
19532
 
19038
19533
  // src/commands/backlog/preparePhaseSession.ts
19039
- import { randomUUID as randomUUID9 } from "crypto";
19534
+ import { randomUUID as randomUUID10 } from "crypto";
19040
19535
 
19041
19536
  // src/commands/backlog/persistPhaseSession.ts
19042
19537
  import os4 from "os";
19043
19538
 
19044
19539
  // src/shared/db/recordPhaseSession.ts
19045
- import { sql as sql24 } from "drizzle-orm";
19540
+ import { sql as sql25 } from "drizzle-orm";
19046
19541
  async function recordPhaseSession(db, itemId2, phaseIdx, claudeSessionId, hostname2, osUser) {
19047
19542
  await db.insert(phaseSessions).values({ itemId: itemId2, phaseIdx, claudeSessionId, hostname: hostname2, osUser }).onConflictDoUpdate({
19048
19543
  target: [
@@ -19051,7 +19546,7 @@ async function recordPhaseSession(db, itemId2, phaseIdx, claudeSessionId, hostna
19051
19546
  phaseSessions.claudeSessionId
19052
19547
  ],
19053
19548
  set: { hostname: hostname2, osUser },
19054
- setWhere: sql24`${phaseSessions.hostname} = 'unknown'`
19549
+ setWhere: sql25`${phaseSessions.hostname} = 'unknown'`
19055
19550
  });
19056
19551
  }
19057
19552
 
@@ -19096,20 +19591,20 @@ async function persistPhaseSessionId(itemId2, phaseIdx, claudeSessionId) {
19096
19591
  import { mkdirSync as mkdirSync14, readFileSync as readFileSync27, rmSync as rmSync4, writeFileSync as writeFileSync23 } from "fs";
19097
19592
  import { homedir as homedir17 } from "os";
19098
19593
  import { dirname as dirname28, join as join51 } from "path";
19099
- import { z as z13 } from "zod";
19100
- var activitySchema = z13.object({
19101
- kind: z13.enum(["command", "backlog"]),
19102
- harness: z13.enum(["claude", "codex", "pi"]).optional(),
19103
- name: z13.string().optional(),
19104
- itemId: z13.number().optional(),
19105
- itemName: z13.string().optional(),
19106
- itemIds: z13.array(z13.number()).optional(),
19107
- phase: z13.number().optional(),
19108
- phaseName: z13.string().optional(),
19109
- totalPhases: z13.number().optional(),
19110
- claudeSessionId: z13.string().optional(),
19111
- watchState: z13.enum(["waiting", "updating"]).optional(),
19112
- 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()
19113
19608
  });
19114
19609
  function activityPath(sessionId) {
19115
19610
  return join51(homedir17(), ".assist", "activity", `activity-${sessionId}.json`);
@@ -19208,7 +19703,7 @@ async function verifyPhaseResume(itemId2, resumeSessionId, phaseLabel2) {
19208
19703
  // src/commands/backlog/preparePhaseSession.ts
19209
19704
  async function preparePhaseSession(item, phase, phaseIndex, phaseNumber, totalPhases, phaseLabel2, spawnOptions) {
19210
19705
  const resumeSessionId = spawnOptions?.resumeSessionId;
19211
- const claudeSessionId = resumeSessionId ?? randomUUID9();
19706
+ const claudeSessionId = resumeSessionId ?? randomUUID10();
19212
19707
  if (resumeSessionId && !await verifyPhaseResume(item.id, resumeSessionId, phaseLabel2)) {
19213
19708
  return void 0;
19214
19709
  }
@@ -19552,7 +20047,7 @@ import chalk86 from "chalk";
19552
20047
  import enquirer7 from "enquirer";
19553
20048
 
19554
20049
  // src/commands/backlog/launchMode.ts
19555
- import { randomUUID as randomUUID10 } from "crypto";
20050
+ import { randomUUID as randomUUID11 } from "crypto";
19556
20051
 
19557
20052
  // src/commands/backlog/handleLaunchSignal.ts
19558
20053
  import chalk85 from "chalk";
@@ -19674,7 +20169,7 @@ async function launchMode(slashCommand, options2) {
19674
20169
  const resumeSessionId = options2?.resumeSessionId;
19675
20170
  if (!resumeSessionId) pullIfConfigured();
19676
20171
  process.env.ASSIST_SESSION_ID ??= String(process.pid);
19677
- const claudeSessionId = resumeSessionId ?? randomUUID10();
20172
+ const claudeSessionId = resumeSessionId ?? randomUUID11();
19678
20173
  const harness = options2?.harness ?? "claude";
19679
20174
  reportLaunchActivity(slashCommand, claudeSessionId, harness, options2);
19680
20175
  const prompt = resumeSessionId ? resumeNudge() : buildSlashCommand(slashCommand, options2?.description);
@@ -19955,10 +20450,10 @@ async function start(id) {
19955
20450
 
19956
20451
  // src/commands/backlog/stop.ts
19957
20452
  import chalk96 from "chalk";
19958
- import { and as and14, eq as eq41 } from "drizzle-orm";
20453
+ import { and as and17, eq as eq44 } from "drizzle-orm";
19959
20454
  async function stop() {
19960
20455
  const { orm } = await getReady();
19961
- 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 });
19962
20457
  if (stopped.length === 0) {
19963
20458
  console.log(chalk96.yellow("No in-progress items to stop."));
19964
20459
  return;
@@ -20016,20 +20511,20 @@ function registerStatusCommands(cmd) {
20016
20511
 
20017
20512
  // src/commands/backlog/movePhase.ts
20018
20513
  import chalk99 from "chalk";
20019
- import { count as count7, eq as eq44 } from "drizzle-orm";
20514
+ import { count as count8, eq as eq47 } from "drizzle-orm";
20020
20515
 
20021
20516
  // src/commands/backlog/reorderPhaseRows.ts
20022
- 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";
20023
20518
 
20024
20519
  // src/commands/backlog/reindexPhases.ts
20025
- 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";
20026
20521
  async function reindexPhases(db, itemId2) {
20027
- 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));
20028
20523
  for (let i = 0; i < remaining.length; i++) {
20029
20524
  const oldIdx = remaining[i].idx;
20030
20525
  if (oldIdx === i) continue;
20031
- await db.update(planTasks).set({ phaseIdx: i }).where(and15(eq42(planTasks.itemId, itemId2), eq42(planTasks.phaseIdx, oldIdx)));
20032
- 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)));
20033
20528
  }
20034
20529
  }
20035
20530
  async function adjustCurrentPhase(db, item, removedIdx) {
@@ -20037,24 +20532,24 @@ async function adjustCurrentPhase(db, item, removedIdx) {
20037
20532
  if (currentPhase === void 0) return;
20038
20533
  const currentIdx = currentPhase - 1;
20039
20534
  if (removedIdx < currentIdx) {
20040
- 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));
20041
20536
  return;
20042
20537
  }
20043
20538
  if (removedIdx !== currentIdx) return;
20044
- 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));
20045
20540
  const cnt = row3?.cnt ?? 0;
20046
- 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));
20047
20542
  }
20048
20543
 
20049
20544
  // src/commands/backlog/reorderPhaseRows.ts
20050
20545
  async function reorderPhaseRows(orm, itemId2, fromIdx, toIdx) {
20051
20546
  await orm.transaction(async (tx) => {
20052
- const [phaseRow] = await tx.select({ name: planPhases.name, manualChecks: planPhases.manualChecks }).from(planPhases).where(and16(eq43(planPhases.itemId, itemId2), eq43(planPhases.idx, fromIdx)));
20053
- 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));
20054
20549
  await tx.delete(planTasks).where(
20055
- and16(eq43(planTasks.itemId, itemId2), eq43(planTasks.phaseIdx, fromIdx))
20550
+ and19(eq46(planTasks.itemId, itemId2), eq46(planTasks.phaseIdx, fromIdx))
20056
20551
  );
20057
- 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)));
20058
20553
  await reindexPhases(tx, itemId2);
20059
20554
  await shiftPhasesUp(tx, itemId2, toIdx);
20060
20555
  await tx.insert(planPhases).values({
@@ -20095,7 +20590,7 @@ async function movePhase(id, from, to) {
20095
20590
  if (!found) return;
20096
20591
  const { orm, item } = found;
20097
20592
  const itemId2 = item.id;
20098
- 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));
20099
20594
  const phaseCount = row3?.cnt ?? 0;
20100
20595
  const fromIdx = toIndex2(from, phaseCount);
20101
20596
  if (fromIdx === void 0) return;
@@ -20111,22 +20606,22 @@ async function movePhase(id, from, to) {
20111
20606
  import chalk101 from "chalk";
20112
20607
 
20113
20608
  // src/commands/backlog/applyPhaseUpdate.ts
20114
- import { and as and17, eq as eq45 } from "drizzle-orm";
20609
+ import { and as and20, eq as eq48 } from "drizzle-orm";
20115
20610
  async function applyPhaseUpdate(orm, itemId2, phaseIdx, fields) {
20116
20611
  await orm.transaction(async (tx) => {
20117
20612
  if (fields.name) {
20118
20613
  await tx.update(planPhases).set({ name: fields.name }).where(
20119
- and17(eq45(planPhases.itemId, itemId2), eq45(planPhases.idx, phaseIdx))
20614
+ and20(eq48(planPhases.itemId, itemId2), eq48(planPhases.idx, phaseIdx))
20120
20615
  );
20121
20616
  }
20122
20617
  if (fields.manualCheck) {
20123
20618
  await tx.update(planPhases).set({ manualChecks: JSON.stringify(fields.manualCheck) }).where(
20124
- and17(eq45(planPhases.itemId, itemId2), eq45(planPhases.idx, phaseIdx))
20619
+ and20(eq48(planPhases.itemId, itemId2), eq48(planPhases.idx, phaseIdx))
20125
20620
  );
20126
20621
  }
20127
20622
  if (fields.task) {
20128
20623
  await tx.delete(planTasks).where(
20129
- and17(eq45(planTasks.itemId, itemId2), eq45(planTasks.phaseIdx, phaseIdx))
20624
+ and20(eq48(planTasks.itemId, itemId2), eq48(planTasks.phaseIdx, phaseIdx))
20130
20625
  );
20131
20626
  if (fields.task.length) {
20132
20627
  await tx.insert(planTasks).values(
@@ -20144,14 +20639,14 @@ async function applyPhaseUpdate(orm, itemId2, phaseIdx, fields) {
20144
20639
 
20145
20640
  // src/commands/backlog/findPhase.ts
20146
20641
  import chalk100 from "chalk";
20147
- 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";
20148
20643
  async function findPhase(id, phase) {
20149
20644
  const found = await findOneItem(id);
20150
20645
  if (!found) return void 0;
20151
20646
  const { orm, item } = found;
20152
20647
  const itemId2 = item.id;
20153
20648
  const phaseIdx = Number.parseInt(phase, 10) - 1;
20154
- 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)));
20155
20650
  if (!row3 || row3.cnt === 0) {
20156
20651
  console.log(
20157
20652
  chalk100.red(
@@ -20324,16 +20819,16 @@ function registerUpdatePhaseCommand(cmd) {
20324
20819
 
20325
20820
  // src/commands/backlog/removePhase.ts
20326
20821
  import chalk102 from "chalk";
20327
- import { and as and19, eq as eq47 } from "drizzle-orm";
20822
+ import { and as and22, eq as eq50 } from "drizzle-orm";
20328
20823
  async function removePhase(id, phase) {
20329
20824
  const found = await findPhase(id, phase);
20330
20825
  if (!found) return;
20331
20826
  const { item, orm, itemId: itemId2, phaseIdx } = found;
20332
20827
  await orm.transaction(async (tx) => {
20333
20828
  await tx.delete(planTasks).where(
20334
- and19(eq47(planTasks.itemId, itemId2), eq47(planTasks.phaseIdx, phaseIdx))
20829
+ and22(eq50(planTasks.itemId, itemId2), eq50(planTasks.phaseIdx, phaseIdx))
20335
20830
  );
20336
- 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)));
20337
20832
  await reindexPhases(tx, itemId2);
20338
20833
  await adjustCurrentPhase(tx, item, phaseIdx);
20339
20834
  });
@@ -20346,13 +20841,13 @@ async function removePhase(id, phase) {
20346
20841
 
20347
20842
  // src/commands/backlog/update/update.ts
20348
20843
  import chalk106 from "chalk";
20349
- import { eq as eq48 } from "drizzle-orm";
20844
+ import { eq as eq51 } from "drizzle-orm";
20350
20845
 
20351
20846
  // src/commands/backlog/update/buildUpdateValues.ts
20352
20847
  import chalk103 from "chalk";
20353
20848
  function buildUpdateValues(options2) {
20354
- const { name, desc: desc8, type, ac, origin } = options2;
20355
- if (!name && !desc8 && !type && !ac && !origin) {
20849
+ const { name, desc: desc9, type, ac, origin } = options2;
20850
+ if (!name && !desc9 && !type && !ac && !origin) {
20356
20851
  console.log(chalk103.red("Nothing to update. Provide at least one flag."));
20357
20852
  process.exitCode = 1;
20358
20853
  return void 0;
@@ -20368,8 +20863,8 @@ function buildUpdateValues(options2) {
20368
20863
  set.name = name;
20369
20864
  fieldNames.push("name");
20370
20865
  }
20371
- if (desc8) {
20372
- set.description = desc8.replaceAll(String.raw`\n`, "\n");
20866
+ if (desc9) {
20867
+ set.description = desc9.replaceAll(String.raw`\n`, "\n");
20373
20868
  fieldNames.push("description");
20374
20869
  }
20375
20870
  if (type) {
@@ -20457,7 +20952,7 @@ async function update(id, options2) {
20457
20952
  if (!built) return;
20458
20953
  const { orm } = found;
20459
20954
  const itemId2 = found.item.id;
20460
- 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));
20461
20956
  console.log(
20462
20957
  chalk106.green(`Updated ${built.fields} on item ${formatItemId(itemId2)}.`)
20463
20958
  );
@@ -20492,9 +20987,9 @@ function registerUpdateFieldCommand(cmd) {
20492
20987
  import chalk108 from "chalk";
20493
20988
 
20494
20989
  // src/commands/backlog/updatePlan/planUpdateSchema.ts
20495
- import { z as z14 } from "zod";
20496
- var planUpdateSchema = z14.strictObject({
20497
- 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")
20498
20993
  });
20499
20994
 
20500
20995
  // src/commands/backlog/updatePlan/readPlanUpdate.ts
@@ -20503,7 +20998,7 @@ function readPlanUpdate(source) {
20503
20998
  }
20504
20999
 
20505
21000
  // src/commands/backlog/updatePlan/reviewPlanUpdate.ts
20506
- import { randomUUID as randomUUID11 } from "crypto";
21001
+ import { randomUUID as randomUUID12 } from "crypto";
20507
21002
  import chalk107 from "chalk";
20508
21003
 
20509
21004
  // src/commands/backlog/updatePlan/isCompleted.ts
@@ -20660,7 +21155,7 @@ async function reviewPlanUpdate(item, phases) {
20660
21155
  if (process.env.ASSIST_SESSION === "1" && sessionId) {
20661
21156
  const decision = await awaitPreviewApproval("Plan update preview", {
20662
21157
  sessionId,
20663
- requestId: randomUUID11(),
21158
+ requestId: randomUUID12(),
20664
21159
  title: `Update the plan for ${formatItemId(item.id)}: ${item.name}`,
20665
21160
  body,
20666
21161
  prNumber: null,
@@ -21089,21 +21584,21 @@ function registerBranch(program) {
21089
21584
  import { basename as basename15 } from "path";
21090
21585
 
21091
21586
  // src/commands/backlog/isDocsLocked.ts
21092
- 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";
21093
21588
  async function isDocsRefreshItem(itemId2) {
21094
21589
  const orm = await getDb();
21095
- 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);
21096
21591
  return row3 !== void 0;
21097
21592
  }
21098
21593
  async function hasOpenDocsUnlock(itemId2) {
21099
21594
  const orm = await getDb();
21100
- const [row3] = await orm.select({ itemId: itemGitRefs.itemId }).from(itemGitRefs).innerJoin(items, eq49(items.id, itemGitRefs.itemId)).where(
21101
- and20(
21102
- eq49(itemGitRefs.itemId, itemId2),
21103
- eq49(itemGitRefs.kind, "docs-unlock"),
21104
- 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(
21105
21600
  itemGitRefs.ref,
21106
- sql25`'phase-' || coalesce(${items.currentPhase}, 1)`
21601
+ sql26`'phase-' || coalesce(${items.currentPhase}, 1)`
21107
21602
  ),
21108
21603
  notInArray2(items.status, ["done", "wontdo"])
21109
21604
  )
@@ -22761,13 +23256,13 @@ import { mkdirSync as mkdirSync17, writeFileSync as writeFileSync27 } from "fs";
22761
23256
  import { randomInt } from "crypto";
22762
23257
 
22763
23258
  // src/commands/notify/deliverPinNotification.ts
22764
- import { randomUUID as randomUUID12 } from "crypto";
23259
+ import { randomUUID as randomUUID13 } from "crypto";
22765
23260
 
22766
23261
  // src/commands/notify/showNotification.ts
22767
23262
  import notifier from "node-notifier";
22768
23263
 
22769
23264
  // src/commands/notify/showNotification/showWindowsNotificationFromWsl.ts
22770
- import { spawn as spawn5 } from "child_process";
23265
+ import { spawn as spawn6 } from "child_process";
22771
23266
  import fs15 from "fs";
22772
23267
  import { createRequire as createRequire2 } from "module";
22773
23268
  import path30 from "path";
@@ -22787,7 +23282,7 @@ function showWindowsNotificationFromWsl(options2) {
22787
23282
  if (sound) {
22788
23283
  args.push("-s", "ms-winsoundevent:Notification.Default");
22789
23284
  }
22790
- const child = spawn5(snoreToastPath, args, {
23285
+ const child = spawn6(snoreToastPath, args, {
22791
23286
  detached: true,
22792
23287
  stdio: "ignore"
22793
23288
  });
@@ -22823,7 +23318,7 @@ var ROUTE_TIMEOUT_MS = 1e4;
22823
23318
  async function relayToViewerNode(notification) {
22824
23319
  const sessionId = process.env.ASSIST_SESSION_ID;
22825
23320
  if (!sessionId) return void 0;
22826
- const requestId = randomUUID12();
23321
+ const requestId = randomUUID13();
22827
23322
  const reply2 = await requestDaemonReply(
22828
23323
  { type: "notify-pin", sessionId, requestId, ...notification },
22829
23324
  "notify-pin-result",
@@ -24063,10 +24558,10 @@ async function sloc(pattern2 = "**/*.ts", options2 = {}) {
24063
24558
  const color = exceedsThreshold ? chalk128.red : chalk128.white;
24064
24559
  console.log(`${color(file)} \u2192 ${chalk128.cyan(lines2)} lines`);
24065
24560
  }
24066
- const total2 = results.reduce((sum3, r) => sum3 + r.lines, 0);
24561
+ const total3 = results.reduce((sum3, r) => sum3 + r.lines, 0);
24067
24562
  console.log(
24068
24563
  chalk128.dim(`
24069
- Total: ${total2} lines across ${files.length} files`)
24564
+ Total: ${total3} lines across ${files.length} files`)
24070
24565
  );
24071
24566
  if (hasViolation) {
24072
24567
  process.exit(1);
@@ -24470,8 +24965,8 @@ function matching(filter) {
24470
24965
  const needle = filter.toLowerCase();
24471
24966
  return (leaf) => leaf.key.toLowerCase().includes(needle);
24472
24967
  }
24473
- function headline(shown, total2, filter) {
24474
- 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`);
24475
24970
  }
24476
24971
  function formatLeaf(leaf, help) {
24477
24972
  const meta = [typeText(leaf), `default: ${formatConfigDefault(leaf)}`];
@@ -24708,15 +25203,15 @@ function registerConfig(program) {
24708
25203
  import chalk146 from "chalk";
24709
25204
 
24710
25205
  // src/commands/browser/formatInspectMatches.ts
24711
- function formatInspectMatches({ matches, total: total2 }, query) {
24712
- if (total2 === 0) return [`no elements match ${query}`];
25206
+ function formatInspectMatches({ matches, total: total3 }, query) {
25207
+ if (total3 === 0) return [`no elements match ${query}`];
24713
25208
  const lines2 = matches.flatMap((match, index3) => [
24714
- `[${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)}`,
24715
25210
  ...match.chain.map((step3) => ` ${step3}`)
24716
25211
  ]);
24717
- if (total2 > matches.length)
25212
+ if (total3 > matches.length)
24718
25213
  lines2.push(
24719
- `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`
24720
25215
  );
24721
25216
  return lines2;
24722
25217
  }
@@ -25945,30 +26440,30 @@ import { dirname as dirname31, join as join70 } from "path";
25945
26440
  import chalk163 from "chalk";
25946
26441
 
25947
26442
  // src/commands/devlog/write/devEntryInputSchema.ts
25948
- import { z as z15 } from "zod";
25949
- var oneLine = z15.string().trim().min(1).refine((value) => !value.includes("\n"), "must be a single line");
25950
- 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");
25951
26446
  var MAX_ITEM_LENGTH = 80;
25952
26447
  var itemText = oneLine.refine(
25953
26448
  (value) => value.length <= MAX_ITEM_LENGTH,
25954
26449
  `must be a short changelog phrase (at most ${MAX_ITEM_LENGTH} characters)`
25955
26450
  );
25956
- 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([]);
25957
26452
  function datesWithinWeek(week, dates) {
25958
26453
  if (!isValidWeek(week)) return true;
25959
26454
  const { start: start2, end } = isoWeekRange(week);
25960
26455
  return start2 <= dates.first && dates.first <= dates.last && dates.last <= end;
25961
26456
  }
25962
- var devEntryInputSchema = z15.object({
25963
- 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"),
25964
26459
  title: oneLine,
25965
- dates: z15.object({ first: isoDate, last: isoDate }).strict(),
25966
- 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(),
25967
26462
  aiGenerated: oneLine,
25968
26463
  added: changeItems,
25969
26464
  changed: changeItems,
25970
26465
  fixed: changeItems,
25971
- lede: z15.string().trim().min(1)
26466
+ lede: z17.string().trim().min(1)
25972
26467
  }).strict().refine((entry) => datesWithinWeek(entry.week, entry.dates), {
25973
26468
  message: "first and last must be in order and within the week",
25974
26469
  path: ["dates"]
@@ -28148,7 +28643,7 @@ function buildFixStructurePlan(issues, options2) {
28148
28643
  tooDeep,
28149
28644
  typeChangeCount: entries.filter((entry) => entry.typeChange).length,
28150
28645
  labelRemovalCount: entries.reduce(
28151
- (total2, entry) => total2 + entry.labelRemovals.length,
28646
+ (total3, entry) => total3 + entry.labelRemovals.length,
28152
28647
  0
28153
28648
  )
28154
28649
  };
@@ -28475,13 +28970,13 @@ function validateProposedContent(labels, title, body) {
28475
28970
  }
28476
28971
 
28477
28972
  // src/commands/github/issue/reviewProposedIssueComment.ts
28478
- import { randomUUID as randomUUID13 } from "crypto";
28973
+ import { randomUUID as randomUUID14 } from "crypto";
28479
28974
  async function reviewProposedIssueComment(title, body) {
28480
28975
  const sessionId = process.env.ASSIST_SESSION_ID;
28481
28976
  if (process.env.ASSIST_SESSION !== "1" || !sessionId) return;
28482
28977
  await awaitPreviewApproval("GitHub issue comment preview", {
28483
28978
  sessionId,
28484
- requestId: randomUUID13(),
28979
+ requestId: randomUUID14(),
28485
28980
  title,
28486
28981
  body,
28487
28982
  prNumber: null,
@@ -28999,13 +29494,13 @@ function resolveCreateIssueMetadata(options2) {
28999
29494
  }
29000
29495
 
29001
29496
  // src/commands/github/issue/reviewProposedIssue.ts
29002
- import { randomUUID as randomUUID14 } from "crypto";
29497
+ import { randomUUID as randomUUID15 } from "crypto";
29003
29498
  async function reviewProposedIssue(title, body, metadata2 = []) {
29004
29499
  const sessionId = process.env.ASSIST_SESSION_ID;
29005
29500
  if (process.env.ASSIST_SESSION !== "1" || !sessionId) return void 0;
29006
29501
  return await awaitPreviewApproval("GitHub issue preview", {
29007
29502
  sessionId,
29008
- requestId: randomUUID14(),
29503
+ requestId: randomUUID15(),
29009
29504
  title,
29010
29505
  body,
29011
29506
  prNumber: null,
@@ -29305,7 +29800,7 @@ function pushUnchangedIssue(number, repo, target, fetchedAt, bodyPath) {
29305
29800
  }
29306
29801
 
29307
29802
  // src/commands/github/issue/reviewProposedIssueEdit.ts
29308
- import { randomUUID as randomUUID15 } from "crypto";
29803
+ import { randomUUID as randomUUID16 } from "crypto";
29309
29804
  async function reviewProposedIssueEdit(title, body, working) {
29310
29805
  const sessionId = process.env.ASSIST_SESSION_ID;
29311
29806
  if (process.env.ASSIST_SESSION !== "1" || !sessionId) return body;
@@ -29313,7 +29808,7 @@ async function reviewProposedIssueEdit(title, body, working) {
29313
29808
  "GitHub issue edit preview",
29314
29809
  {
29315
29810
  sessionId,
29316
- requestId: randomUUID15(),
29811
+ requestId: randomUUID16(),
29317
29812
  title,
29318
29813
  body,
29319
29814
  prNumber: null,
@@ -29728,11 +30223,6 @@ function formatScanCost(costUsd) {
29728
30223
  return `$${costUsd.toFixed(2)}`;
29729
30224
  }
29730
30225
 
29731
- // src/commands/inbox/scanUsageTokens.ts
29732
- function scanUsageTokens(usage) {
29733
- return usage.input + usage.output + usage.cacheRead + (usage.cacheWrite ?? 0);
29734
- }
29735
-
29736
30226
  // src/commands/inbox/formatScanUsage.ts
29737
30227
  function formatScanUsage(usage) {
29738
30228
  const tokens = `${formatTokens(scanUsageTokens(usage))} tokens`;
@@ -29754,357 +30244,10 @@ async function writeInboxLastScan(orm, at2) {
29754
30244
  await orm.insert(metadata).values({ key: INBOX_LAST_SCAN_KEY, value }).onConflictDoUpdate({ target: metadata.key, set: { value } });
29755
30245
  }
29756
30246
 
29757
- // src/commands/inbox/runInboxScanClaude.ts
29758
- import { spawn as spawn6 } from "child_process";
29759
- import { z as z17 } from "zod";
29760
-
29761
- // src/commands/review/attachLineParser.ts
29762
- function flushBuffer(buffer, onLine) {
29763
- let remaining = buffer;
29764
- while (true) {
29765
- const idx = remaining.indexOf("\n");
29766
- if (idx === -1) return remaining;
29767
- const line = remaining.slice(0, idx);
29768
- remaining = remaining.slice(idx + 1);
29769
- if (line.trim()) onLine(line);
29770
- }
29771
- }
29772
- function attachLineParser(child, onLine) {
29773
- let buffer = "";
29774
- child.stdout?.on("data", (chunk) => {
29775
- buffer += chunk.toString("utf8");
29776
- buffer = flushBuffer(buffer, onLine);
29777
- });
29778
- return () => {
29779
- if (buffer.trim()) onLine(buffer);
29780
- };
29781
- }
29782
-
29783
- // src/commands/review/attachStderrCollector.ts
29784
- function attachStderrCollector(child) {
29785
- const state = { value: "" };
29786
- child.stderr?.on("data", (chunk) => {
29787
- state.value += chunk.toString("utf8");
29788
- });
29789
- return state;
29790
- }
29791
-
29792
- // src/commands/inbox/buildInboxScanPrompt.ts
29793
- function buildInboxScanPrompt(since) {
29794
- const sinceUnix = Math.floor(since.getTime() / 1e3);
29795
- return [
29796
- "Triage my Gmail and Slack for messages a person wrote to me that look like they need my reply.",
29797
- "You are read-only: never label, mark read, react to, reply to or otherwise change any message.",
29798
- "",
29799
- "Gmail:",
29800
- '- Call search_threads with query "in:inbox is:unread" (page through all results).',
29801
- "- Call get_thread with messageFormat PLAIN_TEXT on each thread.",
29802
- "- Consider the latest unread message in each thread.",
29803
- "",
29804
- `Slack (only messages since ${since.toISOString()}, unix ${sinceUnix}):`,
29805
- `- Call slack_search_public_and_private with filters "is:dm" and after "${sinceUnix}".`,
29806
- `- 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.`,
29807
- "- Skip messages I wrote myself.",
29808
- "- For a message in a thread, call slack_read_thread and skip it if I have replied in that thread after it.",
29809
- "",
29810
- "Do not flag anything from bots, apps, automated or notification systems (CI, calendars, ticketing, monitoring, no-reply addresses), newsletters or mailing lists.",
29811
- "Flag only messages a human wrote that ask me something, request something of me, or otherwise expect my response.",
29812
- "",
29813
- "For each flagged message return:",
29814
- '- source: "gmail" or "slack"',
29815
- "- messageId: the Gmail message id, or for Slack <channel_id>:<message ts>",
29816
- "- sender: the sender's name",
29817
- "- summary: one sentence on what they need from me",
29818
- "- link: the Gmail message viewUrl or the Slack permalink",
29819
- "- receivedAt: when it was sent, as an ISO 8601 timestamp",
29820
- "",
29821
- "Return an empty messages array when nothing needs a reply."
29822
- ].join("\n");
29823
- }
29824
-
29825
- // src/commands/inbox/describeInboxScanTool.ts
29826
- function pick(input, keys) {
29827
- return keys.map((key) => input[key]).filter(
29828
- (value) => typeof value === "string" || typeof value === "number"
29829
- ).map(String);
29830
- }
29831
- function toolLabel(name) {
29832
- const match = name.match(/^mcp__claude_ai_([^_]+)__(?:slack_)?(.+)$/);
29833
- return match ? `${match[1]} ${match[2]}` : name;
29834
- }
29835
- function describeInboxScanTool(name, input) {
29836
- const record = input && typeof input === "object" ? input : {};
29837
- const detail = pick(record, [
29838
- "query",
29839
- "thread_id",
29840
- "threadId",
29841
- "channel_id",
29842
- "message_ts"
29843
- ]).join(" ");
29844
- return { label: toolLabel(name), detail };
29845
- }
29846
-
29847
- // src/commands/inbox/assistantScanEvents.ts
29848
- var MAX_TEXT = 500;
29849
- function truncate(text20) {
29850
- const trimmed = text20.trim();
29851
- return trimmed.length <= MAX_TEXT ? trimmed : `${trimmed.slice(0, MAX_TEXT - 1)}\u2026`;
29852
- }
29853
- function blockEvent(block) {
29854
- if (block.type === "tool_use") {
29855
- const name = typeof block.name === "string" ? block.name : "tool";
29856
- return { kind: "tool", ...describeInboxScanTool(name, block.input) };
29857
- }
29858
- if (block.type === "text" && typeof block.text === "string" && block.text.trim())
29859
- return { kind: "text", label: "Assistant", detail: truncate(block.text) };
29860
- return void 0;
29861
- }
29862
- function assistantScanEvents(content) {
29863
- if (!Array.isArray(content)) return [];
29864
- const at2 = (/* @__PURE__ */ new Date()).toISOString();
29865
- return content.map(blockEvent).filter((event) => event !== void 0).map((event) => ({ at: at2, ...event }));
29866
- }
29867
-
29868
- // src/commands/review/parseTokenUsage.ts
29869
- function count9(value) {
29870
- return typeof value === "number" ? value : 0;
29871
- }
29872
- function parseTokenUsage(usage, keys) {
29873
- if (typeof usage !== "object" || usage === null) return void 0;
29874
- const raw = usage;
29875
- const parsed = {
29876
- input: count9(raw.input_tokens),
29877
- output: count9(raw.output_tokens),
29878
- cacheRead: count9(raw[keys.cacheRead])
29879
- };
29880
- if (keys.cacheWrite) parsed.cacheWrite = count9(raw[keys.cacheWrite]);
29881
- return parsed;
29882
- }
29883
-
29884
- // src/commands/review/parseClaudeUsage.ts
29885
- function parseClaudeUsage(usage) {
29886
- return parseTokenUsage(usage, {
29887
- cacheRead: "cache_read_input_tokens",
29888
- cacheWrite: "cache_creation_input_tokens"
29889
- });
29890
- }
29891
-
29892
- // src/commands/inbox/emptyScanUsage.ts
29893
- function emptyScanUsage() {
29894
- return {
29895
- input: 0,
29896
- output: 0,
29897
- cacheRead: 0,
29898
- cacheWrite: 0,
29899
- costUsd: null,
29900
- durationMs: null
29901
- };
29902
- }
29903
-
29904
- // src/commands/inbox/createScanUsageTracker.ts
29905
- var numberOrNull = (value) => typeof value === "number" ? value : null;
29906
- function createScanUsageTracker() {
29907
- const usage = emptyScanUsage();
29908
- const turns = /* @__PURE__ */ new Map();
29909
- let unsettled = 0;
29910
- return {
29911
- current: () => ({ ...usage }),
29912
- // stream-json repeats a message's usage on every content-block line, so
29913
- // each turn is counted once by message id, applying only the change.
29914
- addTurn(id, raw) {
29915
- const parsed = parseClaudeUsage(raw);
29916
- if (!parsed) return false;
29917
- const key = typeof id === "string" ? id : `turn-${turns.size}`;
29918
- const previous = turns.get(key);
29919
- turns.set(key, parsed);
29920
- usage.input += parsed.input - (previous?.input ?? 0);
29921
- usage.output += parsed.output - (previous?.output ?? 0);
29922
- usage.cacheRead += parsed.cacheRead - (previous?.cacheRead ?? 0);
29923
- usage.cacheWrite += (parsed.cacheWrite ?? 0) - (previous?.cacheWrite ?? 0);
29924
- unsettled += scanUsageTokens(parsed) - (previous ? scanUsageTokens(previous) : 0);
29925
- return true;
29926
- },
29927
- takeTurnTokens() {
29928
- const tokens = unsettled;
29929
- unsettled = 0;
29930
- return tokens > 0 ? tokens : void 0;
29931
- },
29932
- finish(result) {
29933
- usage.costUsd = numberOrNull(result.total_cost_usd);
29934
- usage.durationMs = numberOrNull(result.duration_ms);
29935
- }
29936
- };
29937
- }
29938
-
29939
- // src/commands/inbox/inboxScanSchema.ts
29940
- import { z as z16 } from "zod";
29941
- var flaggedMessageSchema = z16.object({
29942
- source: z16.enum(["gmail", "slack"]),
29943
- messageId: z16.string().min(1),
29944
- sender: z16.string().min(1),
29945
- summary: z16.string().min(1),
29946
- link: z16.string().min(1),
29947
- receivedAt: z16.string().optional()
29948
- });
29949
- var inboxScanSchema = z16.object({
29950
- messages: z16.array(flaggedMessageSchema)
29951
- });
29952
-
29953
- // src/commands/inbox/parseInboxScanOutput.ts
29954
- function parseInboxScanOutput(stdout) {
29955
- const result = JSON.parse(stdout);
29956
- if (result.is_error)
29957
- throw new Error(`Inbox scan failed: ${result.result ?? "unknown error"}`);
29958
- return inboxScanSchema.parse(result.structured_output).messages;
29959
- }
29960
-
29961
- // src/commands/inbox/parseScanStreamLine.ts
29962
- function parseScanStreamLine(line) {
29963
- try {
29964
- return JSON.parse(line);
29965
- } catch {
29966
- return void 0;
29967
- }
29968
- }
29969
-
29970
- // src/commands/inbox/createInboxScanParser.ts
29971
- function createInboxScanParser({
29972
- onEvent = () => {
29973
- },
29974
- onUsage = () => {
29975
- },
29976
- onModel = () => {
29977
- }
29978
- } = {}) {
29979
- const usage = createScanUsageTracker();
29980
- let resultLine;
29981
- const onAssistant = (message3) => {
29982
- const counted = usage.addTurn(message3?.id, message3?.usage);
29983
- for (const scanEvent of assistantScanEvents(message3?.content)) {
29984
- const tokens = usage.takeTurnTokens();
29985
- onEvent(tokens === void 0 ? scanEvent : { ...scanEvent, tokens });
29986
- }
29987
- if (counted) onUsage(usage.current());
29988
- };
29989
- return {
29990
- onLine(line) {
29991
- const event = parseScanStreamLine(line);
29992
- if (!event) return;
29993
- if (event.type === "system" && typeof event.model === "string")
29994
- onModel(event.model);
29995
- else if (event.type === "assistant") onAssistant(event.message);
29996
- else if (event.type === "result") {
29997
- resultLine = line;
29998
- usage.finish(event);
29999
- onUsage(usage.current());
30000
- }
30001
- },
30002
- finish(failure) {
30003
- if (!resultLine) throw new Error(`Inbox scan failed: ${failure}`);
30004
- return {
30005
- messages: parseInboxScanOutput(resultLine),
30006
- usage: usage.current()
30007
- };
30008
- }
30009
- };
30010
- }
30011
-
30012
- // src/commands/inbox/inboxScanTools.ts
30013
- var gmail = (tool) => `mcp__claude_ai_Gmail__${tool}`;
30014
- var slack = (tool) => `mcp__claude_ai_Slack__${tool}`;
30015
- var inboxScanTools = {
30016
- allowed: [
30017
- gmail("search_threads"),
30018
- gmail("get_thread"),
30019
- slack("slack_search_public_and_private"),
30020
- slack("slack_read_thread")
30021
- ],
30022
- denied: [
30023
- ...[
30024
- "apply_sensitive_message_label",
30025
- "apply_sensitive_thread_label",
30026
- "create_draft",
30027
- "create_label",
30028
- "delete_draft",
30029
- "delete_label",
30030
- "forward",
30031
- "label_message",
30032
- "label_thread",
30033
- "mark_message_spam",
30034
- "mark_thread_spam",
30035
- "reply",
30036
- "send_message",
30037
- "trash_message",
30038
- "trash_thread",
30039
- "unlabel_message",
30040
- "unlabel_thread",
30041
- "unmark_message_spam",
30042
- "unmark_thread_spam",
30043
- "untrash_message",
30044
- "untrash_thread",
30045
- "update_draft",
30046
- "update_label",
30047
- "update_message_labels"
30048
- ].map(gmail),
30049
- ...[
30050
- "slack_add_reaction",
30051
- "slack_create_canvas",
30052
- "slack_create_conversation",
30053
- "slack_schedule_message",
30054
- "slack_send_message",
30055
- "slack_send_message_draft",
30056
- "slack_update_canvas"
30057
- ].map(slack)
30058
- ]
30059
- };
30060
-
30061
- // src/commands/inbox/runInboxScanClaude.ts
30062
- function buildInboxScanArgs(since) {
30063
- return [
30064
- "-p",
30065
- "--tools",
30066
- "",
30067
- "--permission-mode",
30068
- "dontAsk",
30069
- "--allowedTools",
30070
- ...inboxScanTools.allowed,
30071
- "--disallowedTools",
30072
- ...inboxScanTools.denied,
30073
- "--no-session-persistence",
30074
- "--output-format",
30075
- "stream-json",
30076
- "--verbose",
30077
- "--json-schema",
30078
- JSON.stringify(z17.toJSONSchema(inboxScanSchema, { target: "draft-07" })),
30079
- "--",
30080
- buildInboxScanPrompt(since)
30081
- ];
30082
- }
30083
- function describeExit(code, signal) {
30084
- return signal ? `claude was killed (${signal})` : `claude exited ${code}`;
30085
- }
30086
- async function runInboxScanClaude(since, listener = {}) {
30087
- const child = spawn6("claude", buildInboxScanArgs(since), {
30088
- stdio: ["ignore", "pipe", "pipe"],
30089
- windowsHide: true,
30090
- timeout: 20 * 6e4
30091
- });
30092
- const parser = createInboxScanParser(listener);
30093
- const flush = attachLineParser(child, parser.onLine);
30094
- const stderr = attachStderrCollector(child);
30095
- const exit = await new Promise((resolve32, reject) => {
30096
- child.on("error", reject);
30097
- child.on("close", (code, signal) => resolve32(describeExit(code, signal)));
30098
- });
30099
- flush();
30100
- const tail = stderr.value.trim().slice(-500);
30101
- return parser.finish(tail ? `${exit}: ${tail}` : exit);
30102
- }
30103
-
30104
30247
  // src/shared/db/finishJobRun.ts
30105
- import { eq as eq50 } from "drizzle-orm";
30248
+ import { eq as eq53 } from "drizzle-orm";
30106
30249
  async function finishJobRun(db, id, result) {
30107
- await db.update(jobRuns).set(result).where(eq50(jobRuns.id, id));
30250
+ await db.update(jobRuns).set(result).where(eq53(jobRuns.id, id));
30108
30251
  }
30109
30252
 
30110
30253
  // src/shared/db/startJobRun.ts
@@ -30399,7 +30542,7 @@ function registerRefineLaunch(program, resumeFlag) {
30399
30542
  }
30400
30543
 
30401
30544
  // src/commands/fixConflict.ts
30402
- import { randomUUID as randomUUID16 } from "crypto";
30545
+ import { randomUUID as randomUUID17 } from "crypto";
30403
30546
 
30404
30547
  // src/commands/review/checkoutPr.ts
30405
30548
  import { execFileSync as execFileSync17 } from "child_process";
@@ -31184,7 +31327,7 @@ function buildPrompt2(rebase) {
31184
31327
  async function fixConflict(number, options2 = {}) {
31185
31328
  const { resumeSessionId } = options2;
31186
31329
  if (number && !resumeSessionId) await checkoutPr(number);
31187
- const claudeSessionId = resumeSessionId ?? randomUUID16();
31330
+ const claudeSessionId = resumeSessionId ?? randomUUID17();
31188
31331
  emitActivity({
31189
31332
  kind: "command",
31190
31333
  name: "fix-conflict",
@@ -31212,7 +31355,7 @@ function registerFixConflict(program, resumeFlag) {
31212
31355
  }
31213
31356
 
31214
31357
  // src/commands/reviewPrComments.ts
31215
- import { randomUUID as randomUUID17 } from "crypto";
31358
+ import { randomUUID as randomUUID18 } from "crypto";
31216
31359
  function buildPrompt3(number, announce, options2) {
31217
31360
  const args = [
31218
31361
  "/review-pr-comments",
@@ -31238,7 +31381,7 @@ async function reviewPrComments(number, options2 = {}) {
31238
31381
  validateAnnounce(number, announce);
31239
31382
  validateMode(options2);
31240
31383
  if (number && !resumeSessionId) await checkoutPr(number);
31241
- const claudeSessionId = resumeSessionId ?? randomUUID17();
31384
+ const claudeSessionId = resumeSessionId ?? randomUUID18();
31242
31385
  emitActivity({
31243
31386
  kind: "command",
31244
31387
  name: "review-pr-comments",
@@ -31780,7 +31923,7 @@ async function offerSaveExtract(extract2, options2, paths = {}) {
31780
31923
  }
31781
31924
 
31782
31925
  // src/commands/miro/pickAnchors.ts
31783
- import { randomUUID as randomUUID18 } from "crypto";
31926
+ import { randomUUID as randomUUID19 } from "crypto";
31784
31927
 
31785
31928
  // src/commands/miro/isBox.ts
31786
31929
  var boxTypes = /* @__PURE__ */ new Set(["shape", "sticky_note"]);
@@ -31801,7 +31944,7 @@ async function pickAnchors(sessionId, items2) {
31801
31944
  "Miro anchor selection",
31802
31945
  {
31803
31946
  sessionId,
31804
- requestId: randomUUID18(),
31947
+ requestId: randomUUID19(),
31805
31948
  title: "Pick the top-left then the bottom-right box",
31806
31949
  body: encodeMiroBoardPreview(items2),
31807
31950
  prNumber: null,
@@ -32756,9 +32899,9 @@ async function list4() {
32756
32899
  import chalk200 from "chalk";
32757
32900
 
32758
32901
  // src/commands/backlog/removeFeed.ts
32759
- import { eq as eq51 } from "drizzle-orm";
32902
+ import { eq as eq54 } from "drizzle-orm";
32760
32903
  async function removeFeed(db, url) {
32761
- 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 });
32762
32905
  return deleted.length > 0;
32763
32906
  }
32764
32907
 
@@ -32919,17 +33062,17 @@ function getPageSlice(pullRequests, page) {
32919
33062
  const start2 = page * PAGE_SIZE2;
32920
33063
  return pullRequests.slice(start2, start2 + PAGE_SIZE2);
32921
33064
  }
32922
- function pageHeader(page, totalPages, total2) {
33065
+ function pageHeader(page, totalPages, total3) {
32923
33066
  return `
32924
- Page ${page + 1} of ${totalPages} (${total2} total)
33067
+ Page ${page + 1} of ${totalPages} (${total3} total)
32925
33068
  `;
32926
33069
  }
32927
33070
  function displayPage(pullRequests, totalPages, page) {
32928
33071
  console.log(pageHeader(page, totalPages, pullRequests.length));
32929
33072
  for (const pr of getPageSlice(pullRequests, page)) printPr(pr);
32930
33073
  }
32931
- function hasNextPage(page, total2) {
32932
- return page < total2 - 1;
33074
+ function hasNextPage(page, total3) {
33075
+ return page < total3 - 1;
32933
33076
  }
32934
33077
  var NEXT_CHOICE = { name: "Next page", value: "next" };
32935
33078
  var PREV_CHOICE = { name: "Previous page", value: "prev" };
@@ -33032,13 +33175,13 @@ function postReviewComment(vars) {
33032
33175
  }
33033
33176
 
33034
33177
  // src/commands/prs/reviewProposedPrComment.ts
33035
- import { randomUUID as randomUUID19 } from "crypto";
33178
+ import { randomUUID as randomUUID20 } from "crypto";
33036
33179
  async function reviewProposedPrComment(title, body, prNumber) {
33037
33180
  const sessionId = process.env.ASSIST_SESSION_ID;
33038
33181
  if (process.env.ASSIST_SESSION !== "1" || !sessionId) return;
33039
33182
  await awaitPreviewApproval("PR comment preview", {
33040
33183
  sessionId,
33041
- requestId: randomUUID19(),
33184
+ requestId: randomUUID20(),
33042
33185
  title,
33043
33186
  body,
33044
33187
  prNumber,
@@ -34073,7 +34216,7 @@ function parseScreenshotSpecs(specs) {
34073
34216
  }
34074
34217
 
34075
34218
  // src/commands/prs/previewAndApplyEdit.ts
34076
- import { randomUUID as randomUUID20 } from "crypto";
34219
+ import { randomUUID as randomUUID21 } from "crypto";
34077
34220
 
34078
34221
  // src/commands/prs/stageScreenshots.ts
34079
34222
  import { readFile as readFile8 } from "fs/promises";
@@ -34095,7 +34238,7 @@ function stageScreenshots(screenshots = []) {
34095
34238
  async function previewAndApplyEdit(args) {
34096
34239
  const decision = await awaitPreviewApproval("PR preview", {
34097
34240
  sessionId: args.sessionId,
34098
- requestId: randomUUID20(),
34241
+ requestId: randomUUID21(),
34099
34242
  title: args.title ?? args.currentTitle,
34100
34243
  body: args.body,
34101
34244
  prNumber: args.number,
@@ -34430,7 +34573,7 @@ async function placePr(prNumber, title, body, options2, attachments = []) {
34430
34573
  }
34431
34574
 
34432
34575
  // src/commands/prs/previewAndPlace.ts
34433
- import { randomUUID as randomUUID21 } from "crypto";
34576
+ import { randomUUID as randomUUID22 } from "crypto";
34434
34577
 
34435
34578
  // src/commands/review/announcePr.ts
34436
34579
  function announcePr(prNumber) {
@@ -34506,7 +34649,7 @@ function enableAutoMerge() {
34506
34649
  async function previewAndPlace(args) {
34507
34650
  const decision = await awaitPreviewApproval("PR preview", {
34508
34651
  sessionId: args.sessionId,
34509
- requestId: randomUUID21(),
34652
+ requestId: randomUUID22(),
34510
34653
  title: args.title,
34511
34654
  body: args.body,
34512
34655
  prNumber: args.prNumber,
@@ -35137,11 +35280,11 @@ function parseReadBudget(value) {
35137
35280
  `Invalid budget "${value}". Use a duration like 45s, 1m30s or 2m.`
35138
35281
  );
35139
35282
  }
35140
- const total2 = Number(minutes ?? 0) * 60 + Number(seconds ?? 0);
35141
- if (total2 === 0) {
35283
+ const total3 = Number(minutes ?? 0) * 60 + Number(seconds ?? 0);
35284
+ if (total3 === 0) {
35142
35285
  throw new Error(`Invalid budget "${value}". Value must be at least 1s.`);
35143
35286
  }
35144
- return total2;
35287
+ return total3;
35145
35288
  }
35146
35289
 
35147
35290
  // src/commands/readTime/resolveReadTimeTarget.ts
@@ -39033,10 +39176,10 @@ function registerRefactor(program) {
39033
39176
  }
39034
39177
 
39035
39178
  // src/commands/review/checkoutPrSession.ts
39036
- import { randomUUID as randomUUID22 } from "crypto";
39179
+ import { randomUUID as randomUUID23 } from "crypto";
39037
39180
  async function checkoutPrSession(number, prompt = "") {
39038
39181
  await checkoutPr(number);
39039
- const claudeSessionId = randomUUID22();
39182
+ const claudeSessionId = randomUUID23();
39040
39183
  emitActivity({ kind: "command", name: "review", claudeSessionId });
39041
39184
  const { done: done2 } = spawnClaude(prompt, {
39042
39185
  permissionMode: "auto",
@@ -39397,7 +39540,7 @@ function basename24(path109) {
39397
39540
  return path109.slice(path109.lastIndexOf("/") + 1);
39398
39541
  }
39399
39542
  function sum(nodes, key) {
39400
- return nodes.reduce((total2, node) => total2 + node[key], 0);
39543
+ return nodes.reduce((total3, node) => total3 + node[key], 0);
39401
39544
  }
39402
39545
  function byName(a, b) {
39403
39546
  return a.name.localeCompare(b.name);
@@ -39441,7 +39584,7 @@ function buildHighLevelTree(files) {
39441
39584
 
39442
39585
  // src/commands/review/highLevel/buildHighLevelStructure.ts
39443
39586
  function sum2(files, key) {
39444
- return files.reduce((total2, file) => total2 + file[key], 0);
39587
+ return files.reduce((total3, file) => total3 + file[key], 0);
39445
39588
  }
39446
39589
  function countOf(files, status2) {
39447
39590
  return files.filter((file) => file.status === status2).length;
@@ -39642,12 +39785,12 @@ function visitCase(call, context) {
39642
39785
  if (!context.changed) return [toCase(call, context)];
39643
39786
  const lines2 = changedLines(call, context.changed);
39644
39787
  if (lines2.length === 0) return [];
39645
- const total2 = call.getEndLineNumber() - call.getStartLineNumber() + 1;
39788
+ const total3 = call.getEndLineNumber() - call.getStartLineNumber() + 1;
39646
39789
  return [
39647
39790
  toCase(
39648
39791
  call,
39649
39792
  context,
39650
- lines2.length === total2 ? { change: "added" } : { change: "modified", changedLines: lines2 }
39793
+ lines2.length === total3 ? { change: "added" } : { change: "modified", changedLines: lines2 }
39651
39794
  )
39652
39795
  ];
39653
39796
  }
@@ -39816,7 +39959,7 @@ var EVIDENCE_PATTERNS = [
39816
39959
  ];
39817
39960
  function countEvidence(body) {
39818
39961
  return EVIDENCE_PATTERNS.reduce(
39819
- (total2, pattern2) => total2 + (body.match(pattern2)?.length ?? 0),
39962
+ (total3, pattern2) => total3 + (body.match(pattern2)?.length ?? 0),
39820
39963
  0
39821
39964
  );
39822
39965
  }
@@ -40143,7 +40286,7 @@ function gatherHighLevelSubject(prNumber, force) {
40143
40286
  }
40144
40287
 
40145
40288
  // src/commands/review/highLevel/openHighLevelOverlay.ts
40146
- import { randomUUID as randomUUID24 } from "crypto";
40289
+ import { randomUUID as randomUUID25 } from "crypto";
40147
40290
 
40148
40291
  // src/commands/review/highLevel/highLevelProgress.ts
40149
40292
  function toItem2(check2, decision) {
@@ -40402,7 +40545,7 @@ function splitQueuedComments(record) {
40402
40545
  }
40403
40546
 
40404
40547
  // src/commands/review/highLevel/previewHighLevelReview.ts
40405
- import { randomUUID as randomUUID23 } from "crypto";
40548
+ import { randomUUID as randomUUID24 } from "crypto";
40406
40549
 
40407
40550
  // src/commands/review/highLevel/formatHighLevelReviewPreview.ts
40408
40551
  function formatHighLevelReviewPreview(lineLevel, body) {
@@ -40429,7 +40572,7 @@ async function previewHighLevelReview(sessionId, record, submission) {
40429
40572
  "Review",
40430
40573
  {
40431
40574
  sessionId,
40432
- requestId: randomUUID23(),
40575
+ requestId: randomUUID24(),
40433
40576
  title: `${LABELS[submission.event]} ${record.repo}#${record.prNumber}`,
40434
40577
  body: formatHighLevelReviewPreview(submission.comments, submission.body),
40435
40578
  prNumber: record.prNumber,
@@ -40480,7 +40623,7 @@ async function openHighLevelOverlay(sessionId, subject) {
40480
40623
  "High-level review",
40481
40624
  {
40482
40625
  sessionId,
40483
- requestId: randomUUID24(),
40626
+ requestId: randomUUID25(),
40484
40627
  title: `${subject.repo}#${subject.prNumber} \u2014 ${subject.title}`,
40485
40628
  body: JSON.stringify(highLevelPreviewPayload(subject)),
40486
40629
  prNumber: subject.prNumber,
@@ -41057,11 +41200,11 @@ function cells(usage) {
41057
41200
  format(usage.cacheWrite)
41058
41201
  ];
41059
41202
  }
41060
- function sumOf(reported, pick2) {
41061
- 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);
41062
41205
  return values.length === 0 ? void 0 : values.reduce((a, b) => a + b, 0);
41063
41206
  }
41064
- function total(usages) {
41207
+ function total2(usages) {
41065
41208
  const reported = usages.filter((u) => u !== void 0);
41066
41209
  return [
41067
41210
  format(sumOf(reported, (u) => u.input)),
@@ -41082,7 +41225,7 @@ function buildTokenUsageTable(usages) {
41082
41225
  ...usages.map(
41083
41226
  (usage, i) => row2(SLOT_LABELS[i] ?? `Slot ${i + 1}`, cells(usage))
41084
41227
  ),
41085
- row2("**Total**", total(usages))
41228
+ row2("**Total**", total2(usages))
41086
41229
  ].join("\n");
41087
41230
  }
41088
41231
 
@@ -41949,12 +42092,12 @@ function parseCodexEvent(line) {
41949
42092
  }
41950
42093
 
41951
42094
  // src/commands/review/createCodexLineHandler.ts
41952
- function addUsage(total2, turn) {
41953
- if (!total2) return turn;
42095
+ function addUsage(total3, turn) {
42096
+ if (!total3) return turn;
41954
42097
  return {
41955
- input: total2.input + turn.input,
41956
- output: total2.output + turn.output,
41957
- cacheRead: total2.cacheRead + turn.cacheRead
42098
+ input: total3.input + turn.input,
42099
+ output: total3.output + turn.output,
42100
+ cacheRead: total3.cacheRead + turn.cacheRead
41958
42101
  };
41959
42102
  }
41960
42103
  function createCodexLineHandler(name, spinner, model) {
@@ -43526,8 +43669,8 @@ function filterToSql(filter) {
43526
43669
  // src/commands/seq/fetchSeqData.ts
43527
43670
  function buildDataParams(filter, count11, from, to) {
43528
43671
  const sqlFilter = filterToSql(filter);
43529
- const sql32 = `select @Timestamp, @Level, @Exception, @Message from stream where ${sqlFilter} order by @Timestamp desc limit ${count11}`;
43530
- 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 });
43531
43674
  if (from) params.set("rangeStartUtc", from);
43532
43675
  if (to) params.set("rangeEndUtc", to);
43533
43676
  return params;
@@ -43770,7 +43913,7 @@ function registerSeq(program) {
43770
43913
  }
43771
43914
 
43772
43915
  // src/commands/show.ts
43773
- import { randomUUID as randomUUID25 } from "crypto";
43916
+ import { randomUUID as randomUUID26 } from "crypto";
43774
43917
 
43775
43918
  // src/commands/sessions/shared/sendShowPreview.ts
43776
43919
  async function sendShowPreview(request) {
@@ -43929,7 +44072,7 @@ async function show3(options2) {
43929
44072
  try {
43930
44073
  await sendShowPreview({
43931
44074
  sessionId,
43932
- requestId: randomUUID25(),
44075
+ requestId: randomUUID26(),
43933
44076
  title: options2.title ?? "Show",
43934
44077
  body
43935
44078
  });
@@ -44015,7 +44158,7 @@ function readSlackParts(files) {
44015
44158
  }
44016
44159
 
44017
44160
  // src/commands/slack/reviewProposedSlackMessage.ts
44018
- import { randomUUID as randomUUID26 } from "crypto";
44161
+ import { randomUUID as randomUUID27 } from "crypto";
44019
44162
  async function reviewProposedSlackMessage(target, body, workingPath) {
44020
44163
  const sessionId = process.env.ASSIST_SESSION_ID;
44021
44164
  if (process.env.ASSIST_SESSION !== "1" || !sessionId) return;
@@ -44025,7 +44168,7 @@ async function reviewProposedSlackMessage(target, body, workingPath) {
44025
44168
  part ? `Slack message ${part.index} of ${part.total}` : "Slack message preview",
44026
44169
  {
44027
44170
  sessionId,
44028
- requestId: randomUUID26(),
44171
+ requestId: randomUUID27(),
44029
44172
  title: part ? `${destination} (${part.index}/${part.total})` : destination,
44030
44173
  body,
44031
44174
  prNumber: null,
@@ -44150,26 +44293,26 @@ import chalk271 from "chalk";
44150
44293
  // src/commands/sql/loadConnections.ts
44151
44294
  function loadConnections3() {
44152
44295
  const raw = loadGlobalConfigRaw();
44153
- const sql32 = raw.sql;
44154
- return sql32?.connections ?? [];
44296
+ const sql33 = raw.sql;
44297
+ return sql33?.connections ?? [];
44155
44298
  }
44156
44299
  function saveConnections3(connections) {
44157
44300
  const raw = loadGlobalConfigRaw();
44158
- const sql32 = raw.sql ?? {};
44159
- sql32.connections = connections;
44160
- raw.sql = sql32;
44301
+ const sql33 = raw.sql ?? {};
44302
+ sql33.connections = connections;
44303
+ raw.sql = sql33;
44161
44304
  saveGlobalConfig(raw);
44162
44305
  }
44163
44306
  function getDefaultConnection2() {
44164
44307
  const raw = loadGlobalConfigRaw();
44165
- const sql32 = raw.sql;
44166
- return sql32?.defaultConnection;
44308
+ const sql33 = raw.sql;
44309
+ return sql33?.defaultConnection;
44167
44310
  }
44168
44311
  function setDefaultConnection2(name) {
44169
44312
  const raw = loadGlobalConfigRaw();
44170
- const sql32 = raw.sql ?? {};
44171
- sql32.defaultConnection = name;
44172
- raw.sql = sql32;
44313
+ const sql33 = raw.sql ?? {};
44314
+ sql33.defaultConnection = name;
44315
+ raw.sql = sql33;
44173
44316
  saveGlobalConfig(raw);
44174
44317
  }
44175
44318
 
@@ -44240,9 +44383,9 @@ function resolveConnection3(name) {
44240
44383
  }
44241
44384
 
44242
44385
  // src/commands/sql/sqlConnect.ts
44243
- import sql26 from "mssql";
44386
+ import sql27 from "mssql";
44244
44387
  async function sqlConnect(conn) {
44245
- return await sql26.connect({
44388
+ return await sql27.connect({
44246
44389
  server: conn.server,
44247
44390
  port: conn.port,
44248
44391
  user: conn.user,
@@ -44305,11 +44448,11 @@ var MUTATION_PATTERN = new RegExp(
44305
44448
  `\\b(${MUTATION_KEYWORDS.join("|")})\\b`,
44306
44449
  "i"
44307
44450
  );
44308
- function stripComments(sql32) {
44309
- return sql32.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ");
44451
+ function stripComments(sql33) {
44452
+ return sql33.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ");
44310
44453
  }
44311
- function isMutation(sql32) {
44312
- const stripped = stripComments(sql32);
44454
+ function isMutation(sql33) {
44455
+ const stripped = stripComments(sql33);
44313
44456
  if (MUTATION_PATTERN.test(stripped)) return true;
44314
44457
  return /\bSELECT\b[\s\S]+\bINTO\s+\w/i.test(stripped);
44315
44458
  }
@@ -44660,13 +44803,13 @@ function syncCodexHooks(sourcePath) {
44660
44803
  // src/commands/sync/syncCodex.ts
44661
44804
  function syncCodex(claudeDir, options2) {
44662
44805
  if (!isHarnessAvailable("codex")) return;
44663
- const { total: total2, names } = installHarnessCommands(
44806
+ const { total: total3, names } = installHarnessCommands(
44664
44807
  claudeDir,
44665
44808
  harnesses.codex,
44666
44809
  commandToSkill
44667
44810
  );
44668
44811
  syncCodexHooks(path97.join(claudeDir, "..", "codex", "config.toml"));
44669
- console.log(`Synced ${total2} skill(s) to ~/.codex/skills`);
44812
+ console.log(`Synced ${total3} skill(s) to ~/.codex/skills`);
44670
44813
  if (!options2?.prune) return;
44671
44814
  const force = options2.force ?? false;
44672
44815
  reportPrune(
@@ -47382,12 +47525,12 @@ function parseEnvPairs(pairs) {
47382
47525
  if (pairs.length === 0) return void 0;
47383
47526
  const env = {};
47384
47527
  for (const pair of pairs) {
47385
- const eq55 = pair.indexOf("=");
47386
- if (eq55 <= 0) {
47528
+ const eq58 = pair.indexOf("=");
47529
+ if (eq58 <= 0) {
47387
47530
  console.error(`--env must be KEY=VALUE, got "${pair}"`);
47388
47531
  process.exit(1);
47389
47532
  }
47390
- env[pair.slice(0, eq55)] = pair.slice(eq55 + 1);
47533
+ env[pair.slice(0, eq58)] = pair.slice(eq58 + 1);
47391
47534
  }
47392
47535
  return env;
47393
47536
  }
@@ -47400,11 +47543,11 @@ function fail10(spec) {
47400
47543
  process.exit(1);
47401
47544
  }
47402
47545
  function parseParamSpec(spec) {
47403
- const eq55 = spec.indexOf("=");
47404
- const name = eq55 === -1 ? spec : spec.slice(0, eq55);
47405
- if (eq55 !== -1) {
47406
- if (eq55 === 0 || name.endsWith("!")) fail10(spec);
47407
- 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) };
47408
47551
  }
47409
47552
  if (name.endsWith("!")) {
47410
47553
  if (name.length === 1) fail10(spec);
@@ -47941,6 +48084,19 @@ function createAutoExit(exit, graceMs = DEFAULT_GRACE_MS) {
47941
48084
  };
47942
48085
  }
47943
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
+
47944
48100
  // src/commands/sessions/daemon/inbox/createActivityThrottle.ts
47945
48101
  var ACTIVITY_THROTTLE_MS = 1e3;
47946
48102
  function createActivityThrottle(onActivity) {
@@ -47960,10 +48116,10 @@ function createActivityThrottle(onActivity) {
47960
48116
  }
47961
48117
 
47962
48118
  // src/shared/db/readInboxLastRun.ts
47963
- import { eq as eq52 } from "drizzle-orm";
48119
+ import { eq as eq55 } from "drizzle-orm";
47964
48120
  var INBOX_LAST_RUN_KEY = "inbox.lastRun";
47965
48121
  async function readInboxLastRun(orm) {
47966
- 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));
47967
48123
  return row3 ? JSON.parse(row3.value) : void 0;
47968
48124
  }
47969
48125
 
@@ -49123,7 +49279,7 @@ var ClientHub = class extends Set {
49123
49279
  };
49124
49280
 
49125
49281
  // src/commands/sessions/daemon/createSession.ts
49126
- import { randomUUID as randomUUID27 } from "crypto";
49282
+ import { randomUUID as randomUUID28 } from "crypto";
49127
49283
 
49128
49284
  // src/commands/sessions/daemon/sessionBase.ts
49129
49285
  function sessionBase(id, status2) {
@@ -49346,7 +49502,7 @@ function spawnRun(opts) {
49346
49502
  function createSession(id, { prompt, cwd, design, auto, harness, holdPty } = {}) {
49347
49503
  if (harness && harness !== "claude")
49348
49504
  return createHarnessSession(id, harness, prompt, cwd, holdPty);
49349
- const claudeSessionId = randomUUID27();
49505
+ const claudeSessionId = randomUUID28();
49350
49506
  return {
49351
49507
  ...sessionBase(id, prompt ? "running" : "waiting"),
49352
49508
  name: `Session ${id}`,
@@ -50280,10 +50436,10 @@ function processCwd(link3) {
50280
50436
 
50281
50437
  // src/commands/sessions/daemon/worktree/awaitTreeVacated.ts
50282
50438
  var POLL_MS3 = 500;
50283
- var GRACE_MS2 = 5e3;
50439
+ var GRACE_MS3 = 5e3;
50284
50440
  function awaitTreeVacated(session, treePath) {
50285
50441
  return new Promise((resolve32) => {
50286
- let ticks = GRACE_MS2 / POLL_MS3;
50442
+ let ticks = GRACE_MS3 / POLL_MS3;
50287
50443
  const settle = (outcome) => {
50288
50444
  clearTimeout(timer);
50289
50445
  session.closeGrace = void 0;
@@ -50483,13 +50639,13 @@ function drainSessions(sessions, notify2) {
50483
50639
  }
50484
50640
 
50485
50641
  // src/shared/db/recordPhaseActiveMs.ts
50486
- import { sql as sql27 } from "drizzle-orm";
50642
+ import { sql as sql28 } from "drizzle-orm";
50487
50643
  async function recordPhaseActiveMs(db, itemId2, phaseIdx, activeMs) {
50488
50644
  if (activeMs <= 0) return;
50489
50645
  await db.insert(phaseUsage).values({ itemId: itemId2, phaseIdx, activeMs }).onConflictDoUpdate({
50490
50646
  target: [phaseUsage.itemId, phaseUsage.phaseIdx],
50491
50647
  set: {
50492
- activeMs: sql27`${phaseUsage.activeMs} + excluded.active_ms`
50648
+ activeMs: sql28`${phaseUsage.activeMs} + excluded.active_ms`
50493
50649
  }
50494
50650
  });
50495
50651
  }
@@ -50685,7 +50841,8 @@ var PREVIEW_KINDS = [
50685
50841
  "show",
50686
50842
  "ask",
50687
50843
  "question",
50688
- "check"
50844
+ "check",
50845
+ "design"
50689
50846
  ];
50690
50847
  function isPreviewKind(value) {
50691
50848
  return PREVIEW_KINDS.includes(value);
@@ -50704,6 +50861,7 @@ function previewTargetLabel(kind, itemType, prNumber, draft) {
50704
50861
  if (kind === "ask") return "ask";
50705
50862
  if (kind === "question") return "question";
50706
50863
  if (kind === "check") return "check";
50864
+ if (kind === "design") return "design";
50707
50865
  if (kind === "backlog-item") return `backlog ${itemType}`;
50708
50866
  if (prNumber !== null) return `edit #${prNumber}`;
50709
50867
  return draft ? "create draft" : "create";
@@ -51135,10 +51293,10 @@ function applyReviewPause(session, activity2) {
51135
51293
  }
51136
51294
 
51137
51295
  // src/shared/db/getPhaseActiveMs.ts
51138
- import { and as and21, eq as eq53 } from "drizzle-orm";
51296
+ import { and as and24, eq as eq56 } from "drizzle-orm";
51139
51297
  async function getPhaseActiveMs(db, itemId2, phaseIdx) {
51140
51298
  const [row3] = await db.select({ activeMs: phaseUsage.activeMs }).from(phaseUsage).where(
51141
- and21(eq53(phaseUsage.itemId, itemId2), eq53(phaseUsage.phaseIdx, phaseIdx))
51299
+ and24(eq56(phaseUsage.itemId, itemId2), eq56(phaseUsage.phaseIdx, phaseIdx))
51142
51300
  );
51143
51301
  return row3?.activeMs ?? 0;
51144
51302
  }
@@ -51894,7 +52052,7 @@ async function readTranscriptUsage(transcriptPath2) {
51894
52052
  }
51895
52053
 
51896
52054
  // src/shared/db/recordPhaseCycleContext.ts
51897
- import { sql as sql28 } from "drizzle-orm";
52055
+ import { sql as sql29 } from "drizzle-orm";
51898
52056
  async function recordPhaseCycleContext(db, itemId2, phaseIdx, window, resetsAt, pct) {
51899
52057
  if (pct <= 0) return;
51900
52058
  await db.insert(phaseCycleContext).values({ itemId: itemId2, phaseIdx, window, resetsAt, peakContextPct: pct }).onConflictDoUpdate({
@@ -51905,24 +52063,24 @@ async function recordPhaseCycleContext(db, itemId2, phaseIdx, window, resetsAt,
51905
52063
  phaseCycleContext.resetsAt
51906
52064
  ],
51907
52065
  set: {
51908
- peakContextPct: sql28`GREATEST(${phaseCycleContext.peakContextPct}, ${pct})`
52066
+ peakContextPct: sql29`GREATEST(${phaseCycleContext.peakContextPct}, ${pct})`
51909
52067
  }
51910
52068
  });
51911
52069
  }
51912
52070
 
51913
52071
  // src/shared/db/recordPhasePeakContext.ts
51914
- import { sql as sql29 } from "drizzle-orm";
52072
+ import { sql as sql30 } from "drizzle-orm";
51915
52073
  async function recordPhasePeakContext(db, itemId2, phaseIdx, pct) {
51916
52074
  await db.insert(phaseUsage).values({ itemId: itemId2, phaseIdx, peakContextPct: pct }).onConflictDoUpdate({
51917
52075
  target: [phaseUsage.itemId, phaseUsage.phaseIdx],
51918
52076
  set: {
51919
- peakContextPct: sql29`GREATEST(${phaseUsage.peakContextPct}, ${pct})`
52077
+ peakContextPct: sql30`GREATEST(${phaseUsage.peakContextPct}, ${pct})`
51920
52078
  }
51921
52079
  });
51922
52080
  }
51923
52081
 
51924
52082
  // src/shared/db/recordPhaseTranscriptUsage.ts
51925
- import { sql as sql30 } from "drizzle-orm";
52083
+ import { sql as sql31 } from "drizzle-orm";
51926
52084
  async function recordPhaseTranscriptUsage(db, itemId2, phaseIdx, responses) {
51927
52085
  const byId = /* @__PURE__ */ new Map();
51928
52086
  for (const r of responses) byId.set(r.messageId, r);
@@ -51942,8 +52100,8 @@ async function recordPhaseTranscriptUsage(db, itemId2, phaseIdx, responses) {
51942
52100
  await tx.insert(phaseUsage).values({ itemId: itemId2, phaseIdx, tokensUp, tokensDown }).onConflictDoUpdate({
51943
52101
  target: [phaseUsage.itemId, phaseUsage.phaseIdx],
51944
52102
  set: {
51945
- tokensUp: sql30`${phaseUsage.tokensUp} + ${tokensUp}`,
51946
- tokensDown: sql30`${phaseUsage.tokensDown} + ${tokensDown}`
52103
+ tokensUp: sql31`${phaseUsage.tokensUp} + ${tokensUp}`,
52104
+ tokensDown: sql31`${phaseUsage.tokensDown} + ${tokensDown}`
51947
52105
  }
51948
52106
  });
51949
52107
  return { tokensUp, tokensDown };
@@ -51951,17 +52109,17 @@ async function recordPhaseTranscriptUsage(db, itemId2, phaseIdx, responses) {
51951
52109
  }
51952
52110
 
51953
52111
  // src/shared/db/recordWindowTokens.ts
51954
- 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";
51955
52113
  async function recordWindowTokens(db, window, resetsAt, tokensUp, tokensDown) {
51956
52114
  if (tokensUp <= 0 && tokensDown <= 0) return;
51957
52115
  await db.update(usagePeaks).set({
51958
- tokensUp: sql31`${usagePeaks.tokensUp} + ${tokensUp}`,
51959
- tokensDown: sql31`${usagePeaks.tokensDown} + ${tokensDown}`
52116
+ tokensUp: sql32`${usagePeaks.tokensUp} + ${tokensUp}`,
52117
+ tokensDown: sql32`${usagePeaks.tokensDown} + ${tokensDown}`
51960
52118
  }).where(
51961
- and22(
51962
- eq54(usagePeaks.window, window),
51963
- eq54(usagePeaks.resetsAt, resetsAt),
51964
- eq54(usagePeaks.segment, 0)
52119
+ and25(
52120
+ eq57(usagePeaks.window, window),
52121
+ eq57(usagePeaks.resetsAt, resetsAt),
52122
+ eq57(usagePeaks.segment, 0)
51965
52123
  )
51966
52124
  );
51967
52125
  }
@@ -52546,7 +52704,7 @@ function codexRespawnPlan(session) {
52546
52704
  }
52547
52705
 
52548
52706
  // src/commands/sessions/daemon/interactiveRespawnPlan.ts
52549
- import { randomUUID as randomUUID28 } from "crypto";
52707
+ import { randomUUID as randomUUID29 } from "crypto";
52550
52708
 
52551
52709
  // src/commands/sessions/daemon/hasTranscriptOnDisk.ts
52552
52710
  function hasTranscriptOnDisk(session) {
@@ -52573,7 +52731,7 @@ function interactiveRespawnPlan(session, resumes) {
52573
52731
  return null;
52574
52732
  }
52575
52733
  function freshClaudePlan(session, prompt, cwd) {
52576
- const claudeSessionId = randomUUID28();
52734
+ const claudeSessionId = randomUUID29();
52577
52735
  return {
52578
52736
  spawn: () => {
52579
52737
  session.claudeSessionId = claudeSessionId;
@@ -56451,6 +56609,7 @@ async function runDaemon() {
56451
56609
  setDaemonLogSink(manager.clients.emitLog);
56452
56610
  startDaemonLogTrimmer();
56453
56611
  pollRepoConfigCache();
56612
+ void failInterruptedJobRuns();
56454
56613
  inboxScanner.start((type) => broadcast(manager.clients, { type }));
56455
56614
  await startDaemonServer(manager, checkAutoExit);
56456
56615
  await refreshRepoConfigCacheOnStart();
@@ -57142,6 +57301,7 @@ var programRegistrars = [
57142
57301
  registerAsk,
57143
57302
  registerAskQuestion,
57144
57303
  registerAskCheck,
57304
+ registerAskDesign,
57145
57305
  registerSlack,
57146
57306
  registerSql,
57147
57307
  registerTranscript,