@staff0rd/assist 0.1004.0 → 0.1005.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.1004.0",
9
+ version: "0.1005.0",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -8222,7 +8222,7 @@ function allowAppOrigin(req, res, pathname) {
8222
8222
  res.setHeader("Access-Control-Allow-Origin", origin);
8223
8223
  res.setHeader("Vary", "Origin");
8224
8224
  if (req.method !== "OPTIONS") return false;
8225
- res.setHeader("Access-Control-Allow-Methods", "GET, POST");
8225
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
8226
8226
  res.setHeader(
8227
8227
  "Access-Control-Allow-Headers",
8228
8228
  req.headers["access-control-request-headers"] ?? "Content-Type"
@@ -8548,7 +8548,8 @@ async function inboxStatus(_req, res) {
8548
8548
  scanning: reply2.scanning,
8549
8549
  intervalMinutes: reply2.intervalMinutes,
8550
8550
  lastError: reply2.lastError,
8551
- lastScanAt: lastScanAt?.toISOString() ?? null
8551
+ lastScanAt: lastScanAt?.toISOString() ?? null,
8552
+ run: reply2.run ?? null
8552
8553
  });
8553
8554
  }
8554
8555
 
@@ -20848,7 +20849,10 @@ async function hasOpenDocsUnlock(itemId2) {
20848
20849
  and20(
20849
20850
  eq49(itemGitRefs.itemId, itemId2),
20850
20851
  eq49(itemGitRefs.kind, "docs-unlock"),
20851
- eq49(itemGitRefs.ref, sql24`'phase-' || ${items.currentPhase}`),
20852
+ eq49(
20853
+ itemGitRefs.ref,
20854
+ sql24`'phase-' || coalesce(${items.currentPhase}, 1)`
20855
+ ),
20852
20856
  notInArray2(items.status, ["done", "wontdo"])
20853
20857
  )
20854
20858
  ).limit(1);
@@ -25807,7 +25811,7 @@ async function docsConfirm(pin2) {
25807
25811
  return;
25808
25812
  }
25809
25813
  const label = `${formatItemId(state.itemId)} ${found.item.name}`;
