@archme/cli 0.19.0 → 0.20.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/cli.js CHANGED
@@ -12149,7 +12149,9 @@ function openBoxSession(deps, job, slot, pollMs = 1e3) {
12149
12149
  const inputCleanups = [];
12150
12150
  let volumeTouched = false;
12151
12151
  let agentStarted = false;
12152
+ let countersFrozen = false;
12152
12153
  const readCounters = () => {
12154
+ if (countersFrozen) return;
12153
12155
  const c3 = deps.gates.countersFor(slot);
12154
12156
  if (!c3) return;
12155
12157
  sandbox.model_requests = c3.model_requests;
@@ -12192,6 +12194,10 @@ function openBoxSession(deps, job, slot, pollMs = 1e3) {
12192
12194
  labels: { ...labels }
12193
12195
  }),
12194
12196
  readCounters,
12197
+ freezeCounters() {
12198
+ readCounters();
12199
+ countersFrozen = true;
12200
+ },
12195
12201
  failed: (step, reason, stderr = "") => {
12196
12202
  deps.log(`sandbox ${step} step failed: ${reason}`);
12197
12203
  return { kind: "step_failed", step, reason, stderr, metrics };
@@ -12268,6 +12274,236 @@ var init_boxSession = __esm({
12268
12274
  }
12269
12275
  });
12270
12276
 
12277
+ // ../shared/proposalAbout.ts
12278
+ function aboutFromColumns(row) {
12279
+ if (row.about_component) return { kind: "component", path: row.about_component };
12280
+ if (row.about_story) return { kind: "story", id: row.about_story };
12281
+ if (row.about_repo) return { kind: "repo", repo: row.about_repo };
12282
+ return null;
12283
+ }
12284
+ var init_proposalAbout = __esm({
12285
+ "../shared/proposalAbout.ts"() {
12286
+ }
12287
+ });
12288
+
12289
+ // ../shared/proposalDone.ts
12290
+ function isProposalDone(doneOverride, realizationState) {
12291
+ return doneOverride ?? realizationState === "closed";
12292
+ }
12293
+ var init_proposalDone = __esm({
12294
+ "../shared/proposalDone.ts"() {
12295
+ }
12296
+ });
12297
+
12298
+ // ../shared/repoContainer.ts
12299
+ function repoKey(repo) {
12300
+ return repo.trim().toLowerCase();
12301
+ }
12302
+ function sameRepo(a2, b) {
12303
+ if (!a2 || !b) return false;
12304
+ return repoKey(a2) === repoKey(b);
12305
+ }
12306
+ function isContainerPath(path7) {
12307
+ return typeof path7 === "string" && CONTAINER_PATH_RE.test(path7);
12308
+ }
12309
+ function containerIdOf(containerPath) {
12310
+ return containerPath.slice("root.".length);
12311
+ }
12312
+ function isPathWithin(absPath, containerPath) {
12313
+ return absPath === containerPath || absPath.startsWith(containerPath + ".");
12314
+ }
12315
+ function containerPathForRepo(mappings, repo) {
12316
+ if (!repo) return null;
12317
+ const matches = mappings.filter((m) => sameRepo(m.repo, repo) && isContainerPath(m.containerPath));
12318
+ const live = matches.find((m) => !m.removed);
12319
+ return (live ?? matches[0])?.containerPath ?? null;
12320
+ }
12321
+ function resolveRepoScope(mappings, repo) {
12322
+ const containers = mappings.filter((m) => isContainerPath(m.containerPath)).map((m) => m.containerPath);
12323
+ if (containers.length === 0 || !repo) return { kind: "all" };
12324
+ const own = containerPathForRepo(mappings, repo);
12325
+ if (own) return { kind: "container", path: own };
12326
+ return { kind: "excluding", paths: [...new Set(containers)] };
12327
+ }
12328
+ function pathInScope(absPath, scope) {
12329
+ switch (scope.kind) {
12330
+ case "all":
12331
+ return true;
12332
+ case "container":
12333
+ return isPathWithin(absPath, scope.path);
12334
+ case "excluding":
12335
+ return !scope.paths.some((p) => isPathWithin(absPath, p));
12336
+ }
12337
+ }
12338
+ function slugifyId(s) {
12339
+ return s.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
12340
+ }
12341
+ function defaultContainerId(repo, taken = []) {
12342
+ const takenSet = new Set([...taken].map((t) => t.toLowerCase()));
12343
+ const [owner = "", name = ""] = repo.split("/");
12344
+ const short5 = slugifyId(name) || "repo";
12345
+ if (!takenSet.has(short5)) return short5;
12346
+ const qualified = slugifyId(`${owner}_${name}`) || short5;
12347
+ if (!takenSet.has(qualified)) return qualified;
12348
+ for (let i2 = 2; ; i2++) {
12349
+ const candidate = `${qualified}_${i2}`;
12350
+ if (!takenSet.has(candidate)) return candidate;
12351
+ }
12352
+ }
12353
+ var REPO_CONTAINER_KIND, MULTI_REPO_MIN_CLI_VERSION, MULTI_REPO_DAEMON_NOTE, CONTAINER_PATH_RE;
12354
+ var init_repoContainer = __esm({
12355
+ "../shared/repoContainer.ts"() {
12356
+ REPO_CONTAINER_KIND = "repo";
12357
+ MULTI_REPO_MIN_CLI_VERSION = "0.10.0";
12358
+ MULTI_REPO_DAEMON_NOTE = `Every daemon serving this project must run @archme/cli ${MULTI_REPO_MIN_CLI_VERSION} or later (npm i -g @archme/cli, then archme daemon restart): with two repos on a board, older daemons are given none of its jobs.`;
12359
+ CONTAINER_PATH_RE = /^root\.[A-Za-z0-9_]+$/;
12360
+ }
12361
+ });
12362
+
12363
+ // ../shared/waypoints.ts
12364
+ function extractParticipantsFromSequence(sequence) {
12365
+ if (!sequence) return [];
12366
+ const participants = /* @__PURE__ */ new Set();
12367
+ const PARTICIPANT_RE2 = /^\s*participant\s+(\S+?)(?:\s+as\s+.+)?$/;
12368
+ const NOTE_RE = /^\s*Note\s+(?:over|left of|right of)\s+([^:]+):/i;
12369
+ const ACTIVATION_RE = /^\s*(?:activate|deactivate)\s+(\S+)\s*$/i;
12370
+ for (const rawLine of sequence.split("\n")) {
12371
+ const line = rawLine.trim();
12372
+ if (!line) continue;
12373
+ const partMatch = line.match(PARTICIPANT_RE2);
12374
+ if (partMatch) {
12375
+ participants.add(partMatch[1]);
12376
+ continue;
12377
+ }
12378
+ const noteMatch = line.match(NOTE_RE);
12379
+ if (noteMatch) {
12380
+ for (const raw of noteMatch[1].split(",")) {
12381
+ const id = raw.trim();
12382
+ if (id) participants.add(id);
12383
+ }
12384
+ continue;
12385
+ }
12386
+ const actMatch = line.match(ACTIVATION_RE);
12387
+ if (actMatch) {
12388
+ participants.add(actMatch[1]);
12389
+ continue;
12390
+ }
12391
+ const msgMatch = line.match(MESSAGE_RE);
12392
+ if (msgMatch) {
12393
+ const [, from, , to] = msgMatch;
12394
+ participants.add(from);
12395
+ participants.add(to);
12396
+ }
12397
+ }
12398
+ return [...participants];
12399
+ }
12400
+ var MESSAGE_RE;
12401
+ var init_waypoints = __esm({
12402
+ "../shared/waypoints.ts"() {
12403
+ MESSAGE_RE = /^\s*(\{[^}]+\}|\S+?)\s*(--?>>|--?>|->|-->|-x|-\))\s*(\{[^}]+\}|\S+?)\s*:\s*(.*)$/;
12404
+ }
12405
+ });
12406
+
12407
+ // ../shared/boardTriage.ts
12408
+ function flatten(stories, out = []) {
12409
+ for (const s of stories) {
12410
+ out.push(s);
12411
+ if (s.userStories) flatten(s.userStories, out);
12412
+ }
12413
+ return out;
12414
+ }
12415
+ function storySequences(stories, id) {
12416
+ const all = flatten(stories);
12417
+ const root = all.find((s) => s.id === id);
12418
+ if (!root) return null;
12419
+ const sequences = [];
12420
+ const walk = (s) => {
12421
+ if (s.sequence) sequences.push(s.sequence);
12422
+ s.userStories?.forEach(walk);
12423
+ all.filter((c3) => c3.parentId === s.id).forEach(walk);
12424
+ };
12425
+ walk(root);
12426
+ return sequences;
12427
+ }
12428
+ function aboutThisRepo(about, scope) {
12429
+ if (!about) return true;
12430
+ if (about.kind === "repo") return sameRepo(about.repo, scope.repo);
12431
+ const container = scope.containerPath;
12432
+ if (container === null) return true;
12433
+ if (about.kind === "component") return isPathWithin(about.path, container);
12434
+ const sequences = storySequences(scope.stories, about.id);
12435
+ return sequences === null || sequences.some((seq) => extractParticipantsFromSequence(seq).some((p) => isPathWithin(p, container)));
12436
+ }
12437
+ function selectTriageCandidates(rows, scope, limit = TRIAGE_CANDIDATE_LIMIT) {
12438
+ return rows.filter(
12439
+ (r) => r.kind === "proposal" && !isProposalDone(r.done_override, r.realization_state) && r.realization_state !== "abandoned" && r.review_state !== "rejected" && aboutThisRepo(aboutFromColumns(r), scope)
12440
+ ).sort((a2, b) => b.updated_at.localeCompare(a2.updated_at)).slice(0, limit).map((r) => ({
12441
+ id: r.id,
12442
+ title: r.title,
12443
+ description: r.description,
12444
+ stage: r.review_state,
12445
+ about: aboutFromColumns(r)
12446
+ }));
12447
+ }
12448
+ var TRIAGE_CANDIDATE_LIMIT, TRIAGE_PROPOSALS_READ_LIMIT, TRIAGE_PROPOSAL_COLUMNS;
12449
+ var init_boardTriage = __esm({
12450
+ "../shared/boardTriage.ts"() {
12451
+ init_proposalAbout();
12452
+ init_proposalDone();
12453
+ init_repoContainer();
12454
+ init_waypoints();
12455
+ TRIAGE_CANDIDATE_LIMIT = 40;
12456
+ TRIAGE_PROPOSALS_READ_LIMIT = 500;
12457
+ TRIAGE_PROPOSAL_COLUMNS = "id, kind, title, description, review_state, realization_state, done_override, about_component, about_story, about_repo, updated_at";
12458
+ }
12459
+ });
12460
+
12461
+ // src/daemon/triage.ts
12462
+ async function runBoardTriage(job, deps) {
12463
+ const started = Date.now();
12464
+ const done = (o2) => ({ ...o2, ms: Date.now() - started });
12465
+ let rows;
12466
+ try {
12467
+ rows = await deps.loadProposals();
12468
+ } catch (err4) {
12469
+ deps.log(`board triage skipped: ${message(err4)}`);
12470
+ return done({ ran: false, candidates: 0, failure: "read_failed", error: message(err4) });
12471
+ }
12472
+ if (!rows) {
12473
+ deps.log("board triage skipped: could not read the project's proposals");
12474
+ return done({ ran: false, candidates: 0, failure: "read_failed", error: "could not read the project's proposals" });
12475
+ }
12476
+ const candidates = selectTriageCandidates(rows, job.scope);
12477
+ if (candidates.length === 0) return done({ ran: false, candidates: 0 });
12478
+ deps.log(`board triage: ${candidates.length} open item(s)`);
12479
+ try {
12480
+ const { ok, summary: summary2, failure, error } = await deps.run(candidates);
12481
+ const why = [failure, error].filter(Boolean).join(": ");
12482
+ deps.log(`board triage ${ok ? "done" : `failed${why ? ` (${why})` : ""}`}: ${summary2.slice(0, 500).replace(/\n/g, " ")}`);
12483
+ return done({
12484
+ ran: true,
12485
+ candidates: candidates.length,
12486
+ ok,
12487
+ summary: summary2.slice(0, 2e3),
12488
+ ...failure ? { failure } : {},
12489
+ ...error ? { error: error.slice(0, 500) } : {}
12490
+ });
12491
+ } catch (err4) {
12492
+ deps.log(`board triage failed: ${message(err4)}`);
12493
+ return done({ ran: true, candidates: candidates.length, ok: false, error: message(err4) });
12494
+ }
12495
+ }
12496
+ var TRIAGE_TIMEOUT_MS, TRIAGE_MAX_MODEL_REQUESTS, message;
12497
+ var init_triage = __esm({
12498
+ "src/daemon/triage.ts"() {
12499
+ "use strict";
12500
+ init_boardTriage();
12501
+ TRIAGE_TIMEOUT_MS = 10 * 60 * 1e3;
12502
+ TRIAGE_MAX_MODEL_REQUESTS = 200;
12503
+ message = (err4) => err4 instanceof Error ? err4.message : String(err4);
12504
+ }
12505
+ });
12506
+
12271
12507
  // src/daemon/sandbox/runSandboxedJob.ts