25810
- if (found.item.currentPhase !== state.phase) {
25814
+ if ((found.item.currentPhase ?? 1) !== state.phase) {
25811
25815
  console.error(
25812
25816
  chalk165.red(
25813
25817
  `${label} has moved on from phase ${state.phase} since the unlock was requested. Nothing was approved; request a new unlock from the current phase.`
@@ -25845,13 +25849,7 @@ async function docsUnlock() {
25845
25849
  process.exitCode = 1;
25846
25850
  return;
25847
25851
  }
25848
- const phase = found.item.currentPhase;
25849
- if (!phase) {
25850
- fail7(
25851
- `${formatItemId(itemId2)} has no current phase. Docs unlock applies to the phase a session is running.`
25852
- );
25853
- return;
25854
- }
25852
+ const phase = found.item.currentPhase ?? 1;
25855
25853
  const label = `${formatItemId(itemId2)} ${found.item.name} (phase ${phase})`;
25856
25854
  const pin2 = randomInt3(0, 1e3).toString().padStart(3, "0");
25857
25855
  mkdirSync20(getRestrictedDir(), { recursive: true });
@@ -29293,10 +29291,40 @@ async function writeInboxLastScan(orm, at2) {
29293
29291
  }
29294
29292
 
29295
29293
  // src/commands/inbox/runInboxScanClaude.ts
29296
- import { execFile as execFile12 } from "child_process";
29297
- import { promisify as promisify12 } from "util";
29294
+ import { spawn as spawn6 } from "child_process";
29298
29295
  import { z as z15 } from "zod";
29299
29296
 
29297
+ // src/commands/review/attachLineParser.ts
29298
+ function flushBuffer(buffer, onLine) {
29299
+ let remaining = buffer;
29300
+ while (true) {
29301
+ const idx = remaining.indexOf("\n");
29302
+ if (idx === -1) return remaining;
29303
+ const line = remaining.slice(0, idx);
29304
+ remaining = remaining.slice(idx + 1);
29305
+ if (line.trim()) onLine(line);
29306
+ }
29307
+ }
29308
+ function attachLineParser(child, onLine) {
29309
+ let buffer = "";
29310
+ child.stdout?.on("data", (chunk) => {
29311
+ buffer += chunk.toString("utf8");
29312
+ buffer = flushBuffer(buffer, onLine);
29313
+ });
29314
+ return () => {
29315
+ if (buffer.trim()) onLine(buffer);
29316
+ };
29317
+ }
29318
+
29319
+ // src/commands/review/attachStderrCollector.ts
29320
+ function attachStderrCollector(child) {
29321
+ const state = { value: "" };
29322
+ child.stderr?.on("data", (chunk) => {
29323
+ state.value += chunk.toString("utf8");
29324
+ });
29325
+ return state;
29326
+ }
29327
+
29300
29328
  // src/commands/inbox/buildInboxScanPrompt.ts
29301
29329
  function buildInboxScanPrompt(since) {
29302
29330
  const sinceUnix = Math.floor(since.getTime() / 1e3);
@@ -29330,6 +29358,49 @@ function buildInboxScanPrompt(since) {
29330
29358
  ].join("\n");
29331
29359
  }
29332
29360
 
29361
+ // src/commands/inbox/describeInboxScanTool.ts
29362
+ function pick(input, keys) {
29363
+ return keys.map((key) => input[key]).filter(
29364
+ (value) => typeof value === "string" || typeof value === "number"
29365
+ ).map(String);
29366
+ }
29367
+ function toolLabel(name) {
29368
+ const match = name.match(/^mcp__claude_ai_([^_]+)__(?:slack_)?(.+)$/);
29369
+ return match ? `${match[1]} ${match[2]}` : name;
29370
+ }
29371
+ function describeInboxScanTool(name, input) {
29372
+ const record = input && typeof input === "object" ? input : {};
29373
+ const detail = pick(record, [
29374
+ "query",
29375
+ "thread_id",
29376
+ "threadId",
29377
+ "channel_id",
29378
+ "message_ts"
29379
+ ]).join(" ");
29380
+ return { label: toolLabel(name), detail };
29381
+ }
29382
+
29383
+ // src/commands/inbox/assistantScanEvents.ts
29384
+ var MAX_TEXT = 500;
29385
+ function truncate(text18) {
29386
+ const trimmed = text18.trim();
29387
+ return trimmed.length <= MAX_TEXT ? trimmed : `${trimmed.slice(0, MAX_TEXT - 1)}\u2026`;
29388
+ }
29389
+ function blockEvent(block) {
29390
+ if (block.type === "tool_use") {
29391
+ const name = typeof block.name === "string" ? block.name : "tool";
29392
+ return { kind: "tool", ...describeInboxScanTool(name, block.input) };
29393
+ }
29394
+ if (block.type === "text" && typeof block.text === "string" && block.text.trim())
29395
+ return { kind: "text", label: "Assistant", detail: truncate(block.text) };
29396
+ return void 0;
29397
+ }
29398
+ function assistantScanEvents(content) {
29399
+ if (!Array.isArray(content)) return [];
29400
+ const at2 = (/* @__PURE__ */ new Date()).toISOString();
29401
+ return content.map(blockEvent).filter((event) => event !== void 0).map((event) => ({ at: at2, ...event }));
29402
+ }
29403
+
29333
29404
  // src/commands/inbox/inboxScanSchema.ts
29334
29405
  import { z as z14 } from "zod";
29335
29406
  var flaggedMessageSchema = z14.object({
@@ -29344,6 +29415,37 @@ var inboxScanSchema = z14.object({
29344
29415
  messages: z14.array(flaggedMessageSchema)
29345
29416
  });
29346
29417
 
29418
+ // src/commands/inbox/parseInboxScanOutput.ts
29419
+ function parseInboxScanOutput(stdout) {
29420
+ const result = JSON.parse(stdout);
29421
+ if (result.is_error)
29422
+ throw new Error(`Inbox scan failed: ${result.result ?? "unknown error"}`);
29423
+ return inboxScanSchema.parse(result.structured_output).messages;
29424
+ }
29425
+
29426
+ // src/commands/inbox/createInboxScanParser.ts
29427
+ function createInboxScanParser(onEvent) {
29428
+ let resultLine;
29429
+ return {
29430
+ onLine(line) {
29431
+ let event;
29432
+ try {
29433
+ event = JSON.parse(line);
29434
+ } catch {
29435
+ return;
29436
+ }
29437
+ if (event.type === "assistant")
29438
+ for (const scanEvent of assistantScanEvents(event.message?.content))
29439
+ onEvent(scanEvent);
29440
+ else if (event.type === "result") resultLine = line;
29441
+ },
29442
+ finish(failure) {
29443
+ if (!resultLine) throw new Error(`Inbox scan failed: ${failure}`);
29444
+ return parseInboxScanOutput(resultLine);
29445
+ }
29446
+ };
29447
+ }
29448
+
29347
29449
  // src/commands/inbox/inboxScanTools.ts
29348
29450
  var gmail = (tool) => `mcp__claude_ai_Gmail__${tool}`;
29349
29451
  var slack = (tool) => `mcp__claude_ai_Slack__${tool}`;
@@ -29394,7 +29496,6 @@ var inboxScanTools = {
29394
29496
  };
29395
29497
 
29396
29498
  // src/commands/inbox/runInboxScanClaude.ts
29397
- var execFileAsync11 = promisify12(execFile12);
29398
29499
  function buildInboxScanArgs(since) {
29399
29500
  return [
29400
29501
  "-p",
@@ -29408,29 +29509,34 @@ function buildInboxScanArgs(since) {
29408
29509
  ...inboxScanTools.denied,
29409
29510
  "--no-session-persistence",
29410
29511
  "--output-format",
29411
- "json",
29512
+ "stream-json",
29513
+ "--verbose",
29412
29514
  "--json-schema",
29413
29515
  JSON.stringify(z15.toJSONSchema(inboxScanSchema, { target: "draft-07" })),
29414
29516
  "--",
29415
29517
  buildInboxScanPrompt(since)
29416
29518
  ];
29417
29519
  }
29418
- function parseInboxScanOutput(stdout) {
29419
- const result = JSON.parse(stdout);
29420
- if (result.is_error)
29421
- throw new Error(`Inbox scan failed: ${result.result ?? "unknown error"}`);
29422
- return inboxScanSchema.parse(result.structured_output).messages;
29520
+ function describeExit(code, signal) {
29521
+ return signal ? `claude was killed (${signal})` : `claude exited ${code}`;
29423
29522
  }
29424
- async function runInboxScanClaude(since) {
29425
- const run4 = execFileAsync11("claude", buildInboxScanArgs(since), {
29426
- encoding: "utf8",
29523
+ async function runInboxScanClaude(since, onEvent = () => {
29524
+ }) {
29525
+ const child = spawn6("claude", buildInboxScanArgs(since), {
29526
+ stdio: ["ignore", "pipe", "pipe"],
29427
29527
  windowsHide: true,
29428
- timeout: 20 * 6e4,
29429
- maxBuffer: 64 * 1024 * 1024
29528
+ timeout: 20 * 6e4
29430
29529
  });
29431
- run4.child.stdin?.end();
29432
- const { stdout } = await run4;
29433
- return parseInboxScanOutput(stdout);
29530
+ const parser = createInboxScanParser(onEvent);
29531
+ const flush = attachLineParser(child, parser.onLine);
29532
+ const stderr = attachStderrCollector(child);
29533
+ const exit = await new Promise((resolve32, reject) => {
29534
+ child.on("error", reject);
29535
+ child.on("close", (code, signal) => resolve32(describeExit(code, signal)));
29536
+ });
29537
+ flush();
29538
+ const tail = stderr.value.trim().slice(-500);
29539
+ return parser.finish(tail ? `${exit}: ${tail}` : exit);
29434
29540
  }
29435
29541
 
29436
29542
  // src/commands/inbox/runInboxScan.ts
@@ -29446,10 +29552,10 @@ function toRow2(message3) {
29446
29552
  receivedAt: receivedAt && !Number.isNaN(receivedAt.getTime()) ? receivedAt : null
29447
29553
  };
29448
29554
  }
29449
- async function runInboxScan(orm, wrap = (_since, run4) => run4()) {
29555
+ async function runInboxScan(orm, { wrap = (_since, run4) => run4(), onEvent } = {}) {
29450
29556
  const startedAt = /* @__PURE__ */ new Date();
29451
29557
  const since = await readInboxLastScan(orm) ?? new Date(startedAt.getTime() - FIRST_SCAN_LOOKBACK_MS);
29452
- const flagged = await wrap(since, () => runInboxScanClaude(since));
29558
+ const flagged = await wrap(since, () => runInboxScanClaude(since, onEvent));
29453
29559
  const added = await upsertInboxMessages(orm, flagged.map(toRow2));
29454
29560
  await writeInboxLastScan(orm, startedAt);
29455
29561
  return { flagged: flagged.length, added };
@@ -29457,13 +29563,12 @@ async function runInboxScan(orm, wrap = (_since, run4) => run4()) {
29457
29563
 
29458
29564
  // src/commands/inbox/scan.ts
29459
29565
  async function scan() {
29460
- const { flagged, added } = await runInboxScan(
29461
- await getDb(),
29462
- (since, run4) => withSpinner(
29566
+ const { flagged, added } = await runInboxScan(await getDb(), {
29567
+ wrap: (since, run4) => withSpinner(
29463
29568
  `Scanning Gmail and Slack (Slack since ${since.toISOString()})`,
29464
29569
  run4
29465
29570
  )
29466
- );
29571
+ });
29467
29572
  console.log(
29468
29573
  `Flagged ${flagged} message(s) needing a reply, ${chalk183.bold(added)} new.`
29469
29574
  );
@@ -30020,7 +30125,7 @@ function resolveInstallCommand(repoRoot2, install) {
30020
30125
  }
30021
30126
 
30022
30127
  // src/commands/sessions/daemon/worktree/spawnInstall.ts
30023
- import { spawn as spawn6 } from "child_process";
30128
+ import { spawn as spawn7 } from "child_process";
30024
30129
 
30025
30130
  // src/commands/sessions/daemon/worktree/installInvocation.ts
30026
30131
  function installInvocation(worktreePath, command) {
@@ -30046,7 +30151,7 @@ function quoteForPosixShell(value) {
30046
30151
  }
30047
30152
 
30048
30153
  // src/commands/sessions/daemon/worktree/stopInstall.ts
30049
- import { execFile as execFile13 } from "child_process";
30154
+ import { execFile as execFile12 } from "child_process";
30050
30155
  var running2 = /* @__PURE__ */ new Map();
30051
30156
  function trackInstall(worktreePath, child) {
30052
30157
  running2.set(worktreePath, child);
@@ -30067,7 +30172,7 @@ function stopInstall(worktreePath) {
30067
30172
  }
30068
30173
  function killTree(pid) {
30069
30174
  if (process.platform === "win32") {
30070
- execFile13(
30175
+ execFile12(
30071
30176
  "taskkill",
30072
30177
  ["/T", "/F", "/PID", String(pid)],
30073
30178
  { windowsHide: true },
@@ -30090,7 +30195,7 @@ function killTree(pid) {
30090
30195
  var STDERR_TAIL = 2e3;
30091
30196
  function spawnInstall(worktreePath, cwd, command, where, onDone) {
30092
30197
  daemonLog(`worktree ${worktreePath} installing deps${where}: ${command}`);
30093
- const child = spawn6(...installInvocation(cwd, command));
30198
+ const child = spawn7(...installInvocation(cwd, command));
30094
30199
  trackInstall(worktreePath, child);
30095
30200
  let stderr = "";
30096
30201
  child.stderr?.on("data", (chunk) => {
@@ -32089,7 +32194,7 @@ function registerPiHook(program) {
32089
32194
 
32090
32195
  // src/commands/prompts/printPromptsTable.ts
32091
32196
  import chalk200 from "chalk";
32092
- function truncate(str, max) {
32197
+ function truncate2(str, max) {
32093
32198
  if (str.length <= max) return str;
32094
32199
  return `${str.slice(0, max - 1)}\u2026`;
32095
32200
  }
@@ -32098,7 +32203,7 @@ function printPromptsTable(rows) {
32098
32203
  const toolWidth = Math.max(4, ...rows.map((r) => r.tool.length));
32099
32204
  const commandWidth = Math.max(
32100
32205
  7,
32101
- ...rows.map((r) => truncate(r.command, 60).length)
32206
+ ...rows.map((r) => truncate2(r.command, 60).length)
32102
32207
  );
32103
32208
  const header = [
32104
32209
  "#".padStart(countWidth),
@@ -32111,7 +32216,7 @@ function printPromptsTable(rows) {
32111
32216
  for (const row3 of rows) {
32112
32217
  const count10 = String(row3.count).padStart(countWidth);
32113
32218
  const tool = row3.tool.padEnd(toolWidth);
32114
- const command = truncate(row3.command, 60).padEnd(commandWidth);
32219
+ const command = truncate2(row3.command, 60).padEnd(commandWidth);
32115
32220
  console.log(
32116
32221
  `${chalk200.yellow(count10)} ${tool} ${command} ${chalk200.dim(row3.repos)}`
32117
32222
  );
@@ -36131,7 +36236,7 @@ function registerRootCommands(program) {
36131
36236
  }
36132
36237
 
36133
36238
  // src/commands/refactor/check.ts
36134
- import { spawn as spawn7 } from "child_process";
36239
+ import { spawn as spawn8 } from "child_process";
36135
36240
  import * as path48 from "path";
36136
36241
 
36137
36242
  // src/commands/refactor/logViolations.ts
@@ -36279,7 +36384,7 @@ function getViolations(pattern2, options2 = {}, maxLines = DEFAULT_MAX_LINES2) {
36279
36384
  // src/commands/refactor/check.ts
36280
36385
  function runScript(script, cwd) {
36281
36386
  return new Promise((resolve32) => {
36282
- const child = spawn7("npm", ["run", script], {
36387
+ const child = spawn8("npm", ["run", script], {
36283
36388
  stdio: "pipe",
36284
36389
  shell: true,
36285
36390
  cwd
@@ -40320,8 +40425,8 @@ function cells(usage) {
40320
40425
  format(usage.cacheWrite)
40321
40426
  ];
40322
40427
  }
40323
- function sumOf(reported, pick) {
40324
- const values = reported.map(pick).filter((v) => v !== void 0);
40428
+ function sumOf(reported, pick2) {
40429
+ const values = reported.map(pick2).filter((v) => v !== void 0);
40325
40430
  return values.length === 0 ? void 0 : values.reduce((a, b) => a + b, 0);
40326
40431
  }
40327
40432
  function total(usages) {
@@ -40741,7 +40846,7 @@ function buildCodexModelArgs() {
40741
40846
  import { writeFileSync as writeFileSync43 } from "fs";
40742
40847
 
40743
40848
  // src/commands/review/formatToolSummary.ts
40744
- function truncate2(value, max = 80) {
40849
+ function truncate3(value, max = 80) {
40745
40850
  const collapsed = value.replace(/\s+/g, " ").trim();
40746
40851
  if (collapsed.length <= max) return collapsed;
40747
40852
  return `${collapsed.slice(0, max - 1)}\u2026`;
@@ -40761,19 +40866,19 @@ function formatToolSummary(input) {
40761
40866
  const filePath = getString(record, "file_path") ?? getString(record, "path");
40762
40867
  if (filePath) return filePath;
40763
40868
  const command = getString(record, "command");
40764
- if (command) return truncate2(command);
40869
+ if (command) return truncate3(command);
40765
40870
  const url = getString(record, "url");
40766
40871
  if (url) return url;
40767
40872
  const query = getString(record, "query");
40768
- if (query) return truncate2(query);
40873
+ if (query) return truncate3(query);
40769
40874
  const description = getString(record, "description");
40770
- if (description) return truncate2(description);
40875
+ if (description) return truncate3(description);
40771
40876
  return "";
40772
40877
  }
40773
40878
  function simplifyShellCommand(command) {
40774
40879
  const wrapped = command.match(/^\/bin\/bash\s+-lc\s+"(.*)"\s*$/s);
40775
40880
  const inner = wrapped ? wrapped[1].replace(/\\"/g, '"') : command;
40776
- return truncate2(inner);
40881
+ return truncate3(inner);
40777
40882
  }
40778
40883
 
40779
40884
  // src/commands/review/parseTokenUsage.ts
@@ -40916,38 +41021,7 @@ function finaliseReviewerRun(spec, spinner, result) {
40916
41021
  }
40917
41022
 
40918
41023
  // src/commands/review/runStreamingChild.ts
40919
- import { spawn as spawn8 } from "child_process";
40920
-
40921
- // src/commands/review/attachLineParser.ts
40922
- function flushBuffer(buffer, onLine) {
40923
- let remaining = buffer;
40924
- while (true) {
40925
- const idx = remaining.indexOf("\n");
40926
- if (idx === -1) return remaining;
40927
- const line = remaining.slice(0, idx);
40928
- remaining = remaining.slice(idx + 1);
40929
- if (line.trim()) onLine(line);
40930
- }
40931
- }
40932
- function attachLineParser(child, onLine) {
40933
- let buffer = "";
40934
- child.stdout?.on("data", (chunk) => {
40935
- buffer += chunk.toString("utf8");
40936
- buffer = flushBuffer(buffer, onLine);
40937
- });
40938
- return () => {
40939
- if (buffer.trim()) onLine(buffer);
40940
- };
40941
- }
40942
-
40943
- // src/commands/review/attachStderrCollector.ts
40944
- function attachStderrCollector(child) {
40945
- const state = { value: "" };
40946
- child.stderr?.on("data", (chunk) => {
40947
- state.value += chunk.toString("utf8");
40948
- });
40949
- return state;
40950
- }
41024
+ import { spawn as spawn9 } from "child_process";
40951
41025
 
40952
41026
  // src/commands/review/attachStdoutTail.ts
40953
41027
  function attachStdoutTail(child, maxBytes = 8192) {
@@ -41120,7 +41194,7 @@ function writeStdinSafely(child, payload) {
41120
41194
  }
41121
41195
  }
41122
41196
  function startChild(spec) {
41123
- const child = spawn8(spec.command, spec.args, {
41197
+ const child = spawn9(spec.command, spec.args, {
41124
41198
  stdio: ["pipe", "pipe", "pipe"],
41125
41199
  shell: process.platform === "win32",
41126
41200
  ...spec.env ? { env: { ...process.env, ...spec.env } } : {}
@@ -46139,11 +46213,11 @@ function decideLap(end, interrupted) {
46139
46213
  }
46140
46214
 
46141
46215
  // src/commands/watch/runWatchLap.ts
46142
- import { spawn as spawn9 } from "child_process";
46216
+ import { spawn as spawn10 } from "child_process";
46143
46217
  var WATCH_LAP_ARGS = ["watch", "wait", "--pull", "--build"];
46144
46218
  function runWatchLap() {
46145
46219
  return new Promise((resolve32, reject) => {
46146
- const assistFromPath = spawn9("assist", WATCH_LAP_ARGS, {
46220
+ const assistFromPath = spawn10("assist", WATCH_LAP_ARGS, {
46147
46221
  stdio: "inherit",
46148
46222
  shell: process.platform === "win32"
46149
46223
  });
@@ -46494,12 +46568,12 @@ function parseEnvPairs(pairs) {
46494
46568
  if (pairs.length === 0) return void 0;
46495
46569
  const env = {};
46496
46570
  for (const pair of pairs) {
46497
- const eq53 = pair.indexOf("=");
46498
- if (eq53 <= 0) {
46571
+ const eq54 = pair.indexOf("=");
46572
+ if (eq54 <= 0) {
46499
46573
  console.error(`--env must be KEY=VALUE, got "${pair}"`);
46500
46574
  process.exit(1);
46501
46575
  }
46502
- env[pair.slice(0, eq53)] = pair.slice(eq53 + 1);
46576
+ env[pair.slice(0, eq54)] = pair.slice(eq54 + 1);
46503
46577
  }
46504
46578
  return env;
46505
46579
  }
@@ -46512,11 +46586,11 @@ function fail10(spec) {
46512
46586
  process.exit(1);
46513
46587
  }
46514
46588
  function parseParamSpec(spec) {
46515
- const eq53 = spec.indexOf("=");
46516
- const name = eq53 === -1 ? spec : spec.slice(0, eq53);
46517
- if (eq53 !== -1) {
46518
- if (eq53 === 0 || name.endsWith("!")) fail10(spec);
46519
- return { name, default: spec.slice(eq53 + 1) };
46589
+ const eq54 = spec.indexOf("=");
46590
+ const name = eq54 === -1 ? spec : spec.slice(0, eq54);
46591
+ if (eq54 !== -1) {
46592
+ if (eq54 === 0 || name.endsWith("!")) fail10(spec);
46593
+ return { name, default: spec.slice(eq54 + 1) };
46520
46594
  }
46521
46595
  if (name.endsWith("!")) {
46522
46596
  if (name.length === 1) fail10(spec);
@@ -47053,10 +47127,96 @@ function createAutoExit(exit, graceMs = DEFAULT_GRACE_MS) {
47053
47127
  };
47054
47128
  }
47055
47129
 
47056
- // src/commands/sessions/daemon/inbox/isInboxScanDue.ts
47057
- async function isInboxScanDue(intervalMinutes) {
47058
- const last = await readInboxLastScan(await getDb());
47059
- return !last || Date.now() - last.getTime() >= intervalMinutes * 6e4;
47130
+ // src/shared/db/readInboxLastRun.ts
47131
+ import { eq as eq51 } from "drizzle-orm";
47132
+ var INBOX_LAST_RUN_KEY = "inbox.lastRun";
47133
+ async function readInboxLastRun(orm) {
47134
+ const [row3] = await orm.select().from(metadata).where(eq51(metadata.key, INBOX_LAST_RUN_KEY));
47135
+ return row3 ? JSON.parse(row3.value) : void 0;
47136
+ }
47137
+
47138
+ // src/commands/sessions/daemon/inbox/loadScanRun.ts
47139
+ async function loadScanRun() {
47140
+ try {
47141
+ const saved = await readInboxLastRun(await getDb());
47142
+ if (saved) daemonLog(`inbox: restored last scan run (${saved.status})`);
47143
+ return saved;
47144
+ } catch (error) {
47145
+ daemonLog(`inbox: reading the last scan run failed: ${String(error)}`);
47146
+ return void 0;
47147
+ }
47148
+ }
47149
+
47150
+ // src/commands/sessions/daemon/inbox/outcomeEvent.ts
47151
+ function outcomeEvent(outcome) {
47152
+ const at2 = (/* @__PURE__ */ new Date()).toISOString();
47153
+ return outcome.ok ? {
47154
+ at: at2,
47155
+ kind: "result",
47156
+ label: "Result",
47157
+ detail: `Flagged ${outcome.flagged} message(s), ${outcome.added} new`
47158
+ } : { at: at2, kind: "error", label: "Failed", detail: outcome.error };
47159
+ }
47160
+
47161
+ // src/shared/db/writeInboxLastRun.ts
47162
+ async function writeInboxLastRun(orm, run4) {
47163
+ const value = JSON.stringify(run4);
47164
+ await orm.insert(metadata).values({ key: INBOX_LAST_RUN_KEY, value }).onConflictDoUpdate({ target: metadata.key, set: { value } });
47165
+ }
47166
+
47167
+ // src/commands/sessions/daemon/inbox/saveScanRun.ts
47168
+ async function saveScanRun(run4) {
47169
+ try {
47170
+ await writeInboxLastRun(await getDb(), run4);
47171
+ daemonLog(
47172
+ `inbox: saved last scan run (${run4.status}, ${run4.events.length} event(s))`
47173
+ );
47174
+ } catch (error) {
47175
+ daemonLog(`inbox: saving the last scan run failed: ${String(error)}`);
47176
+ }
47177
+ }
47178
+
47179
+ // src/commands/sessions/daemon/inbox/createScanRunLog.ts
47180
+ var ACTIVITY_THROTTLE_MS = 1e3;
47181
+ var MAX_EVENTS = 1e3;
47182
+ function createScanRunLog(onActivity) {
47183
+ let run4;
47184
+ let pending;
47185
+ const flush = () => {
47186
+ pending = void 0;
47187
+ onActivity();
47188
+ };
47189
+ return {
47190
+ current: () => run4,
47191
+ begin() {
47192
+ run4 = {
47193
+ status: "scanning",
47194
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
47195
+ finishedAt: null,
47196
+ events: []
47197
+ };
47198
+ },
47199
+ add(event) {
47200
+ if (!run4 || run4.events.length >= MAX_EVENTS) return;
47201
+ run4.events.push(event);
47202
+ pending ??= setTimeout(flush, ACTIVITY_THROTTLE_MS);
47203
+ },
47204
+ async end(outcome) {
47205
+ clearTimeout(pending);
47206
+ pending = void 0;
47207
+ if (!run4) return;
47208
+ run4.events.push(outcomeEvent(outcome));
47209
+ run4.status = outcome.ok ? "finished" : "failed";
47210
+ run4.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
47211
+ await saveScanRun(run4);
47212
+ },
47213
+ async restore() {
47214
+ const saved = await loadScanRun();
47215
+ if (run4 || !saved) return;
47216
+ run4 = saved;
47217
+ onActivity();
47218
+ }
47219
+ };
47060
47220
  }
47061
47221
 
47062
47222
  // src/commands/inbox/readInboxIntervalMinutes.ts
@@ -47083,17 +47243,48 @@ function readInboxSchedule() {
47083
47243
  };
47084
47244
  }
47085
47245
 
47246
+ // src/commands/sessions/daemon/inbox/createScheduleTracker.ts
47247
+ function createScheduleTracker() {
47248
+ let schedule = { description: "not started" };
47249
+ return {
47250
+ current: () => schedule,
47251
+ refresh() {
47252
+ const next3 = readInboxSchedule();
47253
+ if (next3.description !== schedule.description)
47254
+ daemonLog(`inbox: scheduled scans ${next3.description}`);
47255
+ schedule = next3;
47256
+ return schedule;
47257
+ }
47258
+ };
47259
+ }
47260
+
47261
+ // src/commands/sessions/daemon/inbox/isInboxScanDue.ts
47262
+ async function isInboxScanDue(intervalMinutes) {
47263
+ const last = await readInboxLastScan(await getDb());
47264
+ return !last || Date.now() - last.getTime() >= intervalMinutes * 6e4;
47265
+ }
47266
+
47267
+ // src/commands/sessions/daemon/inbox/isScheduledScanDue.ts
47268
+ async function isScheduledScanDue(intervalMinutes) {
47269
+ try {
47270
+ return await isInboxScanDue(intervalMinutes);
47271
+ } catch (error) {
47272
+ daemonLog(`inbox: reading the last scan time failed: ${String(error)}`);
47273
+ return false;
47274
+ }
47275
+ }
47276
+
47086
47277
  // src/commands/sessions/daemon/inbox/runLoggedInboxScan.ts
47087
- async function runLoggedInboxScan(reason4) {
47278
+ async function runLoggedInboxScan(reason4, onEvent) {
47088
47279
  daemonLog(`inbox: scan started (${reason4})`);
47089
47280
  try {
47090
- const { flagged, added } = await runInboxScan(await getDb());
47281
+ const { flagged, added } = await runInboxScan(await getDb(), { onEvent });
47091
47282
  daemonLog(`inbox: scan flagged ${flagged} message(s), ${added} new`);
47092
- return void 0;
47283
+ return { ok: true, flagged, added };
47093
47284
  } catch (error) {
47094
47285
  const message3 = error instanceof Error ? error.message : String(error);
47095
47286
  daemonLog(`inbox: scan failed: ${message3}`);
47096
- return message3;
47287
+ return { ok: false, error: message3 };
47097
47288
  }
47098
47289
  }
47099
47290
 
@@ -47102,32 +47293,29 @@ var CHECK_MS = 6e4;
47102
47293
  function createInboxScanner() {
47103
47294
  let scanning = false;
47104
47295
  let lastError;
47105
- let schedule = { description: "not started" };
47106
47296
  let notify2 = () => {
47107
47297
  };
47298
+ const schedule = createScheduleTracker();
47299
+ const runLog = createScanRunLog(() => notify2("inbox-activity"));
47108
47300
  const scan2 = async (reason4) => {
47109
47301
  scanning = true;
47110
- notify2();
47111
- lastError = await runLoggedInboxScan(reason4);
47302
+ runLog.begin();
47303
+ notify2("inbox");
47304
+ const outcome = await runLoggedInboxScan(reason4, runLog.add);
47305
+ lastError = outcome.ok ? void 0 : outcome.error;
47306
+ await runLog.end(outcome);
47112
47307
  scanning = false;
47113
- notify2();
47308
+ notify2("inbox");
47114
47309
  };
47115
47310
  const tick = async () => {
47116
- const next3 = readInboxSchedule();
47117
- if (next3.description !== schedule.description)
47118
- daemonLog(`inbox: scheduled scans ${next3.description}`);
47119
- schedule = next3;
47120
- if (!schedule.intervalMinutes || scanning) return;
47121
- try {
47122
- if (await isInboxScanDue(schedule.intervalMinutes))
47123
- await scan2("scheduled");
47124
- } catch (error) {
47125
- daemonLog(`inbox: reading the last scan time failed: ${String(error)}`);
47126
- }
47311
+ const { intervalMinutes } = schedule.refresh();
47312
+ if (!intervalMinutes || scanning) return;
47313
+ if (await isScheduledScanDue(intervalMinutes)) await scan2("scheduled");
47127
47314
  };
47128
47315
  return {
47129
47316
  start(onChange) {
47130
47317
  notify2 = onChange;
47318
+ void runLog.restore();
47131
47319
  void tick();
47132
47320
  const timer = setInterval(() => void tick(), CHECK_MS);
47133
47321
  timer.unref();
@@ -47141,8 +47329,9 @@ function createInboxScanner() {
47141
47329
  status() {
47142
47330
  return {
47143
47331
  scanning,
47144
- intervalMinutes: schedule.intervalMinutes ?? null,
47145
- lastError: lastError ?? null
47332
+ intervalMinutes: schedule.current().intervalMinutes ?? null,
47333
+ lastError: lastError ?? null,
47334
+ run: runLog.current() ?? null
47146
47335
  };
47147
47336
  }
47148
47337
  };
@@ -48806,7 +48995,7 @@ function noteAutoUpdate(installDir, text18) {
48806
48995
  }
48807
48996
 
48808
48997
  // src/commands/sessions/daemon/autoUpdate/runUpdateLap.ts
48809
- import { spawn as spawn11 } from "child_process";
48998
+ import { spawn as spawn12 } from "child_process";
48810
48999
  import { rmSync as rmSync13 } from "fs";
48811
49000
  function clearLapSignals(cwd) {
48812
49001
  const control = watchControlPaths(cwd);
@@ -48818,7 +49007,7 @@ function runUpdateLap(cwd, onOutput) {
48818
49007
  clearLapSignals(cwd);
48819
49008
  return new Promise((resolve32, reject) => {
48820
49009
  const { ASSIST_ACTIVITY_ID: _activity, ...env } = process.env;
48821
- const child = spawn11(
49010
+ const child = spawn12(
48822
49011
  process.execPath,
48823
49012
  [process.argv[1], ...WATCH_LAP_ARGS],
48824
49013
  {
@@ -49424,6 +49613,12 @@ function dismissSessionGated(sessions, id, notify2, discard = false) {
49424
49613
  settle();
49425
49614
  }
49426
49615
 
49616
+ // src/commands/sessions/daemon/closeSession.ts
49617
+ function closeSession(sessions, prPreview, notify2, id, discard) {
49618
+ prPreview.closeAll(id, discard ? "session discarded" : "session dismissed");
49619
+ dismissSessionGated(sessions, id, notify2, discard);
49620
+ }
49621
+
49427
49622
  // src/commands/sessions/daemon/drainSessions.ts
49428
49623
  function drainSessions(sessions, notify2) {
49429
49624
  const drained = [...sessions.values()].map((s) => ({
@@ -49496,6 +49691,31 @@ function flushPhaseActiveMs(session) {
49496
49691
  return chain2;
49497
49692
  }
49498
49693
 
49694
+ // src/commands/sessions/daemon/closeSessionPreviews.ts
49695
+ function closeSessionPreviews(session, waiters, reason4) {
49696
+ const previews = [session.pendingPrPreview, session.pendingShow].filter(
49697
+ (p) => p !== void 0
49698
+ );
49699
+ const waiter = waiters.get(session.id);
49700
+ const blocking = session.pendingPrPreview;
49701
+ if (waiter && blocking && blocking.kind !== "show")
49702
+ sendTo(waiter, {
49703
+ type: "pr-decision",
49704
+ requestId: blocking.requestId,
49705
+ decision: "reject",
49706
+ reason: reason4,
49707
+ dismissed: true
49708
+ });
49709
+ waiters.delete(session.id);
49710
+ session.pendingPrPreview = void 0;
49711
+ session.pendingShow = void 0;
49712
+ for (const p of previews)
49713
+ daemonLog(
49714
+ `pr-preview closed: id=${session.id} requestId=${p.requestId} kind=${p.kind ?? "pr"} (${reason4})`
49715
+ );
49716
+ return previews.length > 0;
49717
+ }
49718
+
49499
49719
  // src/commands/sessions/daemon/logPrDecision.ts
49500
49720
  function count9(value) {
49501
49721
  return Array.isArray(value) ? value.length : 0;
@@ -49737,6 +49957,11 @@ var PrPreviewCoordinator = class {
49737
49957
  decide(d) {
49738
49958
  decidePrPreview(this.sessions, this.waiters, this.notify, d);
49739
49959
  }
49960
+ closeAll(id, reason4) {
49961
+ const session = this.sessions.get(id);
49962
+ if (session && closeSessionPreviews(session, this.waiters, reason4))
49963
+ this.notify();
49964
+ }
49740
49965
  clearWaiter(client) {
49741
49966
  for (const [id, waiter] of this.waiters) {
49742
49967
  if (waiter !== client) continue;
@@ -49811,13 +50036,13 @@ function isBacklogItemId(text18) {
49811
50036
  }
49812
50037
 
49813
50038
  // src/commands/sessions/daemon/generateSessionTitle.ts
49814
- import { execFile as execFile14 } from "child_process";
49815
- import { promisify as promisify13 } from "util";
49816
- var execFileAsync12 = promisify13(execFile14);
50039
+ import { execFile as execFile13 } from "child_process";
50040
+ import { promisify as promisify12 } from "util";
50041
+ var execFileAsync11 = promisify12(execFile13);
49817
50042
  var SESSION_TITLE_MAX_LENGTH = 48;
49818
50043
  async function generateSessionTitle(prompt) {
49819
50044
  try {
49820
- const { stdout } = await execFileAsync12(
50045
+ const { stdout } = await execFileAsync11(
49821
50046
  "claude",
49822
50047
  ["-p", "--model", "haiku", buildPrompt5(prompt)],
49823
50048
  { encoding: "utf8", windowsHide: true, timeout: 3e4 }
@@ -50059,10 +50284,10 @@ function applyReviewPause(session, activity2) {
50059
50284
  }
50060
50285
 
50061
50286
  // src/shared/db/getPhaseActiveMs.ts
50062
- import { and as and21, eq as eq51 } from "drizzle-orm";
50287
+ import { and as and21, eq as eq52 } from "drizzle-orm";
50063
50288
  async function getPhaseActiveMs(db, itemId2, phaseIdx) {
50064
50289
  const [row3] = await db.select({ activeMs: phaseUsage.activeMs }).from(phaseUsage).where(
50065
- and21(eq51(phaseUsage.itemId, itemId2), eq51(phaseUsage.phaseIdx, phaseIdx))
50290
+ and21(eq52(phaseUsage.itemId, itemId2), eq52(phaseUsage.phaseIdx, phaseIdx))
50066
50291
  );
50067
50292
  return row3?.activeMs ?? 0;
50068
50293
  }
@@ -50646,11 +50871,11 @@ function parseEntry(line) {
50646
50871
  // src/commands/sessions/summarise/extractFirstUserMessage.ts
50647
50872
  function extractFirstUserMessage(filePath) {
50648
50873
  for (const text18 of iterateUserMessages(filePath)) {
50649
- return truncate3(text18);
50874
+ return truncate4(text18);
50650
50875
  }
50651
50876
  return void 0;
50652
50877
  }
50653
- function truncate3(text18, maxChars = 500) {
50878
+ function truncate4(text18, maxChars = 500) {
50654
50879
  const trimmed = text18.trim();
50655
50880
  if (trimmed.length <= maxChars) return trimmed;
50656
50881
  return `${trimmed.slice(0, maxChars)}\u2026`;
@@ -50875,7 +51100,7 @@ async function recordPhaseTranscriptUsage(db, itemId2, phaseIdx, responses) {
50875
51100
  }
50876
51101
 
50877
51102
  // src/shared/db/recordWindowTokens.ts
50878
- import { and as and22, eq as eq52, sql as sql30 } from "drizzle-orm";
51103
+ import { and as and22, eq as eq53, sql as sql30 } from "drizzle-orm";
50879
51104
  async function recordWindowTokens(db, window, resetsAt, tokensUp, tokensDown) {
50880
51105
  if (tokensUp <= 0 && tokensDown <= 0) return;
50881
51106
  await db.update(usagePeaks).set({
@@ -50883,9 +51108,9 @@ async function recordWindowTokens(db, window, resetsAt, tokensUp, tokensDown) {
50883
51108
  tokensDown: sql30`${usagePeaks.tokensDown} + ${tokensDown}`
50884
51109
  }).where(
50885
51110
  and22(
50886
- eq52(usagePeaks.window, window),
50887
- eq52(usagePeaks.resetsAt, resetsAt),
50888
- eq52(usagePeaks.segment, 0)
51111
+ eq53(usagePeaks.window, window),
51112
+ eq53(usagePeaks.resetsAt, resetsAt),
51113
+ eq53(usagePeaks.segment, 0)
50889
51114
  )
50890
51115
  );
50891
51116
  }
@@ -52385,10 +52610,10 @@ function restoreAllSessions(spawner, deps2) {
52385
52610
 
52386
52611
  // src/commands/sessions/daemon/retrySession.ts
52387
52612
  function retrySession(session, clients, onStatusChange) {
52388
- const spawn12 = respawnThunk(session);
52389
- if (!spawn12) return false;
52613
+ const spawn13 = respawnThunk(session);
52614
+ if (!spawn13) return false;
52390
52615
  const respawn = () => {
52391
- respawnSession(session, spawn12, "running", clients, onStatusChange);
52616
+ respawnSession(session, spawn13, "running", clients, onStatusChange);
52392
52617
  daemonLog(`session ${session.id} retried: ${session.name}`);
52393
52618
  };
52394
52619
  const pty2 = session.pty;
@@ -53598,13 +53823,13 @@ var SessionManager = class {
53598
53823
  );
53599
53824
  }
53600
53825
  dismissSession = (id) => {
53601
- dismissSessionGated(this.sessions, id, this.notify);
53826
+ closeSession(this.sessions, this.prPreview, this.notify, id, false);
53602
53827
  };
53603
53828
  startAutoUpdate() {
53604
53829
  startAutoUpdate(() => this.treeCtx());
53605
53830
  }
53606
53831
  discardSession = (id) => {
53607
- dismissSessionGated(this.sessions, id, this.notify, true);
53832
+ closeSession(this.sessions, this.prPreview, this.notify, id, true);
53608
53833
  };
53609
53834
  stopSession(id) {
53610
53835
  stopServerSession(this.sessions, id);
@@ -53995,7 +54220,7 @@ async function handleSearchHistory(client, data) {
53995
54220
  }
53996
54221
 
53997
54222
  // src/commands/sessions/daemon/creator.ts
53998
- function creator(isNew, spawn12) {
54223
+ function creator(isNew, spawn13) {
53999
54224
  const reply2 = (client, result) => {
54000
54225
  if (typeof result !== "string") {
54001
54226
  sendTo(client, { type: "error", message: result.error });
@@ -54005,7 +54230,7 @@ function creator(isNew, spawn12) {
54005
54230
  };
54006
54231
  return (client, m, d) => {
54007
54232
  if (m.links.route(client, d)) return;
54008
- const result = spawn12(m, d);
54233
+ const result = spawn13(m, d);
54009
54234
  if (result instanceof Promise)
54010
54235
  result.then(
54011
54236
  (resolved) => reply2(client, resolved),
@@ -54494,12 +54719,12 @@ function isPrCheckoutArgs(args) {
54494
54719
  }
54495
54720
 
54496
54721
  // src/commands/sessions/daemon/worktree/prCheckoutHolder.ts
54497
- import { execFile as execFile15 } from "child_process";
54722
+ import { execFile as execFile14 } from "child_process";
54498
54723
  import { existsSync as existsSync103 } from "fs";
54499
54724
  function prHeadBranch2(number, cwd) {
54500
54725
  const { headBranch } = prCliCommands(number, cwd);
54501
54726
  return new Promise((resolve32) => {
54502
- execFile15(
54727
+ execFile14(
54503
54728
  headBranch.file,
54504
54729
  headBranch.args,
54505
54730
  { cwd, encoding: "utf8", windowsHide: true },
@@ -54526,7 +54751,7 @@ function spawnAssistCreate(m, d) {
54526
54751
  const assistArgs = d.assistArgs ?? [];
54527
54752
  const cwd = d.cwd;
54528
54753
  const inPlace = d.inPlace === true;
54529
- const spawn12 = (holder) => m.spawnAssist(
54754
+ const spawn13 = (holder) => m.spawnAssist(
54530
54755
  assistArgs,
54531
54756
  holder ?? cwd,
54532
54757
  {
@@ -54536,8 +54761,8 @@ function spawnAssistCreate(m, d) {
54536
54761
  },
54537
54762
  spawnContextFrom(d)
54538
54763
  );
54539
- if (inPlace || !isPrCheckoutArgs(assistArgs)) return spawn12();
54540
- return prCheckoutHolder(assistArgs, cwd).then(spawn12);
54764
+ if (inPlace || !isPrCheckoutArgs(assistArgs)) return spawn13();
54765
+ return prCheckoutHolder(assistArgs, cwd).then(spawn13);
54541
54766
  }
54542
54767
 
54543
54768
  // src/commands/sessions/daemon/spawnCreate.ts
@@ -54819,7 +55044,7 @@ async function runDaemon() {
54819
55044
  setDaemonLogSink(manager.clients.emitLog);
54820
55045
  startDaemonLogTrimmer();
54821
55046
  pollRepoConfigCache();
54822
- inboxScanner.start(() => broadcast(manager.clients, { type: "inbox" }));
55047
+ inboxScanner.start((type) => broadcast(manager.clients, { type }));
54823
55048
  await startDaemonServer(manager, checkAutoExit);
54824
55049
  await refreshRepoConfigCacheOnStart();
54825
55050
  }
@@ -54846,7 +55071,7 @@ function registerDaemon(program) {
54846
55071
  }
54847
55072
 
54848
55073
  // src/commands/sessions/closeSession.ts
54849
- async function closeSession() {
55074
+ async function closeSession2() {
54850
55075
  if (!inWebSession()) {
54851
55076
  console.log("No daemon-managed session to close.");
54852
55077
  return;
@@ -55444,7 +55669,7 @@ function registerSessions(program) {
55444
55669
  internalCommand(
55445
55670
  cmd.command("close").description(
55446
55671
  "Dismiss the current daemon-managed session, ending it and reaping its worktree"
55447
- ).action(closeSession),
55672
+ ).action(closeSession2),
55448
55673
  "/close"
55449
55674
  );
55450
55675
  internalCommand(