12272
12508
  function sandboxJobOf(job) {
12273
12509
  return {
@@ -12290,7 +12526,7 @@ function sandboxJobOf(job) {
12290
12526
  scan_ref: job.scan_ref ?? null
12291
12527
  };
12292
12528
  }
12293
- async function runSandboxedJob(deps, job, opts) {
12529
+ async function runSandboxedJob(deps, job, opts, settle = async (o2) => o2) {
12294
12530
  const { slot } = opts;
12295
12531
  const t = { ...DEFAULT_SANDBOX_TIMEOUTS, ...opts.timeouts };
12296
12532
  const { settings } = deps;
@@ -12393,29 +12629,97 @@ async function runSandboxedJob(deps, job, opts) {
12393
12629
  metrics
12394
12630
  };
12395
12631
  };
12632
+ const runTriage = async (pre, req) => {
12633
+ session.freezeCounters();
12634
+ const box = {
12635
+ model_requests: 0,
12636
+ upstream_429: 0,
12637
+ last_upstream_status: null,
12638
+ cap_hits: 0,
12639
+ box_ms: 0,
12640
+ memory_peak_bytes: null
12641
+ };
12642
+ const failed2 = (failure, error) => ({ ok: false, summary: "", ...failure ? { failure } : {}, ...error ? { error } : {}, box });
12643
+ try {
12644
+ deps.gates.beginTriage(slot, TRIAGE_MAX_MODEL_REQUESTS);
12645
+ const input = await writeInput("triage", {
12646
+ kind: "triage",
12647
+ job: sjob,
12648
+ projectSlug: pre.projectSlug,
12649
+ candidates: req.candidates,
12650
+ touchedComponents: req.touchedComponents,
12651
+ touchedStories: req.touchedStories,
12652
+ model: TRIAGE_CLAUDE_MODEL,
12653
+ timeoutMs: t.triageMs,
12654
+ gateway: slot.gateway
12655
+ });
12656
+ const r = await runBox(spec("triage", deps.agentBoxEnv(slot.gateway), input.dir), t.triageMs + t.graceMs);
12657
+ await input.cleanup();
12658
+ const c3 = deps.gates.countersFor(slot);
12659
+ if (c3) {
12660
+ box.model_requests = c3.model_requests;
12661
+ box.upstream_429 = c3.upstream_429;
12662
+ box.last_upstream_status = c3.last_upstream_status;
12663
+ box.cap_hits = c3.cap_hits;
12664
+ }
12665
+ if (r.kind === "refused") return failed2("infra", r.reason);
12666
+ box.box_ms = r.ms;
12667
+ durations.sandbox_triage = r.ms;
12668
+ const parsed = r.killCause ? null : deps.parseResultLine(r.exit.stdout, r.exit.nonce);
12669
+ if (parsed?.ok && parsed.result.kind === "triage") box.memory_peak_bytes = parsed.result.memoryPeakBytes;
12670
+ return { ...classifyTriageBox(r.killCause, parsed, box), box };
12671
+ } catch (e) {
12672
+ return failed2("infra", e instanceof Error ? e.message : String(e));
12673
+ }
12674
+ };
12396
12675
  try {
12397
12676
  const pre = await deps.prefetch(job);
12677
+ let outcome;
12398
12678
  try {
12399
- return await runBoxes(pre);
12679
+ outcome = await runBoxes(pre);
12400
12680
  } catch (e) {
12401
12681
  if (e instanceof SandboxInfraError) throw e;
12402
12682
  throw new SandboxInfraError(e instanceof Error ? e.message : String(e), session.agentStarted);
12403
12683
  }
12684
+ return await settle(outcome, { prefetch: pre, triage: { run: (req) => runTriage(pre, req) } });
12404
12685
  } finally {
12405
12686
  await session.teardown();
12406
12687
  }
12407
12688
  }
12689
+ function classifyTriageBox(killCause, parsed, counters) {
12690
+ const fail2 = (failure, error) => ({ ok: false, summary: "", ...failure ? { failure } : {}, ...error ? { error } : {} });
12691
+ if (counters.cap_hits > 0) return fail2("cap", `the triage step hit its ${TRIAGE_MAX_MODEL_REQUESTS}-request cap`);
12692
+ if (killCause === "timeout") return fail2("timeout", "the triage box timed out");
12693
+ if (killCause) return fail2("infra", killCause);
12694
+ if (!parsed || !parsed.ok) return fail2("malformed", parsed ? parsed.reason : "no result line");
12695
+ const r = parsed.result;
12696
+ if (r.kind !== "triage") return fail2("malformed", `unexpected result kind ${r.kind}`);
12697
+ if (r.error) return fail2("infra", r.error);
12698
+ const claude = parseClaudeResult(r.claudeStdout);
12699
+ if (r.exitCode !== 0 || claude.isError) {
12700
+ const status = counters.last_upstream_status;
12701
+ const error = `claude exited ${r.exitCode ?? r.signal ?? "?"}${claude.isError ? " (is_error)" : ""}`;
12702
+ if (status === 429) return fail2("rate_limit", `${error}; last upstream status 429`);
12703
+ if (status === 401 || status === 403) return fail2("auth", `${error}; last upstream status ${status}`);
12704
+ return fail2(void 0, error);
12705
+ }
12706
+ return { ok: true, summary: claude.summary.trim() };
12707
+ }
12408
12708
  var DEFAULT_SANDBOX_TIMEOUTS, SandboxInfraError;
12409
12709
  var init_runSandboxedJob = __esm({
12410
12710
  "src/daemon/sandbox/runSandboxedJob.ts"() {
12411
12711
  "use strict";
12712
+ init_daemonModel();
12713
+ init_claudeFailure();
12714
+ init_triage();
12412
12715
  init_boxSession();
12413
12716
  init_types();
12414
12717
  DEFAULT_SANDBOX_TIMEOUTS = {
12415
12718
  claudeMs: 30 * 60 * 1e3,
12416
12719
  largeDiffClaudeMs: 45 * 60 * 1e3,
12417
12720
  graceMs: 2 * 60 * 1e3,
12418
- cloneMs: 10 * 60 * 1e3
12721
+ cloneMs: 10 * 60 * 1e3,
12722
+ triageMs: TRIAGE_TIMEOUT_MS
12419
12723
  };
12420
12724
  SandboxInfraError = class extends Error {
12421
12725
  constructor(message2, agentStarted) {
@@ -14394,71 +14698,6 @@ var init_esm3 = __esm({
14394
14698
  }
14395
14699
  });
14396
14700
 
14397
- // ../shared/repoContainer.ts
14398
- function repoKey(repo) {
14399
- return repo.trim().toLowerCase();
14400
- }
14401
- function sameRepo(a2, b) {
14402
- if (!a2 || !b) return false;
14403
- return repoKey(a2) === repoKey(b);
14404
- }
14405
- function isContainerPath(path7) {
14406
- return typeof path7 === "string" && CONTAINER_PATH_RE.test(path7);
14407
- }
14408
- function containerIdOf(containerPath) {
14409
- return containerPath.slice("root.".length);
14410
- }
14411
- function isPathWithin(absPath, containerPath) {
14412
- return absPath === containerPath || absPath.startsWith(containerPath + ".");
14413
- }
14414
- function containerPathForRepo(mappings, repo) {
14415
- if (!repo) return null;
14416
- const matches = mappings.filter((m) => sameRepo(m.repo, repo) && isContainerPath(m.containerPath));
14417
- const live = matches.find((m) => !m.removed);
14418
- return (live ?? matches[0])?.containerPath ?? null;
14419
- }
14420
- function resolveRepoScope(mappings, repo) {
14421
- const containers = mappings.filter((m) => isContainerPath(m.containerPath)).map((m) => m.containerPath);
14422
- if (containers.length === 0 || !repo) return { kind: "all" };
14423
- const own = containerPathForRepo(mappings, repo);
14424
- if (own) return { kind: "container", path: own };
14425
- return { kind: "excluding", paths: [...new Set(containers)] };
14426
- }
14427
- function pathInScope(absPath, scope) {
14428
- switch (scope.kind) {
14429
- case "all":
14430
- return true;
14431
- case "container":
14432
- return isPathWithin(absPath, scope.path);
14433
- case "excluding":
14434
- return !scope.paths.some((p) => isPathWithin(absPath, p));
14435
- }
14436
- }
14437
- function slugifyId(s) {
14438
- return s.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
14439
- }
14440
- function defaultContainerId(repo, taken = []) {
14441
- const takenSet = new Set([...taken].map((t) => t.toLowerCase()));
14442
- const [owner = "", name = ""] = repo.split("/");
14443
- const short5 = slugifyId(name) || "repo";
14444
- if (!takenSet.has(short5)) return short5;
14445
- const qualified = slugifyId(`${owner}_${name}`) || short5;
14446
- if (!takenSet.has(qualified)) return qualified;
14447
- for (let i2 = 2; ; i2++) {
14448
- const candidate = `${qualified}_${i2}`;
14449
- if (!takenSet.has(candidate)) return candidate;
14450
- }
14451
- }
14452
- var REPO_CONTAINER_KIND, MULTI_REPO_MIN_CLI_VERSION, MULTI_REPO_DAEMON_NOTE, CONTAINER_PATH_RE;
14453
- var init_repoContainer = __esm({
14454
- "../shared/repoContainer.ts"() {
14455
- REPO_CONTAINER_KIND = "repo";
14456
- MULTI_REPO_MIN_CLI_VERSION = "0.10.0";
14457
- MULTI_REPO_DAEMON_NOTE = `Every daemon serving this project must run @archme/cli ${MULTI_REPO_MIN_CLI_VERSION} or later (npm i -g @archme/cli, then archme daemon restart): with two repos on a board, older daemons are given none of its jobs.`;
14458
- CONTAINER_PATH_RE = /^root\.[A-Za-z0-9_]+$/;
14459
- }
14460
- });
14461
-
14462
14701
  // ../shared/seedArchitecture.ts
14463
14702
  function seedArchitectureFromRows(rows) {
14464
14703
  const components = [];
@@ -14579,7 +14818,7 @@ function resolveWaypoint(waypoint, storyScope) {
14579
14818
  leafId: segments[segments.length - 1] ?? ""
14580
14819
  };
14581
14820
  }
14582
- function extractParticipantsFromSequence(sequence) {
14821
+ function extractParticipantsFromSequence2(sequence) {
14583
14822
  if (!sequence) return [];
14584
14823
  const participants = /* @__PURE__ */ new Set();
14585
14824
  for (const rawLine of sequence.split("\n")) {
@@ -14590,7 +14829,7 @@ function extractParticipantsFromSequence(sequence) {
14590
14829
  if (partMatch[1]) participants.add(partMatch[1]);
14591
14830
  continue;
14592
14831
  }
14593
- const msgMatch = line.match(MESSAGE_RE);
14832
+ const msgMatch = line.match(MESSAGE_RE2);
14594
14833
  if (msgMatch) {
14595
14834
  if (msgMatch[1]) participants.add(msgMatch[1]);
14596
14835
  if (msgMatch[3]) participants.add(msgMatch[3]);
@@ -14640,7 +14879,7 @@ function resolveAffected(arch, changedFiles, changedSymbolsByFile, scope = { kin
14640
14879
  const seenStory = /* @__PURE__ */ new Set();
14641
14880
  for (const story of arch.stories) {
14642
14881
  if (seenStory.has(story.id)) continue;
14643
- const hopPaths = extractParticipantsFromSequence(story.sequence).map((wp) => {
14882
+ const hopPaths = extractParticipantsFromSequence2(story.sequence).map((wp) => {
14644
14883
  const r = resolveWaypoint(wp, story.scope);
14645
14884
  return [...r.scopePath, r.leafId];
14646
14885
  });
@@ -14767,14 +15006,14 @@ async function loadArchitectureForSeeding(supabase, projectId, branch) {
14767
15006
  }
14768
15007
  return seedArchitectureFromRows(rows);
14769
15008
  }
14770
- var MESSAGE_RE, PARTICIPANT_RE, DISPLAY_FILE_CAP;
15009
+ var MESSAGE_RE2, PARTICIPANT_RE, DISPLAY_FILE_CAP;
14771
15010
  var init_affected = __esm({
14772
15011
  "src/scan/affected.ts"() {
14773
15012
  "use strict";
14774
15013
  init_esm3();
14775
15014
  init_repoContainer();
14776
15015
  init_seedArchitecture();
14777
- MESSAGE_RE = /^\s*(\{[^}]+\}|\S+?)\s*(--?>>|--?>|->|-->|-x|-\))\s*(\{[^}]+\}|\S+?)\s*:\s*(.*)$/;
15016
+ MESSAGE_RE2 = /^\s*(\{[^}]+\}|\S+?)\s*(--?>>|--?>|->|-->|-x|-\))\s*(\{[^}]+\}|\S+?)\s*:\s*(.*)$/;
14778
15017
  PARTICIPANT_RE = /^\s*participant\s+(\S+?)(?:\s+as\s+.+)?$/;
14779
15018
  DISPLAY_FILE_CAP = 200;
14780
15019
  }
@@ -16701,50 +16940,6 @@ Everything a reader sees in a sequence \u2014 arrow labels, Note text, and the c
16701
16940
  }
16702
16941
  });
16703
16942
 
16704
- // ../shared/waypoints.ts
16705
- function extractParticipantsFromSequence2(sequence) {
16706
- if (!sequence) return [];
16707
- const participants = /* @__PURE__ */ new Set();
16708
- const PARTICIPANT_RE2 = /^\s*participant\s+(\S+?)(?:\s+as\s+.+)?$/;
16709
- const NOTE_RE = /^\s*Note\s+(?:over|left of|right of)\s+([^:]+):/i;
16710
- const ACTIVATION_RE = /^\s*(?:activate|deactivate)\s+(\S+)\s*$/i;
16711
- for (const rawLine of sequence.split("\n")) {
16712
- const line = rawLine.trim();
16713
- if (!line) continue;
16714
- const partMatch = line.match(PARTICIPANT_RE2);
16715
- if (partMatch) {
16716
- participants.add(partMatch[1]);
16717
- continue;
16718
- }
16719
- const noteMatch = line.match(NOTE_RE);
16720
- if (noteMatch) {
16721
- for (const raw of noteMatch[1].split(",")) {
16722
- const id = raw.trim();
16723
- if (id) participants.add(id);
16724
- }
16725
- continue;
16726
- }
16727
- const actMatch = line.match(ACTIVATION_RE);
16728
- if (actMatch) {
16729
- participants.add(actMatch[1]);
16730
- continue;
16731
- }
16732
- const msgMatch = line.match(MESSAGE_RE2);
16733
- if (msgMatch) {
16734
- const [, from, , to] = msgMatch;
16735
- participants.add(from);
16736
- participants.add(to);
16737
- }
16738
- }
16739
- return [...participants];
16740
- }
16741
- var MESSAGE_RE2;
16742
- var init_waypoints = __esm({
16743
- "../shared/waypoints.ts"() {
16744
- MESSAGE_RE2 = /^\s*(\{[^}]+\}|\S+?)\s*(--?>>|--?>|->|-->|-x|-\))\s*(\{[^}]+\}|\S+?)\s*:\s*(.*)$/;
16745
- }
16746
- });
16747
-
16748
16943
  // ../shared/leafEndpoints.ts
16749
16944
  var LEAF_ENDPOINT_GUIDANCE;
16750
16945
  var init_leafEndpoints = __esm({
@@ -17636,103 +17831,30 @@ async function ensureBugsFolder(client, projectId) {
17636
17831
  cache.set(projectId, existingId);
17637
17832
  return existingId;
17638
17833
  }
17639
- const { data: created, error: createErr } = await client.rpc("create_proposal", {
17640
- p_project_id: projectId,
17641
- p_kind: "folder",
17642
- p_title: BUGS_FOLDER_TITLE,
17643
- p_description: BUGS_FOLDER_DESCRIPTION
17644
- });
17645
- if (createErr) throw createErr;
17646
- const createdId = created?.id ?? null;
17647
- if (createdId) cache.set(projectId, createdId);
17648
- return createdId;
17649
- } catch (err4) {
17650
- console.warn(
17651
- `[bugs-folder] could not resolve/create the "${BUGS_FOLDER_TITLE}" folder for project ${projectId}; bug filing falls back to agent find-or-create:`,
17652
- err4 instanceof Error ? err4.message : err4
17653
- );
17654
- return null;
17655
- }
17656
- }
17657
- var cache;
17658
- var init_bugsFolder = __esm({
17659
- "src/daemon/bugsFolder.ts"() {
17660
- "use strict";
17661
- init_bugReport();
17662
- cache = /* @__PURE__ */ new Map();
17663
- }
17664
- });
17665
-
17666
- // ../shared/proposalAbout.ts
17667
- function aboutFromColumns(row) {
17668
- if (row.about_component) return { kind: "component", path: row.about_component };
17669
- if (row.about_story) return { kind: "story", id: row.about_story };
17670
- if (row.about_repo) return { kind: "repo", repo: row.about_repo };
17671
- return null;
17672
- }
17673
- var init_proposalAbout = __esm({
17674
- "../shared/proposalAbout.ts"() {
17675
- }
17676
- });
17677
-
17678
- // ../shared/proposalDone.ts
17679
- function isProposalDone(doneOverride, realizationState) {
17680
- return doneOverride ?? realizationState === "closed";
17681
- }
17682
- var init_proposalDone = __esm({
17683
- "../shared/proposalDone.ts"() {
17684
- }
17685
- });
17686
-
17687
- // ../shared/boardTriage.ts
17688
- function flatten(stories, out = []) {
17689
- for (const s of stories) {
17690
- out.push(s);
17691
- if (s.userStories) flatten(s.userStories, out);
17692
- }
17693
- return out;
17694
- }
17695
- function storySequences(stories, id) {
17696
- const all = flatten(stories);
17697
- const root = all.find((s) => s.id === id);
17698
- if (!root) return null;
17699
- const sequences = [];
17700
- const walk = (s) => {
17701
- if (s.sequence) sequences.push(s.sequence);
17702
- s.userStories?.forEach(walk);
17703
- all.filter((c3) => c3.parentId === s.id).forEach(walk);
17704
- };
17705
- walk(root);
17706
- return sequences;
17707
- }
17708
- function aboutThisRepo(about, scope) {
17709
- if (!about) return true;
17710
- if (about.kind === "repo") return sameRepo(about.repo, scope.repo);
17711
- const container = scope.containerPath;
17712
- if (container === null) return true;
17713
- if (about.kind === "component") return isPathWithin(about.path, container);
17714
- const sequences = storySequences(scope.stories, about.id);
17715
- return sequences === null || sequences.some((seq) => extractParticipantsFromSequence2(seq).some((p) => isPathWithin(p, container)));
17716
- }
17717
- function selectTriageCandidates(rows, scope, limit = TRIAGE_CANDIDATE_LIMIT) {
17718
- return rows.filter(
17719
- (r) => r.kind === "proposal" && !isProposalDone(r.done_override, r.realization_state) && r.realization_state !== "abandoned" && r.review_state !== "rejected" && aboutThisRepo(aboutFromColumns(r), scope)
17720
- ).sort((a2, b) => b.updated_at.localeCompare(a2.updated_at)).slice(0, limit).map((r) => ({
17721
- id: r.id,
17722
- title: r.title,
17723
- description: r.description,
17724
- stage: r.review_state,
17725
- about: aboutFromColumns(r)
17726
- }));
17834
+ const { data: created, error: createErr } = await client.rpc("create_proposal", {
17835
+ p_project_id: projectId,
17836
+ p_kind: "folder",
17837
+ p_title: BUGS_FOLDER_TITLE,
17838
+ p_description: BUGS_FOLDER_DESCRIPTION
17839
+ });
17840
+ if (createErr) throw createErr;
17841
+ const createdId = created?.id ?? null;
17842
+ if (createdId) cache.set(projectId, createdId);
17843
+ return createdId;
17844
+ } catch (err4) {
17845
+ console.warn(
17846
+ `[bugs-folder] could not resolve/create the "${BUGS_FOLDER_TITLE}" folder for project ${projectId}; bug filing falls back to agent find-or-create:`,
17847
+ err4 instanceof Error ? err4.message : err4
17848
+ );
17849
+ return null;
17850
+ }
17727
17851
  }
17728
- var TRIAGE_CANDIDATE_LIMIT;
17729
- var init_boardTriage = __esm({
17730
- "../shared/boardTriage.ts"() {
17731
- init_proposalAbout();
17732
- init_proposalDone();
17733
- init_repoContainer();
17734
- init_waypoints();
17735
- TRIAGE_CANDIDATE_LIMIT = 40;
17852
+ var cache;
17853
+ var init_bugsFolder = __esm({
17854
+ "src/daemon/bugsFolder.ts"() {
17855
+ "use strict";
17856
+ init_bugReport();
17857
+ cache = /* @__PURE__ */ new Map();
17736
17858
  }
17737
17859
  });
17738
17860
 
@@ -17809,50 +17931,6 @@ var init_triagePrompt = __esm({
17809
17931
  }
17810
17932
  });
17811
17933
 
17812
- // src/daemon/triage.ts
17813
- async function runBoardTriage(job, deps) {
17814
- const started = Date.now();
17815
- const done = (o2) => ({ ...o2, ms: Date.now() - started });
17816
- let rows;
17817
- try {
17818
- rows = await deps.loadProposals();
17819
- } catch (err4) {
17820
- deps.log(`board triage skipped: ${message(err4)}`);
17821
- return done({ ran: false, candidates: 0, error: message(err4) });
17822
- }
17823
- if (!rows) {
17824
- deps.log("board triage skipped: could not read the project's proposals");
17825
- return done({ ran: false, candidates: 0, error: "could not read the project's proposals" });
17826
- }
17827
- const candidates = selectTriageCandidates(rows, job.scope);
17828
- if (candidates.length === 0) return done({ ran: false, candidates: 0 });
17829
- const prompt = buildTriagePrompt({
17830
- ...job.prompt,
17831
- candidates,
17832
- budgetMinutes: Math.round(TRIAGE_TIMEOUT_MS / 6e4)
17833
- });
17834
- deps.log(`board triage: ${candidates.length} open item(s), spawning ${TRIAGE_CLAUDE_MODEL}`);
17835
- try {
17836
- const { ok, summary: summary2 } = await deps.spawn({ prompt, model: TRIAGE_CLAUDE_MODEL, timeoutMs: TRIAGE_TIMEOUT_MS });
17837
- deps.log(`board triage ${ok ? "done" : "failed"}: ${summary2.slice(0, 500).replace(/\n/g, " ")}`);
17838
- return done({ ran: true, candidates: candidates.length, ok, summary: summary2.slice(0, 2e3) });
17839
- } catch (err4) {
17840
- deps.log(`board triage failed: ${message(err4)}`);
17841
- return done({ ran: true, candidates: candidates.length, ok: false, error: message(err4) });
17842
- }
17843
- }
17844
- var TRIAGE_TIMEOUT_MS, message;
17845
- var init_triage = __esm({
17846
- "src/daemon/triage.ts"() {
17847
- "use strict";
17848
- init_boardTriage();
17849
- init_daemonModel();
17850
- init_triagePrompt();
17851
- TRIAGE_TIMEOUT_MS = 10 * 60 * 1e3;
17852
- message = (err4) => err4 instanceof Error ? err4.message : String(err4);
17853
- }
17854
- });
17855
-
17856
17934
  // src/daemon/repoMappings.ts
17857
17935
  async function loadRepoMappings(supabase, projectId, log = console.warn) {
17858
17936
  let rows = null;
@@ -18570,12 +18648,12 @@ function defaultReadFile(path7) {
18570
18648
  return readFileSync4(path7, "utf8");
18571
18649
  }
18572
18650
  function findPackageRoot2(startDir, opts = {}) {
18573
- const readFile24 = opts.readFile ?? defaultReadFile;
18651
+ const readFile25 = opts.readFile ?? defaultReadFile;
18574
18652
  const stopAt = parse(startDir).root;
18575
18653
  let dir = startDir;
18576
18654
  for (; ; ) {
18577
18655
  try {
18578
- const parsed = JSON.parse(readFile24(join15(dir, "package.json")));
18656
+ const parsed = JSON.parse(readFile25(join15(dir, "package.json")));
18579
18657
  if (parsed.name === PACKAGE_NAME) return dir;
18580
18658
  } catch {
18581
18659
  }
@@ -20346,6 +20424,11 @@ var init_platformDevices = __esm({
20346
20424
  });
20347
20425
 
20348
20426
  // src/daemon/jobReads.ts
20427
+ async function loadTriageProposals(client, projectId) {
20428
+ const { data, error } = await client.from("proposals").select(TRIAGE_PROPOSAL_COLUMNS).eq("project_id", projectId).eq("kind", "proposal").not("realization_state", "in", "(closed,abandoned)").order("updated_at", { ascending: false }).limit(TRIAGE_PROPOSALS_READ_LIMIT);
20429
+ if (error) return null;
20430
+ return data ?? [];
20431
+ }
20349
20432
  async function lookupProjectSlug(client, projectId) {
20350
20433
  const { data, error } = await client.from("projects").select("slug, organizations(slug)").eq("id", projectId).single();
20351
20434
  if (error || !data) throw new Error(`Project ${projectId} not found: ${error?.message}`);
@@ -20386,7 +20469,8 @@ function sessionJobReads(client, job) {
20386
20469
  bugsFolderId: () => ensureBugsFolder(client, job.project_id),
20387
20470
  writesByPhase: () => detectWritesByPhase(client, job.project_id, job.archme_branch, job.id),
20388
20471
  mcpActivity: () => detectMcpActivity(client, job.id),
20389
- architectureCounts: () => countArchitecture(client, job.project_id, job.archme_branch)
20472
+ architectureCounts: () => countArchitecture(client, job.project_id, job.archme_branch),
20473
+ triageProposals: () => loadTriageProposals(client, job.project_id).catch(() => null)
20390
20474
  };
20391
20475
  }
20392
20476
  function hostedJobReads(post) {
@@ -20425,6 +20509,15 @@ function hostedJobReads(post) {
20425
20509
  const counts = (await out()).architecture_counts;
20426
20510
  if (!counts) throw new Error("job-context returned no architecture counts");
20427
20511
  return counts;
20512
+ },
20513
+ // Not memoized: read once, after the verdict. An older server rejects the part (400): null, triage skipped.
20514
+ triageProposals: async () => {
20515
+ try {
20516
+ const { proposals } = await post("triage");
20517
+ return Array.isArray(proposals) ? proposals : null;
20518
+ } catch {
20519
+ return null;
20520
+ }
20428
20521
  }
20429
20522
  };
20430
20523
  }
@@ -20434,6 +20527,7 @@ function jobReadsFor(deps, job) {
20434
20527
  var init_jobReads = __esm({
20435
20528
  "src/daemon/jobReads.ts"() {
20436
20529
  "use strict";
20530
+ init_boardTriage();
20437
20531
  init_architectureCounts2();
20438
20532
  init_affected();
20439
20533
  init_bugsFolder();
@@ -20465,6 +20559,19 @@ function minimal(r) {
20465
20559
  const m2 = { kind: "clone", outcome: r.outcome, memoryPeakBytes: r.memoryPeakBytes, durations_ms: {}, error: RESULT_TRUNCATED };
20466
20560
  return m2;
20467
20561
  }
20562
+ if (r.kind === "triage") {
20563
+ const m2 = {
20564
+ kind: "triage",
20565
+ exitCode: r.exitCode,
20566
+ signal: r.signal,
20567
+ claudeStdout: "",
20568
+ promptBytes: r.promptBytes,
20569
+ memoryPeakBytes: r.memoryPeakBytes,
20570
+ durations_ms: {},
20571
+ error: RESULT_TRUNCATED
20572
+ };
20573
+ return m2;
20574
+ }
20468
20575
  const m = {
20469
20576
  kind: "agent",
20470
20577
  exitCode: r.exitCode,
@@ -20490,6 +20597,10 @@ function formatResultLine(result, nonce, cap = RESULT_MAX_BYTES) {
20490
20597
  line = encode_(withTruncatedError({ ...noAffected, claudeStdout: "" }));
20491
20598
  if (fits(line, cap)) return line;
20492
20599
  }
20600
+ if (result.kind === "triage") {
20601
+ line = encode_(withTruncatedError({ ...result, claudeStdout: "" }));
20602
+ if (fits(line, cap)) return line;
20603
+ }
20493
20604
  return encode_(minimal(result));
20494
20605
  }
20495
20606
  function isObj(v) {
@@ -20511,6 +20622,13 @@ function shapeError(o2) {
20511
20622
  if (!isObj(o2.outcomes) || !Object.values(o2.outcomes).every((v) => typeof v === "string")) return "outcomes";
20512
20623
  return null;
20513
20624
  }
20625
+ if (o2.kind === "triage") {
20626
+ if (!isNumOrNull(o2.exitCode)) return "exitCode";
20627
+ if (o2.signal !== null && typeof o2.signal !== "string") return "signal";
20628
+ if (typeof o2.claudeStdout !== "string") return "claudeStdout";
20629
+ if (typeof o2.promptBytes !== "number") return "promptBytes";
20630
+ return null;
20631
+ }
20514
20632
  if (o2.kind === "agent") {
20515
20633
  if (!isNumOrNull(o2.exitCode)) return "exitCode";
20516
20634
  if (o2.signal !== null && typeof o2.signal !== "string") return "signal";
@@ -21713,6 +21831,18 @@ var init_slots = __esm({
21713
21831
  b.step = step;
21714
21832
  this.github.onStepChange(index);
21715
21833
  }
21834
+ /** The triage step (FEAT-169): same binding, so the job's MCP token and its
21835
+ * re-mint stay live, but fresh counters under the triage cap, and no GitHub
21836
+ * egress. The agent's counters must be read first: they are dropped here. */
21837
+ beginTriage(slot, maxModelRequests) {
21838
+ const index = indexOf(slot);
21839
+ const b = this.slotMap.binding(index);
21840
+ if (!b) throw new Error(`slot ${index} is not bound`);
21841
+ b.step = "triage";
21842
+ b.counters = zeroCounters();
21843
+ b.maxModelRequests = maxModelRequests;
21844
+ this.github.onStepChange(index);
21845
+ }
21716
21846
  /** Unbinds the slot (it answers 403 again) and returns the job's final counters. */
21717
21847
  clearJob(slot) {
21718
21848
  const index = indexOf(slot);
@@ -23045,6 +23175,27 @@ async function diffPrompt(input, deps, repoDir, log, mark) {
23045
23175
  );
23046
23176
  return { prompt, affected, seedStats };
23047
23177
  }
23178
+ async function awaitClaude(proc, writeStderr) {
23179
+ const out = [];
23180
+ let outBytes = 0;
23181
+ proc.stdout?.on("data", (c3) => {
23182
+ const b = typeof c3 === "string" ? Buffer.from(c3) : c3;
23183
+ out.push(b);
23184
+ outBytes += b.length;
23185
+ while (out.length > 1 && outBytes - out[0].length > 2 * CLAUDE_STDOUT_CAP_BYTES) outBytes -= out.shift().length;
23186
+ });
23187
+ proc.stderr?.on("data", (c3) => writeStderr(c3));
23188
+ const r = await proc;
23189
+ const exitCode = r.exitCode ?? null;
23190
+ const signal = r.signal ?? null;
23191
+ const spawnError = exitCode === null && signal === null ? (r.shortMessage ?? r.message ?? "claude did not start").slice(0, 500) : void 0;
23192
+ return {
23193
+ exitCode,
23194
+ signal,
23195
+ stdout: capTail(Buffer.concat(out).toString("utf8"), CLAUDE_STDOUT_CAP_BYTES),
23196
+ ...spawnError ? { spawnError } : {}
23197
+ };
23198
+ }
23048
23199
  async function runAgentStep(input, deps = {}) {
23049
23200
  const repoDir = deps.repoDir ?? REPO_DIR;
23050
23201
  const log = deps.log ?? (() => {
@@ -23093,31 +23244,19 @@ async function runAgentStep(input, deps = {}) {
23093
23244
  // A box is Linux: a prompt over 128 KiB cannot be one argv string.
23094
23245
  promptViaStdin: true
23095
23246
  });
23096
- const out = [];
23097
- let outBytes = 0;
23098
- proc.stdout?.on("data", (c3) => {
23099
- const b = typeof c3 === "string" ? Buffer.from(c3) : c3;
23100
- out.push(b);
23101
- outBytes += b.length;
23102
- while (out.length > 1 && outBytes - out[0].length > 2 * CLAUDE_STDOUT_CAP_BYTES) outBytes -= out.shift().length;
23103
- });
23104
- proc.stderr?.on("data", (c3) => writeStderr(c3));
23105
- const r = await proc;
23247
+ const { exitCode, signal, stdout, spawnError } = await awaitClaude(proc, writeStderr);
23106
23248
  mark("claude");
23107
- const exitCode = r.exitCode ?? null;
23108
- const signal = r.signal ?? null;
23109
23249
  log(`claude exited (code ${exitCode ?? "null"}, signal ${signal ?? "null"})`);
23110
- const spawnError = exitCode === null && signal === null ? r.shortMessage ?? r.message ?? "claude did not start" : void 0;
23111
23250
  return {
23112
23251
  result: {
23113
23252
  kind: "agent",
23114
23253
  exitCode,
23115
23254
  signal,
23116
- claudeStdout: capTail(Buffer.concat(out).toString("utf8"), CLAUDE_STDOUT_CAP_BYTES),
23255
+ claudeStdout: stdout,
23117
23256
  affected,
23118
23257
  ...seedStats ? { seed: seedStats } : {},
23119
23258
  promptBytes,
23120
- ...spawnError ? { error: spawnError.slice(0, 500) } : {}
23259
+ ...spawnError ? { error: spawnError } : {}
23121
23260
  },
23122
23261
  exitCode: exitCode ?? 1
23123
23262
  };
@@ -23186,6 +23325,7 @@ function createSandboxParts(settings) {
23186
23325
  return {
23187
23326
  bindJob: (slot, b) => gates.bindJob(slot, b),
23188
23327
  setStep: (slot, step) => gates.setStep(slot, step),
23328
+ beginTriage: (slot, cap) => gates.beginTriage(slot, cap),
23189
23329
  clearJob: (slot) => {
23190
23330
  gates.clearJob(slot);
23191
23331
  },
@@ -24071,6 +24211,16 @@ function sandboxDepsFor(ctx, job, deviceId, host) {
24071
24211
  gatewayPresent: (slot) => gatewayPresent(slot, networkInterfaces2())
24072
24212
  };
24073
24213
  }
24214
+ function triageEventFields(t, box) {
24215
+ return {
24216
+ ran: t.ran,
24217
+ candidates: t.candidates,
24218
+ ...t.ok !== void 0 ? { ok: t.ok } : {},
24219
+ ...t.failure ? { failure: t.failure } : {},
24220
+ ...t.error ? { error: t.error } : {},
24221
+ ...box ?? {}
24222
+ };
24223
+ }
24074
24224
  async function completeClaudeRun(ctx, job, deviceId, run) {
24075
24225
  const { metrics, logs, startedAt, markPhase, log } = run;
24076
24226
  const affectedForComplete = run.affected;
@@ -24122,7 +24272,10 @@ async function completeClaudeRun(ctx, job, deviceId, run) {
24122
24272
  await rpcRollback(ctx, job.id, deviceId);
24123
24273
  return;
24124
24274
  }
24125
- if (shuttingDown && killReasons.get(job.id) === "shutdown") return;
24275
+ if (shuttingDown && killReasons.get(job.id) === "shutdown") {
24276
+ if (boxedJobs.has(job.id)) throw new Error("daemon shutdown \u2014 interrupted");
24277
+ return;
24278
+ }
24126
24279
  }
24127
24280
  const changed = outcome.changed;
24128
24281
  log(`done (${outcome.kind}, changed=${changed}, ${writes} commit(s) [${diffWrites} diff / ${structuralWrites} structural], ${reads ?? "?"} mcp tool call(s)): ${summary2.slice(0, 200).replace(/\n/g, " ")}`);
@@ -24142,11 +24295,6 @@ async function completeClaudeRun(ctx, job, deviceId, run) {
24142
24295
  affectedFieldForComplete(job.source_mode, affectedForComplete)
24143
24296
  );
24144
24297
  }
24145
- async function loadTriageProposals(client, projectId) {
24146
- const { data, error } = await client.from("proposals").select("id, kind, title, description, review_state, realization_state, done_override, about_component, about_story, about_repo, updated_at").eq("project_id", projectId).eq("kind", "proposal").not("realization_state", "in", "(closed,abandoned)").order("updated_at", { ascending: false }).limit(500);
24147
- if (error) return null;
24148
- return data ?? [];
24149
- }
24150
24298
  async function spawnTriage(jobId, mcpConfigPath, cwd, opts) {
24151
24299
  if (shuttingDown) return { ok: false, summary: "skipped: the daemon is shutting down" };
24152
24300
  const proc = spawnClaude({
@@ -24407,15 +24555,161 @@ async function runJob(ctx, job, claimDeviceId) {
24407
24555
  if (slot) sandboxRun: {
24408
24556
  boxedJobs.add(job.id);
24409
24557
  log(`sandbox: running boxed on slot ${slot.index}`);
24410
- let outcome;
24411
24558
  try {
24412
- outcome = await runSandboxedJob(sandboxDepsFor(ctx, job, deviceId, sandboxHost), job, {
24559
+ await runSandboxedJob(sandboxDepsFor(ctx, job, deviceId, sandboxHost), job, {
24413
24560
  slot,
24414
24561
  timeouts: {
24415
24562
  claudeMs: firstScan ? sandboxHost.settings.scanTimeoutMs : CLAUDE_TIMEOUT_MS,
24416
24563
  largeDiffClaudeMs: CLAUDE_LARGE_DIFF_TIMEOUT_MS
24417
24564
  },
24418
24565
  ...firstScan ? { maxModelRequests: sandboxHost.settings.maxScanModelRequests } : {}
24566
+ }, async (outcome, held) => {
24567
+ let triageBox = null;
24568
+ Object.assign(timings, outcome.metrics.durations_ms);
24569
+ Object.assign(metrics, outcome.metrics, { durations_ms: timings });
24570
+ const sandboxMetrics = outcome.metrics.sandbox;
24571
+ try {
24572
+ if (outcome.kind === "skip") {
24573
+ log(`after_sha is already at or behind the clean marker \u2014 completing no_op without advancing the marker`);
24574
+ await rpcComplete(
24575
+ ctx,
24576
+ job.id,
24577
+ deviceId,
24578
+ "Push is behind the last reflected commit; skipped.",
24579
+ "no_op",
24580
+ false,
24581
+ { mode: "skip", sandbox: sandboxMetrics, durations_ms: timings },
24582
+ { stdout: "", stderr: "" },
24583
+ false
24584
+ /* advance_marker */
24585
+ );
24586
+ return;
24587
+ }
24588
+ if (outcome.kind === "rejected") {
24589
+ log(`${outcome.message} \u2014 completing no_op without advancing the marker`);
24590
+ await rpcComplete(
24591
+ ctx,
24592
+ job.id,
24593
+ deviceId,
24594
+ outcome.message,
24595
+ "no_op",
24596
+ false,
24597
+ { mode: "rejected", sandbox: sandboxMetrics, durations_ms: timings },
24598
+ { stdout: "", stderr: "" },
24599
+ false
24600
+ /* advance_marker */
24601
+ );
24602
+ return;
24603
+ }
24604
+ if (outcome.kind === "step_failed") {
24605
+ logs = { stdout: "", stderr: truncateLog(outcome.stderr, LOG_STDERR_CAP_BYTES) };
24606
+ throw new SandboxExitError(
24607
+ `sandbox ${outcome.step} step failed: ${outcome.reason}`,
24608
+ classifySandboxExit({
24609
+ counters: sandboxMetrics,
24610
+ exitCode: null,
24611
+ stderr: outcome.stderr,
24612
+ stepFailure: outcome.reason
24613
+ })
24614
+ );
24615
+ }
24616
+ markPhase("claude_exit", { code: outcome.exitCode ?? "null", signal: outcome.signal ?? "null" });
24617
+ logs = {
24618
+ stdout: truncateLog(outcome.claudeStdout, LOG_STDOUT_CAP_BYTES),
24619
+ stderr: truncateLog(outcome.stderr, LOG_STDERR_CAP_BYTES)
24620
+ };
24621
+ metrics.exit_code = outcome.exitCode;
24622
+ metrics.signal = outcome.signal;
24623
+ if (cancelled.has(job.id)) {
24624
+ log(`cancelled while running, not marking complete`);
24625
+ await rpcRollback(ctx, job.id, deviceId);
24626
+ return;
24627
+ }
24628
+ const verdict = classifySandboxExit({
24629
+ counters: sandboxMetrics,
24630
+ exitCode: outcome.exitCode,
24631
+ stderr: outcome.stderr,
24632
+ claudeIsError: parseClaudeResult(outcome.claudeStdout).isError
24633
+ });
24634
+ if (verdict.kind === "terminal") throw new SandboxExitError(verdict.message, verdict);
24635
+ if (outcome.exitCode !== 0) {
24636
+ const detail = claudeFailureDetail(outcome.stderr, outcome.claudeStdout);
24637
+ if (detail) log(`claude output: ${detail.replace(/\n/g, " ")}`);
24638
+ throw new ClaudeRunError(
24639
+ buildClaudeExitMessage(outcome.exitCode, outcome.signal ? ` (${outcome.signal})` : "", outcome.stderr),
24640
+ detail,
24641
+ // The gate's own 401/403, never the box's text (BUG-143).
24642
+ verdict.kind === "upstream_auth_failure",
24643
+ claudeErrorDetails(outcome.claudeStdout),
24644
+ verdict
24645
+ );
24646
+ }
24647
+ const jobReads = readsFor(ctx, job, deviceId);
24648
+ if (firstScan) {
24649
+ if (verdict.kind === "upstream_rate_limit" || verdict.kind === "upstream_auth_failure") {
24650
+ throw new ClaudeRunError(
24651
+ `claude reported is_error in its JSON result (no successful completion)`,
24652
+ null,
24653
+ verdict.kind === "upstream_auth_failure",
24654
+ claudeErrorDetails(outcome.claudeStdout),
24655
+ verdict
24656
+ );
24657
+ }
24658
+ const gate = firstScanGate(await jobReads.architectureCounts());
24659
+ if (!gate.ok) throw new Error(gate.reason);
24660
+ }
24661
+ await completeClaudeRun(ctx, job, deviceId, {
24662
+ stdout: outcome.claudeStdout,
24663
+ stderr: outcome.stderr,
24664
+ metrics,
24665
+ logs,
24666
+ affected: outcome.affected,
24667
+ startedAt,
24668
+ markPhase,
24669
+ log,
24670
+ reads: jobReads,
24671
+ sandboxVerdict: verdict,
24672
+ // Board triage in a third box on this slot, never on the host: a
24673
+ // host agent reading the repo would undo the box. First scans have none.
24674
+ ...firstScan ? {} : {
24675
+ triage: () => runBoardTriage(
24676
+ {
24677
+ scope: {
24678
+ repo: `${job.repo_owner}/${job.repo_name}`,
24679
+ containerPath: held.prefetch.repoContainer,
24680
+ stories: held.prefetch.seedArch?.stories ?? []
24681
+ }
24682
+ },
24683
+ {
24684
+ loadProposals: () => jobReads.triageProposals(),
24685
+ run: async (candidates) => {
24686
+ const { box, ...run } = await held.triage.run({
24687
+ candidates,
24688
+ touchedComponents: outcome.affected?.components.map((c3) => c3.path) ?? [],
24689
+ touchedStories: outcome.affected?.stories.map(({ id, title }) => ({ id, title })) ?? []
24690
+ });
24691
+ triageBox = box;
24692
+ return run;
24693
+ },
24694
+ log
24695
+ }
24696
+ )
24697
+ }
24698
+ });
24699
+ } finally {
24700
+ await rpcReportEvent(ctx, job, deviceId, "sandbox_job_metrics", {
24701
+ job_id: job.id,
24702
+ project_id: job.project_id,
24703
+ outcome: outcome.kind,
24704
+ ...outcome.kind === "step_failed" ? { step: outcome.step, reason: outcome.reason } : {},
24705
+ ...outcome.kind === "claude" ? { exit_code: outcome.exitCode } : {},
24706
+ files: outcome.metrics.files ?? null,
24707
+ bytes: outcome.metrics.bytes ?? null,
24708
+ model: outcome.metrics.model ?? null,
24709
+ ...sandboxMetrics,
24710
+ ...metrics.triage ? { triage: triageEventFields(metrics.triage, triageBox) } : {}
24711
+ });
24712
+ }
24419
24713
  });
24420
24714
  } catch (err4) {
24421
24715
  if (err4 instanceof SandboxInfraError && !err4.agentStarted && !shuttingDown && !cancelled.has(job.id) && sandboxHost.settings.mode === "shadow") {
@@ -24439,121 +24733,6 @@ async function runJob(ctx, job, claimDeviceId) {
24439
24733
  );
24440
24734
  return;
24441
24735
  }
24442
- Object.assign(timings, outcome.metrics.durations_ms);
24443
- Object.assign(metrics, outcome.metrics, { durations_ms: timings });
24444
- const sandboxMetrics = outcome.metrics.sandbox;
24445
- await rpcReportEvent(ctx, job, deviceId, "sandbox_job_metrics", {
24446
- job_id: job.id,
24447
- project_id: job.project_id,
24448
- outcome: outcome.kind,
24449
- ...outcome.kind === "step_failed" ? { step: outcome.step, reason: outcome.reason } : {},
24450
- ...outcome.kind === "claude" ? { exit_code: outcome.exitCode } : {},
24451
- files: outcome.metrics.files ?? null,
24452
- bytes: outcome.metrics.bytes ?? null,
24453
- model: outcome.metrics.model ?? null,
24454
- ...sandboxMetrics
24455
- });
24456
- if (outcome.kind === "skip") {
24457
- log(`after_sha is already at or behind the clean marker \u2014 completing no_op without advancing the marker`);
24458
- await rpcComplete(
24459
- ctx,
24460
- job.id,
24461
- deviceId,
24462
- "Push is behind the last reflected commit; skipped.",
24463
- "no_op",
24464
- false,
24465
- { mode: "skip", sandbox: sandboxMetrics, durations_ms: timings },
24466
- { stdout: "", stderr: "" },
24467
- false
24468
- /* advance_marker */
24469
- );
24470
- return;
24471
- }
24472
- if (outcome.kind === "rejected") {
24473
- log(`${outcome.message} \u2014 completing no_op without advancing the marker`);
24474
- await rpcComplete(
24475
- ctx,
24476
- job.id,
24477
- deviceId,
24478
- outcome.message,
24479
- "no_op",
24480
- false,
24481
- { mode: "rejected", sandbox: sandboxMetrics, durations_ms: timings },
24482
- { stdout: "", stderr: "" },
24483
- false
24484
- /* advance_marker */
24485
- );
24486
- return;
24487
- }
24488
- if (outcome.kind === "step_failed") {
24489
- logs = { stdout: "", stderr: truncateLog(outcome.stderr, LOG_STDERR_CAP_BYTES) };
24490
- throw new SandboxExitError(
24491
- `sandbox ${outcome.step} step failed: ${outcome.reason}`,
24492
- classifySandboxExit({
24493
- counters: sandboxMetrics,
24494
- exitCode: null,
24495
- stderr: outcome.stderr,
24496
- stepFailure: outcome.reason
24497
- })
24498
- );
24499
- }
24500
- markPhase("claude_exit", { code: outcome.exitCode ?? "null", signal: outcome.signal ?? "null" });
24501
- logs = {
24502
- stdout: truncateLog(outcome.claudeStdout, LOG_STDOUT_CAP_BYTES),
24503
- stderr: truncateLog(outcome.stderr, LOG_STDERR_CAP_BYTES)
24504
- };
24505
- metrics.exit_code = outcome.exitCode;
24506
- metrics.signal = outcome.signal;
24507
- if (cancelled.has(job.id)) {
24508
- log(`cancelled while running, not marking complete`);
24509
- await rpcRollback(ctx, job.id, deviceId);
24510
- return;
24511
- }
24512
- const verdict = classifySandboxExit({
24513
- counters: sandboxMetrics,
24514
- exitCode: outcome.exitCode,
24515
- stderr: outcome.stderr,
24516
- claudeIsError: parseClaudeResult(outcome.claudeStdout).isError
24517
- });
24518
- if (verdict.kind === "terminal") throw new SandboxExitError(verdict.message, verdict);
24519
- if (outcome.exitCode !== 0) {
24520
- const detail = claudeFailureDetail(outcome.stderr, outcome.claudeStdout);
24521
- if (detail) log(`claude output: ${detail.replace(/\n/g, " ")}`);
24522
- throw new ClaudeRunError(
24523
- buildClaudeExitMessage(outcome.exitCode, outcome.signal ? ` (${outcome.signal})` : "", outcome.stderr),
24524
- detail,
24525
- // The gate's own 401/403, never the box's text (BUG-143).
24526
- verdict.kind === "upstream_auth_failure",
24527
- claudeErrorDetails(outcome.claudeStdout),
24528
- verdict
24529
- );
24530
- }
24531
- const jobReads = readsFor(ctx, job, deviceId);
24532
- if (firstScan) {
24533
- if (verdict.kind === "upstream_rate_limit" || verdict.kind === "upstream_auth_failure") {
24534
- throw new ClaudeRunError(
24535
- `claude reported is_error in its JSON result (no successful completion)`,
24536
- null,
24537
- verdict.kind === "upstream_auth_failure",
24538
- claudeErrorDetails(outcome.claudeStdout),
24539
- verdict
24540
- );
24541
- }
24542
- const gate = firstScanGate(await jobReads.architectureCounts());
24543
- if (!gate.ok) throw new Error(gate.reason);
24544
- }
24545
- await completeClaudeRun(ctx, job, deviceId, {
24546
- stdout: outcome.claudeStdout,
24547
- stderr: outcome.stderr,
24548
- metrics,
24549
- logs,
24550
- affected: outcome.affected,
24551
- startedAt,
24552
- markPhase,
24553
- log,
24554
- reads: jobReads,
24555
- sandboxVerdict: verdict
24556
- });
24557
24736
  return;
24558
24737
  }
24559
24738
  }
@@ -24786,24 +24965,27 @@ async function runJob(ctx, job, claimDeviceId) {
24786
24965
  markPhase,
24787
24966
  log,
24788
24967
  triage: () => runBoardTriage(
24968
+ { scope: { repo: jobRepo, containerPath: jobScope?.containerPath ?? null, stories: seedStories } },
24789
24969
  {
24790
- scope: { repo: jobRepo, containerPath: jobScope?.containerPath ?? null, stories: seedStories },
24791
- prompt: {
24792
- projectSlug,
24793
- repo: jobRepo,
24794
- mode: effectiveMode,
24795
- prNumber: job.pr_number ?? null,
24796
- afterSha: diff.after,
24797
- rangeLabel: diff.rangeLabel,
24798
- changedFiles: diff.changedFiles,
24799
- touchedComponents: affectedForComplete?.components.map((c3) => c3.path) ?? [],
24800
- touchedStories: affectedForComplete?.stories.map(({ id, title }) => ({ id, title })) ?? [],
24801
- checkoutDir: worktreeDir
24802
- }
24803
- },
24804
- {
24805
- loadProposals: () => loadTriageProposals(ctx.supabase, job.project_id),
24806
- spawn: (opts) => spawnTriage(job.id, configPath, worktreeDir, opts),
24970
+ loadProposals: () => readsFor(ctx, job, deviceId).triageProposals(),
24971
+ run: (candidates) => spawnTriage(job.id, configPath, worktreeDir, {
24972
+ prompt: buildTriagePrompt({
24973
+ projectSlug,
24974
+ repo: jobRepo,
24975
+ mode: effectiveMode,
24976
+ prNumber: job.pr_number ?? null,
24977
+ afterSha: diff.after,
24978
+ rangeLabel: diff.rangeLabel,
24979
+ changedFiles: diff.changedFiles,
24980
+ touchedComponents: affectedForComplete?.components.map((c3) => c3.path) ?? [],
24981
+ touchedStories: affectedForComplete?.stories.map(({ id, title }) => ({ id, title })) ?? [],
24982
+ candidates,
24983
+ checkoutDir: worktreeDir,
24984
+ budgetMinutes: Math.round(TRIAGE_TIMEOUT_MS / 6e4)
24985
+ }),
24986
+ model: TRIAGE_CLAUDE_MODEL,
24987
+ timeoutMs: TRIAGE_TIMEOUT_MS
24988
+ }),
24807
24989
  log
24808
24990
  }
24809
24991
  )
@@ -25372,6 +25554,8 @@ var init_run = __esm({
25372
25554
  init_multiRepoScan();
25373
25555
  init_bugsFolder();
25374
25556
  init_triage();
25557
+ init_triagePrompt();
25558
+ init_daemonModel();
25375
25559
  init_repoMappings();
25376
25560
  init_repoContainer();
25377
25561
  init_defaults();
@@ -25626,6 +25810,18 @@ ${ANCHOR_VERIFICATION}`;
25626
25810
  setConfinementGate(gate) {
25627
25811
  confinementGate = gate;
25628
25812
  },
25813
+ // Kill-state seams: what a cancel (realtime) or the shutdown handler sets for a job.
25814
+ cancelJob(jobId) {
25815
+ cancelled.add(jobId);
25816
+ killReasons.set(jobId, "cancel");
25817
+ },
25818
+ beginShutdown(killJobId) {
25819
+ shuttingDown = true;
25820
+ if (killJobId) killReasons.set(killJobId, "shutdown");
25821
+ },
25822
+ endShutdown() {
25823
+ shuttingDown = false;
25824
+ },
25629
25825
  setSandboxMode(mode) {
25630
25826
  sandboxMode = mode;
25631
25827
  },
@@ -26144,8 +26340,8 @@ async function defaultLoadSupabaseState(_deviceId) {
26144
26340
  async function defaultLoadUptime(pid) {
26145
26341
  if (process.platform === "linux") {
26146
26342
  try {
26147
- const { readFile: readFile24 } = await import("node:fs/promises");
26148
- const stat15 = await readFile24(`/proc/${pid}/stat`, "utf8");
26343
+ const { readFile: readFile25 } = await import("node:fs/promises");
26344
+ const stat15 = await readFile25(`/proc/${pid}/stat`, "utf8");
26149
26345
  const parts = stat15.split(") ").pop()?.split(" ") ?? [];
26150
26346
  const ticks = Number(parts[19]);
26151
26347
  if (!Number.isFinite(ticks)) return null;
@@ -32683,6 +32879,55 @@ function parseDigest(data) {
32683
32879
  tools: data.tools
32684
32880
  };
32685
32881
  }
32882
+ function parseAbout(raw, where) {
32883
+ if (raw === null || raw === void 0) return null;
32884
+ if (!isObj2(raw)) fail(`${where} must be an object or null`);
32885
+ if (raw.kind === "component") return { kind: "component", path: str3(raw, "path", where) };
32886
+ if (raw.kind === "story") return { kind: "story", id: str3(raw, "id", where) };
32887
+ if (raw.kind === "repo") return { kind: "repo", repo: str3(raw, "repo", where) };
32888
+ fail(`${where}.kind must be component, story or repo`);
32889
+ }
32890
+ function parseCandidates(raw) {
32891
+ if (!Array.isArray(raw) || raw.length > TRIAGE_CANDIDATE_LIMIT) {
32892
+ fail(`candidates must be an array of at most ${TRIAGE_CANDIDATE_LIMIT}`);
32893
+ }
32894
+ return raw.map((c3, i2) => {
32895
+ const where = `candidates[${i2}]`;
32896
+ if (!isObj2(c3)) fail(`${where} must be an object`);
32897
+ return {
32898
+ id: str3(c3, "id", where),
32899
+ title: str3(c3, "title", where),
32900
+ description: optStr(c3, "description", where),
32901
+ stage: optStr(c3, "stage", where),
32902
+ about: parseAbout(c3.about, `${where}.about`)
32903
+ };
32904
+ });
32905
+ }
32906
+ function parseTriage(data, job) {
32907
+ const timeoutMs = data.timeoutMs;
32908
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) fail("timeoutMs must be a positive integer");
32909
+ const gateway = str3(data, "gateway", "input");
32910
+ if (!IPV4_RE2.test(gateway)) fail("gateway must be an IPv4 address");
32911
+ const comps = data.touchedComponents;
32912
+ if (!Array.isArray(comps) || !comps.every((c3) => typeof c3 === "string")) fail("touchedComponents must be strings");
32913
+ const stories = data.touchedStories;
32914
+ if (!Array.isArray(stories)) fail("touchedStories must be an array");
32915
+ return {
32916
+ kind: "triage",
32917
+ job,
32918
+ projectSlug: str3(data, "projectSlug", "input"),
32919
+ candidates: parseCandidates(data.candidates),
32920
+ touchedComponents: [...comps],
32921
+ touchedStories: stories.map((s, i2) => {
32922
+ if (!isObj2(s)) fail(`touchedStories[${i2}] must be an object`);
32923
+ if (typeof s.title !== "string") fail(`touchedStories[${i2}].title must be a string`);
32924
+ return { id: str3(s, "id", `touchedStories[${i2}]`), title: s.title };
32925
+ }),
32926
+ model: str3(data, "model", "input"),
32927
+ timeoutMs,
32928
+ gateway
32929
+ };
32930
+ }
32686
32931
  function parseInput(raw) {
32687
32932
  let data;
32688
32933
  try {
@@ -32723,7 +32968,8 @@ function parseInput(raw) {
32723
32968
  };
32724
32969
  return input;
32725
32970
  }
32726
- fail("kind must be clone, agent, digest or probe");
32971
+ if (data.kind === "triage") return parseTriage(data, job);
32972
+ fail("kind must be clone, agent, digest, probe or triage");
32727
32973
  }
32728
32974
  async function readInput(path7 = INPUT_PATH, read = (p) => readFile23(p, "utf8")) {
32729
32975
  let raw;
@@ -32739,6 +32985,7 @@ var init_input = __esm({
32739
32985
  "src/daemon/sandboxJob/input.ts"() {
32740
32986
  "use strict";
32741
32987
  init_types();
32988
+ init_boardTriage();
32742
32989
  InputSchemaError = class extends Error {
32743
32990
  constructor(message2) {
32744
32991
  super(`input.json: ${message2}`);
@@ -32939,13 +33186,83 @@ var init_digest2 = __esm({
32939
33186
  }
32940
33187
  });
32941
33188
 
33189
+ // src/daemon/sandboxJob/triage.ts
33190
+ import { mkdir as mkdir21, readFile as readFile24 } from "node:fs/promises";
33191
+ async function runTriageStep(input, deps = {}) {
33192
+ const repoDir = deps.repoDir ?? REPO_DIR;
33193
+ const log = deps.log ?? (() => {
33194
+ });
33195
+ const mark = deps.mark ?? (() => {
33196
+ });
33197
+ const spawn2 = deps.spawn ?? ((o2) => spawnClaude(o2));
33198
+ const writeStderr = deps.writeStderr ?? ((c3) => {
33199
+ process.stderr.write(c3);
33200
+ });
33201
+ const diff = parsePersistedDiff(await readFile24(deps.diffPath ?? DIFF_PATH, "utf8"));
33202
+ mark("read_diff");
33203
+ const { job } = input;
33204
+ const prompt = buildTriagePrompt({
33205
+ projectSlug: input.projectSlug,
33206
+ repo: `${job.repo_owner}/${job.repo_name}`,
33207
+ mode: job.source_mode === "pr_update" ? "pr_update" : "diff",
33208
+ prNumber: job.pr_number ?? null,
33209
+ afterSha: diff.after,
33210
+ rangeLabel: diff.rangeLabel,
33211
+ changedFiles: diff.changedFiles,
33212
+ touchedComponents: input.touchedComponents,
33213
+ touchedStories: input.touchedStories,
33214
+ candidates: input.candidates,
33215
+ checkoutDir: repoDir,
33216
+ budgetMinutes: Math.round(input.timeoutMs / 6e4)
33217
+ });
33218
+ const promptBytes = Buffer.byteLength(prompt, "utf8");
33219
+ const mcpConfigPath = await writeBoxMcpConfig(input.gateway, deps.mcpDir);
33220
+ for (const d of deps.homeDirs ?? [BOX_HOME, BOX_CLAUDE_CONFIG_DIR]) await mkdir21(d, { recursive: true, mode: 448 });
33221
+ log(`spawning triage claude (model ${input.model}, ${input.candidates.length} candidate(s), prompt ${promptBytes} bytes)`);
33222
+ const proc = spawn2({
33223
+ prompt,
33224
+ mcpConfigPath,
33225
+ cwd: repoDir,
33226
+ timeoutMs: input.timeoutMs,
33227
+ model: input.model,
33228
+ allowedTools: TRIAGE_ALLOWED_TOOLS,
33229
+ builtinTools: TRIAGE_BUILTIN_TOOLS,
33230
+ jsonOutput: true,
33231
+ settingSources: "user",
33232
+ promptViaStdin: true
33233
+ });
33234
+ const { exitCode, signal, stdout, spawnError } = await awaitClaude(proc, writeStderr);
33235
+ mark("claude");
33236
+ log(`triage claude exited (code ${exitCode ?? "null"}, signal ${signal ?? "null"})`);
33237
+ return {
33238
+ result: {
33239
+ kind: "triage",
33240
+ exitCode,
33241
+ signal,
33242
+ claudeStdout: stdout,
33243
+ promptBytes,
33244
+ ...spawnError ? { error: spawnError } : {}
33245
+ },
33246
+ exitCode: exitCode ?? 1
33247
+ };
33248
+ }
33249
+ var init_triage2 = __esm({
33250
+ "src/daemon/sandboxJob/triage.ts"() {
33251
+ "use strict";
33252
+ init_triagePrompt();
33253
+ init_spawn_claude();
33254
+ init_types();
33255
+ init_agent();
33256
+ }
33257
+ });
33258
+
32942
33259
  // src/daemon/sandboxJob/main.ts
32943
33260
  var main_exports = {};
32944
33261
  __export(main_exports, {
32945
33262
  readNonceLine: () => readNonceLine,
32946
33263
  runSandboxJob: () => runSandboxJob
32947
33264
  });
32948
- import { mkdir as mkdir21 } from "node:fs/promises";
33265
+ import { mkdir as mkdir22 } from "node:fs/promises";
32949
33266
  function readNonceLine(stream = process.stdin) {
32950
33267
  return new Promise((resolve9) => {
32951
33268
  let buf = "";
@@ -32978,6 +33295,19 @@ function emptyResult(step, error) {
32978
33295
  const r2 = { kind: "clone", outcome: "diff", memoryPeakBytes: null, durations_ms: {}, error };
32979
33296
  return r2;
32980
33297
  }
33298
+ if (step === "triage") {
33299
+ const r2 = {
33300
+ kind: "triage",
33301
+ exitCode: null,
33302
+ signal: null,
33303
+ claudeStdout: "",
33304
+ promptBytes: 0,
33305
+ memoryPeakBytes: null,
33306
+ durations_ms: {},
33307
+ error
33308
+ };
33309
+ return r2;
33310
+ }
32981
33311
  const r = {
32982
33312
  kind: "agent",
32983
33313
  exitCode: null,
@@ -33021,19 +33351,20 @@ async function runSandboxJob(argv, deps = {}) {
33021
33351
  return code;
33022
33352
  };
33023
33353
  const step = argv[0];
33024
- if (step !== "clone" && step !== "agent" && step !== "digest" && step !== "probe") {
33025
- const msg = `unknown step ${JSON.stringify(step ?? "")}; expected clone, agent, digest or probe`;
33354
+ if (step === void 0 || !STEPS.includes(step)) {
33355
+ const msg = `unknown step ${JSON.stringify(step ?? "")}; expected clone, agent, digest, probe or triage`;
33026
33356
  log(msg);
33027
33357
  return emit2(emptyResult("clone", msg), EXIT_INPUT_SCHEMA);
33028
33358
  }
33359
+ const stepName = step;
33029
33360
  let input;
33030
33361
  try {
33031
33362
  input = await (deps.readInput ?? readInput)(deps.inputPath ?? INPUT_PATH);
33032
- if (input.kind !== step) throw new InputSchemaError(`kind ${input.kind} does not match step ${step}`);
33363
+ if (input.kind !== stepName) throw new InputSchemaError(`kind ${input.kind} does not match step ${step}`);
33033
33364
  } catch (err4) {
33034
33365
  const msg = err4 instanceof Error ? err4.message : String(err4);
33035
33366
  log(msg);
33036
- return emit2(emptyResult(step, msg), err4 instanceof InputSchemaError ? EXIT_INPUT_SCHEMA : 1);
33367
+ return emit2(emptyResult(stepName, msg), err4 instanceof InputSchemaError ? EXIT_INPUT_SCHEMA : 1);
33037
33368
  }
33038
33369
  mark("input");
33039
33370
  if (input.kind === "probe") {
@@ -33049,31 +33380,35 @@ async function runSandboxJob(argv, deps = {}) {
33049
33380
  if (input.kind === "digest") {
33050
33381
  log(`digest job=${input.jobId}`);
33051
33382
  try {
33052
- await mkdir21(deps.homeDir ?? process.env.HOME ?? BOX_HOME, { recursive: true, mode: 448 });
33383
+ await mkdir22(deps.homeDir ?? process.env.HOME ?? BOX_HOME, { recursive: true, mode: 448 });
33053
33384
  const { result, exitCode } = await runDigestStep(input, { log, mark, ...deps.digest });
33054
33385
  return emit2({ ...result, memoryPeakBytes: null, durations_ms: {} }, exitCode);
33055
33386
  } catch (err4) {
33056
33387
  const msg = err4 instanceof Error ? err4.message : String(err4);
33057
33388
  log(`failed: ${msg}`);
33058
- return emit2(emptyResult(step, msg), 1);
33389
+ return emit2(emptyResult(stepName, msg), 1);
33059
33390
  }
33060
33391
  }
33061
- log(`${step} job=${input.job.id} repo=${input.job.repo_owner}/${input.job.repo_name} ${input.job.after_sha ? `after=${input.job.after_sha.slice(0, 8)}` : `scan=${(input.job.scan_ref ?? "").slice(0, 8)}`}`);
33392
+ log(`${stepName} job=${input.job.id} repo=${input.job.repo_owner}/${input.job.repo_name} ${input.job.after_sha ? `after=${input.job.after_sha.slice(0, 8)}` : `scan=${(input.job.scan_ref ?? "").slice(0, 8)}`}`);
33062
33393
  try {
33063
- await mkdir21(deps.homeDir ?? process.env.HOME ?? BOX_HOME, { recursive: true, mode: 448 });
33394
+ await mkdir22(deps.homeDir ?? process.env.HOME ?? BOX_HOME, { recursive: true, mode: 448 });
33064
33395
  if (input.kind === "clone") {
33065
33396
  const { result: result2, exitCode: exitCode2 } = await runCloneStep(input, { log, mark, ...deps.clone });
33066
33397
  return emit2({ ...result2, memoryPeakBytes: null, durations_ms: {} }, exitCode2);
33067
33398
  }
33399
+ if (input.kind === "triage") {
33400
+ const { result: result2, exitCode: exitCode2 } = await runTriageStep(input, { log, mark, ...deps.triage });
33401
+ return emit2({ ...result2, memoryPeakBytes: null, durations_ms: {} }, exitCode2);
33402
+ }
33068
33403
  const { result, exitCode } = await runAgentStep(input, { log, mark, ...deps.agent });
33069
33404
  return emit2({ ...result, memoryPeakBytes: null, durations_ms: {} }, exitCode);
33070
33405
  } catch (err4) {
33071
33406
  const msg = err4 instanceof Error ? err4.message : String(err4);
33072
33407
  log(`failed: ${msg}`);
33073
- return emit2(emptyResult(step, msg), 1);
33408
+ return emit2(emptyResult(stepName, msg), 1);
33074
33409
  }
33075
33410
  }
33076
- var NONCE_LINE_MAX_BYTES;
33411
+ var STEPS, NONCE_LINE_MAX_BYTES;
33077
33412
  var init_main2 = __esm({
33078
33413
  "src/daemon/sandboxJob/main.ts"() {
33079
33414
  "use strict";
@@ -33084,6 +33419,8 @@ var init_main2 = __esm({
33084
33419
  init_agent();
33085
33420
  init_probe();
33086
33421
  init_digest2();
33422
+ init_triage2();
33423
+ STEPS = ["clone", "agent", "digest", "probe", "triage"];
33087
33424
  NONCE_LINE_MAX_BYTES = 256;
33088
33425
  }
33089
33426
  });
@@ -33162,7 +33499,7 @@ var KNOWN_COMMANDS = /* @__PURE__ */ new Set([
33162
33499
  "doctor",
33163
33500
  // Hidden: operator-only (platform admins), deliberately absent from printHelp.
33164
33501
  "concierge-token",
33165
- // Hidden: the per-job sandbox image's entrypoint (`sandbox-job clone|agent|digest|probe`).
33502
+ // Hidden: the per-job sandbox image's entrypoint (`sandbox-job clone|agent|digest|triage|probe`).
33166
33503
  "sandbox-job"
33167
33504
  ]);
33168
33505
  var VERSION_FLAGS = /* @__PURE__ */ new Set(["--version", "-v"]);