@sjawhar/claude-envoy 4.11.0 → 4.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.omp-plugin/plugin.json +1 -1
  3. package/AGENTS.md +43 -497
  4. package/dist/codex-hook.js +2076 -2042
  5. package/dist/dispatch.js +2106 -2050
  6. package/dist/envoy-channel.js +2077 -2043
  7. package/dist/session-hook.js +2076 -2042
  8. package/legion/skills/legion-architect/SKILL.md +88 -66
  9. package/legion/skills/legion-architect/references/acceptance.md +89 -258
  10. package/legion/skills/legion-architect/references/decomposition.md +94 -213
  11. package/legion/skills/legion-architect/references/design-gate.md +88 -353
  12. package/legion/skills/legion-architect/references/wake-routing.md +51 -43
  13. package/legion/skills/legion-controller/SKILL.md +50 -181
  14. package/legion/skills/legion-controller/references/admission.md +25 -54
  15. package/legion/skills/legion-controller/references/backlog-stewardship.md +23 -119
  16. package/legion/skills/legion-controller/references/consolidation.md +9 -93
  17. package/legion/skills/legion-controller/references/daily-report.md +21 -99
  18. package/legion/skills/legion-controller/references/escalation.md +16 -118
  19. package/legion/skills/legion-controller/references/finding-asks.md +31 -162
  20. package/legion/skills/legion-controller/references/park-asks.md +33 -0
  21. package/legion/skills/legion-controller/references/parked-decisions.md +20 -264
  22. package/legion/skills/legion-controller/references/session.md +26 -84
  23. package/legion/skills/legion-controller/references/slack-mentions.md +18 -134
  24. package/legion/skills/legion-controller/references/triage.md +18 -89
  25. package/legion/skills/legion-controller/references/wakes.md +22 -549
  26. package/legion/skills/legion-controller/references/weekly-audit.md +9 -90
  27. package/legion/skills/legion-oracle/SKILL.md +19 -28
  28. package/legion/skills/legion-retro/SKILL.md +54 -93
  29. package/legion/skills/legion-retro/references/learnings.md +21 -33
  30. package/legion/skills/legion-retro/references/pr-body-content.md +21 -37
  31. package/legion/skills/legion-worker/SKILL.md +50 -64
  32. package/legion/skills/legion-worker/references/ci-checks.md +16 -84
  33. package/legion/skills/legion-worker/references/conflicts-and-rewrites.md +34 -93
  34. package/legion/skills/legion-worker/references/default-branch-check.md +22 -60
  35. package/legion/skills/legion-worker/references/findings.md +25 -180
  36. package/legion/skills/legion-worker/references/foreign-path.md +14 -22
  37. package/legion/skills/legion-worker/references/gvisor.md +20 -0
  38. package/legion/skills/legion-worker/references/merge-gate.md +43 -419
  39. package/legion/skills/legion-worker/references/plan-tests.md +8 -28
  40. package/legion/skills/legion-worker/references/pr-body.md +19 -218
  41. package/legion/skills/legion-worker/references/review-threads.md +16 -70
  42. package/legion/skills/legion-worker/references/tools.md +31 -578
  43. package/legion/skills/legion-worker/references/withheld-capability.md +12 -163
  44. package/legion/skills/simplify-settled-diff/SKILL.md +23 -41
  45. package/legion/skills/simplify-settled-diff/references/personas/code-quality-reviewer.md +14 -14
  46. package/legion/skills/simplify-settled-diff/references/personas/code-reuse-reviewer.md +4 -4
  47. package/legion/skills/simplify-settled-diff/references/personas/efficiency-reviewer.md +8 -8
  48. package/package.json +1 -1
  49. package/skills/agent-secrets/SKILL.md +46 -312
  50. package/skills/agent-secrets/references/store-a-secret.md +9 -0
  51. package/skills/approval-review/SKILL.md +20 -76
  52. package/skills/asd-ste100/SKILL.md +43 -85
  53. package/skills/asd-ste100/examples/before-after.md +18 -53
  54. package/skills/dispatch/SKILL.md +1 -1
  55. package/skills/dispatch-writing-specs/SKILL.md +1 -1
  56. package/skills/envoy/SKILL.md +56 -126
  57. package/skills/envoy/references/check-settlement.md +26 -43
  58. package/skills/envoy/references/deliveries.md +26 -144
  59. package/skills/envoy/references/legion.md +12 -45
  60. package/skills/envoy/references/roles.md +11 -9
  61. package/skills/envoy/references/sources.md +13 -25
  62. package/skills/outside-message/SKILL.md +24 -81
  63. package/skills/plain-words/SKILL.md +24 -55
  64. package/skills/thermonuclear-code-quality/SKILL.md +16 -26
  65. package/skills/thermonuclear-deep-review/SKILL.md +22 -31
  66. package/legion/skills/legion-worker/references/cleanup-deletion.md +0 -22
  67. package/legion/skills/legion-worker/references/systematic-rename.md +0 -19
  68. package/skills/asd-ste100/references/writing-rules.md +0 -59
  69. package/skills/plain-words/references/mechanics.md +0 -49
@@ -14635,7 +14635,7 @@ var dispatchToolSpecs = [
14635
14635
  verdict: "pass",
14636
14636
  commit: "1111111111111111111111111111111111111111"
14637
14637
  },
14638
- description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. A " + "commit that repository does not hold is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and that owner/repo. Record the result after the commit is pushed. A repository " + "Dispatch cannot read records the result as before. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED, as it refuses every other write. " + "A check a document version rewords while the result is being written is 409 " + "CHECK_CONTENDED, with nothing recorded: run the same command again. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + ISSUE_REFERENCE,
14638
+ description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch, no private host and no issue key: Dispatch keeps only words " + "of letters, digits and plain punctuation, and of those leaves out every word that holds " + "`://`, a private or Dispatch host, or an issue key of one of its projects; the record keeps " + "the whole reading. --dry-run prints the line the record would print, and records nothing. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. A " + "commit that repository does not hold is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and that owner/repo. Record the result after the commit is pushed. A repository " + "Dispatch cannot read records the result as before. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED, as it refuses every other write. " + "A check a document version rewords while the result is being written is 409 " + "CHECK_CONTENDED, with nothing recorded: run the same command again. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + ISSUE_REFERENCE,
14639
14639
  arguments: (z) => ({
14640
14640
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
14641
14641
  check: z.string().describe("The check block's id, or its canonical reference dispatch://KEY/artifact/verification-md#b-<id> when the id is not unique among the issue's Verification document and those of the issues above it.").optional(),
@@ -17442,7 +17442,7 @@ function flagTable(tool, fields) {
17442
17442
  add("--help", { action: "help", text: "Prints this help." });
17443
17443
  add("--dry-run", {
17444
17444
  action: "dry-run",
17445
- text: "Checks the arguments as the call would, then prints them as JSON and sends nothing."
17445
+ text: tool === "dispatch_result" ? "Checks the arguments as the call would and prints them as JSON. A record's dry run then asks Dispatch for the pull-request body line the record would print, and prints it; Dispatch records nothing. A retraction's dry run sends nothing." : "Checks the arguments as the call would, then prints them as JSON and sends nothing."
17446
17446
  });
17447
17447
  return flags;
17448
17448
  }
@@ -17716,7 +17716,7 @@ function commandsHelp() {
17716
17716
  return ` ${commandName(spec.name).padEnd(width)} ${sentence}`;
17717
17717
  }),
17718
17718
  "",
17719
- "Run dispatch <command> --help for its flags and an example; --dry-run checks a command's arguments as the call would and prints them as given, sending nothing.",
17719
+ "Run dispatch <command> --help for its flags and an example; --dry-run checks a command's arguments as the call would and prints them as given, sending nothing, except that dispatch result's dry run of a record also prints the pull-request body line Dispatch would write for it, recording nothing.",
17720
17720
  ""
17721
17721
  ].join(`
17722
17722
  `);
@@ -19645,6 +19645,9 @@ function reviewNoRouteRefusal(baseUrl, route, version) {
19645
19645
  const health = isCleanUrl(baseUrl) ? `${baseUrl}/healthz` : "/healthz on that server";
19646
19646
  return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${shown} answered no route for ${route} each time the review was sent, and an ` + "answer of no route records no review. This build is older than that route. No other review " + "route was asked: the review route an older build serves takes no version, and it " + `would record the review at a version that build chooses, which may not be version ${version}. ` + `The no-route answer does not name the build; GET ${health} names the commit of the ` + "build that answers it, when that build was stamped with one.");
19647
19647
  }
19648
+ function resultDryRunNoRouteRefusal(baseUrl, route) {
19649
+ return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${urlForText(baseUrl, DISPATCH_URL_SETTING)} answered no route for ${route} each ` + "time the dry run was sent: this build is older than a result's dry run, so it cannot show " + "the pull-request body line before the record. Nothing was recorded.");
19650
+ }
19648
19651
  var ISSUE_EVENTS_PAGE_MAX = 200;
19649
19652
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
19650
19653
  function requestSignal(signal, deadlineMs) {
@@ -20152,6 +20155,20 @@ class DispatchClient {
20152
20155
  async recordResult(issue, input) {
20153
20156
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
20154
20157
  }
20158
+ async dryRunResult(issue, input) {
20159
+ const path = ["api", "v1", "issues", await this.#resolveIssue(issue), "results", "dry-run"];
20160
+ try {
20161
+ const { payload } = await this.#jsonAnswer("POST", path, input, {
20162
+ writes: false
20163
+ });
20164
+ return payload;
20165
+ } catch (error) {
20166
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
20167
+ throw error;
20168
+ const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
20169
+ throw resultDryRunNoRouteRefusal(this.#baseUrl, route);
20170
+ }
20171
+ }
20155
20172
  async issueResults(issue, at) {
20156
20173
  return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], undefined, at === undefined ? undefined : { at });
20157
20174
  }
@@ -23384,372 +23401,265 @@ async function otherAdviceLines(render) {
23384
23401
  }
23385
23402
  }
23386
23403
 
23387
- // ../envoy-client/src/dispatch-commands/render-graph.ts
23388
- function referenceLines(read) {
23389
- if (typeof read === "string")
23390
- return [`- ${read}`];
23391
- const edges = read.edges ?? [];
23392
- if (edges.length === 0)
23393
- return ["- none"];
23394
- return edges.map(edgeLine);
23395
- }
23396
- function isItemKind(kind) {
23397
- return ITEM_KINDS.some((item) => item === kind);
23398
- }
23399
- function edgeLine(edge) {
23400
- const { node } = edge;
23401
- const excerpt = edge.excerpt === undefined ? "" : `${textHead(edge.excerpt.text)} \xB7 `;
23402
- const block = edge.block === undefined ? "" : ` (block ${edge.block.ref ?? edge.block.id})`;
23403
- const parent = node.parent ?? undefined;
23404
- const item = node.kind === "block" && node.document === undefined && isItemKind(parent?.kind) ? parent : undefined;
23405
- const source = item === undefined ? `${node.kind} ${node.ref ?? node.id}` : `${item.kind} ${item.ref ?? item.id} block ${node.block_id ?? node.id}`;
23406
- return `- ${edge.kind} ${source} (${excerpt}${edge.created_at})${block}`;
23407
- }
23408
- function unavailableReason(error) {
23409
- return dispatchAnswered(error, 404) ? "unavailable" : `unavailable: ${messageFor(error)}`;
23410
- }
23411
- async function graphReferences(client, query) {
23412
- try {
23413
- return await client.getReferences(query);
23414
- } catch (error) {
23415
- return unavailableReason(error);
23404
+ // ../envoy-client/src/dispatch-commands/render-issue.ts
23405
+ function componentsLine(components) {
23406
+ const ids = components.ids ?? [];
23407
+ const unknown = components.unknown ?? [];
23408
+ const inherited = components.inherited_from === null ? "" : ` (inherited from ${components.inherited_from})`;
23409
+ const retired = unknown.length === 0 ? "" : ` (retired: ${unknown.join(", ")})`;
23410
+ switch (components.mode) {
23411
+ case "explicit":
23412
+ return `Components: ${ids.length === 0 ? "none live" : ids.join(", ")}${inherited}${retired}`;
23413
+ case "none":
23414
+ return `Components: none \u2014 ${components.reason ?? ""}${inherited}`;
23415
+ case "inherit":
23416
+ return "Components: unassigned";
23417
+ default:
23418
+ return `Components: ${components.mode}${inherited}${retired}`;
23416
23419
  }
23417
23420
  }
23418
- async function issueReferencesOrUnavailable(client, key) {
23419
- try {
23420
- return await client.getIssueReferences(key);
23421
- } catch (error) {
23422
- return unavailableReason(error);
23423
- }
23421
+ function advanceText(advance) {
23422
+ return `${advance.id} (${advance.inherited ? "inherited" : "own"})`;
23424
23423
  }
23425
- async function issueCoverageOrReason(client, key) {
23426
- try {
23427
- return await client.issueCoverage(key);
23428
- } catch (error) {
23429
- return unavailableReason(error);
23424
+ function advancesLine(issue) {
23425
+ if (issue.advances === undefined) {
23426
+ return "Advances: unknown (this Dispatch server predates priorities; upgrade it)";
23430
23427
  }
23428
+ const advances = issue.advances ?? [];
23429
+ if (advances.length === 0)
23430
+ return "Advances: no priority";
23431
+ return `Advances: ${advances.map(advanceText).join(", ")}`;
23431
23432
  }
23432
- async function graphSections(client, ref) {
23433
- const [incoming, outgoing] = await Promise.all([
23434
- graphReferences(client, { to: ref }),
23435
- graphReferences(client, { from: ref })
23436
- ]);
23437
- return graphSectionLines(incoming, outgoing);
23438
- }
23439
- function graphSectionLines(incoming, outgoing) {
23440
- return [
23441
- ...typeof incoming === "string" ? [] : nodeLine(incoming.node),
23442
- "Referenced by:",
23443
- ...referenceLines(incoming),
23444
- "Links:",
23445
- ...referenceLines(outgoing)
23446
- ];
23447
- }
23448
- function nodeLine(node) {
23449
- if (node.made_by === undefined)
23450
- return [];
23451
- const fact = (by, time) => `${by == null || by.length === 0 ? "nobody recorded" : by.map(actorText).join(", ")}${time == null ? "" : ` at ${time}`}`;
23452
- const made = fact(node.made_by, node.made_at);
23453
- const changed = fact(node.changed_by, node.changed_at);
23454
- const { parent } = node;
23455
- const partOf = parent == null ? "" : ` \xB7 part of ${parent.ref ?? `${parent.kind} ${parent.id}`}${node.parent_version == null ? "" : ` (${isItemKind(parent.kind) ? "revision" : "version"} ${node.parent_version})`}`;
23456
- return [
23457
- `Node: ${node.kind} ${node.ref ?? node.id} \xB7 made by ${made} \xB7 changed by ${changed}${partOf}`
23458
- ];
23433
+ function claimText(claim, agents, read = {}) {
23434
+ const titles = agents?.titles;
23435
+ const liveness = holderLiveness(claim, agents, read);
23436
+ const holding = claimHolds(claim, titles, liveness);
23437
+ const takeableAt = claimTakeableAt(liveness);
23438
+ const unresponsive = liveness.holder_state === "unresponsive" && liveness.last_seen != null ? ` \xB7 unresponsive since ${liveness.last_seen}${takeableAt === null ? "" : `, takeable at ${takeableAt}`}` : " \xB7 unresponsive";
23439
+ const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : holding === "unresponsive" ? unresponsive : "";
23440
+ return `${actorLabel(claim.actor, titles)} since ${claim.at}${marker}`;
23459
23441
  }
23460
- function blockLines(node, ref, typed, noun = "Block") {
23461
- const unit = ref.item === undefined ? "version" : "revision";
23462
- const blockID = node.block_id ?? ref.block;
23463
- const head = ref.item === undefined ? [
23464
- `Block: ${blockID}`,
23465
- ...typed === undefined ? [] : [`Type: ${typed.type}`],
23466
- `Document: ${node.document ?? ref.document}`,
23467
- ...(typed?.attributes ?? []).map((attribute) => `${attribute.name}: ${attribute.value === "" ? "(empty)" : attribute.value}`),
23468
- ...node.changed_version === undefined ? [] : [`Changed in version: ${node.changed_version}`],
23469
- ...node.text === undefined ? [] : ["Text:", node.text]
23470
- ] : [
23471
- `${noun} ${blockID} of ${ref.item.kind} ${ref.item.id}${node.changed_version === undefined ? "" : ` (changed in revision ${node.changed_version})`}:`,
23472
- ...node.text === undefined ? [] : [node.text]
23473
- ];
23474
- const { pin } = node;
23475
- if (pin === undefined)
23476
- return head;
23477
- const state = pin.state === "unchanged" ? `Unchanged since ${unit} ${pin.version}.` : pin.state === "changed" ? `Changed since ${unit} ${pin.version}; last changed in ${unit} ${node.changed_version}.` : `Removed in ${unit} ${pin.removed_version}.`;
23478
- return [
23479
- ...head,
23480
- `Pinned to ${unit}: ${pin.version}`,
23481
- state,
23482
- `Text at ${unit} ${pin.version}:`,
23483
- pin.text
23484
- ];
23442
+ function holderLiveness(claim, agents, read) {
23443
+ if (claim.actor.kind !== "session")
23444
+ return read;
23445
+ const row = agents?.liveness.get(claim.actor.id);
23446
+ if (row === undefined)
23447
+ return read;
23448
+ const holderState = read.holder_state ?? row.holder_state;
23449
+ const lastSeen = read.last_seen ?? row.last_seen;
23450
+ const takeableAt = read.takeable_at ?? row.takeable_at;
23451
+ return {
23452
+ ...holderState === undefined ? {} : { holder_state: holderState },
23453
+ ...lastSeen === undefined ? {} : { last_seen: lastSeen },
23454
+ ...takeableAt === undefined ? {} : { takeable_at: takeableAt }
23455
+ };
23485
23456
  }
23486
- async function typedBlockOf(client, ref) {
23487
- if (ref.item !== undefined || ref.block === undefined)
23457
+ async function liveAgents(client, needed) {
23458
+ if (!needed) {
23488
23459
  return;
23460
+ }
23489
23461
  try {
23490
- const blocks = ref.owner.kind === "project" ? await client.projectArtifactBlocks(ref.owner.project, ref.id) : await client.issueArtifactBlocks(ref.owner.issue, ref.id);
23491
- return blocks.find((block) => block.id === ref.block);
23462
+ const agents = await client.listAgents();
23463
+ return {
23464
+ titles: new Map(agents.map((agent) => [agent.session_id, agent.title])),
23465
+ liveness: new Map(agents.map((agent) => [agent.session_id, agentLiveness(agent)]))
23466
+ };
23492
23467
  } catch {
23493
23468
  return;
23494
23469
  }
23495
23470
  }
23496
- function askPartNoun(ask, node, blockID) {
23497
- if (ask.answer?.id === blockID)
23498
- return "Answer";
23499
- if ((ask.options ?? []).some((option) => option.id === blockID))
23500
- return "Option";
23501
- const placed = (ask.revision ?? 0) > 0 && (ask.options ?? []).every((option) => option.id !== undefined) && (ask.answer === null || ask.answer.id !== undefined);
23502
- return placed && node.pin?.state !== "removed" ? "Question" : "Part";
23471
+ function agentLiveness(agent) {
23472
+ return {
23473
+ ...agent.state === undefined ? {} : { holder_state: agent.state },
23474
+ ...agent.last_seen > 0 ? { last_seen: new Date(agent.last_seen).toISOString() } : {}
23475
+ };
23503
23476
  }
23504
-
23505
- // ../envoy-client/src/dispatch-commands/render-item.ts
23506
- function askSummary({ ask, replies, answers }, askRef, pictures, incoming, outgoing) {
23507
- const answer = ask.answer;
23508
- const earlierAnswers = (answers ?? []).slice(0, -1);
23509
- const parts = askPartEdges(ask, incoming);
23510
- const partRef = (id) => `${askRef}#b-${encodeBlockId(id)}`;
23511
- const chain = (replies ?? []).flatMap((reply) => [
23512
- `${reply.id} \xB7 ${actorText(reply.author)}`,
23513
- `Body: ${reply.body}`
23514
- ]);
23515
- const resolutionWords = dispatchWordsText(ask.resolution?.dispatch_words);
23516
- return [
23517
- `Question: ${ask.question}`,
23518
- ...anchorLines(ask),
23519
- "Options:",
23520
- ...(ask.options ?? []).length === 0 ? ["- none"] : (ask.options ?? []).flatMap((option) => [
23521
- `- ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}${option.id === undefined ? "" : ` (${partRef(option.id)})`}`,
23522
- ...partReferenceLines(parts.at, option.id)
23523
- ]),
23524
- `State: ${ask.state}`,
23525
- `Ask id: ${ask.id}`,
23526
- "Answer:",
23527
- ...answer === null ? ["- none"] : [
23528
- `- By: ${actorActText(answer.user, answer.act)}`,
23529
- `- Selected: ${(answer.selected ?? []).length === 0 ? "none" : (answer.selected ?? []).join(", ")}`,
23530
- ...answer.text === null ? [] : [`- Text: ${answer.text}`],
23531
- ...answer.id === undefined ? [] : [`- Reference: ${partRef(answer.id)}`],
23532
- ...partReferenceLines(parts.at, answer.id)
23533
- ],
23534
- ...earlierAnswers.length === 0 ? [] : [
23535
- "Earlier answers:",
23536
- ...earlierAnswers.map((earlier) => `- ${earlier.at} \xB7 ${actorActText(earlier.user, earlier.act)} \xB7 ${askAnswerText(earlier)}`)
23537
- ],
23538
- ...ask.resolution === undefined ? [] : [
23539
- "Resolution:",
23540
- `- By: ${ask.resolution.actor.id}`,
23541
- `- Kind: ${ask.resolution.kind}`,
23542
- ...ask.resolution.reason === "" ? [] : [`- Reason: ${ask.resolution.reason}`],
23543
- ...resolutionWords === undefined ? [] : [`- ${resolutionWords}`]
23544
- ],
23545
- "Replies:",
23546
- ...chain.length === 0 ? ["- none"] : chain,
23547
- ...pictures,
23548
- ...graphSectionLines(parts.rest, outgoing)
23549
- ].join(`
23550
- `);
23477
+ function holdsSession(claim) {
23478
+ return claim?.actor.kind === "session";
23551
23479
  }
23552
- function askPartEdges(ask, incoming) {
23553
- const ids = new Set([...(ask.options ?? []).map((option) => option.id), ask.answer?.id].filter((id) => id !== undefined));
23554
- const at = new Map;
23555
- if (typeof incoming === "string" || ids.size === 0)
23556
- return { at, rest: incoming };
23557
- const rest = [];
23558
- for (const edge of incoming.edges ?? []) {
23559
- const part = edge.block?.block_id;
23560
- if (part === undefined || !ids.has(part)) {
23561
- rest.push(edge);
23562
- continue;
23563
- }
23564
- const { block: _block, ...atPart } = edge;
23565
- const held = at.get(part);
23566
- if (held === undefined)
23567
- at.set(part, [atPart]);
23568
- else
23569
- held.push(atPart);
23570
- }
23571
- return { at, rest: { node: incoming.node, edges: rest } };
23480
+ function isRouteStatus(value) {
23481
+ return ISSUE_ROUTE_STATUSES.some((status) => status === value);
23572
23482
  }
23573
- function partReferenceLines(at, id) {
23574
- const edges = id === undefined ? undefined : at.get(id);
23575
- if (edges === undefined || edges.length === 0)
23576
- return [];
23577
- return [" Referenced by:", ...edges.map((edge) => ` ${edgeLine(edge)}`)];
23483
+ function routeHeldBySession(issue) {
23484
+ return issue.route_status === "live" && issue.route?.startsWith("role:") === true;
23578
23485
  }
23579
- function openAskAge(ageSeconds) {
23580
- const seconds = Math.max(0, Math.floor(ageSeconds));
23581
- if (seconds < 60)
23582
- return `${seconds}s`;
23583
- const minutes = Math.floor(seconds / 60);
23584
- if (minutes < 60)
23585
- return `${minutes}m${seconds % 60 === 0 ? "" : ` ${seconds % 60}s`}`;
23586
- const hours = Math.floor(minutes / 60);
23587
- if (hours < 24)
23588
- return `${hours}h${minutes % 60 === 0 ? "" : ` ${minutes % 60}m`}`;
23589
- const days = Math.floor(hours / 24);
23590
- return `${days}d${hours % 24 === 0 ? "" : ` ${hours % 24}h`}`;
23486
+ function routeText(issue, titles) {
23487
+ if (issue.route === null)
23488
+ return "none";
23489
+ const holder = issue.route_holder ?? null;
23490
+ const reach = {
23491
+ live: routeHeldBySession(issue) && holder !== null ? ` (held by ${titles?.get(holder) ?? holder})` : "",
23492
+ holder_unresponsive: issue.route.startsWith("role:") ? ` (its holder${holder === null ? "" : ` ${titles?.get(holder) ?? holder}`} is unresponsive: messages wait for it)` : " (that session is unresponsive: messages wait for it)",
23493
+ no_holder: issue.route.startsWith("role:") ? " (nobody holds it right now)" : " (that session is not running right now)",
23494
+ unknown: issue.route_status_reason === "refilling" ? " (the Envoy listener's agent list is refilling, so whether it reaches anyone is unknown; try again in a moment)" : " (the Envoy listener did not answer, so whether it reaches anyone is unknown)"
23495
+ };
23496
+ const status = issue.route_status;
23497
+ return issue.route + (status != null && isRouteStatus(status) ? reach[status] : "");
23591
23498
  }
23592
- function namedPerson(person) {
23593
- return person === undefined || person === "" ? undefined : person;
23499
+ function progressText(progress, sep) {
23500
+ if (progress === undefined)
23501
+ return "";
23502
+ const parts = [];
23503
+ if (progress.tasks !== null)
23504
+ parts.push(`tasks ${progress.tasks.done}/${progress.tasks.total}`);
23505
+ if (progress.children !== null) {
23506
+ parts.push(`children ${progress.children.done}/${progress.children.total}`);
23507
+ }
23508
+ return parts.join(sep);
23594
23509
  }
23595
- function waitsOnPerson(ask) {
23596
- return namedPerson(ask.waiting_on_person);
23510
+ function repositoryLine(issue) {
23511
+ if (issue.resolved_repo === undefined) {
23512
+ return "Repository: unknown (this Dispatch server predates repository fields; upgrade it)";
23513
+ }
23514
+ if (issue.resolved_repo === null)
23515
+ return "Repository: none";
23516
+ if (issue.repo !== null && issue.repo !== undefined)
23517
+ return `Repository: ${issue.repo} (own)`;
23518
+ return `Repository: ${issue.resolved_repo} (inherited or project default)`;
23597
23519
  }
23598
- function openAskLine(ask, linkBase) {
23599
- const priority = ask.priority === null ? "" : `P${ask.priority} \xB7 `;
23600
- return `- ${openAskAge(ask.age_seconds)} \xB7 ${priority}${ownerTitle(ask.owner)} \xB7 asked of ${waitsOnPerson(ask) ?? "nobody"} \xB7 ${ask.question} \xB7 ${linkFor(ask.ref, linkBase)}`;
23520
+ function olderServerWarnings(issue) {
23521
+ const warnings = [
23522
+ ...issue.resolved_repo !== undefined ? [] : [
23523
+ `dispatch: warning: Dispatch issue is missing resolved_repo: this Dispatch server predates repository fields, so ${issue.key}'s repository is unknown; upgrade the server`
23524
+ ],
23525
+ ...issue.advances !== undefined ? [] : [
23526
+ `dispatch: warning: Dispatch issue is missing advances: this Dispatch server predates priorities, so the priorities ${issue.key} advances are unknown; upgrade the server`
23527
+ ]
23528
+ ];
23529
+ return warnings.length === 0 ? {} : { warnings };
23601
23530
  }
23602
- function formatOpenAsksSummary(response, linkBase) {
23603
- const scope = "active open asks you authored on open issues and project documents";
23604
- if (response.count === 0) {
23605
- return ["There are no unanswered asks for this session.", `Scope: ${scope}.`].join(`
23606
- `);
23531
+ function issueSummary(issue, events, references, graph, linkBase, coverage, agents) {
23532
+ const asks = issue.open_asks ?? [];
23533
+ const labels = issue.labels ?? [];
23534
+ const links = issue.external_links ?? [];
23535
+ const members = typeof references === "string" ? [] : references.members ?? [];
23536
+ const spec = issue.artifacts?.find((artifact) => artifact.primary);
23537
+ const specApproval = spec === undefined ? undefined : approvalLine(spec, typeof issue.closed_at === "string");
23538
+ if (issue.priority === undefined)
23539
+ throw new Error("Dispatch issue is missing priority");
23540
+ if (issue.assignee === undefined)
23541
+ throw new Error("Dispatch issue is missing assignee");
23542
+ if (issue.components === undefined)
23543
+ throw new Error("Dispatch issue is missing components");
23544
+ if (issue.claim === undefined)
23545
+ throw new Error("Dispatch issue is missing claim");
23546
+ if (issue.external_links === undefined) {
23547
+ throw new Error("Dispatch issue is missing external_links");
23607
23548
  }
23608
- const waitingOnHuman = (response.asks ?? []).filter((ask) => ask.waiting_on === "human");
23609
- const waitingOnAgent = (response.asks ?? []).filter((ask) => ask.waiting_on === "agent");
23610
23549
  return [
23611
- `${response.count} unanswered ${response.count === 1 ? "ask" : "asks"} you authored on active issues and project documents.`,
23612
- "",
23613
- `Waiting on human (${waitingOnHuman.length}):`,
23614
- ...waitingOnHuman.map((ask) => openAskLine(ask, linkBase)),
23615
- "",
23616
- `Waiting on agent (${waitingOnAgent.length}):`,
23617
- ...waitingOnAgent.map((ask) => openAskLine(ask, linkBase))
23550
+ `Title: ${issue.title}`,
23551
+ `Key: ${issue.key}`,
23552
+ `Link: ${linkFor(`/issues/${encodeURIComponent(issue.key)}`, linkBase)}`,
23553
+ `Status: ${issue.status}`,
23554
+ `Assignee: ${issue.assignee ?? "unassigned"}`,
23555
+ `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, agents, issue)}`,
23556
+ ...issue.priority === null ? [] : [`Priority: P${issue.priority}`],
23557
+ `Labels: ${labels.length === 0 ? "none" : labels.join(", ")}`,
23558
+ componentsLine(issue.components),
23559
+ advancesLine(issue),
23560
+ `Route: ${routeText(issue, agents?.titles)}`,
23561
+ repositoryLine(issue),
23562
+ `Progress: ${progressText(issue.progress, ", ") || "none"}`,
23563
+ ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
23564
+ ...typeof coverage === "string" ? [`Coverage: ${coverage}`] : (coverage.gaps ?? []).map((gap) => `Coverage: ${gap}`),
23565
+ "External links:",
23566
+ ...links.length === 0 ? ["- none"] : links.map((link) => `- ${link.url}${link.kind === undefined ? "" : ` (${link.kind})`}`),
23567
+ "Documents:",
23568
+ ...documentListLines(issue.artifacts ?? []),
23569
+ "Open asks:",
23570
+ ...asks.length === 0 ? ["- none"] : asks.map((ask) => `- ${ask.id}: ${ask.question}`),
23571
+ "References:",
23572
+ ...typeof references === "string" ? [`- ${references}`] : members.length === 0 ? ["- none"] : members.map(({ artifact, depth, via }) => `- ${artifact.project}/${artifact.slug} \xB7 depth ${depth} via ${via.kind} ${via.id}`),
23573
+ ...typeof references === "string" || !references.truncated ? [] : ["- more references beyond 8 hops"],
23574
+ "Events:",
23575
+ ...events.length === 0 ? ["- none"] : events.map(eventLine),
23576
+ ...graph
23618
23577
  ].join(`
23619
23578
  `);
23620
23579
  }
23621
- function commentSummary({ comment, replies }, graph) {
23622
- const root = [
23623
- `${comment.id} \xB7 ${actorText(comment.author)}`,
23624
- ...anchorLines(comment),
23625
- ...replyBlockLines(comment),
23626
- `Body: ${comment.body}`
23627
- ];
23628
- const chain = (replies ?? []).flatMap((reply) => [
23629
- `${reply.id} \xB7 ${actorText(reply.author)}`,
23630
- ...anchorLines(reply),
23631
- ...replyBlockLines(reply),
23632
- ...reply.answers != null && reply.answers !== comment.id ? [`Answers: ${reply.answers}`] : [],
23633
- `Body: ${reply.body}`
23634
- ]);
23580
+ function logSummary(issue, events) {
23635
23581
  return [
23636
- "Comment:",
23637
- ...root,
23638
- "Reply chain:",
23639
- ...chain.length === 0 ? ["- none"] : chain,
23640
- ...graph
23582
+ `Key: ${issue.key}`,
23583
+ "Events:",
23584
+ ...events.length === 0 ? ["- none"] : events.map(eventLine)
23641
23585
  ].join(`
23642
23586
  `);
23643
23587
  }
23644
- function replyBlockLines(record) {
23645
- const block = record.reply_block;
23646
- if (block === undefined || block === null)
23647
- return [];
23648
- return [
23649
- block.removed ? `Re: block ${block.block_id} (removed)` : `Re: block ${block.block_id}: ${textHead(block.text)}`
23650
- ];
23588
+ function eventHead(event) {
23589
+ switch (event.type) {
23590
+ case "ask.opened":
23591
+ case "ask.anchor_refreshed":
23592
+ case "ask.edited":
23593
+ case "ask.handed_back":
23594
+ case "ask.resolved":
23595
+ return textHead(event.payload.question);
23596
+ case "ask.answered": {
23597
+ const previousAnswer = event.payload.previous_answer;
23598
+ return `${textHead(event.payload.question)} -> ${textHead(askAnswerText(event.payload.answer))}${previousAnswer === undefined ? "" : ` (was: ${textHead(askAnswerText(previousAnswer))})`}`;
23599
+ }
23600
+ case "ask.asked_of":
23601
+ return `${textHead(event.payload.question)} -> asked of ${event.payload.asked_of ?? "the assignee of its issue"}`;
23602
+ case "comment.created":
23603
+ case "comment.answered":
23604
+ case "comment.anchor_refreshed":
23605
+ case "comment.edited":
23606
+ case "comment.resolved":
23607
+ case "comment.reopened":
23608
+ case "suggestion.accepted":
23609
+ case "suggestion.rejected":
23610
+ case "message.created":
23611
+ case "message.answered":
23612
+ return textHead(event.payload.body);
23613
+ case "artifact.version":
23614
+ return textHead(`${event.payload.name} v${event.payload.version.number}${event.payload.version.summary ? `: ${event.payload.version.summary}` : ""}`);
23615
+ case "artifact.approved":
23616
+ case "artifact.changes_requested": {
23617
+ const { name, version, kind, reason } = event.payload;
23618
+ const verb = event.type === "artifact.approved" ? "approved" : "changes requested";
23619
+ const reviewer = kind === "plan_review" ? " by plan review" : kind === "person" ? " by a person" : "";
23620
+ return textHead(`${name} v${version} ${verb}${reviewer}${reason ? `: ${reason}` : ""}`);
23621
+ }
23622
+ case "artifact.human_edited":
23623
+ return textHead(humanEditHead(event.payload));
23624
+ case "issue.created": {
23625
+ const forced = event.payload.forced;
23626
+ const head = `status ${event.payload.status}`;
23627
+ if (forced === undefined)
23628
+ return head;
23629
+ return forced.past.length === 0 ? `${head} \xB7 forced, the near-copy check did not answer` : `${head} \xB7 forced past ${forced.past.join(", ")}`;
23630
+ }
23631
+ case "issue.updated":
23632
+ case "issue.closed":
23633
+ return `status ${event.payload.status}`;
23634
+ default:
23635
+ return;
23636
+ }
23651
23637
  }
23652
- function anchorLines(record) {
23653
- return [
23654
- ...record.anchor?.quote === undefined ? [] : [`> ${record.anchor.quote}`],
23655
- ...record.anchor_block === undefined ? [] : [`Position: ${positionText(record.anchor_block)}`],
23656
- ...record.anchor_block_error === undefined ? [] : [`Position: unavailable (${record.anchor_block_error})`]
23657
- ];
23638
+ function eventRef(event) {
23639
+ const payload = event.payload;
23640
+ const id = typeof payload === "object" && payload !== null && "id" in payload ? payload.id : undefined;
23641
+ if (typeof id !== "string" || id === "" || event.issue_key === null)
23642
+ return;
23643
+ const kind = event.type.startsWith("message.") ? "message" : event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("ask.") ? "ask" : undefined;
23644
+ return kind === undefined ? undefined : `dispatch://${event.issue_key}/${kind}/${id}`;
23658
23645
  }
23659
- function positionText(block) {
23660
- const { table, path } = block;
23661
- const segments = (path ?? []).map((entry) => `${entry.type}[${entry.index}]`);
23662
- if (table === undefined || table.row === null)
23663
- return segments.join(" \u203A ");
23664
- const tableAt = (path ?? []).findIndex((entry) => entry.type === "table");
23665
- const cells = table.cells ?? [];
23666
- const label = (table.column === null ? cells : cells.slice(0, table.column)).map((cell) => cell.trim()).filter((cell) => cell !== "" && !/^\d+$/.test(cell)).join(" \xB7 ");
23667
- const row = label === "" ? `row ${table.row}` : `row ${table.row} (${label})`;
23668
- const header = table.header === null || table.header === "" ? String(table.column) : table.header;
23669
- return [
23670
- ...segments.slice(0, tableAt + 1),
23671
- table.column === null ? row : `${row}, column ${header}`
23672
- ].join(" \u203A ");
23646
+ function eventActorText(actor) {
23647
+ const title = actor.kind === "session" ? actor.origin?.session_title : undefined;
23648
+ return title === undefined || title === "" ? actorText(actor) : `${actorText(actor)} (${title})`;
23673
23649
  }
23674
- function messageSummary({ message, replies }, graph) {
23675
- const root = [
23676
- `${message.id} \xB7 ${actorText(message.author)}`,
23677
- ...replyBlockLines(message),
23678
- `Body: ${message.body}`
23679
- ];
23680
- const chain = (replies ?? []).flatMap((reply) => [
23681
- `${reply.id} \xB7 ${actorText(reply.author)}`,
23682
- ...replyBlockLines(reply),
23683
- `Body: ${reply.body}`
23684
- ]);
23650
+ function eventLine(event) {
23651
+ const head = eventHead(event);
23652
+ const ref = eventRef(event);
23653
+ return `- #${event.seq} ${event.type}${ref === undefined ? "" : ` ${ref}`} \xB7 ${eventActorText(event.actor)} \xB7 ${event.created_at}${head === undefined || head === "" ? "" : ` \xB7 ${head}`}`;
23654
+ }
23655
+ function childrenSummary(issue) {
23685
23656
  return [
23686
- "Message:",
23687
- ...root,
23688
- "Reply chain:",
23689
- ...chain.length === 0 ? ["- none"] : chain,
23690
- ...graph
23657
+ `Key: ${issue.key}`,
23658
+ "Children:",
23659
+ ...(issue.children ?? []).length === 0 ? ["- none"] : (issue.children ?? []).map((child) => `- ${child.key}: ${child.title} (${child.status})`)
23691
23660
  ].join(`
23692
23661
  `);
23693
23662
  }
23694
- async function openAnchoredThreads(client, resolved) {
23695
- const asksPromise = resolved.owner.kind === "project" ? client.getArtifactAsks(resolved.artifact.id) : Promise.resolve(resolved.issue?.open_asks ?? []);
23696
- const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "");
23697
- const commentsResultPromise = commentsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
23698
- const asks = (await asksPromise).filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id);
23699
- const commentsResult = await commentsResultPromise;
23700
- if (commentsResult.status === "rejected" && !dispatchAnswered(commentsResult.reason, 404)) {
23701
- throw commentsResult.reason;
23702
- }
23703
- const comments = commentsResult.status === "fulfilled" ? commentsResult.value : [];
23704
- const askReplies = new Map(asks.map((ask) => [ask.id, []]));
23705
- for (const comment of comments) {
23706
- if (comment.ask_id)
23707
- askReplies.get(comment.ask_id)?.push(comment);
23708
- }
23709
- const askThreads = asks.map((ask) => [
23710
- `ask ${ask.id} \xB7 ${actorText(ask.author)} \xB7 ${ask.created_at}`,
23711
- ...anchorLines(ask),
23712
- `Question: ${ask.question}`,
23713
- ...threadReplyLines(askReplies.get(ask.id) ?? [])
23714
- ].join(`
23715
- `));
23716
- const byId = new Map(comments.map((comment) => [comment.id, comment]));
23717
- const roots = comments.filter((comment) => comment.reply_to === null && !comment.ask_id && !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id);
23718
- const replies = new Map(roots.map((root) => [root.id, []]));
23719
- for (const comment of comments) {
23720
- const root = comment.reply_to === null ? undefined : threadRootId(comment, byId);
23721
- if (root !== undefined)
23722
- replies.get(root)?.push(comment);
23723
- }
23724
- const commentThreads = roots.map((root) => [
23725
- `comment ${root.id} \xB7 ${actorText(root.author)} \xB7 ${root.created_at}`,
23726
- ...anchorLines(root),
23727
- `Body: ${root.body}`,
23728
- ...threadReplyLines(replies.get(root.id) ?? [])
23729
- ].join(`
23730
- `));
23731
- return [...askThreads, ...commentThreads];
23732
- }
23733
- function threadReplyLines(replies) {
23734
- return replies.flatMap((reply) => [
23735
- `reply ${reply.id} \xB7 ${actorText(reply.author)} \xB7 ${reply.created_at}`,
23736
- `Body: ${reply.body}`
23737
- ]);
23738
- }
23739
- function threadRootId(comment, byId) {
23740
- const seen = new Set;
23741
- let current = comment;
23742
- while (current.reply_to !== null) {
23743
- if (seen.has(current.id))
23744
- return;
23745
- seen.add(current.id);
23746
- const parent = byId.get(current.reply_to);
23747
- if (parent === undefined)
23748
- return;
23749
- current = parent;
23750
- }
23751
- return current.id;
23752
- }
23753
23663
 
23754
23664
  // ../envoy-client/src/dispatch-subscribe.ts
23755
23665
  function followedAsk(details) {
@@ -23878,1893 +23788,2014 @@ async function followedAskDetails(client, ask, artifact) {
23878
23788
  return { ...await askOwnerDetails(client, ask, artifact), follows: { ask: ask.id } };
23879
23789
  }
23880
23790
 
23881
- // ../envoy-client/src/dispatch-commands/asks.ts
23882
- function askUrgency(args) {
23883
- const value = args.urgency;
23884
- return ASK_URGENCIES.find((urgency) => urgency === value);
23885
- }
23886
- var askHintLimit = 8;
23887
- function openAskChoices(asks, owner) {
23888
- if (asks.length === 0)
23889
- return `${owner} holds no open ask.`;
23890
- const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)}\u2026 ${textHead(ask.question)}`);
23891
- return `The open asks of ${owner} are: ${hints.join(", ")}.`;
23892
- }
23893
- function askIDInputProblem(asks, owner) {
23894
- return `ask ids are uuids. Write the whole id, or at least its first 8 characters. ${openAskChoices(asks, owner)}`;
23895
- }
23896
- async function movedApprovalLine(client, askID) {
23897
- const ask = (await client.getAsk(askID).catch(() => {
23898
- return;
23899
- }))?.ask;
23900
- const approval = ask?.approval;
23901
- if (ask?.kind !== "approval" || approval === undefined)
23902
- return;
23903
- const listed = approval.documents ?? [];
23904
- const documents = listed.length > 0 ? listed : [
23905
- {
23906
- name: approval.name,
23907
- requested_version: approval.requested_version,
23908
- version: approval.version
23909
- }
23910
- ];
23911
- const moved = movedApprovalDocuments(documents);
23912
- if (moved.length === 0)
23913
- return;
23914
- const firstMoved = moved[0];
23915
- if (firstMoved === undefined)
23916
- return;
23917
- const command = handBackApprovalCommand({
23918
- owner: ask.issue_key === null ? { kind: "project", key: ask.approval_artifact?.project ?? "<project>" } : { kind: "issue", key: ask.issue_key },
23919
- artifactID: approval.artifact_id,
23920
- primary: ask.approval_artifact?.primary === true,
23921
- verification: documents.length > 1 && ask.approval_artifact?.primary === true,
23922
- summaryVersion: firstMoved.requested_version
23923
- });
23924
- return "The reply did not hand the ask to the human: it is an open approval request, and " + `${movedApprovalClauses(moved)}. No reply hands a moved approval request back. Once the ` + `human has agreed to every point in it, run: ${command}`;
23925
- }
23926
- async function replyToAskCandidates(client, owner, resolved) {
23927
- if (owner.kind === "issue") {
23928
- const issue = resolved?.issue ?? await client.getIssue(owner.issue);
23929
- return { asks: issue.open_asks ?? [], owner: "this issue" };
23930
- }
23931
- if (resolved === undefined)
23932
- throw new Error("project document is missing its resolved artifact");
23933
- return {
23934
- asks: await client.getArtifactAsks(resolved.artifact.id, "open"),
23935
- owner: "this document"
23936
- };
23937
- }
23938
- async function resolveReplyToAsk(tool, client, target, resolved, id) {
23939
- const whole = normalizeUUID(id);
23940
- if (whole !== undefined)
23941
- return whole;
23942
- const { asks, owner } = await replyToAskCandidates(client, target, resolved);
23943
- if (!isIdPrefix(id)) {
23944
- throw new ToolInputError(tool, [askIDInputProblem(asks, owner)], { aboutAFlag: false });
23791
+ // ../envoy-client/src/dispatch-commands/issues.ts
23792
+ function componentsChange(input, after) {
23793
+ switch (input.mode) {
23794
+ case "explicit":
23795
+ return `components -> explicit [${(after.ids ?? []).join(", ")}]`;
23796
+ case "none":
23797
+ return `components -> none (${after.reason ?? input.reason ?? ""})`;
23798
+ case "inherit":
23799
+ return "components -> inherit";
23800
+ default:
23801
+ return `components -> ${input.mode}`;
23945
23802
  }
23946
- return resolveIdPrefix(tool, "ask", id, owner, async () => asks, {
23947
- refusal: (found, all) => found.length === 0 ? `reply_to_ask ${id} names no open ask of ${owner}. ${openAskChoices(all, owner)}` : `reply_to_ask ${id} names ${found.length} open asks of ${owner}. Write more of the id. ${openAskChoices(all, owner)}`
23948
- });
23949
23803
  }
23950
- var askIdShapeProblem = "ask ids are uuids (a prefix of at least 8 hex characters works)";
23951
- async function readAskRef(tool, id, ownerName, client, list) {
23952
- const fullID = normalizeUUID(id);
23953
- if (fullID !== undefined) {
23954
- try {
23955
- return await client.getAsk(fullID);
23956
- } catch (error) {
23957
- if (!(error instanceof DispatchServiceError) || error.status !== 404)
23958
- throw error;
23959
- const blocks = (await list()).filter((ask) => ask.block_id?.toLowerCase() === fullID);
23960
- if (blocks.length !== 1 || blocks[0] === undefined)
23961
- throw error;
23962
- return client.getAsk(blocks[0].id);
23963
- }
23964
- }
23965
- const asks = await list();
23966
- let matches = asks.filter((ask) => ask.block_id === id);
23967
- if (matches.length === 0) {
23968
- if (!isIdPrefix(id)) {
23969
- throw new ToolInputError(tool, [
23970
- `ask id ${id} must be a full uuid, a prefix of at least 8 hex characters, or the id of an :::ask block on ${ownerName}`
23971
- ]);
23972
- }
23973
- const prefix = id.toLowerCase();
23974
- matches = asks.filter((ask) => ask.id.toLowerCase().startsWith(prefix) || (ask.block_id?.toLowerCase().startsWith(prefix) ?? false));
23804
+ var architectureComponentsAction = 'Review the `dispatch` skill, "Architecture components", to attach it to the parts it changes or mark it as non-architectural with a reason.';
23805
+ var LEGION_OWNS_STATUS = "Legion's daemon moves this issue's status on an issue it runs, so leave it alone \u2014 a status written here is undone.";
23806
+ async function architectureGuidance(client, project, components) {
23807
+ if (components.mode === "none" || (components.ids ?? []).length > 0)
23808
+ return;
23809
+ try {
23810
+ if ((await client.listArchitectureSources(project)).length === 0)
23811
+ return;
23812
+ return `Project ${project} has an architecture model, but this issue is not linked to any of its current components. ${architectureComponentsAction}`;
23813
+ } catch (error) {
23814
+ return `Could not check whether project ${project} has an architecture model: ${messageFor(error)}. ${architectureComponentsAction}`;
23975
23815
  }
23976
- if (matches.length === 1 && matches[0] !== undefined)
23977
- return client.getAsk(matches[0].id);
23978
- throw new ToolInputError(tool, [
23979
- matches.length === 0 ? `ask id ${id} matches none of the asks on ${ownerName}; use the full id` : `ask id ${id} matches ${matches.length} asks on ${ownerName}; use the full id`
23980
- ]);
23981
23816
  }
23982
- async function sessionOpenAsks(client, sessionId) {
23983
- const session = sessionId?.trim();
23984
- if (!session)
23985
- throw new Error("host session id is required to read this session's open asks");
23986
- return (await client.openAsks(session)).asks ?? [];
23817
+ function isDuplicateCandidate(value) {
23818
+ if (typeof value !== "object" || value === null)
23819
+ return false;
23820
+ const candidate = value;
23821
+ return typeof candidate.key === "string" && typeof candidate.title === "string" && typeof candidate.status === "string" && typeof candidate.snippet === "string" && typeof candidate.shared_terms === "number" && typeof candidate.href === "string";
23987
23822
  }
23988
- function openAskHints(asks) {
23989
- if (asks.length === 0)
23990
- return "you have no open asks";
23991
- const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)} \u2014 ${textHead(ask.question)}`);
23992
- return `your open asks: ${hints.join("; ")}`;
23823
+ function duplicateCandidates(error) {
23824
+ if (error.candidates === undefined || !error.candidates.every(isDuplicateCandidate))
23825
+ throw error;
23826
+ return error.candidates;
23993
23827
  }
23994
- async function resolveAskArgument(tool, args, client, sessionId) {
23995
- const id = askId(args);
23996
- if (normalizeUUID(id) === undefined && !isIdPrefix(id)) {
23997
- const asks = await sessionOpenAsks(client, sessionId).catch(() => {
23998
- return;
23999
- });
24000
- throw new ToolInputError(tool, [
24001
- asks === undefined ? askIdShapeProblem : `${askIdShapeProblem}; ${openAskHints(asks)}`
24002
- ]);
24003
- }
24004
- const resolved = await resolveIdPrefix(tool, "ask", id, "this session", () => sessionOpenAsks(client, sessionId));
24005
- const reference = stringArg(args, "ask");
24006
- const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
24007
- if (ref === null)
24008
- return { id: resolved };
24009
- const read = await client.getAsk(resolved);
24010
- await refuseItemOffRef(tool, "ask", ref, reference, read.ask, async () => {
24011
- const document = await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true });
24012
- return document.artifact.id;
24013
- });
24014
- return { id: resolved, read };
23828
+ function refuseUnsavedRepository(verb, issue, repo) {
23829
+ if (repo === undefined || issue.repo !== undefined)
23830
+ return;
23831
+ const lost = repo === "" ? "the repository was not cleared" : `${repo} was not saved`;
23832
+ throw new Error(`Dispatch ${verb} ${issue.key} without its repository: this Dispatch server predates repository fields, so ${lost}; upgrade the server`);
24015
23833
  }
24016
- async function openAsksCommand(context) {
24017
- const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
24018
- const client = dispatchClient();
24019
- const project = optionalString(ownerArguments.args, "project");
24020
- if (project !== undefined) {
24021
- const response = await client.openAsksForProject(project);
24022
- return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
23834
+ function advancesRevisionToSend(issue, named) {
23835
+ if (issue.advances_revision === undefined) {
23836
+ throw new Error(`Dispatch read ${issue.key} without its advances: this Dispatch server predates priorities, so nothing was sent; upgrade the server`);
24023
23837
  }
24024
- const sessionId = input.sessionId?.trim();
24025
- if (!sessionId)
24026
- throw new Error("host session id is required for dispatch open-asks");
24027
- const response = await client.openAsks(sessionId);
24028
- return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
23838
+ return named ?? issue.advances_revision;
24029
23839
  }
24030
- async function askCommand(context) {
24031
- const {
24032
- args,
24033
- client,
24034
- actor,
24035
- input,
24036
- linkBase,
24037
- documentOwner,
24038
- resolveDocument,
24039
- writePictures,
24040
- issue
24041
- } = context;
24042
- const anchorArgs = asObject(args.anchor);
24043
- const owner = documentOwner();
24044
- const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
24045
- const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
24046
- const options = args.options;
24047
- const multiple = optionalBoolean(args, "multiple");
24048
- const urgency = askUrgency(args);
24049
- const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
24050
- const question = await writePictures(resolved, askQuestionWithRef(args));
24051
- const askInput = {
24052
- question,
24053
- ...Array.isArray(options) ? { options } : {},
24054
- ...multiple === undefined ? {} : { multiple },
24055
- ...urgency === undefined ? {} : { urgency },
24056
- ...anchored === undefined ? {} : { anchor: anchored },
24057
- actor
23840
+ async function issueCommand(context) {
23841
+ const { args, client, actor, input, linkBase } = context;
23842
+ const project = stringArg(args, "project");
23843
+ const title = stringArg(args, "title");
23844
+ const parent = optionalString(args, "parent");
23845
+ const external = optionalString(args, "external");
23846
+ const force = optionalBoolean(args, "force");
23847
+ const spec = optionalString(args, "spec");
23848
+ const priority = optionalPriority(args, "priority");
23849
+ const assignee = optionalString(args, "assignee");
23850
+ const components = optionalComponents(args, "components");
23851
+ const repo = optionalString(args, "repo");
23852
+ const labels = args.labels;
23853
+ const blockedBy = args.blocked_by;
23854
+ const advances = optionalStringArray(args, "advances");
23855
+ try {
23856
+ const created = await client.issue({
23857
+ project,
23858
+ title,
23859
+ ...parent === undefined ? {} : { parent },
23860
+ ...Array.isArray(blockedBy) ? { blocked_by: blockedBy } : {},
23861
+ ...advances === undefined ? {} : { advances },
23862
+ ...external === undefined ? {} : { external },
23863
+ ...force === undefined ? {} : { force },
23864
+ ...spec === undefined ? {} : { spec },
23865
+ ...priority === undefined ? {} : { priority },
23866
+ ...assignee === undefined ? {} : { assignee },
23867
+ ...components === undefined ? {} : { components },
23868
+ ...repo === undefined ? {} : { repo },
23869
+ ...Array.isArray(labels) ? { labels } : {},
23870
+ actor
23871
+ });
23872
+ refuseUnsavedRepository(created.created ? "created" : "already holds", created, repo);
23873
+ const adviceLines = await otherAdviceLines(async () => {
23874
+ const componentGuidance = await architectureGuidance(client, created.project, created.components);
23875
+ return [
23876
+ ...renderAdvice(input.tool, created.key, created.advice, {
23877
+ isPrimarySpec: spec !== undefined
23878
+ }),
23879
+ ...componentGuidance === undefined ? [] : [componentGuidance]
23880
+ ];
23881
+ });
23882
+ const href = linkFor(`/issues/${encodeURIComponent(created.key)}`, linkBase);
23883
+ const assigned = created.assignee === undefined ? "" : created.assignee === null ? "; unassigned" : `; assigned to ${created.assignee}`;
23884
+ const suffixes = `${assigned}${await notSubscribed(issueTopic(created.key), input.subscriptions)}`;
23885
+ return {
23886
+ text: [
23887
+ created.created ? `Created ${created.key}: ${created.title} \u2192 ${href}${suffixes}` : `Dispatch already holds ${created.key}: ${created.title} \u2192 ${href}; nothing was created${suffixes}`,
23888
+ ...created.created ? relatedCheckLines(created.advice?.suggestions, {
23889
+ project: created.project,
23890
+ text: title,
23891
+ linkBase
23892
+ }) : [],
23893
+ ...adviceLines
23894
+ ].join(`
23895
+ `),
23896
+ details: {
23897
+ issue: created.key,
23898
+ ...created.advice === undefined ? {} : { advice: created.advice }
23899
+ }
23900
+ };
23901
+ } catch (error) {
23902
+ if (!(error instanceof DispatchServiceError) || error.code !== "POSSIBLE_DUPLICATE") {
23903
+ throw error;
23904
+ }
23905
+ const candidates = duplicateCandidates(error);
23906
+ return {
23907
+ text: [
23908
+ `Not created: "${title}" is a near copy of an open issue.`,
23909
+ ...candidates.map((candidate) => {
23910
+ const href = linkFor(candidate.href, linkBase);
23911
+ return `${candidate.key} [${candidate.status}] ${candidate.title} \u2192 ${href}`;
23912
+ }),
23913
+ "Read each issue above. If one is the same work, fold this into it by the duplicate rule of skill://dispatch-first.",
23914
+ "If none is, run dispatch issue again with --force, and write in the new issue's spec why it is not each issue named here."
23915
+ ].join(`
23916
+ `),
23917
+ details: { duplicates: candidates },
23918
+ refused: true
23919
+ };
23920
+ }
23921
+ }
23922
+ async function issueUpdateCommand(context) {
23923
+ const { args, client, actor, input, issue } = context;
23924
+ const issueKey = issue();
23925
+ const status = optionalString(args, "status");
23926
+ const reason = optionalString(args, "reason");
23927
+ const title = optionalString(args, "title");
23928
+ const route = optionalString(args, "route");
23929
+ const parent = optionalString(args, "parent");
23930
+ const components = optionalComponents(args, "components");
23931
+ const repo = optionalString(args, "repo");
23932
+ const rankBefore = optionalString(args, "before");
23933
+ const rankAfter = optionalString(args, "after");
23934
+ const priority = optionalPriority(args, "priority");
23935
+ const assignee = optionalNullableString(args, "assignee");
23936
+ const labels = Array.isArray(args.labels) ? args.labels : undefined;
23937
+ const blockedBy = Array.isArray(args.blocked_by) ? args.blocked_by : undefined;
23938
+ const advances = optionalStringArray(args, "advances");
23939
+ const advancesRevision = optionalNumber(args, "advances_revision");
23940
+ const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
23941
+ let before;
23942
+ try {
23943
+ before = await client.getIssue(issueKey);
23944
+ } catch (error) {
23945
+ throw refusalWithCode(error);
23946
+ }
23947
+ const advancesWrite = advances === undefined ? undefined : { advances, advances_revision: advancesRevisionToSend(before, advancesRevision) };
23948
+ if (status === "done" && typeof before.closed_at === "string") {
23949
+ throw refusalWithCode(new DispatchServiceError("ISSUE_CLOSED", 409, "issue is closed"), `${issueKey} closed at ${before.closed_at}, so the reason was not posted and the close was not sent`);
23950
+ }
23951
+ let closingNote;
23952
+ if (reason !== undefined) {
23953
+ try {
23954
+ const message = await client.message(issueKey, { body: reason, actor });
23955
+ closingNote = {
23956
+ id: message.id,
23957
+ ref: dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id)
23958
+ };
23959
+ } catch (error) {
23960
+ if (error instanceof DispatchWriteLandedError) {
23961
+ throw new Error(`${error.message} That was the closing reason, so the close was not sent: read the issue's messages for it, then close with a reason that points at it, since retrying this call posts its reason again.`, { cause: error });
23962
+ }
23963
+ const told = writeMayHaveLanded(error) ? "the reason may or may not have been posted, and the close was not sent: read the issue's messages before retrying, since retrying this call posts its reason again" : "the reason was not posted, so the close was not sent";
23964
+ if (error instanceof DispatchServiceError)
23965
+ throw refusalWithCode(error, told);
23966
+ throw withAccount(error, told);
23967
+ }
23968
+ }
23969
+ const existingLinks = before.external_links ?? [];
23970
+ const linked = existingLinks.map((link) => link.url);
23971
+ const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
23972
+ const sentLinks = requestedLinks === undefined ? undefined : requestedLinks.length === 0 ? [] : [...existingLinks, ...newLinks.map((url) => ({ url }))];
23973
+ const rank = rankBefore === undefined && rankAfter === undefined ? undefined : {
23974
+ ...rankBefore === undefined ? {} : { before: rankBefore },
23975
+ ...rankAfter === undefined ? {} : { after: rankAfter }
24058
23976
  };
24059
- const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
24060
- const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
24061
- const checkLines = relatedCheckLines(ask.advice?.suggestions, {
24062
- project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
24063
- text: stringArg(args, "question"),
24064
- linkBase
23977
+ let after;
23978
+ try {
23979
+ after = await client.updateIssue(issueKey, {
23980
+ ...status === undefined ? {} : { status },
23981
+ ...title === undefined ? {} : { title },
23982
+ ...labels === undefined ? {} : { labels },
23983
+ ...priority === undefined ? {} : { priority },
23984
+ ...assignee === undefined ? {} : { assignee },
23985
+ ...route === undefined ? {} : { route },
23986
+ ...parent === undefined ? {} : { parent: parent === "" ? null : parent },
23987
+ ...blockedBy === undefined ? {} : { blocked_by: blockedBy },
23988
+ ...advancesWrite,
23989
+ ...components === undefined ? {} : { components },
23990
+ ...repo === undefined ? {} : { repo: repo === "" ? null : repo },
23991
+ ...sentLinks === undefined ? {} : { external_links: sentLinks },
23992
+ ...rank === undefined ? {} : { rank },
23993
+ actor
23994
+ });
23995
+ } catch (error) {
23996
+ if (error instanceof DispatchWriteLandedError)
23997
+ throw error;
23998
+ const answered = error instanceof DispatchWriteUnsettledError ? error.last : error;
23999
+ const taken = dispatchAnswered(answered, 500) && newLinks.length > 0 ? `one of ${newLinks.join(", ")} may already be linked from another issue (a URL links exactly one issue)` : "";
24000
+ if (closingNote === undefined) {
24001
+ if (taken !== "" && !(error instanceof DispatchServiceError)) {
24002
+ throw withAccount(error, taken);
24003
+ }
24004
+ throw refusalWithCode(error, taken);
24005
+ }
24006
+ const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
24007
+ const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
24008
+ const landed = writeMayHaveLanded(error) ? `${posted}, and the close may or may not have taken effect. Read the issue's status before retrying: done means it closed; otherwise retry with a reason that points at message ${closingNote.id}, since retrying this call posts its reason again` : `${posted} but the issue did not close. Retrying this call posts its reason again, so ${fix}retry with a reason that points at message ${closingNote.id}`;
24009
+ if (error instanceof DispatchServiceError)
24010
+ throw refusalWithCode(error, taken, landed);
24011
+ throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
24012
+ }
24013
+ refuseUnsavedRepository("updated", after, repo);
24014
+ const links = after.external_links ?? [];
24015
+ const linkCount = `(${links.length} ${links.length === 1 ? "link" : "links"})`;
24016
+ const stated = (after.advances ?? []).filter((advance) => !advance.inherited).map((advance) => advance.id);
24017
+ const changes = [
24018
+ ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
24019
+ ...status === undefined ? [] : [`status ${before.status} -> ${after.status}`],
24020
+ ...title === undefined ? [] : [`title "${after.title}"`],
24021
+ ...labels === undefined ? [] : [
24022
+ (after.labels ?? []).length === 0 ? "labels cleared" : `labels ${(after.labels ?? []).join(", ")}`
24023
+ ],
24024
+ ...priority === undefined ? [] : [after.priority === null ? "priority cleared" : `priority -> P${after.priority}`],
24025
+ ...assignee === undefined ? [] : [after.assignee === null ? "assignee cleared" : `assignee -> ${after.assignee}`],
24026
+ ...rank === undefined ? [] : [
24027
+ `rank -> ${[
24028
+ ...rankAfter === undefined ? [] : [`after ${rankAfter}`],
24029
+ ...rankBefore === undefined ? [] : [`before ${rankBefore}`]
24030
+ ].join(", ")}`
24031
+ ],
24032
+ ...requestedLinks === undefined ? [] : [
24033
+ requestedLinks.length === 0 ? "external links cleared" : newLinks.length === 0 ? `already linked ${requestedLinks.join(", ")} ${linkCount}` : `linked ${newLinks.join(", ")} ${linkCount}`
24034
+ ],
24035
+ ...route === undefined ? [] : [after.route === null ? "route cleared" : `route ${after.route}`],
24036
+ ...parent === undefined ? [] : [after.parent === null ? "parent cleared" : `parent -> ${after.parent}`],
24037
+ ...blockedBy === undefined ? [] : [
24038
+ (after.blocked_by ?? []).length === 0 ? "blocked_by cleared" : `blocked by ${(after.blocked_by ?? []).join(", ")}`
24039
+ ],
24040
+ ...advances === undefined ? [] : [stated.length === 0 ? "advances cleared" : `advances ${stated.join(", ")}`],
24041
+ ...components === undefined ? [] : [componentsChange(components, after.components)],
24042
+ ...repo === undefined ? [] : [
24043
+ after.repo === null ? `repo cleared (resolves to ${after.resolved_repo ?? "none"})` : `repo -> ${after.repo}`
24044
+ ]
24045
+ ];
24046
+ const adviceLines = renderAdvice(input.tool, after.key, after.advice, {
24047
+ setsStatus: status !== undefined
24065
24048
  });
24066
- const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
24067
- const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
24068
- const asked = waitsOnPerson(ask);
24069
24049
  return {
24070
24050
  text: [
24071
- `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
24072
- ...checkLines,
24073
- ...declinedLines,
24074
- await followsAsk(askOwner, input.subscriptions),
24051
+ `${after.key}: ${changes.join("; ")}${await notSubscribed(issueTopic(after.key), input.subscriptions)}`,
24075
24052
  ...adviceLines
24076
24053
  ].join(`
24077
24054
  `),
24078
24055
  details: {
24079
- ...await followedAskDetails(client, ask, resolved?.artifact),
24080
- ...ask.advice === undefined ? {} : { advice: ask.advice }
24056
+ issue: after.key,
24057
+ status: after.status,
24058
+ external_links: (after.external_links ?? []).map((link) => link.url),
24059
+ ...closingNote === undefined ? {} : { message: closingNote.id },
24060
+ ...after.advice === undefined ? {} : { advice: after.advice }
24081
24061
  }
24082
24062
  };
24083
24063
  }
24084
- async function editAskCommand(context) {
24085
- const { args, client, actor, input } = context;
24086
- const question = optionalString(args, "question");
24087
- const options = args.options;
24088
- const multiple = optionalBoolean(args, "multiple");
24089
- const urgency = askUrgency(args);
24090
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
24091
- const ask = await client.editAsk(id, {
24092
- ...question === undefined ? {} : { question },
24093
- ...Array.isArray(options) ? { options } : {},
24094
- ...multiple === undefined ? {} : { multiple },
24095
- ...urgency === undefined ? {} : { urgency },
24096
- actor
24097
- });
24098
- return {
24099
- text: `Ask edited: ${ask.question}`,
24100
- details: await askOwnerDetails(client, ask)
24101
- };
24102
- }
24103
- async function resolveAskCommand(context) {
24104
- const { args, client, actor, input } = context;
24105
- const kind = stringArg(args, "kind");
24106
- const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
24107
- const ask = await client.resolveAsk(id, {
24108
- kind,
24109
- reason: stringArg(args, "reason"),
24110
- actor
24111
- });
24112
- if (ask.resolution === undefined)
24113
- throw new Error("resolved ask is missing its resolution");
24114
- return {
24115
- text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
24116
- details: await askOwnerDetails(client, ask)
24117
- };
24118
- }
24119
- async function followCommand(context) {
24120
- const { args, client, actor, input } = context;
24121
- const sessionId = input.sessionId?.trim();
24122
- if (!sessionId)
24123
- throw new Error("host session id is required for dispatch follow");
24124
- const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
24125
- const action = stringArg(args, "action");
24126
- if (action === "unfollow") {
24127
- await client.unfollowAsk(ask, sessionId, actor);
24128
- return { text: `Unfollowed ask ${ask}.`, details: { ask } };
24064
+ async function claimCommand(context) {
24065
+ const { args, client, actor, input, issue } = context;
24066
+ const issueKey = issue();
24067
+ const release = optionalBoolean(args, "release") ?? false;
24068
+ let after;
24069
+ try {
24070
+ after = release ? await client.releaseIssueClaim(issueKey, { actor }) : await client.claimIssue(issueKey, { actor });
24071
+ } catch (error) {
24072
+ throw refusalWithCode(error);
24073
+ }
24074
+ const held = after.claim;
24075
+ const legionManaged = after.legion_managed_status === true;
24076
+ let text;
24077
+ if (release) {
24078
+ const released = `${issueKey}: claim released; nobody is working it now. Its status is still ${after.status}`;
24079
+ text = legionManaged ? `${released}; ${LEGION_OWNS_STATUS}` : `${released} \u2014 move it yourself if that is no longer where the work is.`;
24080
+ } else {
24081
+ if (held === null) {
24082
+ throw new Error(`Dispatch claimed ${issueKey} but answered with no claim`);
24083
+ }
24084
+ const claimed = `${issueKey}: claimed by you since ${held.at}. Its status is ${after.status}`;
24085
+ const reaches = `A person's answers, comments and messages on ${issueKey} now reach you directly.`;
24086
+ text = legionManaged ? `${claimed}; ${LEGION_OWNS_STATUS} Release the claim when you stop. ${reaches}` : `${claimed}; a claim moves nothing, so move it to in_progress with dispatch issue-update when you start, and release the claim when you stop. ${reaches}`;
24129
24087
  }
24130
- const read = refRead ?? await client.getAsk(ask);
24131
- await client.followAsk(ask, sessionId, actor);
24132
24088
  return {
24133
- text: `Following ask ${ask}: its answer and replies reach this session directly.`,
24134
- details: await followedAskDetails(client, read.ask)
24089
+ text: `${text}${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
24090
+ details: { issue: issueKey, status: after.status, claim: held }
24135
24091
  };
24136
24092
  }
24137
-
24138
- // ../envoy-client/src/dispatch-commands/conversation.ts
24139
- async function resolveCommentCommand(context) {
24140
- const { args, client, actor, input } = context;
24141
- const reference = stringArg(args, "comment");
24142
- const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
24143
- let id = reference;
24144
- let document;
24145
- if (ref?.owner.kind === "issue") {
24146
- const issueKey = ref.owner.issue;
24147
- id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
24148
- } else if (ref !== null) {
24149
- const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
24150
- document = artifact;
24151
- id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
24152
- }
24153
- if (ref !== null) {
24154
- const read = await client.getComment(id);
24155
- await refuseItemOffRef(input.tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
24156
- }
24157
- const comment = await client.resolveComment(id, actor);
24158
- const { label, details } = await commentOwnerResult(client, comment, document);
24159
- return { text: `Resolved comment ${comment.id} on ${label}.`, details };
24093
+ async function searchCommand(context) {
24094
+ const { args, client, linkBase } = context;
24095
+ const query = stringArg(args, "query");
24096
+ const project = optionalString(args, "project");
24097
+ const limit = optionalNumber(args, "limit");
24098
+ const offset = optionalNumber(args, "offset");
24099
+ const search = await client.search(query, {
24100
+ ...project === undefined ? {} : { project },
24101
+ ...limit === undefined ? {} : { limit },
24102
+ ...offset === undefined ? {} : { offset }
24103
+ });
24104
+ return searchAnswer(search, query, offset, linkBase);
24160
24105
  }
24161
- async function commentCommand(context) {
24162
- const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
24163
- const artifactReference = optionalString(args, "artifact");
24164
- const owner = documentOwner();
24165
- const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
24166
- const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
24167
- const replyTo = itemReplyTo(args, "reply_to");
24168
- const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
24169
- const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
24170
- const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
24171
- const requestedTurn = optionalString(args, "turn");
24172
- const body = await writePictures(resolved, stringArg(args, "body"));
24173
- const commentInput = {
24174
- body,
24175
- ...anchored === undefined ? {} : { anchor: anchored },
24176
- ...replyTo === undefined ? {} : { reply_to: replyTo.id },
24177
- ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
24178
- ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
24179
- ...requestedTurn === undefined ? {} : { turn: requestedTurn },
24180
- actor
24181
- };
24182
- const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
24183
- const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
24184
- const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
24185
- const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
24186
- isAskReply: replyToAsk !== undefined,
24187
- replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
24106
+ async function relatedCommand(context) {
24107
+ const { args, client, linkBase } = context;
24108
+ const project = stringArg(args, "project");
24109
+ const title = optionalString(args, "title");
24110
+ const text = optionalString(args, "text");
24111
+ const excludeIssues = optionalStringArray(args, "exclude_issues");
24112
+ const keywordsOnly = optionalBoolean(args, "keywords_only");
24113
+ const suggestions = await client.related(project, {
24114
+ ...title === undefined ? {} : { title },
24115
+ ...text === undefined ? {} : { text },
24116
+ ...excludeIssues === undefined ? {} : { exclude_issues: excludeIssues },
24117
+ ...keywordsOnly === undefined ? {} : { keywords_only: keywordsOnly }
24188
24118
  });
24189
- if (replyToAsk !== undefined) {
24190
- const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
24191
- const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
24192
- return {
24193
- text: [
24194
- `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
24195
- ...moved === undefined ? [] : [moved],
24196
- ...adviceLines
24197
- ].join(`
24198
- `),
24199
- details: {
24200
- ...commentDetails,
24201
- ask: replyToAsk,
24202
- follows: { ask: replyToAsk },
24203
- ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
24204
- ...comment.advice === undefined ? {} : { advice: comment.advice }
24205
- }
24206
- };
24207
- }
24208
24119
  return {
24209
- text: [
24210
- `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
24211
- ...adviceLines
24212
- ].join(`
24120
+ text: relatedCheckLines(suggestions, {
24121
+ project,
24122
+ text: [title, text].filter((part) => part !== undefined).join(`
24213
24123
  `),
24214
- details: {
24215
- ...commentDetails,
24216
- ...comment.advice === undefined ? {} : { advice: comment.advice }
24217
- }
24124
+ linkBase
24125
+ }).join(`
24126
+ `),
24127
+ details: { project, suggestions }
24218
24128
  };
24219
24129
  }
24220
- async function suggestCommand(context) {
24221
- const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
24222
- const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
24223
- const anchored = anchor(resolved.artifact, args);
24224
- if (anchored === undefined)
24225
- throw new Error("quote is required");
24226
- const body = optionalString(args, "body");
24227
- const suggestionInput = {
24228
- ...body === undefined ? {} : { body },
24229
- anchor: anchored,
24230
- replace_with: stringArg(args, "replace_with"),
24231
- actor
24130
+ async function issuesCommand(context) {
24131
+ const { args, client } = context;
24132
+ const project = stringArg(args, "project");
24133
+ const status = optionalString(args, "status");
24134
+ const parent = optionalString(args, "parent");
24135
+ const label = optionalString(args, "label");
24136
+ const priority = optionalPriorityFilter(args, "priority");
24137
+ const updatedSince = optionalString(args, "updated_since");
24138
+ const routeStatus = optionalString(args, "route_status");
24139
+ const filters = {
24140
+ project,
24141
+ ...status === undefined ? {} : { status },
24142
+ ...parent === undefined ? {} : { parent },
24143
+ ...label === undefined ? {} : { label },
24144
+ ...priority === undefined ? {} : { priority },
24145
+ ...updatedSince === undefined ? {} : { updated_since: updatedSince },
24146
+ ...routeStatus === undefined ? {} : { route_status: routeStatus }
24232
24147
  };
24233
- const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
24148
+ const page = optionalBoolean(args, "all") === true ? await client.listAllIssues(filters).then((issues) => ({
24149
+ issues,
24150
+ total: issues.length,
24151
+ limit: issues.length,
24152
+ offset: 0
24153
+ })) : await client.listIssuePage(filters, {
24154
+ limit: optionalNumber(args, "limit") ?? DEFAULT_ISSUE_PAGE_LIMIT,
24155
+ offset: optionalNumber(args, "offset") ?? 0
24156
+ });
24157
+ const { total, limit, offset } = page;
24158
+ const rows = (page.issues ?? []).map((row) => ({
24159
+ key: row.key,
24160
+ title: row.title,
24161
+ status: row.status,
24162
+ priority: row.priority,
24163
+ parent: row.parent,
24164
+ labels: row.labels ?? [],
24165
+ open_asks: row.open_asks,
24166
+ claim: row.claim ?? null,
24167
+ route: row.route ?? null,
24168
+ route_status: row.route_status ?? null,
24169
+ route_holder: row.route_holder ?? null,
24170
+ route_status_reason: row.route_status_reason ?? null,
24171
+ updated_at: row.updated_at,
24172
+ progress: row.progress
24173
+ }));
24174
+ const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
24175
+ const isPartial = offset !== 0 || rows.length !== total;
24176
+ const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
24234
24177
  return {
24235
- text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
24236
- details: writeResultDetails(resolved, { comment: comment.id })
24178
+ text: rows.length === 0 ? `No issues in ${project}.${isPartial ? ` (${showing})` : ""}` : [
24179
+ `${rows.length} ${rows.length === 1 ? "issue" : "issues"} in ${project}` + (isPartial ? ` (${showing})` : ""),
24180
+ ...rows.map((row) => {
24181
+ const progress = progressText(row.progress, " \xB7 ");
24182
+ return `${row.key} [${row.status}]${row.priority === null ? "" : ` P${row.priority}`} ${row.title}` + (row.open_asks === 0 ? "" : ` \xB7 ${row.open_asks} open ${row.open_asks === 1 ? "ask" : "asks"}`) + (row.claim === null ? "" : ` \xB7 claimed by ${claimText(row.claim, agents)}`) + (progress === "" ? "" : ` \xB7 ${progress}`) + (row.route === null || row.route_status === "live" || row.route_status === null ? "" : ` \xB7 route ${routeText(row)}`);
24183
+ })
24184
+ ].join(`
24185
+ `),
24186
+ details: { issues: rows, total, offset, limit }
24237
24187
  };
24238
24188
  }
24239
- function conversationReadBack(messageId) {
24240
- return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
24189
+ var BRIEF_READING_CHARACTERS = 200;
24190
+ var COMPARISON_REASONS = {
24191
+ no_pull_request_or_branch: "the issue has no pull request and no branch to compare with",
24192
+ repository_unreadable: "Dispatch cannot read the repository",
24193
+ read_failed: "a read Dispatch made did not answer"
24194
+ };
24195
+ function learnedText(learned) {
24196
+ if (learned.kind === "read_at")
24197
+ return `Dispatch read it ${learned.at}`;
24198
+ return `GitHub updated it ${learned.at}`;
24241
24199
  }
24242
- async function messageCommand(context) {
24243
- const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
24244
- const target = messageInReplyTo(args);
24245
- const inReplyTo = target?.id;
24246
- const written = stringArg(args, "body");
24247
- if (owner === null && inReplyTo !== undefined) {
24248
- let body = written;
24249
- if (pictures.length > 0) {
24250
- const sessionId = input.sessionId?.trim();
24251
- if (!sessionId) {
24252
- throw new Error("host session id is required to send pictures in a direct-message reply");
24253
- }
24254
- body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
24255
- }
24256
- const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
24257
- if (reply.duplicate === true && reply.body === body) {
24258
- return {
24259
- text: `Dispatch already has this exact text in the conversation (message ${reply.id}); ` + "nothing new was posted. Send different text if you have more to say.",
24260
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
24261
- };
24262
- }
24263
- if (reply.body !== body) {
24264
- return {
24265
- text: `Message ${inReplyTo} was already answered by message ${reply.id}; Dispatch kept ` + "that reply and posted nothing. Wait for their next message rather than answering " + "this one again.",
24266
- details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
24267
- };
24268
- }
24269
- const readBack = conversationReadBack(inReplyTo);
24270
- const parent = reply.in_reply_to ?? undefined;
24271
- const follows = parent === inReplyTo ? undefined : parent;
24200
+ function basisText(basis) {
24201
+ const learned = basis.learned_at === undefined ? "" : ` (${learnedText(basis.learned_at)})`;
24202
+ if (basis.kind === "pull_request") {
24203
+ const number = basis.pull_request === undefined ? "" : `#${basis.pull_request} `;
24204
+ return `the head of pull request ${number}at ${basis.commit ?? "an unnamed commit"}${learned}`;
24205
+ }
24206
+ if (basis.kind === "branch")
24207
+ return `branch ${basis.branch ?? "unnamed"}${learned}`;
24208
+ return `the commit you named, ${basis.commit ?? ""}${learned}`;
24209
+ }
24210
+ function basisPlace(basis) {
24211
+ if (basis.kind === "pull_request") {
24212
+ return basis.pull_request === undefined ? "the head of a pull request" : `the head of pull request #${basis.pull_request}`;
24213
+ }
24214
+ if (basis.kind === "branch")
24215
+ return `on branch ${basis.branch ?? "unnamed"}`;
24216
+ return "the commit you named";
24217
+ }
24218
+ function commitStandsText(stands) {
24219
+ if (stands === undefined) {
24220
+ return "Where that commit stands is not known: this Dispatch server does not say";
24221
+ }
24222
+ if (stands.answer === "at_basis") {
24223
+ return stands.basis === undefined ? "That commit is one of the compared commits" : `That commit is ${basisPlace(stands.basis)}`;
24224
+ }
24225
+ if (stands.answer === "other_commit")
24226
+ return "That commit is none of the compared commits";
24227
+ return stands.reason === undefined ? "Where that commit stands is not known" : `Where that commit stands is not known: ${COMPARISON_REASONS[stands.reason]}`;
24228
+ }
24229
+ function checkWordsText(check, result) {
24230
+ const versions = `result version ${result.check_version}, check version ${check.version}`;
24231
+ if (result.check_words_moved === undefined) {
24232
+ return `Whether the check's words moved is not known (${versions})`;
24233
+ }
24234
+ return result.check_words_moved ? `The check's words moved after this result (${versions})` : `The check's words did not move after this result (${versions})`;
24235
+ }
24236
+ function passStandsText(pass) {
24237
+ if (pass === undefined)
24238
+ return "Whether a pass stands is not known: this Dispatch server does not say";
24239
+ if (pass.answer === "yes") {
24240
+ const roles = pass.roles ?? [];
24241
+ return roles.length === 0 ? "A pass stands: yes" : `A pass stands: yes, from ${roles.join(", ")}`;
24242
+ }
24243
+ if (pass.answer === "no")
24244
+ return "A pass stands: no";
24245
+ return "A pass stands: not known";
24246
+ }
24247
+ function readingLines(result, brief, indent = " ") {
24248
+ const observed = result.observed;
24249
+ if (observed === "")
24250
+ return [`${indent}The role recorded no reading.`];
24251
+ const cut = brief && result.commit_stands?.answer !== "at_basis";
24252
+ if (cut && observed.length > BRIEF_READING_CHARACTERS) {
24253
+ return [
24254
+ `${indent}Reading: ${observed.slice(0, BRIEF_READING_CHARACTERS)}\u2026 (result ${result.id})`
24255
+ ];
24256
+ }
24257
+ return [`${indent}Reading: ${observed}`];
24258
+ }
24259
+ function resultLines(check, result, brief) {
24260
+ const lines = [
24261
+ ` - ${result.verdict} by ${result.role} at ${result.commit_sha}. ${commitStandsText(result.commit_stands)}. ${checkWordsText(check, result)}. Recorded ${result.created_at}. Result ${result.id}.`
24262
+ ];
24263
+ const retracted = result.retracted;
24264
+ if (retracted !== undefined) {
24265
+ lines.push(` Retracted by ${actorText(retracted.actor)} at ${retracted.created_at}. The reason: ${retracted.reason}`);
24266
+ }
24267
+ return [...lines, ...readingLines(result, brief)];
24268
+ }
24269
+ function ciCheckLines(check, ci, brief) {
24270
+ const passStandsLine = ` ${passStandsText(check.pass_stands)}.`;
24271
+ const pullRequestLine = ` Pull request line: ${ci.line}`;
24272
+ const derived = check.results?.[0];
24273
+ if (derived === undefined) {
24274
+ return [
24275
+ `- ${check.block_id} (${check.when}): no result: ${ci.detail} ${check.text}`,
24276
+ passStandsLine,
24277
+ pullRequestLine
24278
+ ];
24279
+ }
24280
+ const stands = commitStandsText(derived.commit_stands);
24281
+ return [
24282
+ `- ${check.block_id} (${check.when}): ${derived.verdict} at ${derived.commit_sha} by ${derived.role} (CI run ${ci.run}, ${ci.case}), ${stands.charAt(0).toLowerCase()}${stands.slice(1)}. ${check.text}`,
24283
+ passStandsLine,
24284
+ pullRequestLine,
24285
+ ...readingLines(derived, brief, " ")
24286
+ ];
24287
+ }
24288
+ function checkLines(check, brief) {
24289
+ if (check.ci !== undefined)
24290
+ return ciCheckLines(check, check.ci, brief);
24291
+ const bases = check.compared_with ?? [];
24292
+ const reason = check.compared_nothing;
24293
+ const compared = bases.length > 0 ? `Compared with ${bases.map(basisText).join(", ")}` : reason === undefined ? "Compared with nothing, and this Dispatch server does not say why" : `Compared with nothing: ${COMPARISON_REASONS[reason]}`;
24294
+ const results = check.results ?? [];
24295
+ return [
24296
+ `- ${check.block_id} (${check.when}). ${compared}. ${passStandsText(check.pass_stands)}.`,
24297
+ ` The check's words: ${check.text}`,
24298
+ ...results.length === 0 ? [" No result is recorded for this check."] : results.flatMap((result) => resultLines(check, result, brief))
24299
+ ];
24300
+ }
24301
+ function formatCheckResults(results, brief = false) {
24302
+ if (results.verification_artifact_id === "") {
24303
+ return `${results.issue} has no Verification document, so it has no checks. Write one (verification.md) with a check block per thing that must be proved.`;
24304
+ }
24305
+ const checks = results.checks ?? [];
24306
+ if (checks.length === 0) {
24307
+ return `${results.issue}'s Verification document holds no check blocks.`;
24308
+ }
24309
+ const blocks = checks.map((check) => checkLines(check, brief).join(`
24310
+ `));
24311
+ return [`Checks of ${results.issue}:`, ...blocks].join(`
24312
+
24313
+ `);
24314
+ }
24315
+ function dryRunAsksDispatch(tool, args) {
24316
+ return tool === "dispatch_result" && args["retract"] === undefined;
24317
+ }
24318
+ async function resultCommand(context) {
24319
+ const { args, client, actor } = context;
24320
+ const retract = optionalString(args, "retract");
24321
+ if (retract !== undefined) {
24322
+ const retraction = await client.retractResult(retract, {
24323
+ actor,
24324
+ reason: stringArg(args, "reason")
24325
+ });
24272
24326
  return {
24273
- text: follows === undefined ? `Replied to message ${inReplyTo} with message ${reply.id}. ${readBack}` : `Replied to message ${inReplyTo} with message ${reply.id}, a follow-up threaded ` + `under your reply ${follows}. ${readBack}`,
24327
+ text: `Retracted result ${retraction.result_id}. ${actorText(retraction.actor)} retracted it at ${retraction.created_at}. The reason: ${retraction.reason}
24328
+
24329
+ The result stays readable, and it proves nothing from now on. Record a new result where the check still needs one.`,
24274
24330
  details: {
24275
- message: reply.id,
24276
- in_reply_to: inReplyTo,
24277
- posted: true,
24278
- ...follows === undefined ? {} : { follows }
24331
+ result: retraction.result_id,
24332
+ reason: retraction.reason,
24333
+ created_at: retraction.created_at
24279
24334
  }
24280
24335
  };
24281
24336
  }
24282
- const issueKey = issue();
24283
- const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
24284
- const message = await client.message(issueKey, {
24285
- body,
24286
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
24287
- ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
24288
- actor
24289
- });
24290
- const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
24291
- const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
24337
+ const issue = stringArg(args, "issue");
24338
+ const optional = {
24339
+ ...defined("surface", optionalString(args, "surface")),
24340
+ ...defined("run", optionalString(args, "run")),
24341
+ ...defined("observed", optionalString(args, "observed")),
24342
+ ...defined("negative_control", optionalString(args, "negative_control")),
24343
+ ...defined("failed", optionalNumber(args, "failed")),
24344
+ ...defined("skipped", optionalNumber(args, "skipped")),
24345
+ ...defined("excluded", optionalNumber(args, "excluded")),
24346
+ ...defined("screenshots", optionalStringArray(args, "screenshots"))
24347
+ };
24348
+ const input = {
24349
+ actor,
24350
+ check: stringArg(args, "check"),
24351
+ role: stringArg(args, "role"),
24352
+ verdict: stringArg(args, "verdict"),
24353
+ commit: stringArg(args, "commit"),
24354
+ ...optional
24355
+ };
24356
+ if (context.input.dryRun === true) {
24357
+ const dry = await client.dryRunResult(issue, input);
24358
+ return {
24359
+ text: `Nothing was recorded: this is a dry run.
24360
+
24361
+ Pull request body line:
24362
+ ${dry.line}`,
24363
+ details: { issue, check: input.check, verdict: input.verdict, line: dry.line }
24364
+ };
24365
+ }
24366
+ let recorded;
24367
+ try {
24368
+ recorded = await client.recordResult(issue, input);
24369
+ } catch (error) {
24370
+ if (dispatchAnswered(error, 409) && error.code === "CHECK_CONTENDED") {
24371
+ throw refusalWithCode(error, "the check moved twice while this result was being written, and nothing was recorded: run the same dispatch result command again");
24372
+ }
24373
+ throw error;
24374
+ }
24292
24375
  return {
24293
- text: [
24294
- `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
24295
- ...adviceLines
24296
- ].join(`
24297
- `),
24376
+ text: `Recorded ${recorded.result.verdict} for check ${recorded.result.check_block_id} of ${recorded.result.check_issue_key} at ${recorded.result.commit_sha}, as ${recorded.result.role}.
24377
+
24378
+ Pull request body line:
24379
+ ${recorded.line}`,
24298
24380
  details: {
24299
- issue: issueKey,
24300
- message: message.id,
24301
- ...message.advice === undefined ? {} : { advice: message.advice }
24381
+ issue,
24382
+ result: recorded.result.id,
24383
+ check: recorded.result.check_block_id,
24384
+ verdict: recorded.result.verdict,
24385
+ line: recorded.line
24302
24386
  }
24303
24387
  };
24304
24388
  }
24305
- function arrivalText(attempt) {
24306
- if (attempt === undefined)
24307
- return "Dispatch recorded no delivery attempt for it";
24308
- if (attempt.state === "failed") {
24309
- return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
24310
- }
24311
- if (attempt.state === "pending")
24312
- return "its delivery is still on its way";
24313
- if (attempt.state === "queued") {
24314
- return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
24315
- }
24316
- return `it reached that session as ${attempt.delivery}`;
24317
- }
24318
- async function sendToAgentCommand(context) {
24389
+ async function resultsCommand(context) {
24319
24390
  const { args, client } = context;
24320
- const session = stringArg(args, "session");
24321
- const inReplyTo = optionalString(args, "in_reply_to");
24322
- const message = await client.agentMessage(session, {
24323
- body: stringArg(args, "body"),
24324
- delivery: stringArg(args, "delivery"),
24325
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
24326
- });
24327
- const attempt = message.deliveries?.at(-1);
24328
- const readBack = conversationReadBack(message.id);
24329
- const arrival = arrivalText(attempt);
24391
+ const issue = stringArg(args, "issue");
24392
+ const at = optionalString(args, "at");
24393
+ const brief = optionalBoolean(args, "brief") === true;
24394
+ const results = await client.issueResults(issue, at);
24395
+ const checks = results.checks ?? [];
24330
24396
  return {
24331
- text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
24397
+ text: formatCheckResults(results, brief),
24332
24398
  details: {
24333
- session,
24334
- message: message.id,
24335
- ...attempt === undefined ? {} : { delivery: attempt.state },
24336
- ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
24399
+ issue,
24400
+ checks: checks.length,
24401
+ results: checks.reduce((total, check) => total + (check.results ?? []).length, 0)
24337
24402
  }
24338
24403
  };
24339
24404
  }
24340
24405
 
24341
- // ../envoy-client/src/dispatch-commands/documents.ts
24342
- import { resolve as resolvePath2 } from "path";
24343
-
24344
- // ../contracts/src/go-blank.ts
24345
- var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
24346
-
24347
- // ../envoy-client/src/dispatch-commands/documents.ts
24348
- async function blockAsks(client, resolved, state) {
24349
- const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
24350
- return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
24406
+ // ../envoy-client/src/dispatch-commands/render-graph.ts
24407
+ function referenceLines(read) {
24408
+ if (typeof read === "string")
24409
+ return [`- ${read}`];
24410
+ const edges = read.edges ?? [];
24411
+ if (edges.length === 0)
24412
+ return ["- none"];
24413
+ return edges.map(edgeLine);
24351
24414
  }
24352
- async function readUploadedFile(client, artifact, details, requested, owner, shown) {
24353
- const versions = artifact.versions ?? [];
24354
- const latest = Math.max(0, ...versions.map((version) => version.number));
24355
- const number = requested ?? latest;
24356
- const of = number === latest ? "" : ` of ${latest}`;
24357
- const bytesRoute = `GET /api/v1/artifacts/${artifact.id}/versions/${number} serves its bytes.`;
24358
- const tooLarge = (mime, bytes) => ({
24359
- text: `${oversizePictureText(artifact.name, bytes)}, so dispatch doc-read cannot show this ` + `uploaded ${mime} picture (version ${number}${of}). ${bytesRoute}`,
24360
- details
24361
- });
24362
- const stated = versions.find((version) => version.number === number);
24363
- if (artifact.kind === "image" && stated?.size !== undefined && stated.size > PICTURE_SHOWN_MAX_BYTES) {
24364
- return tooLarge(stated.mime ?? "image", stated.size);
24365
- }
24366
- const file = await client.fileVersion(artifact.id, number);
24367
- const size = `${file.bytes.length.toLocaleString("en-US")} bytes`;
24368
- if (artifact.kind === "image") {
24369
- const image = toolImage(file.bytes);
24370
- if (image !== undefined) {
24371
- const address = `dispatch://${owner}/artifact/${artifact.slug}@v${number}`;
24372
- shown?.add(address);
24373
- return {
24374
- text: `Picture ${artifact.name}: ${image.mimeType}, version ${number}${of}, ${size}.
24375
- ` + shownPictureLine(1, address, artifact.name, image.mimeType, file.bytes.length),
24376
- details,
24377
- images: [image]
24378
- };
24379
- }
24380
- if (sniffPictureType(file.bytes) !== undefined)
24381
- return tooLarge(file.mime, file.bytes.length);
24415
+ function isItemKind(kind) {
24416
+ return ITEM_KINDS.some((item) => item === kind);
24417
+ }
24418
+ function edgeLine(edge) {
24419
+ const { node } = edge;
24420
+ const excerpt = edge.excerpt === undefined ? "" : `${textHead(edge.excerpt.text)} \xB7 `;
24421
+ const block = edge.block === undefined ? "" : ` (block ${edge.block.ref ?? edge.block.id})`;
24422
+ const parent = node.parent ?? undefined;
24423
+ const item = node.kind === "block" && node.document === undefined && isItemKind(parent?.kind) ? parent : undefined;
24424
+ const source = item === undefined ? `${node.kind} ${node.ref ?? node.id}` : `${item.kind} ${item.ref ?? item.id} block ${node.block_id ?? node.id}`;
24425
+ return `- ${edge.kind} ${source} (${excerpt}${edge.created_at})${block}`;
24426
+ }
24427
+ function unavailableReason(error) {
24428
+ return dispatchAnswered(error, 404) ? "unavailable" : `unavailable: ${messageFor(error)}`;
24429
+ }
24430
+ async function graphReferences(client, query) {
24431
+ try {
24432
+ return await client.getReferences(query);
24433
+ } catch (error) {
24434
+ return unavailableReason(error);
24382
24435
  }
24383
- let text;
24436
+ }
24437
+ async function issueReferencesOrUnavailable(client, key) {
24384
24438
  try {
24385
- text = new TextDecoder("utf-8", { fatal: true }).decode(file.bytes);
24386
- } catch {
24387
- return {
24388
- text: `${artifact.name} is an uploaded ${file.mime} file (version ${number}${of}, ${size}) that is not ` + `UTF-8 text, so dispatch doc-read cannot show it. ${bytesRoute}`,
24389
- details
24390
- };
24439
+ return await client.getIssueReferences(key);
24440
+ } catch (error) {
24441
+ return unavailableReason(error);
24391
24442
  }
24392
- return {
24393
- text: `File ${artifact.name}: ${file.mime}, version ${number}${of}, ${size}.
24394
-
24395
- ${text}`,
24396
- details
24397
- };
24398
24443
  }
24399
- var BLOCK_OPENING_CHARS = 60;
24400
- async function listDocumentBlocks(client, artifact) {
24401
- const live = await liveBlocks(client, artifact);
24402
- const { bytes, blocks } = live;
24403
- const decoder = new TextDecoder;
24404
- const lines = [
24405
- `Blocks of ${artifact.name}, in document order, each indented under the block holding it: id, type, (token; anchored comments and asks), opening words, then a typed block's serves and needs. A table lists its rows by the index delete_row takes and its cells by the row and the column delete_column takes.`
24406
- ];
24407
- const holders = [];
24408
- for (const block of blocks) {
24409
- while (holders.length > 0 && block.from >= (holders.at(-1)?.to ?? 0))
24410
- holders.pop();
24411
- const indent = " ".repeat(holders.length);
24412
- const flat = decoder.decode(bytes.subarray(block.from, block.to)).replace(/\s+/g, " ").trim();
24413
- const points = Array.from(flat);
24414
- const opening = points.length > BLOCK_OPENING_CHARS ? `${points.slice(0, BLOCK_OPENING_CHARS).join("")}\u2026` : flat;
24415
- const { comments, asks } = block.references;
24416
- lines.push(`${indent}${block.id} ${block.type} (${block.token ?? "no token"}; ${comments} comment${comments === 1 ? "" : "s"}, ${asks} ask${asks === 1 ? "" : "s"}): ${opening}`);
24417
- for (const attribute of block.attributes ?? []) {
24418
- if (attribute.kind === "block[]" && attribute.value !== "") {
24419
- lines.push(`${indent} ${attribute.name}: ${attribute.value}`);
24420
- }
24421
- }
24422
- if (block.type === "table") {
24423
- if (block.table === undefined) {
24424
- lines.push(`${indent} This Dispatch does not report table rows yet, so no row or column index is listed.`);
24425
- } else {
24426
- for (const row of block.table.rows ?? []) {
24427
- lines.push(`${indent} row ${row.index}, ${row.id === "" ? "no id yet" : `id ${row.id}`}`);
24428
- for (const cell of row.cells ?? []) {
24429
- const under = cell.header === "" ? "" : `, under ${JSON.stringify(cell.header)}`;
24430
- lines.push(`${indent} row ${cell.row} column ${cell.column}, ${cell.id === "" ? "no id yet" : `id ${cell.id}`}${under}: ${cell.text === "" ? "(empty)" : cell.text}`);
24431
- }
24432
- }
24433
- }
24434
- }
24435
- holders.push(block);
24444
+ async function issueCoverageOrReason(client, key) {
24445
+ try {
24446
+ return await client.issueCoverage(key);
24447
+ } catch (error) {
24448
+ return unavailableReason(error);
24436
24449
  }
24437
- return { text: lines.join(`
24438
- `), token: live.token, version: live.version };
24439
24450
  }
24440
- async function refuseOpenDecisionBlocks(client, tool, resolved) {
24441
- const artifact = resolved.artifact;
24442
- const latest = artifact.approval?.latest_version;
24443
- if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
24444
- return;
24445
- const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
24446
- if (blocks.length === 0)
24447
- return;
24448
- const [documentAsks, version] = await Promise.all([
24449
- blockAsks(client, resolved),
24450
- client.docRead(artifact.id, latest)
24451
+ async function graphSections(client, ref) {
24452
+ const [incoming, outgoing] = await Promise.all([
24453
+ graphReferences(client, { to: ref }),
24454
+ graphReferences(client, { from: ref })
24451
24455
  ]);
24452
- const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
24453
- const lines = version.markdown.split(`
24454
- `);
24455
- const stillOpen = (named, state) => state === "answered" ? `${named}, answered but still open in version ${latest}: it settles into a version on its own in about two seconds; wait for that version` : `${named}, ${state} but still open in version ${latest}: write the decision into the text with dispatch doc-edit, which writes a version that carries it`;
24456
- const open = blocks.flatMap((block) => {
24457
- const ask = asks.get(block.id);
24458
- const id = typedBlockIdAttribute(block.id);
24459
- const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
24460
- const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
24461
- const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
24462
- if (states.length === 0)
24463
- return [`${named}, which version ${latest} does not hold yet`];
24464
- if (!states.includes("open") && states.some((state) => state !== undefined))
24465
- return [];
24466
- if (ask !== undefined)
24467
- return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
24468
- const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
24469
- const sourceId = attribute("copied_from");
24470
- const document = attribute("copied_from_document");
24471
- if (sourceId === undefined || document === undefined) {
24472
- return [`${named}, whose ask Dispatch has not opened yet`];
24473
- }
24474
- const source = parseDispatchRef(document);
24475
- const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
24476
- const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
24477
- return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
24478
- });
24479
- if (open.length === 0)
24480
- return;
24481
- const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
24482
- throw new Error([
24483
- `dispatch ${commandName(tool)} was not called: ${artifact.name} (version ${latest}) has ${count}. Answering one writes a new version, which would move this request to that version and leave it waiting on you.`,
24484
- ...open.map((line) => `- ${line}`),
24485
- "Do not request approval over an open block, even when a human asked for it. Tell the human which block is open and ask them to answer it or to waive it. Once it is answered, it settles into a version on its own in about two seconds. When the human approved an earlier version and their answer is the whole change since it, Dispatch carries the approval to the new version in their name: request nothing. When the answer changes design text outside the block, rewrite that text (never to restate the answer), then request approval again once the human has agreed to every point in the new version, with a one-sentence --summary naming what changed since the earlier approval. On a document nobody has approved, wait for that version, then request. If they waive it, close the block with dispatch resolve-ask (--kind resolved, their words as the --reason), write their decision into the text with dispatch doc-edit, then request approval again once the human has agreed to every point in the new version. The call opens the request, or hands an open one back to the human."
24486
- ].join(`
24487
- `));
24456
+ return graphSectionLines(incoming, outgoing);
24488
24457
  }
24489
- async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
24490
- const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
24491
- if (removing.length === 0)
24492
- return;
24493
- const artifact = resolved.artifact;
24494
- const blocks = await client.artifactBlocks(artifact.id);
24495
- const askBlocks = blocks.filter((block) => block.type === "ask");
24496
- const removed = new Set;
24497
- for (const operation of removing) {
24498
- const target = blocks.find((block) => block.id === operation.block);
24499
- if (target === undefined)
24500
- continue;
24501
- for (const block of askBlocks) {
24502
- if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
24503
- removed.add(block.id);
24504
- }
24505
- }
24506
- }
24507
- if (removed.size === 0)
24458
+ function graphSectionLines(incoming, outgoing) {
24459
+ return [
24460
+ ...typeof incoming === "string" ? [] : nodeLine(incoming.node),
24461
+ "Referenced by:",
24462
+ ...referenceLines(incoming),
24463
+ "Links:",
24464
+ ...referenceLines(outgoing)
24465
+ ];
24466
+ }
24467
+ function nodeLine(node) {
24468
+ if (node.made_by === undefined)
24469
+ return [];
24470
+ const fact = (by, time) => `${by == null || by.length === 0 ? "nobody recorded" : by.map(actorText).join(", ")}${time == null ? "" : ` at ${time}`}`;
24471
+ const made = fact(node.made_by, node.made_at);
24472
+ const changed = fact(node.changed_by, node.changed_at);
24473
+ const { parent } = node;
24474
+ const partOf = parent == null ? "" : ` \xB7 part of ${parent.ref ?? `${parent.kind} ${parent.id}`}${node.parent_version == null ? "" : ` (${isItemKind(parent.kind) ? "revision" : "version"} ${node.parent_version})`}`;
24475
+ return [
24476
+ `Node: ${node.kind} ${node.ref ?? node.id} \xB7 made by ${made} \xB7 changed by ${changed}${partOf}`
24477
+ ];
24478
+ }
24479
+ function blockLines(node, ref, typed, noun = "Block") {
24480
+ const unit = ref.item === undefined ? "version" : "revision";
24481
+ const blockID = node.block_id ?? ref.block;
24482
+ const head = ref.item === undefined ? [
24483
+ `Block: ${blockID}`,
24484
+ ...typed === undefined ? [] : [`Type: ${typed.type}`],
24485
+ `Document: ${node.document ?? ref.document}`,
24486
+ ...(typed?.attributes ?? []).map((attribute) => `${attribute.name}: ${attribute.value === "" ? "(empty)" : attribute.value}`),
24487
+ ...node.changed_version === undefined ? [] : [`Changed in version: ${node.changed_version}`],
24488
+ ...node.text === undefined ? [] : ["Text:", node.text]
24489
+ ] : [
24490
+ `${noun} ${blockID} of ${ref.item.kind} ${ref.item.id}${node.changed_version === undefined ? "" : ` (changed in revision ${node.changed_version})`}:`,
24491
+ ...node.text === undefined ? [] : [node.text]
24492
+ ];
24493
+ const { pin } = node;
24494
+ if (pin === undefined)
24495
+ return head;
24496
+ const state = pin.state === "unchanged" ? `Unchanged since ${unit} ${pin.version}.` : pin.state === "changed" ? `Changed since ${unit} ${pin.version}; last changed in ${unit} ${node.changed_version}.` : `Removed in ${unit} ${pin.removed_version}.`;
24497
+ return [
24498
+ ...head,
24499
+ `Pinned to ${unit}: ${pin.version}`,
24500
+ state,
24501
+ `Text at ${unit} ${pin.version}:`,
24502
+ pin.text
24503
+ ];
24504
+ }
24505
+ async function typedBlockOf(client, ref) {
24506
+ if (ref.item !== undefined || ref.block === undefined)
24508
24507
  return;
24509
- const asks = await blockAsks(client, resolved, "open");
24510
- const open = asks.filter((ask) => removed.has(ask.block_id));
24511
- if (open.length === 0)
24508
+ try {
24509
+ const blocks = ref.owner.kind === "project" ? await client.projectArtifactBlocks(ref.owner.project, ref.id) : await client.issueArtifactBlocks(ref.owner.issue, ref.id);
24510
+ return blocks.find((block) => block.id === ref.block);
24511
+ } catch {
24512
24512
  return;
24513
- const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
24514
- throw new Error([
24515
- `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
24516
- ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
24517
- "A decision block leaves the document once its ask is answered or resolved. Until then, reword it with replace, relocate it with move, or change its question, options, urgency or multiple with dispatch edit-ask if you asked it; each keeps it."
24518
- ].join(`
24519
- `));
24513
+ }
24520
24514
  }
24521
- async function docEditCommand(context) {
24522
- const { args, client, actor, input, linkBase, documentOwner, resolveDocument } = context;
24523
- const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
24524
- const ops = args.ops;
24525
- const summary = optionalString(args, "summary");
24526
- const { precondition: rawPrecondition } = args;
24527
- const precondition = rawPrecondition;
24528
- await refuseRemovingOpenDecisionBlocks(client, input.tool, resolved, ops);
24529
- const edited = await client.docEdit(resolved.artifact.id, {
24530
- ops,
24531
- ...summary === undefined ? {} : { summary },
24532
- ...precondition === undefined ? {} : { precondition },
24533
- actor
24534
- });
24535
- const retyped = ops.filter((operation) => operation.op === "retype").length;
24536
- const versionText = edited.version === null ? "no new version" : `version ${edited.version.number}`;
24537
- const retypedText = retyped === 0 ? "" : `; retyped ${retyped} block${retyped === 1 ? "" : "s"}`;
24538
- const nothingChanged = edited.changed === false;
24539
- const head = nothingChanged ? `Applied ${edited.applied} ops${retypedText}; nothing changed (${versionText})` : `Applied ${edited.applied} ops${retypedText} (${versionText})`;
24540
- const unchangedOps = edited.unchanged_ops ?? [];
24541
- const unchangedText = unchangedOps.length === 0 ? "" : `; ${unchangedOps.length === 1 ? "operation" : "operations"} ${unchangedOps.join(", ")} changed nothing`;
24542
- const lostOps = edited.lost_ops;
24543
- const lostText = lostOps === undefined || lostOps !== null && lostOps.length === 0 ? "" : lostOps === null ? "; could not confirm this edit survived, because the live document is being reloaded or holds a tree too deep to read \u2014 re-read it" : `; ${versionText} carries text the live document no longer has: a concurrent change removed what ${lostOps.length === 1 ? "operation" : "operations"} ${lostOps.join(", ")} wrote \u2014 re-read the document`;
24544
- const applied = `${head}${unchangedText}${lostText}`;
24545
- const editAskText = ops.map((operation) => /^:{3,}ask\{.*\n([\s\S]*)/mu.exec(operation.markdown ?? operation.with ?? "")?.[1]).find((text) => text !== undefined) ?? resolved.issue?.title ?? "";
24546
- const checkLines = decisionBlockLines(edited.advice, {
24547
- project: resolved.artifact.project,
24548
- text: editAskText,
24549
- linkBase
24550
- });
24551
- const declinedLines = resolved.issue === undefined ? [] : declinedAskLines(edited.advice, resolved.issue.key, linkBase);
24552
- const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, resolvedTopic(resolved).label, edited.advice, {
24553
- isPlan: documentPlaysPlan(resolved.artifact)
24554
- }));
24555
- const written = edited.written;
24556
- const writtenLines = written === undefined || written === "" ? [] : [written];
24557
- const tokenTrailer = edited.token === undefined ? [] : [`Document token: ${edited.token}`];
24558
- return {
24559
- text: [
24560
- `${applied}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
24561
- ...checkLines,
24562
- ...declinedLines,
24563
- ...writtenLines,
24564
- ...tokenTrailer,
24565
- ...adviceLines
24566
- ].join(`
24567
- `),
24568
- details: writeResultDetails(resolved, {
24569
- applied: edited.applied,
24570
- ...edited.version === null ? {} : { version: edited.version.number },
24571
- ...nothingChanged ? { changed: false } : {},
24572
- ...lostOps === undefined ? {} : { lost_ops: lostOps },
24573
- ...edited.token === undefined ? {} : { token: edited.token },
24574
- ...edited.advice === undefined ? {} : { advice: edited.advice }
24575
- })
24576
- };
24515
+ function askPartNoun(ask, node, blockID) {
24516
+ if (ask.answer?.id === blockID)
24517
+ return "Answer";
24518
+ if ((ask.options ?? []).some((option) => option.id === blockID))
24519
+ return "Option";
24520
+ const placed = (ask.revision ?? 0) > 0 && (ask.options ?? []).every((option) => option.id !== undefined) && (ask.answer === null || ask.answer.id !== undefined);
24521
+ return placed && node.pin?.state !== "removed" ? "Question" : "Part";
24577
24522
  }
24578
- async function docReadCommand(context) {
24579
- const { args, client, ownerArguments, shown, documentOwner, resolveDocument } = context;
24580
- const { agentArtifact } = ownerArguments;
24581
- if (agentArtifact !== undefined) {
24582
- const artifact = await client.getAgentArtifact(agentArtifact.session, agentArtifact.slug);
24583
- if (optionalBoolean(args, "blocks") === true) {
24584
- throw new Error(`${artifact.name} is an uploaded ${artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
24585
- }
24586
- return readUploadedFile(client, artifact, { session: agentArtifact.session, artifact: artifact.slug }, optionalNumber(args, "version") ?? agentArtifact.version, `agent/${agentArtifact.session}`, shown);
24587
- }
24588
- const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
24589
- const resolved = await resolveDocument(documentOwner(), artifactReference);
24590
- const version = optionalNumber(args, "version") ?? ownerArguments.ref?.version;
24591
- if (optionalBoolean(args, "blocks") === true) {
24592
- if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
24593
- throw new Error(`${resolved.artifact.name} is an uploaded ${resolved.artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
24594
- }
24595
- const listed = await listDocumentBlocks(client, resolved.artifact);
24596
- const trailer = [
24597
- ...listed.token === undefined ? [] : [`Document token: ${listed.token}`],
24598
- `Document version: ${listed.version === null ? "none yet" : listed.version}`
24599
- ];
24600
- return {
24601
- text: `${listed.text}
24602
-
24603
- ${trailer.join(`
24604
- `)}`,
24605
- details: resolved.owner.kind === "project" ? {
24606
- project: resolved.artifact.project,
24607
- document: documentLabel(resolved.artifact.project, resolved.artifact.slug)
24608
- } : { issue: resolved.issue?.key }
24609
- };
24610
- }
24611
- if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
24612
- const { artifact } = resolved;
24613
- return readUploadedFile(client, artifact, resolved.owner.kind === "project" ? {
24614
- project: artifact.project,
24615
- document: documentLabel(artifact.project, artifact.slug)
24616
- } : { issue: resolved.issue?.key }, version, resolved.owner.kind === "project" ? resolved.owner.project : resolved.owner.issue, shown);
24617
- }
24618
- const documentPromise = client.docRead(resolved.artifact.id, version);
24619
- const threadsPromise = openAnchoredThreads(client, resolved);
24620
- const threadsResultPromise = threadsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
24621
- const document = await documentPromise;
24622
- const threadsResult = await threadsResultPromise;
24623
- if (threadsResult.status === "rejected")
24624
- throw threadsResult.reason;
24625
- const threads = threadsResult.value;
24626
- const approval = approvalLine(resolved.artifact, typeof resolved.issue?.closed_at === "string");
24627
- const trailer = [
24628
- ..."token" in document && document.token !== undefined ? [`Document token: ${document.token}`] : [],
24629
- ..."sha256" in document && document.sha256 !== undefined ? [`Content: sha256:${document.sha256}`] : [],
24630
- ...approval === undefined ? [] : [approval]
24631
- ];
24632
- return {
24633
- text: [
24634
- document.markdown,
24635
- ...trailer.length === 0 ? [] : [trailer.join(`
24636
- `)],
24637
- ...threads.length === 0 ? [] : ["Open anchored threads:", ...threads]
24638
- ].join(`
24639
24523
 
24640
- `),
24641
- details: resolved.owner.kind === "project" ? {
24642
- project: resolved.artifact.project,
24643
- document: `${resolved.artifact.project}/${resolved.artifact.slug}`
24644
- } : { issue: resolved.issue?.key }
24645
- };
24646
- }
24647
- async function requestApprovalCommand(context) {
24648
- const { args, client, actor, input, ownerArguments, documentOwner, resolveDocument } = context;
24649
- const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
24650
- const resolved = await resolveDocument(documentOwner(), artifactReference);
24651
- await refuseOpenDecisionBlocks(client, input.tool, resolved);
24652
- const includeVerification = optionalBoolean(args, "include_verification") === true;
24653
- const result = await client.requestApproval(resolved.artifact.id, {
24654
- actor,
24655
- summary: stringArg(args, "summary"),
24656
- ...includeVerification ? { include_verification: true } : {}
24657
- });
24658
- const gaps = result.coverage ?? [];
24659
- const coverageLines = result.coverage_unread ? [
24660
- `Coverage of ${resolved.artifact.name}: unread. Dispatch could not read what the spec's requirements lack, so no line here says there is no gap; the request is recorded either way. Read the coverage again with dispatch read --issue, and mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
24661
- ] : gaps.length === 0 ? [] : [
24662
- `Coverage of ${resolved.artifact.name}: ${gaps.map((gap) => `${gap}.`).join(" ")} Mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
24663
- ];
24664
- if (result.ask === null) {
24665
- return {
24666
- text: [
24667
- `${resolved.artifact.name} (document id ${resolved.artifact.id}) is already approved at version ${result.version} by ${result.approval.by?.id ?? "unknown"}; no new request was opened. A change outside the decision blocks after approval makes it stale, so request again only for such a version, once the human has agreed to every point in it, with a --summary naming what changed since version ${result.version}; the human's own answer to a decision block carries the approval when that answer is the whole change.`,
24668
- ...coverageLines
24669
- ].join(`
24670
- `),
24671
- details: {
24672
- ...resolved.owner.kind === "project" ? documentResultDetails(resolved.artifact) : { issue: resolved.issue?.key },
24673
- artifact: resolved.artifact.id,
24674
- version: result.version
24675
- }
24676
- };
24677
- }
24678
- const details = await followedAskDetails(client, result.ask, resolved.artifact);
24679
- const outcome = result.recorded ? `Approval requested for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}).` : `The approval request for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}) already waits on the human, so this call changed nothing: nothing since it last reached the human (a newer version, a human's reply in its thread, or your progress note) left it waiting on you.`;
24680
- const waitsOn = waitsOnPerson(result.ask);
24681
- return {
24682
- text: [
24683
- `${outcome}${waitsOn === undefined ? "" : ` It waits on ${waitsOn}.`} The human's Inbox asks: ${JSON.stringify(result.ask.question)}. The answer arrives as artifact.approved or artifact.changes_requested. An edit before the answer moves this request to the new version and leaves it waiting on you, and a change outside the decision blocks after approval makes the approval stale: either way, request again for the new version once the human has agreed to every point in it, which hands this request back or opens a new one, with a --summary naming what changed since the earlier approval. The human's own answer to a decision block carries the approval when that answer is the whole change since the approved version, and answers an open request Approve in their name: request nothing then.`,
24684
- ...coverageLines
24685
- ].join(`
24686
- `),
24687
- details: { ...details, artifact: resolved.artifact.id, version: result.version }
24688
- };
24689
- }
24690
- async function planApproveCommand(context) {
24691
- const { args, client, actor, documentOwner, resolveDocument } = context;
24692
- const planOwner = documentOwner();
24693
- const named = optionalString(args, "artifact");
24694
- const byRole = named === undefined && planOwner.kind === "issue" ? (await client.getIssue(planOwner.issue)).plan_artifact_id ?? "" : "";
24695
- const resolved = await resolveDocument(planOwner, named ?? (byRole || "plan.md"));
24696
- const version = numberArg(args, "version");
24697
- const review = await client.planApprove(resolved.artifact.id, { actor, version });
24698
- return {
24699
- text: `The plan review approved ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${review.version}; no human is asked to approve a plan. A later plan version makes this approval stale: run the review again and record it the same way.`,
24700
- details: {
24701
- issue: resolved.issue?.key,
24702
- artifact: resolved.artifact.id,
24703
- version: review.version
24704
- }
24705
- };
24706
- }
24707
- function artifactUnderName(artifacts, name) {
24708
- const written = name.trim();
24709
- return artifacts.find((held) => held.slug === written) ?? artifacts.find((held) => held.name === written);
24710
- }
24711
- function artifactNameExistsProblem(held, owner) {
24712
- const versions = held.versions ?? [];
24713
- const newest = versions[versions.length - 1];
24714
- if (newest === undefined) {
24715
- return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}), which has no version yet and which ${actorText(held.created_by)} created. ${ARTIFACT_NAME_EXISTS_RULE}`;
24716
- }
24717
- const authors = (newest.authors ?? []).map(actorText);
24718
- const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
24719
- return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${ARTIFACT_NAME_EXISTS_RULE}`;
24720
- }
24721
- var STORED_LINE_QUOTED = 200;
24722
- function quotedStoredLine(line) {
24723
- if (line.length <= STORED_LINE_QUOTED)
24724
- return JSON.stringify(line);
24725
- const head = JSON.stringify(line.slice(0, STORED_LINE_QUOTED));
24726
- return `${head} (cut after ${STORED_LINE_QUOTED} of its ${line.length} characters)`;
24727
- }
24728
- function firstStoredDifference(given, stored) {
24729
- const written = given.split(`
24730
- `);
24731
- const holds = stored.split(`
24732
- `);
24733
- for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
24734
- const wrote = written[line];
24735
- const held = holds[line];
24736
- if (wrote === held)
24737
- continue;
24738
- if (wrote === undefined && held !== undefined) {
24739
- return `the store writes a line ${line + 1}, ${quotedStoredLine(held)}`;
24740
- }
24741
- if (held === undefined && wrote !== undefined) {
24742
- return `the store drops line ${line + 1}, ${quotedStoredLine(wrote)}`;
24743
- }
24744
- if (wrote !== undefined && held !== undefined) {
24745
- return `line ${line + 1} reads ${quotedStoredLine(wrote)} and is stored as ${quotedStoredLine(held)}`;
24746
- }
24747
- }
24748
- return "the stored text differs from the text given";
24749
- }
24750
- var STORED_TEXT_PRINTED = 2000;
24751
- function storedTextPrinted(stored) {
24752
- if (stored.length <= STORED_TEXT_PRINTED)
24753
- return { text: stored, cut: "" };
24754
- const head = stored.slice(0, STORED_TEXT_PRINTED);
24755
- const lastLineFeed = head.lastIndexOf(`
24756
- `);
24757
- const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
24758
- return {
24759
- text,
24760
- cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
24761
- };
24762
- }
24763
- function storedTextProblem(given, stored, name) {
24764
- const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
24765
- const printed = storedTextPrinted(stored);
24524
+ // ../envoy-client/src/dispatch-commands/render-item.ts
24525
+ function askSummary({ ask, replies, answers }, askRef, pictures, incoming, outgoing) {
24526
+ const answer = ask.answer;
24527
+ const earlierAnswers = (answers ?? []).slice(0, -1);
24528
+ const parts = askPartEdges(ask, incoming);
24529
+ const partRef = (id) => `${askRef}#b-${encodeBlockId(id)}`;
24530
+ const chain = (replies ?? []).flatMap((reply) => [
24531
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
24532
+ `Body: ${reply.body}`
24533
+ ]);
24534
+ const resolutionWords = dispatchWordsText(ask.resolution?.dispatch_words);
24766
24535
  return [
24767
- `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
24768
- ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
24769
- `${printed.cut}
24770
- --- the text Dispatch stores ---
24771
- ${printed.text}`,
24772
- "--- end of the text Dispatch stores ---"
24773
- ].join("");
24774
- }
24775
- function storedTextCheckFailed(error, name) {
24776
- const failure = `Dispatch could not say how it would store this text, so nothing was uploaded: POST /api/v1/markdown/round-trip failed with ${messageFor(error)}.`;
24777
- if (!dispatchAnswered(error, 413)) {
24778
- return `${failure} Send the upload again once that call is answered.`;
24779
- }
24780
- const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
24781
- return `${failure} This text is longer than the check reads, and sending the upload again does not change that: a markdown document is at most 1 MiB, so shorten it or split it across documents of at most that.${asBytes}`;
24782
- }
24783
- function roundTripRouteAbsent(error) {
24784
- return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
24785
- }
24786
- function withoutFinalLineFeed(text) {
24787
- return text.endsWith(`
24788
- `) ? text.slice(0, -1) : text;
24789
- }
24790
- async function artifactCommand(context) {
24791
- const { args, client, actor, input, documentOwner, issue } = context;
24792
- const summary = optionalString(args, "summary");
24793
- const name = stringArg(args, "name");
24794
- const content = optionalString(args, "content");
24795
- const path = optionalString(args, "path");
24796
- const options = { name, ...summary === undefined ? {} : { summary }, actor };
24797
- const artifactOwner = documentOwner();
24798
- const blank = content === undefined || goBlankPattern.test(content);
24799
- if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
24800
- const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
24801
- if (held !== undefined) {
24802
- throw new ToolInputError(input.tool, [
24803
- artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`)
24804
- ]);
24805
- }
24806
- }
24807
- if (!blank) {
24808
- let stored;
24809
- try {
24810
- stored = await client.markdownRoundTrip(content);
24811
- } catch (error) {
24812
- if (!roundTripRouteAbsent(error)) {
24813
- throw new Error(storedTextCheckFailed(error, name), { cause: error });
24814
- }
24815
- }
24816
- if (stored !== undefined && withoutFinalLineFeed(stored) !== withoutFinalLineFeed(content)) {
24817
- throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
24818
- }
24819
- }
24820
- const artifactInput = path !== undefined ? {
24821
- ...options,
24822
- file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
24823
- type: Bun.file(resolvePath2(input.cwd, path)).type
24824
- })
24825
- } : content !== undefined ? { ...options, content } : options;
24826
- const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
24827
- const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
24828
- const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
24829
- const adviceLines = renderAdvice(input.tool, uploadOwner.label, result.advice, {
24830
- isPrimarySpec: result.artifact.primary || result.artifact.name === "spec.md",
24831
- isPlan: documentPlaysPlan(result.artifact)
24832
- });
24833
- return {
24834
- text: [
24835
- path === undefined && content === undefined ? `Made ${result.artifact.name} as an empty document (artifact slug ${result.artifact.slug}; ${artifactRef}). Write in it with dispatch doc-edit.${await notSubscribed(uploadOwner, input.subscriptions)}` : `Uploaded ${result.artifact.name} as version ${result.version.number} (artifact slug ${result.artifact.slug}; ${artifactRef})${await notSubscribed(uploadOwner, input.subscriptions)}`,
24836
- ...adviceLines
24837
- ].join(`
24838
- `),
24839
- details: artifactOwner.kind === "project" ? {
24840
- ...documentResultDetails(result.artifact),
24841
- version: result.version.number,
24842
- ...result.advice === undefined ? {} : { advice: result.advice }
24843
- } : {
24844
- issue: issue(),
24845
- artifact: result.artifact.id,
24846
- version: result.version.number,
24847
- ...result.advice === undefined ? {} : { advice: result.advice }
24848
- }
24849
- };
24850
- }
24851
-
24852
- // ../envoy-client/src/dispatch-commands/handoffs.ts
24853
- async function handoffWriteCommand(context) {
24854
- const { args, client, actor, input, issue } = context;
24855
- if (!input.sessionId?.trim()) {
24856
- throw new Error("host session id is required for dispatch handoff-write");
24857
- }
24858
- let recorded;
24859
- try {
24860
- recorded = await client.writeHandoff(issue(), stringArg(args, "phase"), {
24861
- actor,
24862
- body: stringArg(args, "body")
24863
- });
24864
- } catch (error) {
24865
- throw refusalWithCode(error);
24866
- }
24867
- return {
24868
- text: `Recorded the ${recorded.phase} handoff of ${recorded.issue_key}, version ${recorded.version} (id ${recorded.id})`,
24869
- details: {
24870
- issue: recorded.issue_key,
24871
- phase: recorded.phase,
24872
- version: recorded.version,
24873
- handoff: recorded.id
24874
- }
24875
- };
24536
+ `Question: ${ask.question}`,
24537
+ ...anchorLines(ask),
24538
+ "Options:",
24539
+ ...(ask.options ?? []).length === 0 ? ["- none"] : (ask.options ?? []).flatMap((option) => [
24540
+ `- ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}${option.id === undefined ? "" : ` (${partRef(option.id)})`}`,
24541
+ ...partReferenceLines(parts.at, option.id)
24542
+ ]),
24543
+ `State: ${ask.state}`,
24544
+ `Ask id: ${ask.id}`,
24545
+ "Answer:",
24546
+ ...answer === null ? ["- none"] : [
24547
+ `- By: ${actorActText(answer.user, answer.act)}`,
24548
+ `- Selected: ${(answer.selected ?? []).length === 0 ? "none" : (answer.selected ?? []).join(", ")}`,
24549
+ ...answer.text === null ? [] : [`- Text: ${answer.text}`],
24550
+ ...answer.id === undefined ? [] : [`- Reference: ${partRef(answer.id)}`],
24551
+ ...partReferenceLines(parts.at, answer.id)
24552
+ ],
24553
+ ...earlierAnswers.length === 0 ? [] : [
24554
+ "Earlier answers:",
24555
+ ...earlierAnswers.map((earlier) => `- ${earlier.at} \xB7 ${actorActText(earlier.user, earlier.act)} \xB7 ${askAnswerText(earlier)}`)
24556
+ ],
24557
+ ...ask.resolution === undefined ? [] : [
24558
+ "Resolution:",
24559
+ `- By: ${ask.resolution.actor.id}`,
24560
+ `- Kind: ${ask.resolution.kind}`,
24561
+ ...ask.resolution.reason === "" ? [] : [`- Reason: ${ask.resolution.reason}`],
24562
+ ...resolutionWords === undefined ? [] : [`- ${resolutionWords}`]
24563
+ ],
24564
+ "Replies:",
24565
+ ...chain.length === 0 ? ["- none"] : chain,
24566
+ ...pictures,
24567
+ ...graphSectionLines(parts.rest, outgoing)
24568
+ ].join(`
24569
+ `);
24876
24570
  }
24877
- async function handoffReadCommand(context) {
24878
- const { args, client, issue } = context;
24879
- const issueKey = issue();
24880
- const phase = stringArg(args, "phase");
24881
- const version = optionalNumber(args, "version");
24882
- let handoff;
24883
- try {
24884
- if (version === undefined) {
24885
- handoff = await client.latestHandoff(issueKey, phase);
24886
- } else {
24887
- const listed = await client.listHandoffs(issueKey);
24888
- const ofPhase = listed.filter((summary) => summary.phase === phase);
24889
- const match = ofPhase.find((summary) => summary.version === version);
24890
- if (match === undefined) {
24891
- const newest = Math.max(0, ...ofPhase.map((summary) => summary.version));
24892
- throw new Error(`HANDOFF_NOT_FOUND: issue ${issueKey} has no ${phase} handoff version ${version}; ${newest === 0 ? `it has no ${phase} handoff at all` : `its newest ${phase} handoff is version ${newest}`}`);
24893
- }
24894
- handoff = await client.handoff(match.id);
24571
+ function askPartEdges(ask, incoming) {
24572
+ const ids = new Set([...(ask.options ?? []).map((option) => option.id), ask.answer?.id].filter((id) => id !== undefined));
24573
+ const at = new Map;
24574
+ if (typeof incoming === "string" || ids.size === 0)
24575
+ return { at, rest: incoming };
24576
+ const rest = [];
24577
+ for (const edge of incoming.edges ?? []) {
24578
+ const part = edge.block?.block_id;
24579
+ if (part === undefined || !ids.has(part)) {
24580
+ rest.push(edge);
24581
+ continue;
24895
24582
  }
24896
- } catch (error) {
24897
- throw refusalWithCode(error);
24583
+ const { block: _block, ...atPart } = edge;
24584
+ const held = at.get(part);
24585
+ if (held === undefined)
24586
+ at.set(part, [atPart]);
24587
+ else
24588
+ held.push(atPart);
24898
24589
  }
24899
- return {
24900
- text: `${handoff.issue_key} ${handoff.phase} handoff, version ${handoff.version} (id ${handoff.id}), written by ${actorText(handoff.author)} at ${handoff.created_at}
24901
- ${handoff.body}`,
24902
- details: {
24903
- issue: handoff.issue_key,
24904
- phase: handoff.phase,
24905
- version: handoff.version,
24906
- handoff: handoff.id
24907
- }
24908
- };
24590
+ return { at, rest: { node: incoming.node, edges: rest } };
24909
24591
  }
24910
-
24911
- // ../envoy-client/src/dispatch-commands/render-issue.ts
24912
- function componentsLine(components) {
24913
- const ids = components.ids ?? [];
24914
- const unknown = components.unknown ?? [];
24915
- const inherited = components.inherited_from === null ? "" : ` (inherited from ${components.inherited_from})`;
24916
- const retired = unknown.length === 0 ? "" : ` (retired: ${unknown.join(", ")})`;
24917
- switch (components.mode) {
24918
- case "explicit":
24919
- return `Components: ${ids.length === 0 ? "none live" : ids.join(", ")}${inherited}${retired}`;
24920
- case "none":
24921
- return `Components: none \u2014 ${components.reason ?? ""}${inherited}`;
24922
- case "inherit":
24923
- return "Components: unassigned";
24924
- default:
24925
- return `Components: ${components.mode}${inherited}${retired}`;
24926
- }
24592
+ function partReferenceLines(at, id) {
24593
+ const edges = id === undefined ? undefined : at.get(id);
24594
+ if (edges === undefined || edges.length === 0)
24595
+ return [];
24596
+ return [" Referenced by:", ...edges.map((edge) => ` ${edgeLine(edge)}`)];
24927
24597
  }
24928
- function advanceText(advance) {
24929
- return `${advance.id} (${advance.inherited ? "inherited" : "own"})`;
24598
+ function openAskAge(ageSeconds) {
24599
+ const seconds = Math.max(0, Math.floor(ageSeconds));
24600
+ if (seconds < 60)
24601
+ return `${seconds}s`;
24602
+ const minutes = Math.floor(seconds / 60);
24603
+ if (minutes < 60)
24604
+ return `${minutes}m${seconds % 60 === 0 ? "" : ` ${seconds % 60}s`}`;
24605
+ const hours = Math.floor(minutes / 60);
24606
+ if (hours < 24)
24607
+ return `${hours}h${minutes % 60 === 0 ? "" : ` ${minutes % 60}m`}`;
24608
+ const days = Math.floor(hours / 24);
24609
+ return `${days}d${hours % 24 === 0 ? "" : ` ${hours % 24}h`}`;
24930
24610
  }
24931
- function advancesLine(issue) {
24932
- if (issue.advances === undefined) {
24933
- return "Advances: unknown (this Dispatch server predates priorities; upgrade it)";
24934
- }
24935
- const advances = issue.advances ?? [];
24936
- if (advances.length === 0)
24937
- return "Advances: no priority";
24938
- return `Advances: ${advances.map(advanceText).join(", ")}`;
24611
+ function namedPerson(person) {
24612
+ return person === undefined || person === "" ? undefined : person;
24939
24613
  }
24940
- function claimText(claim, agents, read = {}) {
24941
- const titles = agents?.titles;
24942
- const liveness = holderLiveness(claim, agents, read);
24943
- const holding = claimHolds(claim, titles, liveness);
24944
- const takeableAt = claimTakeableAt(liveness);
24945
- const unresponsive = liveness.holder_state === "unresponsive" && liveness.last_seen != null ? ` \xB7 unresponsive since ${liveness.last_seen}${takeableAt === null ? "" : `, takeable at ${takeableAt}`}` : " \xB7 unresponsive";
24946
- const marker = holding === "unknown" ? " \xB7 liveness unknown" : holding === "lapsed" ? " \xB7 not running" : holding === "unresponsive" ? unresponsive : "";
24947
- return `${actorLabel(claim.actor, titles)} since ${claim.at}${marker}`;
24614
+ function waitsOnPerson(ask) {
24615
+ return namedPerson(ask.waiting_on_person);
24948
24616
  }
24949
- function holderLiveness(claim, agents, read) {
24950
- if (claim.actor.kind !== "session")
24951
- return read;
24952
- const row = agents?.liveness.get(claim.actor.id);
24953
- if (row === undefined)
24954
- return read;
24955
- const holderState = read.holder_state ?? row.holder_state;
24956
- const lastSeen = read.last_seen ?? row.last_seen;
24957
- const takeableAt = read.takeable_at ?? row.takeable_at;
24958
- return {
24959
- ...holderState === undefined ? {} : { holder_state: holderState },
24960
- ...lastSeen === undefined ? {} : { last_seen: lastSeen },
24961
- ...takeableAt === undefined ? {} : { takeable_at: takeableAt }
24962
- };
24617
+ function openAskLine(ask, linkBase) {
24618
+ const priority = ask.priority === null ? "" : `P${ask.priority} \xB7 `;
24619
+ return `- ${openAskAge(ask.age_seconds)} \xB7 ${priority}${ownerTitle(ask.owner)} \xB7 asked of ${waitsOnPerson(ask) ?? "nobody"} \xB7 ${ask.question} \xB7 ${linkFor(ask.ref, linkBase)}`;
24963
24620
  }
24964
- async function liveAgents(client, needed) {
24965
- if (!needed) {
24966
- return;
24967
- }
24968
- try {
24969
- const agents = await client.listAgents();
24970
- return {
24971
- titles: new Map(agents.map((agent) => [agent.session_id, agent.title])),
24972
- liveness: new Map(agents.map((agent) => [agent.session_id, agentLiveness(agent)]))
24973
- };
24974
- } catch {
24975
- return;
24621
+ function formatOpenAsksSummary(response, linkBase) {
24622
+ const scope = "active open asks you authored on open issues and project documents";
24623
+ if (response.count === 0) {
24624
+ return ["There are no unanswered asks for this session.", `Scope: ${scope}.`].join(`
24625
+ `);
24976
24626
  }
24627
+ const waitingOnHuman = (response.asks ?? []).filter((ask) => ask.waiting_on === "human");
24628
+ const waitingOnAgent = (response.asks ?? []).filter((ask) => ask.waiting_on === "agent");
24629
+ return [
24630
+ `${response.count} unanswered ${response.count === 1 ? "ask" : "asks"} you authored on active issues and project documents.`,
24631
+ "",
24632
+ `Waiting on human (${waitingOnHuman.length}):`,
24633
+ ...waitingOnHuman.map((ask) => openAskLine(ask, linkBase)),
24634
+ "",
24635
+ `Waiting on agent (${waitingOnAgent.length}):`,
24636
+ ...waitingOnAgent.map((ask) => openAskLine(ask, linkBase))
24637
+ ].join(`
24638
+ `);
24977
24639
  }
24978
- function agentLiveness(agent) {
24979
- return {
24980
- ...agent.state === undefined ? {} : { holder_state: agent.state },
24981
- ...agent.last_seen > 0 ? { last_seen: new Date(agent.last_seen).toISOString() } : {}
24982
- };
24640
+ function commentSummary({ comment, replies }, graph) {
24641
+ const root = [
24642
+ `${comment.id} \xB7 ${actorText(comment.author)}`,
24643
+ ...anchorLines(comment),
24644
+ ...replyBlockLines(comment),
24645
+ `Body: ${comment.body}`
24646
+ ];
24647
+ const chain = (replies ?? []).flatMap((reply) => [
24648
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
24649
+ ...anchorLines(reply),
24650
+ ...replyBlockLines(reply),
24651
+ ...reply.answers != null && reply.answers !== comment.id ? [`Answers: ${reply.answers}`] : [],
24652
+ `Body: ${reply.body}`
24653
+ ]);
24654
+ return [
24655
+ "Comment:",
24656
+ ...root,
24657
+ "Reply chain:",
24658
+ ...chain.length === 0 ? ["- none"] : chain,
24659
+ ...graph
24660
+ ].join(`
24661
+ `);
24983
24662
  }
24984
- function holdsSession(claim) {
24985
- return claim?.actor.kind === "session";
24663
+ function replyBlockLines(record) {
24664
+ const block = record.reply_block;
24665
+ if (block === undefined || block === null)
24666
+ return [];
24667
+ return [
24668
+ block.removed ? `Re: block ${block.block_id} (removed)` : `Re: block ${block.block_id}: ${textHead(block.text)}`
24669
+ ];
24986
24670
  }
24987
- function isRouteStatus(value) {
24988
- return ISSUE_ROUTE_STATUSES.some((status) => status === value);
24671
+ function anchorLines(record) {
24672
+ return [
24673
+ ...record.anchor?.quote === undefined ? [] : [`> ${record.anchor.quote}`],
24674
+ ...record.anchor_block === undefined ? [] : [`Position: ${positionText(record.anchor_block)}`],
24675
+ ...record.anchor_block_error === undefined ? [] : [`Position: unavailable (${record.anchor_block_error})`]
24676
+ ];
24989
24677
  }
24990
- function routeHeldBySession(issue) {
24991
- return issue.route_status === "live" && issue.route?.startsWith("role:") === true;
24678
+ function positionText(block) {
24679
+ const { table, path } = block;
24680
+ const segments = (path ?? []).map((entry) => `${entry.type}[${entry.index}]`);
24681
+ if (table === undefined || table.row === null)
24682
+ return segments.join(" \u203A ");
24683
+ const tableAt = (path ?? []).findIndex((entry) => entry.type === "table");
24684
+ const cells = table.cells ?? [];
24685
+ const label = (table.column === null ? cells : cells.slice(0, table.column)).map((cell) => cell.trim()).filter((cell) => cell !== "" && !/^\d+$/.test(cell)).join(" \xB7 ");
24686
+ const row = label === "" ? `row ${table.row}` : `row ${table.row} (${label})`;
24687
+ const header = table.header === null || table.header === "" ? String(table.column) : table.header;
24688
+ return [
24689
+ ...segments.slice(0, tableAt + 1),
24690
+ table.column === null ? row : `${row}, column ${header}`
24691
+ ].join(" \u203A ");
24992
24692
  }
24993
- function routeText(issue, titles) {
24994
- if (issue.route === null)
24995
- return "none";
24996
- const holder = issue.route_holder ?? null;
24997
- const reach = {
24998
- live: routeHeldBySession(issue) && holder !== null ? ` (held by ${titles?.get(holder) ?? holder})` : "",
24999
- holder_unresponsive: issue.route.startsWith("role:") ? ` (its holder${holder === null ? "" : ` ${titles?.get(holder) ?? holder}`} is unresponsive: messages wait for it)` : " (that session is unresponsive: messages wait for it)",
25000
- no_holder: issue.route.startsWith("role:") ? " (nobody holds it right now)" : " (that session is not running right now)",
25001
- unknown: issue.route_status_reason === "refilling" ? " (the Envoy listener's agent list is refilling, so whether it reaches anyone is unknown; try again in a moment)" : " (the Envoy listener did not answer, so whether it reaches anyone is unknown)"
25002
- };
25003
- const status = issue.route_status;
25004
- return issue.route + (status != null && isRouteStatus(status) ? reach[status] : "");
24693
+ function messageSummary({ message, replies }, graph) {
24694
+ const root = [
24695
+ `${message.id} \xB7 ${actorText(message.author)}`,
24696
+ ...replyBlockLines(message),
24697
+ `Body: ${message.body}`
24698
+ ];
24699
+ const chain = (replies ?? []).flatMap((reply) => [
24700
+ `${reply.id} \xB7 ${actorText(reply.author)}`,
24701
+ ...replyBlockLines(reply),
24702
+ `Body: ${reply.body}`
24703
+ ]);
24704
+ return [
24705
+ "Message:",
24706
+ ...root,
24707
+ "Reply chain:",
24708
+ ...chain.length === 0 ? ["- none"] : chain,
24709
+ ...graph
24710
+ ].join(`
24711
+ `);
25005
24712
  }
25006
- function progressText(progress, sep) {
25007
- if (progress === undefined)
25008
- return "";
25009
- const parts = [];
25010
- if (progress.tasks !== null)
25011
- parts.push(`tasks ${progress.tasks.done}/${progress.tasks.total}`);
25012
- if (progress.children !== null) {
25013
- parts.push(`children ${progress.children.done}/${progress.children.total}`);
24713
+ async function openAnchoredThreads(client, resolved) {
24714
+ const asksPromise = resolved.owner.kind === "project" ? client.getArtifactAsks(resolved.artifact.id) : Promise.resolve(resolved.issue?.open_asks ?? []);
24715
+ const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "");
24716
+ const commentsResultPromise = commentsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
24717
+ const asks = (await asksPromise).filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id);
24718
+ const commentsResult = await commentsResultPromise;
24719
+ if (commentsResult.status === "rejected" && !dispatchAnswered(commentsResult.reason, 404)) {
24720
+ throw commentsResult.reason;
25014
24721
  }
25015
- return parts.join(sep);
24722
+ const comments = commentsResult.status === "fulfilled" ? commentsResult.value : [];
24723
+ const askReplies = new Map(asks.map((ask) => [ask.id, []]));
24724
+ for (const comment of comments) {
24725
+ if (comment.ask_id)
24726
+ askReplies.get(comment.ask_id)?.push(comment);
24727
+ }
24728
+ const askThreads = asks.map((ask) => [
24729
+ `ask ${ask.id} \xB7 ${actorText(ask.author)} \xB7 ${ask.created_at}`,
24730
+ ...anchorLines(ask),
24731
+ `Question: ${ask.question}`,
24732
+ ...threadReplyLines(askReplies.get(ask.id) ?? [])
24733
+ ].join(`
24734
+ `));
24735
+ const byId = new Map(comments.map((comment) => [comment.id, comment]));
24736
+ const roots = comments.filter((comment) => comment.reply_to === null && !comment.ask_id && !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id);
24737
+ const replies = new Map(roots.map((root) => [root.id, []]));
24738
+ for (const comment of comments) {
24739
+ const root = comment.reply_to === null ? undefined : threadRootId(comment, byId);
24740
+ if (root !== undefined)
24741
+ replies.get(root)?.push(comment);
24742
+ }
24743
+ const commentThreads = roots.map((root) => [
24744
+ `comment ${root.id} \xB7 ${actorText(root.author)} \xB7 ${root.created_at}`,
24745
+ ...anchorLines(root),
24746
+ `Body: ${root.body}`,
24747
+ ...threadReplyLines(replies.get(root.id) ?? [])
24748
+ ].join(`
24749
+ `));
24750
+ return [...askThreads, ...commentThreads];
25016
24751
  }
25017
- function repositoryLine(issue) {
25018
- if (issue.resolved_repo === undefined) {
25019
- return "Repository: unknown (this Dispatch server predates repository fields; upgrade it)";
24752
+ function threadReplyLines(replies) {
24753
+ return replies.flatMap((reply) => [
24754
+ `reply ${reply.id} \xB7 ${actorText(reply.author)} \xB7 ${reply.created_at}`,
24755
+ `Body: ${reply.body}`
24756
+ ]);
24757
+ }
24758
+ function threadRootId(comment, byId) {
24759
+ const seen = new Set;
24760
+ let current = comment;
24761
+ while (current.reply_to !== null) {
24762
+ if (seen.has(current.id))
24763
+ return;
24764
+ seen.add(current.id);
24765
+ const parent = byId.get(current.reply_to);
24766
+ if (parent === undefined)
24767
+ return;
24768
+ current = parent;
25020
24769
  }
25021
- if (issue.resolved_repo === null)
25022
- return "Repository: none";
25023
- if (issue.repo !== null && issue.repo !== undefined)
25024
- return `Repository: ${issue.repo} (own)`;
25025
- return `Repository: ${issue.resolved_repo} (inherited or project default)`;
24770
+ return current.id;
25026
24771
  }
25027
- function olderServerWarnings(issue) {
25028
- const warnings = [
25029
- ...issue.resolved_repo !== undefined ? [] : [
25030
- `dispatch: warning: Dispatch issue is missing resolved_repo: this Dispatch server predates repository fields, so ${issue.key}'s repository is unknown; upgrade the server`
25031
- ],
25032
- ...issue.advances !== undefined ? [] : [
25033
- `dispatch: warning: Dispatch issue is missing advances: this Dispatch server predates priorities, so the priorities ${issue.key} advances are unknown; upgrade the server`
25034
- ]
24772
+
24773
+ // ../envoy-client/src/dispatch-commands/asks.ts
24774
+ function askUrgency(args) {
24775
+ const value = args.urgency;
24776
+ return ASK_URGENCIES.find((urgency) => urgency === value);
24777
+ }
24778
+ var askHintLimit = 8;
24779
+ function openAskChoices(asks, owner) {
24780
+ if (asks.length === 0)
24781
+ return `${owner} holds no open ask.`;
24782
+ const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)}\u2026 ${textHead(ask.question)}`);
24783
+ return `The open asks of ${owner} are: ${hints.join(", ")}.`;
24784
+ }
24785
+ function askIDInputProblem(asks, owner) {
24786
+ return `ask ids are uuids. Write the whole id, or at least its first 8 characters. ${openAskChoices(asks, owner)}`;
24787
+ }
24788
+ async function movedApprovalLine(client, askID) {
24789
+ const ask = (await client.getAsk(askID).catch(() => {
24790
+ return;
24791
+ }))?.ask;
24792
+ const approval = ask?.approval;
24793
+ if (ask?.kind !== "approval" || approval === undefined)
24794
+ return;
24795
+ const listed = approval.documents ?? [];
24796
+ const documents = listed.length > 0 ? listed : [
24797
+ {
24798
+ name: approval.name,
24799
+ requested_version: approval.requested_version,
24800
+ version: approval.version
24801
+ }
25035
24802
  ];
25036
- return warnings.length === 0 ? {} : { warnings };
24803
+ const moved = movedApprovalDocuments(documents);
24804
+ if (moved.length === 0)
24805
+ return;
24806
+ const firstMoved = moved[0];
24807
+ if (firstMoved === undefined)
24808
+ return;
24809
+ const command = handBackApprovalCommand({
24810
+ owner: ask.issue_key === null ? { kind: "project", key: ask.approval_artifact?.project ?? "<project>" } : { kind: "issue", key: ask.issue_key },
24811
+ artifactID: approval.artifact_id,
24812
+ primary: ask.approval_artifact?.primary === true,
24813
+ verification: documents.length > 1 && ask.approval_artifact?.primary === true,
24814
+ summaryVersion: firstMoved.requested_version
24815
+ });
24816
+ return "The reply did not hand the ask to the human: it is an open approval request, and " + `${movedApprovalClauses(moved)}. No reply hands a moved approval request back. Once the ` + `human has agreed to every point in it, run: ${command}`;
25037
24817
  }
25038
- function issueSummary(issue, events, references, graph, linkBase, coverage, agents) {
25039
- const asks = issue.open_asks ?? [];
25040
- const labels = issue.labels ?? [];
25041
- const links = issue.external_links ?? [];
25042
- const members = typeof references === "string" ? [] : references.members ?? [];
25043
- const spec = issue.artifacts?.find((artifact) => artifact.primary);
25044
- const specApproval = spec === undefined ? undefined : approvalLine(spec, typeof issue.closed_at === "string");
25045
- if (issue.priority === undefined)
25046
- throw new Error("Dispatch issue is missing priority");
25047
- if (issue.assignee === undefined)
25048
- throw new Error("Dispatch issue is missing assignee");
25049
- if (issue.components === undefined)
25050
- throw new Error("Dispatch issue is missing components");
25051
- if (issue.claim === undefined)
25052
- throw new Error("Dispatch issue is missing claim");
25053
- if (issue.external_links === undefined) {
25054
- throw new Error("Dispatch issue is missing external_links");
24818
+ async function replyToAskCandidates(client, owner, resolved) {
24819
+ if (owner.kind === "issue") {
24820
+ const issue = resolved?.issue ?? await client.getIssue(owner.issue);
24821
+ return { asks: issue.open_asks ?? [], owner: "this issue" };
25055
24822
  }
25056
- return [
25057
- `Title: ${issue.title}`,
25058
- `Key: ${issue.key}`,
25059
- `Link: ${linkFor(`/issues/${encodeURIComponent(issue.key)}`, linkBase)}`,
25060
- `Status: ${issue.status}`,
25061
- `Assignee: ${issue.assignee ?? "unassigned"}`,
25062
- `Claimed by: ${issue.claim === null ? "nobody" : claimText(issue.claim, agents, issue)}`,
25063
- ...issue.priority === null ? [] : [`Priority: P${issue.priority}`],
25064
- `Labels: ${labels.length === 0 ? "none" : labels.join(", ")}`,
25065
- componentsLine(issue.components),
25066
- advancesLine(issue),
25067
- `Route: ${routeText(issue, agents?.titles)}`,
25068
- repositoryLine(issue),
25069
- `Progress: ${progressText(issue.progress, ", ") || "none"}`,
25070
- ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
25071
- ...typeof coverage === "string" ? [`Coverage: ${coverage}`] : (coverage.gaps ?? []).map((gap) => `Coverage: ${gap}`),
25072
- "External links:",
25073
- ...links.length === 0 ? ["- none"] : links.map((link) => `- ${link.url}${link.kind === undefined ? "" : ` (${link.kind})`}`),
25074
- "Documents:",
25075
- ...documentListLines(issue.artifacts ?? []),
25076
- "Open asks:",
25077
- ...asks.length === 0 ? ["- none"] : asks.map((ask) => `- ${ask.id}: ${ask.question}`),
25078
- "References:",
25079
- ...typeof references === "string" ? [`- ${references}`] : members.length === 0 ? ["- none"] : members.map(({ artifact, depth, via }) => `- ${artifact.project}/${artifact.slug} \xB7 depth ${depth} via ${via.kind} ${via.id}`),
25080
- ...typeof references === "string" || !references.truncated ? [] : ["- more references beyond 8 hops"],
25081
- "Events:",
25082
- ...events.length === 0 ? ["- none"] : events.map(eventLine),
25083
- ...graph
25084
- ].join(`
25085
- `);
24823
+ if (resolved === undefined)
24824
+ throw new Error("project document is missing its resolved artifact");
24825
+ return {
24826
+ asks: await client.getArtifactAsks(resolved.artifact.id, "open"),
24827
+ owner: "this document"
24828
+ };
25086
24829
  }
25087
- function logSummary(issue, events) {
25088
- return [
25089
- `Key: ${issue.key}`,
25090
- "Events:",
25091
- ...events.length === 0 ? ["- none"] : events.map(eventLine)
25092
- ].join(`
25093
- `);
24830
+ async function resolveReplyToAsk(tool, client, target, resolved, id) {
24831
+ const whole = normalizeUUID(id);
24832
+ if (whole !== undefined)
24833
+ return whole;
24834
+ const { asks, owner } = await replyToAskCandidates(client, target, resolved);
24835
+ if (!isIdPrefix(id)) {
24836
+ throw new ToolInputError(tool, [askIDInputProblem(asks, owner)], { aboutAFlag: false });
24837
+ }
24838
+ return resolveIdPrefix(tool, "ask", id, owner, async () => asks, {
24839
+ refusal: (found, all) => found.length === 0 ? `reply_to_ask ${id} names no open ask of ${owner}. ${openAskChoices(all, owner)}` : `reply_to_ask ${id} names ${found.length} open asks of ${owner}. Write more of the id. ${openAskChoices(all, owner)}`
24840
+ });
25094
24841
  }
25095
- function eventHead(event) {
25096
- switch (event.type) {
25097
- case "ask.opened":
25098
- case "ask.anchor_refreshed":
25099
- case "ask.edited":
25100
- case "ask.handed_back":
25101
- case "ask.resolved":
25102
- return textHead(event.payload.question);
25103
- case "ask.answered": {
25104
- const previousAnswer = event.payload.previous_answer;
25105
- return `${textHead(event.payload.question)} -> ${textHead(askAnswerText(event.payload.answer))}${previousAnswer === undefined ? "" : ` (was: ${textHead(askAnswerText(previousAnswer))})`}`;
25106
- }
25107
- case "ask.asked_of":
25108
- return `${textHead(event.payload.question)} -> asked of ${event.payload.asked_of ?? "the assignee of its issue"}`;
25109
- case "comment.created":
25110
- case "comment.answered":
25111
- case "comment.anchor_refreshed":
25112
- case "comment.edited":
25113
- case "comment.resolved":
25114
- case "comment.reopened":
25115
- case "suggestion.accepted":
25116
- case "suggestion.rejected":
25117
- case "message.created":
25118
- case "message.answered":
25119
- return textHead(event.payload.body);
25120
- case "artifact.version":
25121
- return textHead(`${event.payload.name} v${event.payload.version.number}${event.payload.version.summary ? `: ${event.payload.version.summary}` : ""}`);
25122
- case "artifact.approved":
25123
- case "artifact.changes_requested": {
25124
- const { name, version, kind, reason } = event.payload;
25125
- const verb = event.type === "artifact.approved" ? "approved" : "changes requested";
25126
- const reviewer = kind === "plan_review" ? " by plan review" : kind === "person" ? " by a person" : "";
25127
- return textHead(`${name} v${version} ${verb}${reviewer}${reason ? `: ${reason}` : ""}`);
24842
+ var askIdShapeProblem = "ask ids are uuids (a prefix of at least 8 hex characters works)";
24843
+ async function readAskRef(tool, id, ownerName, client, list) {
24844
+ const fullID = normalizeUUID(id);
24845
+ if (fullID !== undefined) {
24846
+ try {
24847
+ return await client.getAsk(fullID);
24848
+ } catch (error) {
24849
+ if (!(error instanceof DispatchServiceError) || error.status !== 404)
24850
+ throw error;
24851
+ const blocks = (await list()).filter((ask) => ask.block_id?.toLowerCase() === fullID);
24852
+ if (blocks.length !== 1 || blocks[0] === undefined)
24853
+ throw error;
24854
+ return client.getAsk(blocks[0].id);
25128
24855
  }
25129
- case "artifact.human_edited":
25130
- return textHead(humanEditHead(event.payload));
25131
- case "issue.created": {
25132
- const forced = event.payload.forced;
25133
- const head = `status ${event.payload.status}`;
25134
- if (forced === undefined)
25135
- return head;
25136
- return forced.past.length === 0 ? `${head} \xB7 forced, the near-copy check did not answer` : `${head} \xB7 forced past ${forced.past.join(", ")}`;
24856
+ }
24857
+ const asks = await list();
24858
+ let matches = asks.filter((ask) => ask.block_id === id);
24859
+ if (matches.length === 0) {
24860
+ if (!isIdPrefix(id)) {
24861
+ throw new ToolInputError(tool, [
24862
+ `ask id ${id} must be a full uuid, a prefix of at least 8 hex characters, or the id of an :::ask block on ${ownerName}`
24863
+ ]);
25137
24864
  }
25138
- case "issue.updated":
25139
- case "issue.closed":
25140
- return `status ${event.payload.status}`;
25141
- default:
24865
+ const prefix = id.toLowerCase();
24866
+ matches = asks.filter((ask) => ask.id.toLowerCase().startsWith(prefix) || (ask.block_id?.toLowerCase().startsWith(prefix) ?? false));
24867
+ }
24868
+ if (matches.length === 1 && matches[0] !== undefined)
24869
+ return client.getAsk(matches[0].id);
24870
+ throw new ToolInputError(tool, [
24871
+ matches.length === 0 ? `ask id ${id} matches none of the asks on ${ownerName}; use the full id` : `ask id ${id} matches ${matches.length} asks on ${ownerName}; use the full id`
24872
+ ]);
24873
+ }
24874
+ async function sessionOpenAsks(client, sessionId) {
24875
+ const session = sessionId?.trim();
24876
+ if (!session)
24877
+ throw new Error("host session id is required to read this session's open asks");
24878
+ return (await client.openAsks(session)).asks ?? [];
24879
+ }
24880
+ function openAskHints(asks) {
24881
+ if (asks.length === 0)
24882
+ return "you have no open asks";
24883
+ const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)} \u2014 ${textHead(ask.question)}`);
24884
+ return `your open asks: ${hints.join("; ")}`;
24885
+ }
24886
+ async function resolveAskArgument(tool, args, client, sessionId) {
24887
+ const id = askId(args);
24888
+ if (normalizeUUID(id) === undefined && !isIdPrefix(id)) {
24889
+ const asks = await sessionOpenAsks(client, sessionId).catch(() => {
25142
24890
  return;
24891
+ });
24892
+ throw new ToolInputError(tool, [
24893
+ asks === undefined ? askIdShapeProblem : `${askIdShapeProblem}; ${openAskHints(asks)}`
24894
+ ]);
25143
24895
  }
24896
+ const resolved = await resolveIdPrefix(tool, "ask", id, "this session", () => sessionOpenAsks(client, sessionId));
24897
+ const reference = stringArg(args, "ask");
24898
+ const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
24899
+ if (ref === null)
24900
+ return { id: resolved };
24901
+ const read = await client.getAsk(resolved);
24902
+ await refuseItemOffRef(tool, "ask", ref, reference, read.ask, async () => {
24903
+ const document = await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true });
24904
+ return document.artifact.id;
24905
+ });
24906
+ return { id: resolved, read };
25144
24907
  }
25145
- function eventRef(event) {
25146
- const payload = event.payload;
25147
- const id = typeof payload === "object" && payload !== null && "id" in payload ? payload.id : undefined;
25148
- if (typeof id !== "string" || id === "" || event.issue_key === null)
25149
- return;
25150
- const kind = event.type.startsWith("message.") ? "message" : event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("ask.") ? "ask" : undefined;
25151
- return kind === undefined ? undefined : `dispatch://${event.issue_key}/${kind}/${id}`;
24908
+ async function openAsksCommand(context) {
24909
+ const { input, linkBase, ownerArguments, newClient: dispatchClient } = context;
24910
+ const client = dispatchClient();
24911
+ const project = optionalString(ownerArguments.args, "project");
24912
+ if (project !== undefined) {
24913
+ const response = await client.openAsksForProject(project);
24914
+ return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
24915
+ }
24916
+ const sessionId = input.sessionId?.trim();
24917
+ if (!sessionId)
24918
+ throw new Error("host session id is required for dispatch open-asks");
24919
+ const response = await client.openAsks(sessionId);
24920
+ return { text: formatOpenAsksSummary(response, linkBase), details: { ...response } };
25152
24921
  }
25153
- function eventActorText(actor) {
25154
- const title = actor.kind === "session" ? actor.origin?.session_title : undefined;
25155
- return title === undefined || title === "" ? actorText(actor) : `${actorText(actor)} (${title})`;
24922
+ async function askCommand(context) {
24923
+ const {
24924
+ args,
24925
+ client,
24926
+ actor,
24927
+ input,
24928
+ linkBase,
24929
+ documentOwner,
24930
+ resolveDocument,
24931
+ writePictures,
24932
+ issue
24933
+ } = context;
24934
+ const anchorArgs = asObject(args.anchor);
24935
+ const owner = documentOwner();
24936
+ const artifactReference = optionalString(args, "artifact") ?? (anchorArgs === null ? undefined : optionalString(anchorArgs, "artifact"));
24937
+ const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
24938
+ const options = args.options;
24939
+ const multiple = optionalBoolean(args, "multiple");
24940
+ const urgency = askUrgency(args);
24941
+ const anchored = anchorArgs && resolved ? anchor(resolved.artifact, anchorArgs) : undefined;
24942
+ const question = await writePictures(resolved, askQuestionWithRef(args));
24943
+ const askInput = {
24944
+ question,
24945
+ ...Array.isArray(options) ? { options } : {},
24946
+ ...multiple === undefined ? {} : { multiple },
24947
+ ...urgency === undefined ? {} : { urgency },
24948
+ ...anchored === undefined ? {} : { anchor: anchored },
24949
+ actor
24950
+ };
24951
+ const ask = resolved?.owner.kind === "project" ? await client.artifactAsk(resolved.artifact.id, askInput) : await client.ask(issue(), askInput);
24952
+ const askOwner = ask.issue_key !== null ? issueTopic(ask.issue_key) : resolved === undefined ? issueTopic(issue()) : documentTopic(resolved.artifact);
24953
+ const checkLines = relatedCheckLines(ask.advice?.suggestions, {
24954
+ project: resolved?.artifact.project ?? (ask.issue_key ?? "").replace(/-[0-9]+$/, ""),
24955
+ text: stringArg(args, "question"),
24956
+ linkBase
24957
+ });
24958
+ const declinedLines = ask.issue_key === null ? [] : declinedAskLines(ask.advice, ask.issue_key, linkBase);
24959
+ const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, askOwner.label, ask.advice, {}));
24960
+ const asked = waitsOnPerson(ask);
24961
+ return {
24962
+ text: [
24963
+ `Asked ${ask.id} on ${askOwner.label} (urgency ${ask.urgency})${asked === undefined ? "" : `, waiting on ${asked}`}: ${ask.question}`,
24964
+ ...checkLines,
24965
+ ...declinedLines,
24966
+ await followsAsk(askOwner, input.subscriptions),
24967
+ ...adviceLines
24968
+ ].join(`
24969
+ `),
24970
+ details: {
24971
+ ...await followedAskDetails(client, ask, resolved?.artifact),
24972
+ ...ask.advice === undefined ? {} : { advice: ask.advice }
24973
+ }
24974
+ };
25156
24975
  }
25157
- function eventLine(event) {
25158
- const head = eventHead(event);
25159
- const ref = eventRef(event);
25160
- return `- #${event.seq} ${event.type}${ref === undefined ? "" : ` ${ref}`} \xB7 ${eventActorText(event.actor)} \xB7 ${event.created_at}${head === undefined || head === "" ? "" : ` \xB7 ${head}`}`;
24976
+ async function editAskCommand(context) {
24977
+ const { args, client, actor, input } = context;
24978
+ const question = optionalString(args, "question");
24979
+ const options = args.options;
24980
+ const multiple = optionalBoolean(args, "multiple");
24981
+ const urgency = askUrgency(args);
24982
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
24983
+ const ask = await client.editAsk(id, {
24984
+ ...question === undefined ? {} : { question },
24985
+ ...Array.isArray(options) ? { options } : {},
24986
+ ...multiple === undefined ? {} : { multiple },
24987
+ ...urgency === undefined ? {} : { urgency },
24988
+ actor
24989
+ });
24990
+ return {
24991
+ text: `Ask edited: ${ask.question}`,
24992
+ details: await askOwnerDetails(client, ask)
24993
+ };
25161
24994
  }
25162
- function childrenSummary(issue) {
25163
- return [
25164
- `Key: ${issue.key}`,
25165
- "Children:",
25166
- ...(issue.children ?? []).length === 0 ? ["- none"] : (issue.children ?? []).map((child) => `- ${child.key}: ${child.title} (${child.status})`)
25167
- ].join(`
25168
- `);
24995
+ async function resolveAskCommand(context) {
24996
+ const { args, client, actor, input } = context;
24997
+ const kind = stringArg(args, "kind");
24998
+ const { id } = await resolveAskArgument(input.tool, args, client, input.sessionId);
24999
+ const ask = await client.resolveAsk(id, {
25000
+ kind,
25001
+ reason: stringArg(args, "reason"),
25002
+ actor
25003
+ });
25004
+ if (ask.resolution === undefined)
25005
+ throw new Error("resolved ask is missing its resolution");
25006
+ return {
25007
+ text: `${kind === "retracted" ? "Retracted" : "Resolved"} ask ${ask.id}: ${ask.resolution.reason}`,
25008
+ details: await askOwnerDetails(client, ask)
25009
+ };
25169
25010
  }
25170
-
25171
- // ../envoy-client/src/dispatch-commands/issues.ts
25172
- function componentsChange(input, after) {
25173
- switch (input.mode) {
25174
- case "explicit":
25175
- return `components -> explicit [${(after.ids ?? []).join(", ")}]`;
25176
- case "none":
25177
- return `components -> none (${after.reason ?? input.reason ?? ""})`;
25178
- case "inherit":
25179
- return "components -> inherit";
25180
- default:
25181
- return `components -> ${input.mode}`;
25011
+ async function followCommand(context) {
25012
+ const { args, client, actor, input } = context;
25013
+ const sessionId = input.sessionId?.trim();
25014
+ if (!sessionId)
25015
+ throw new Error("host session id is required for dispatch follow");
25016
+ const { id: ask, read: refRead } = await resolveAskArgument(input.tool, args, client, sessionId);
25017
+ const action = stringArg(args, "action");
25018
+ if (action === "unfollow") {
25019
+ await client.unfollowAsk(ask, sessionId, actor);
25020
+ return { text: `Unfollowed ask ${ask}.`, details: { ask } };
25182
25021
  }
25022
+ const read = refRead ?? await client.getAsk(ask);
25023
+ await client.followAsk(ask, sessionId, actor);
25024
+ return {
25025
+ text: `Following ask ${ask}: its answer and replies reach this session directly.`,
25026
+ details: await followedAskDetails(client, read.ask)
25027
+ };
25183
25028
  }
25184
- var architectureComponentsAction = 'Review the `dispatch` skill, "Architecture components", to attach it to the parts it changes or mark it as non-architectural with a reason.';
25185
- var LEGION_OWNS_STATUS = "Legion's daemon moves this issue's status on an issue it runs, so leave it alone \u2014 a status written here is undone.";
25186
- async function architectureGuidance(client, project, components) {
25187
- if (components.mode === "none" || (components.ids ?? []).length > 0)
25188
- return;
25189
- try {
25190
- if ((await client.listArchitectureSources(project)).length === 0)
25191
- return;
25192
- return `Project ${project} has an architecture model, but this issue is not linked to any of its current components. ${architectureComponentsAction}`;
25193
- } catch (error) {
25194
- return `Could not check whether project ${project} has an architecture model: ${messageFor(error)}. ${architectureComponentsAction}`;
25029
+
25030
+ // ../envoy-client/src/dispatch-commands/conversation.ts
25031
+ async function resolveCommentCommand(context) {
25032
+ const { args, client, actor, input } = context;
25033
+ const reference = stringArg(args, "comment");
25034
+ const ref = reference.startsWith("dispatch://") ? parseDispatchRef(reference) : null;
25035
+ let id = reference;
25036
+ let document;
25037
+ if (ref?.owner.kind === "issue") {
25038
+ const issueKey = ref.owner.issue;
25039
+ id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getComments(issueKey));
25040
+ } else if (ref !== null) {
25041
+ const artifact = (await resolveArtifact(client, ref.owner, ref.artifact, { canonical: true })).artifact;
25042
+ document = artifact;
25043
+ id = await resolveIdPrefix(input.tool, "comment", ref.id, refOwnerName(ref), () => client.getArtifactComments(artifact.id));
25195
25044
  }
25196
- }
25197
- function isDuplicateCandidate(value) {
25198
- if (typeof value !== "object" || value === null)
25199
- return false;
25200
- const candidate = value;
25201
- return typeof candidate.key === "string" && typeof candidate.title === "string" && typeof candidate.status === "string" && typeof candidate.snippet === "string" && typeof candidate.shared_terms === "number" && typeof candidate.href === "string";
25202
- }
25203
- function duplicateCandidates(error) {
25204
- if (error.candidates === undefined || !error.candidates.every(isDuplicateCandidate))
25205
- throw error;
25206
- return error.candidates;
25207
- }
25208
- function refuseUnsavedRepository(verb, issue, repo) {
25209
- if (repo === undefined || issue.repo !== undefined)
25210
- return;
25211
- const lost = repo === "" ? "the repository was not cleared" : `${repo} was not saved`;
25212
- throw new Error(`Dispatch ${verb} ${issue.key} without its repository: this Dispatch server predates repository fields, so ${lost}; upgrade the server`);
25213
- }
25214
- function advancesRevisionToSend(issue, named) {
25215
- if (issue.advances_revision === undefined) {
25216
- throw new Error(`Dispatch read ${issue.key} without its advances: this Dispatch server predates priorities, so nothing was sent; upgrade the server`);
25045
+ if (ref !== null) {
25046
+ const read = await client.getComment(id);
25047
+ await refuseItemOffRef(input.tool, "comment", ref, reference, read.comment, async () => document === undefined ? "" : document.id);
25217
25048
  }
25218
- return named ?? issue.advances_revision;
25049
+ const comment = await client.resolveComment(id, actor);
25050
+ const { label, details } = await commentOwnerResult(client, comment, document);
25051
+ return { text: `Resolved comment ${comment.id} on ${label}.`, details };
25219
25052
  }
25220
- async function issueCommand(context) {
25221
- const { args, client, actor, input, linkBase } = context;
25222
- const project = stringArg(args, "project");
25223
- const title = stringArg(args, "title");
25224
- const parent = optionalString(args, "parent");
25225
- const external = optionalString(args, "external");
25226
- const force = optionalBoolean(args, "force");
25227
- const spec = optionalString(args, "spec");
25228
- const priority = optionalPriority(args, "priority");
25229
- const assignee = optionalString(args, "assignee");
25230
- const components = optionalComponents(args, "components");
25231
- const repo = optionalString(args, "repo");
25232
- const labels = args.labels;
25233
- const blockedBy = args.blocked_by;
25234
- const advances = optionalStringArray(args, "advances");
25235
- try {
25236
- const created = await client.issue({
25237
- project,
25238
- title,
25239
- ...parent === undefined ? {} : { parent },
25240
- ...Array.isArray(blockedBy) ? { blocked_by: blockedBy } : {},
25241
- ...advances === undefined ? {} : { advances },
25242
- ...external === undefined ? {} : { external },
25243
- ...force === undefined ? {} : { force },
25244
- ...spec === undefined ? {} : { spec },
25245
- ...priority === undefined ? {} : { priority },
25246
- ...assignee === undefined ? {} : { assignee },
25247
- ...components === undefined ? {} : { components },
25248
- ...repo === undefined ? {} : { repo },
25249
- ...Array.isArray(labels) ? { labels } : {},
25250
- actor
25251
- });
25252
- refuseUnsavedRepository(created.created ? "created" : "already holds", created, repo);
25253
- const adviceLines = await otherAdviceLines(async () => {
25254
- const componentGuidance = await architectureGuidance(client, created.project, created.components);
25255
- return [
25256
- ...renderAdvice(input.tool, created.key, created.advice, {
25257
- isPrimarySpec: spec !== undefined
25258
- }),
25259
- ...componentGuidance === undefined ? [] : [componentGuidance]
25260
- ];
25261
- });
25262
- const href = linkFor(`/issues/${encodeURIComponent(created.key)}`, linkBase);
25263
- const assigned = created.assignee === undefined ? "" : created.assignee === null ? "; unassigned" : `; assigned to ${created.assignee}`;
25264
- const suffixes = `${assigned}${await notSubscribed(issueTopic(created.key), input.subscriptions)}`;
25053
+ async function commentCommand(context) {
25054
+ const { args, client, actor, input, documentOwner, resolveDocument, writePictures, issue } = context;
25055
+ const artifactReference = optionalString(args, "artifact");
25056
+ const owner = documentOwner();
25057
+ const resolved = owner.kind === "project" || artifactReference === undefined ? owner.kind === "project" ? await resolveDocument(owner, artifactReference) : undefined : await resolveDocument(owner, artifactReference);
25058
+ const anchored = resolved ? anchor(resolved.artifact, args) : undefined;
25059
+ const replyTo = itemReplyTo(args, "reply_to");
25060
+ const replyToAskTarget = itemReplyTo(args, "reply_to_ask");
25061
+ const replyToAsk = replyToAskTarget === undefined ? undefined : await resolveReplyToAsk(input.tool, client, owner, resolved, replyToAskTarget.id);
25062
+ const replyToBlock = replyTo?.block ?? replyToAskTarget?.block;
25063
+ const requestedTurn = optionalString(args, "turn");
25064
+ const body = await writePictures(resolved, stringArg(args, "body"));
25065
+ const commentInput = {
25066
+ body,
25067
+ ...anchored === undefined ? {} : { anchor: anchored },
25068
+ ...replyTo === undefined ? {} : { reply_to: replyTo.id },
25069
+ ...replyToBlock === undefined ? {} : { reply_to_block: replyToBlock },
25070
+ ...replyToAsk === undefined ? {} : { ask_id: replyToAsk },
25071
+ ...requestedTurn === undefined ? {} : { turn: requestedTurn },
25072
+ actor
25073
+ };
25074
+ const comment = resolved?.owner.kind === "project" ? await client.artifactComment(resolved.artifact.id, commentInput) : await client.comment(issue(), commentInput);
25075
+ const commentOwner = resolved === undefined ? issueTopic(issue()) : resolvedTopic(resolved);
25076
+ const commentDetails = resolved === undefined ? { issue: comment.issue_key, comment: comment.id } : writeResultDetails(resolved, { comment: comment.id });
25077
+ const adviceLines = renderAdvice(input.tool, commentOwner.label, comment.advice, {
25078
+ isAskReply: replyToAsk !== undefined,
25079
+ replyToOwnAsk: replyToAsk !== undefined && (comment.advice?.your_open_asks?.some((ask) => ask.id === replyToAsk) ?? false)
25080
+ });
25081
+ if (replyToAsk !== undefined) {
25082
+ const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
25083
+ const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
25265
25084
  return {
25266
25085
  text: [
25267
- created.created ? `Created ${created.key}: ${created.title} \u2192 ${href}${suffixes}` : `Dispatch already holds ${created.key}: ${created.title} \u2192 ${href}; nothing was created${suffixes}`,
25268
- ...created.created ? relatedCheckLines(created.advice?.suggestions, {
25269
- project: created.project,
25270
- text: title,
25271
- linkBase
25272
- }) : [],
25086
+ `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
25087
+ ...moved === undefined ? [] : [moved],
25273
25088
  ...adviceLines
25274
25089
  ].join(`
25275
25090
  `),
25276
25091
  details: {
25277
- issue: created.key,
25278
- ...created.advice === undefined ? {} : { advice: created.advice }
25092
+ ...commentDetails,
25093
+ ask: replyToAsk,
25094
+ follows: { ask: replyToAsk },
25095
+ ...comment.ask_waiting_on === undefined ? {} : { ask_waiting_on: comment.ask_waiting_on },
25096
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
25097
+ }
25098
+ };
25099
+ }
25100
+ return {
25101
+ text: [
25102
+ `Posted comment ${comment.id}${await notSubscribed(commentOwner, input.subscriptions)}`,
25103
+ ...adviceLines
25104
+ ].join(`
25105
+ `),
25106
+ details: {
25107
+ ...commentDetails,
25108
+ ...comment.advice === undefined ? {} : { advice: comment.advice }
25109
+ }
25110
+ };
25111
+ }
25112
+ async function suggestCommand(context) {
25113
+ const { args, client, actor, input, documentOwner, resolveDocument, issue } = context;
25114
+ const resolved = await resolveDocument(documentOwner(), stringArg(args, "artifact"));
25115
+ const anchored = anchor(resolved.artifact, args);
25116
+ if (anchored === undefined)
25117
+ throw new Error("quote is required");
25118
+ const body = optionalString(args, "body");
25119
+ const suggestionInput = {
25120
+ ...body === undefined ? {} : { body },
25121
+ anchor: anchored,
25122
+ replace_with: stringArg(args, "replace_with"),
25123
+ actor
25124
+ };
25125
+ const comment = resolved.owner.kind === "project" ? await client.artifactSuggest(resolved.artifact.id, suggestionInput) : await client.suggest(issue(), suggestionInput);
25126
+ return {
25127
+ text: `Posted suggestion ${comment.id}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
25128
+ details: writeResultDetails(resolved, { comment: comment.id })
25129
+ };
25130
+ }
25131
+ function conversationReadBack(messageId) {
25132
+ return `${commandLine("dispatch_read", { message: messageId })} reads the conversation back.`;
25133
+ }
25134
+ async function messageCommand(context) {
25135
+ const { args, client, actor, input, owner, pictures, postWithPictures, issue } = context;
25136
+ const target = messageInReplyTo(args);
25137
+ const inReplyTo = target?.id;
25138
+ const written = stringArg(args, "body");
25139
+ if (owner === null && inReplyTo !== undefined) {
25140
+ let body = written;
25141
+ if (pictures.length > 0) {
25142
+ const sessionId = input.sessionId?.trim();
25143
+ if (!sessionId) {
25144
+ throw new Error("host session id is required to send pictures in a direct-message reply");
25279
25145
  }
25280
- };
25281
- } catch (error) {
25282
- if (!(error instanceof DispatchServiceError) || error.code !== "POSSIBLE_DUPLICATE") {
25283
- throw error;
25146
+ body = await postWithPictures(written, `agent/${sessionId}`, (upload) => client.agentArtifact(sessionId, upload));
25284
25147
  }
25285
- const candidates = duplicateCandidates(error);
25148
+ const reply = await client.messageReply(inReplyTo, { body, attempt: 1, actor }, { followUp: true });
25149
+ if (reply.duplicate === true && reply.body === body) {
25150
+ return {
25151
+ text: `Dispatch already has this exact text in the conversation (message ${reply.id}); ` + "nothing new was posted. Send different text if you have more to say.",
25152
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false, duplicate: true }
25153
+ };
25154
+ }
25155
+ if (reply.body !== body) {
25156
+ return {
25157
+ text: `Message ${inReplyTo} was already answered by message ${reply.id}; Dispatch kept ` + "that reply and posted nothing. Wait for their next message rather than answering " + "this one again.",
25158
+ details: { message: reply.id, in_reply_to: inReplyTo, posted: false }
25159
+ };
25160
+ }
25161
+ const readBack = conversationReadBack(inReplyTo);
25162
+ const parent = reply.in_reply_to ?? undefined;
25163
+ const follows = parent === inReplyTo ? undefined : parent;
25286
25164
  return {
25287
- text: [
25288
- `Not created: "${title}" is a near copy of an open issue.`,
25289
- ...candidates.map((candidate) => {
25290
- const href = linkFor(candidate.href, linkBase);
25291
- return `${candidate.key} [${candidate.status}] ${candidate.title} \u2192 ${href}`;
25292
- }),
25293
- "Read each issue above. If one is the same work, fold this into it by the duplicate rule of skill://dispatch-first.",
25294
- "If none is, run dispatch issue again with --force, and write in the new issue's spec why it is not each issue named here."
25295
- ].join(`
25296
- `),
25297
- details: { duplicates: candidates },
25298
- refused: true
25165
+ text: follows === undefined ? `Replied to message ${inReplyTo} with message ${reply.id}. ${readBack}` : `Replied to message ${inReplyTo} with message ${reply.id}, a follow-up threaded ` + `under your reply ${follows}. ${readBack}`,
25166
+ details: {
25167
+ message: reply.id,
25168
+ in_reply_to: inReplyTo,
25169
+ posted: true,
25170
+ ...follows === undefined ? {} : { follows }
25171
+ }
25299
25172
  };
25300
25173
  }
25301
- }
25302
- async function issueUpdateCommand(context) {
25303
- const { args, client, actor, input, issue } = context;
25304
25174
  const issueKey = issue();
25305
- const status = optionalString(args, "status");
25306
- const reason = optionalString(args, "reason");
25307
- const title = optionalString(args, "title");
25308
- const route = optionalString(args, "route");
25309
- const parent = optionalString(args, "parent");
25310
- const components = optionalComponents(args, "components");
25311
- const repo = optionalString(args, "repo");
25312
- const rankBefore = optionalString(args, "before");
25313
- const rankAfter = optionalString(args, "after");
25314
- const priority = optionalPriority(args, "priority");
25315
- const assignee = optionalNullableString(args, "assignee");
25316
- const labels = Array.isArray(args.labels) ? args.labels : undefined;
25317
- const blockedBy = Array.isArray(args.blocked_by) ? args.blocked_by : undefined;
25318
- const advances = optionalStringArray(args, "advances");
25319
- const advancesRevision = optionalNumber(args, "advances_revision");
25320
- const requestedLinks = Array.isArray(args.external_links) ? [...new Set(args.external_links)] : undefined;
25321
- let before;
25322
- try {
25323
- before = await client.getIssue(issueKey);
25324
- } catch (error) {
25325
- throw refusalWithCode(error);
25175
+ const body = await postWithPictures(written, issueKey, (upload) => client.artifact(issueKey, upload));
25176
+ const message = await client.message(issueKey, {
25177
+ body,
25178
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo },
25179
+ ...target?.block === undefined ? {} : { in_reply_to_block: target.block },
25180
+ actor
25181
+ });
25182
+ const messageRef = dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id);
25183
+ const adviceLines = renderAdvice(input.tool, issueKey, message.advice, {});
25184
+ return {
25185
+ text: [
25186
+ `Posted message ${message.id} (${messageRef})${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
25187
+ ...adviceLines
25188
+ ].join(`
25189
+ `),
25190
+ details: {
25191
+ issue: issueKey,
25192
+ message: message.id,
25193
+ ...message.advice === undefined ? {} : { advice: message.advice }
25194
+ }
25195
+ };
25196
+ }
25197
+ function arrivalText(attempt) {
25198
+ if (attempt === undefined)
25199
+ return "Dispatch recorded no delivery attempt for it";
25200
+ if (attempt.state === "failed") {
25201
+ return `its delivery failed: ${attempt.error ?? "the listener gave no reason"}`;
25326
25202
  }
25327
- const advancesWrite = advances === undefined ? undefined : { advances, advances_revision: advancesRevisionToSend(before, advancesRevision) };
25328
- if (status === "done" && typeof before.closed_at === "string") {
25329
- throw refusalWithCode(new DispatchServiceError("ISSUE_CLOSED", 409, "issue is closed"), `${issueKey} closed at ${before.closed_at}, so the reason was not posted and the close was not sent`);
25203
+ if (attempt.state === "pending")
25204
+ return "its delivery is still on its way";
25205
+ if (attempt.state === "queued") {
25206
+ return `that session is stopped, so its delivery is queued: it gets the message if it runs again within ${DELIVERY_DUPLICATE_WINDOW_HOURS} hours`;
25330
25207
  }
25331
- let closingNote;
25332
- if (reason !== undefined) {
25333
- try {
25334
- const message = await client.message(issueKey, { body: reason, actor });
25335
- closingNote = {
25336
- id: message.id,
25337
- ref: dispatchChildRef(dispatchIssueRef(issueKey), "message", message.id)
25208
+ return `it reached that session as ${attempt.delivery}`;
25209
+ }
25210
+ async function sendToAgentCommand(context) {
25211
+ const { args, client } = context;
25212
+ const session = stringArg(args, "session");
25213
+ const inReplyTo = optionalString(args, "in_reply_to");
25214
+ const message = await client.agentMessage(session, {
25215
+ body: stringArg(args, "body"),
25216
+ delivery: stringArg(args, "delivery"),
25217
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
25218
+ });
25219
+ const attempt = message.deliveries?.at(-1);
25220
+ const readBack = conversationReadBack(message.id);
25221
+ const arrival = arrivalText(attempt);
25222
+ return {
25223
+ text: `Sent message ${message.id} to session ${session}; ${arrival}. ${readBack}`,
25224
+ details: {
25225
+ session,
25226
+ message: message.id,
25227
+ ...attempt === undefined ? {} : { delivery: attempt.state },
25228
+ ...inReplyTo === undefined ? {} : { in_reply_to: inReplyTo }
25229
+ }
25230
+ };
25231
+ }
25232
+
25233
+ // ../envoy-client/src/dispatch-commands/documents.ts
25234
+ import { resolve as resolvePath2 } from "path";
25235
+
25236
+ // ../contracts/src/go-blank.ts
25237
+ var goBlankPattern = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u;
25238
+
25239
+ // ../envoy-client/src/dispatch-commands/documents.ts
25240
+ async function blockAsks(client, resolved, state) {
25241
+ const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
25242
+ return asks.filter((ask) => typeof ask.block_id === "string" && ask.block_artifact?.id === resolved.artifact.id);
25243
+ }
25244
+ async function readUploadedFile(client, artifact, details, requested, owner, shown) {
25245
+ const versions = artifact.versions ?? [];
25246
+ const latest = Math.max(0, ...versions.map((version) => version.number));
25247
+ const number = requested ?? latest;
25248
+ const of = number === latest ? "" : ` of ${latest}`;
25249
+ const bytesRoute = `GET /api/v1/artifacts/${artifact.id}/versions/${number} serves its bytes.`;
25250
+ const tooLarge = (mime, bytes) => ({
25251
+ text: `${oversizePictureText(artifact.name, bytes)}, so dispatch doc-read cannot show this ` + `uploaded ${mime} picture (version ${number}${of}). ${bytesRoute}`,
25252
+ details
25253
+ });
25254
+ const stated = versions.find((version) => version.number === number);
25255
+ if (artifact.kind === "image" && stated?.size !== undefined && stated.size > PICTURE_SHOWN_MAX_BYTES) {
25256
+ return tooLarge(stated.mime ?? "image", stated.size);
25257
+ }
25258
+ const file = await client.fileVersion(artifact.id, number);
25259
+ const size = `${file.bytes.length.toLocaleString("en-US")} bytes`;
25260
+ if (artifact.kind === "image") {
25261
+ const image = toolImage(file.bytes);
25262
+ if (image !== undefined) {
25263
+ const address = `dispatch://${owner}/artifact/${artifact.slug}@v${number}`;
25264
+ shown?.add(address);
25265
+ return {
25266
+ text: `Picture ${artifact.name}: ${image.mimeType}, version ${number}${of}, ${size}.
25267
+ ` + shownPictureLine(1, address, artifact.name, image.mimeType, file.bytes.length),
25268
+ details,
25269
+ images: [image]
25338
25270
  };
25339
- } catch (error) {
25340
- if (error instanceof DispatchWriteLandedError) {
25341
- throw new Error(`${error.message} That was the closing reason, so the close was not sent: read the issue's messages for it, then close with a reason that points at it, since retrying this call posts its reason again.`, { cause: error });
25271
+ }
25272
+ if (sniffPictureType(file.bytes) !== undefined)
25273
+ return tooLarge(file.mime, file.bytes.length);
25274
+ }
25275
+ let text;
25276
+ try {
25277
+ text = new TextDecoder("utf-8", { fatal: true }).decode(file.bytes);
25278
+ } catch {
25279
+ return {
25280
+ text: `${artifact.name} is an uploaded ${file.mime} file (version ${number}${of}, ${size}) that is not ` + `UTF-8 text, so dispatch doc-read cannot show it. ${bytesRoute}`,
25281
+ details
25282
+ };
25283
+ }
25284
+ return {
25285
+ text: `File ${artifact.name}: ${file.mime}, version ${number}${of}, ${size}.
25286
+
25287
+ ${text}`,
25288
+ details
25289
+ };
25290
+ }
25291
+ var BLOCK_OPENING_CHARS = 60;
25292
+ async function listDocumentBlocks(client, artifact) {
25293
+ const live = await liveBlocks(client, artifact);
25294
+ const { bytes, blocks } = live;
25295
+ const decoder = new TextDecoder;
25296
+ const lines = [
25297
+ `Blocks of ${artifact.name}, in document order, each indented under the block holding it: id, type, (token; anchored comments and asks), opening words, then a typed block's serves and needs. A table lists its rows by the index delete_row takes and its cells by the row and the column delete_column takes.`
25298
+ ];
25299
+ const holders = [];
25300
+ for (const block of blocks) {
25301
+ while (holders.length > 0 && block.from >= (holders.at(-1)?.to ?? 0))
25302
+ holders.pop();
25303
+ const indent = " ".repeat(holders.length);
25304
+ const flat = decoder.decode(bytes.subarray(block.from, block.to)).replace(/\s+/g, " ").trim();
25305
+ const points = Array.from(flat);
25306
+ const opening = points.length > BLOCK_OPENING_CHARS ? `${points.slice(0, BLOCK_OPENING_CHARS).join("")}\u2026` : flat;
25307
+ const { comments, asks } = block.references;
25308
+ lines.push(`${indent}${block.id} ${block.type} (${block.token ?? "no token"}; ${comments} comment${comments === 1 ? "" : "s"}, ${asks} ask${asks === 1 ? "" : "s"}): ${opening}`);
25309
+ for (const attribute of block.attributes ?? []) {
25310
+ if (attribute.kind === "block[]" && attribute.value !== "") {
25311
+ lines.push(`${indent} ${attribute.name}: ${attribute.value}`);
25342
25312
  }
25343
- const told = writeMayHaveLanded(error) ? "the reason may or may not have been posted, and the close was not sent: read the issue's messages before retrying, since retrying this call posts its reason again" : "the reason was not posted, so the close was not sent";
25344
- if (error instanceof DispatchServiceError)
25345
- throw refusalWithCode(error, told);
25346
- throw withAccount(error, told);
25347
25313
  }
25348
- }
25349
- const existingLinks = before.external_links ?? [];
25350
- const linked = existingLinks.map((link) => link.url);
25351
- const newLinks = requestedLinks?.filter((url) => !linked.includes(url)) ?? [];
25352
- const sentLinks = requestedLinks === undefined ? undefined : requestedLinks.length === 0 ? [] : [...existingLinks, ...newLinks.map((url) => ({ url }))];
25353
- const rank = rankBefore === undefined && rankAfter === undefined ? undefined : {
25354
- ...rankBefore === undefined ? {} : { before: rankBefore },
25355
- ...rankAfter === undefined ? {} : { after: rankAfter }
25356
- };
25357
- let after;
25358
- try {
25359
- after = await client.updateIssue(issueKey, {
25360
- ...status === undefined ? {} : { status },
25361
- ...title === undefined ? {} : { title },
25362
- ...labels === undefined ? {} : { labels },
25363
- ...priority === undefined ? {} : { priority },
25364
- ...assignee === undefined ? {} : { assignee },
25365
- ...route === undefined ? {} : { route },
25366
- ...parent === undefined ? {} : { parent: parent === "" ? null : parent },
25367
- ...blockedBy === undefined ? {} : { blocked_by: blockedBy },
25368
- ...advancesWrite,
25369
- ...components === undefined ? {} : { components },
25370
- ...repo === undefined ? {} : { repo: repo === "" ? null : repo },
25371
- ...sentLinks === undefined ? {} : { external_links: sentLinks },
25372
- ...rank === undefined ? {} : { rank },
25373
- actor
25374
- });
25375
- } catch (error) {
25376
- if (error instanceof DispatchWriteLandedError)
25377
- throw error;
25378
- const answered = error instanceof DispatchWriteUnsettledError ? error.last : error;
25379
- const taken = dispatchAnswered(answered, 500) && newLinks.length > 0 ? `one of ${newLinks.join(", ")} may already be linked from another issue (a URL links exactly one issue)` : "";
25380
- if (closingNote === undefined) {
25381
- if (taken !== "" && !(error instanceof DispatchServiceError)) {
25382
- throw withAccount(error, taken);
25314
+ if (block.type === "table") {
25315
+ if (block.table === undefined) {
25316
+ lines.push(`${indent} This Dispatch does not report table rows yet, so no row or column index is listed.`);
25317
+ } else {
25318
+ for (const row of block.table.rows ?? []) {
25319
+ lines.push(`${indent} row ${row.index}, ${row.id === "" ? "no id yet" : `id ${row.id}`}`);
25320
+ for (const cell of row.cells ?? []) {
25321
+ const under = cell.header === "" ? "" : `, under ${JSON.stringify(cell.header)}`;
25322
+ lines.push(`${indent} row ${cell.row} column ${cell.column}, ${cell.id === "" ? "no id yet" : `id ${cell.id}`}${under}: ${cell.text === "" ? "(empty)" : cell.text}`);
25323
+ }
25324
+ }
25325
+ }
25326
+ }
25327
+ holders.push(block);
25328
+ }
25329
+ return { text: lines.join(`
25330
+ `), token: live.token, version: live.version };
25331
+ }
25332
+ async function refuseOpenDecisionBlocks(client, tool, resolved) {
25333
+ const artifact = resolved.artifact;
25334
+ const latest = artifact.approval?.latest_version;
25335
+ if (latest === undefined || latest < 1 || artifact.approval?.state === "approved")
25336
+ return;
25337
+ const blocks = (await client.artifactBlocks(artifact.id)).filter((block) => block.type === "ask");
25338
+ if (blocks.length === 0)
25339
+ return;
25340
+ const [documentAsks, version] = await Promise.all([
25341
+ blockAsks(client, resolved),
25342
+ client.docRead(artifact.id, latest)
25343
+ ]);
25344
+ const asks = new Map(documentAsks.map((ask) => [ask.block_id, ask]));
25345
+ const lines = version.markdown.split(`
25346
+ `);
25347
+ const stillOpen = (named, state) => state === "answered" ? `${named}, answered but still open in version ${latest}: it settles into a version on its own in about two seconds; wait for that version` : `${named}, ${state} but still open in version ${latest}: write the decision into the text with dispatch doc-edit, which writes a version that carries it`;
25348
+ const open = blocks.flatMap((block) => {
25349
+ const ask = asks.get(block.id);
25350
+ const id = typedBlockIdAttribute(block.id);
25351
+ const openers = lines.filter((line) => line.includes(`ask{${id} `) || line.includes(`ask{${id}}`));
25352
+ const states = openers.map((line) => /\bstate="(\w+)"/.exec(line)?.[1]);
25353
+ const named = ask === undefined ? `block ${block.id}` : `${JSON.stringify(ask.question)} (block ${block.id}, ask ${ask.id})`;
25354
+ if (states.length === 0)
25355
+ return [`${named}, which version ${latest} does not hold yet`];
25356
+ if (!states.includes("open") && states.some((state) => state !== undefined))
25357
+ return [];
25358
+ if (ask !== undefined)
25359
+ return ask.state === "open" ? [named] : [stillOpen(named, ask.state)];
25360
+ const attribute = (name) => openers.map((line) => new RegExp(`\\b${name}="([^"]+)"`).exec(line)?.[1]).find((value) => value !== undefined);
25361
+ const sourceId = attribute("copied_from");
25362
+ const document = attribute("copied_from_document");
25363
+ if (sourceId === undefined || document === undefined) {
25364
+ return [`${named}, whose ask Dispatch has not opened yet`];
25365
+ }
25366
+ const source = parseDispatchRef(document);
25367
+ const where = source === null ? document : source.owner.kind === "project" ? documentLabel(source.owner.project, source.id) : `${source.owner.issue} ${source.id}`;
25368
+ const ref = source?.owner.kind === "issue" ? dispatchChildRef(dispatchIssueRef(source.owner.issue), "ask", sourceId) : dispatchChildRef(document, "ask", sourceId);
25369
+ return [`${named}, a copy of ask ${ref}, which is open on ${where}: answer it there`];
25370
+ });
25371
+ if (open.length === 0)
25372
+ return;
25373
+ const count = open.length === 1 ? "1 open decision block" : `${open.length} open decision blocks`;
25374
+ throw new Error([
25375
+ `dispatch ${commandName(tool)} was not called: ${artifact.name} (version ${latest}) has ${count}. Answering one writes a new version, which would move this request to that version and leave it waiting on you.`,
25376
+ ...open.map((line) => `- ${line}`),
25377
+ "Do not request approval over an open block, even when a human asked for it. Tell the human which block is open and ask them to answer it or to waive it. Once it is answered, it settles into a version on its own in about two seconds. When the human approved an earlier version and their answer is the whole change since it, Dispatch carries the approval to the new version in their name: request nothing. When the answer changes design text outside the block, rewrite that text (never to restate the answer), then request approval again once the human has agreed to every point in the new version, with a one-sentence --summary naming what changed since the earlier approval. On a document nobody has approved, wait for that version, then request. If they waive it, close the block with dispatch resolve-ask (--kind resolved, their words as the --reason), write their decision into the text with dispatch doc-edit, then request approval again once the human has agreed to every point in the new version. The call opens the request, or hands an open one back to the human."
25378
+ ].join(`
25379
+ `));
25380
+ }
25381
+ async function refuseRemovingOpenDecisionBlocks(client, tool, resolved, ops) {
25382
+ const removing = ops.filter((operation) => operation.block !== undefined && (operation.op === "delete" || operation.op === "retype" && operation.type !== "ask"));
25383
+ if (removing.length === 0)
25384
+ return;
25385
+ const artifact = resolved.artifact;
25386
+ const blocks = await client.artifactBlocks(artifact.id);
25387
+ const askBlocks = blocks.filter((block) => block.type === "ask");
25388
+ const removed = new Set;
25389
+ for (const operation of removing) {
25390
+ const target = blocks.find((block) => block.id === operation.block);
25391
+ if (target === undefined)
25392
+ continue;
25393
+ for (const block of askBlocks) {
25394
+ if (block.id === target.id || operation.op === "delete" && block.from >= target.from && block.to <= target.to) {
25395
+ removed.add(block.id);
25383
25396
  }
25384
- throw refusalWithCode(error, taken);
25385
25397
  }
25386
- const posted = `the reason already landed as message ${closingNote.id} (${closingNote.ref})`;
25387
- const fix = error instanceof DispatchGatewayError && error.transient ? "" : "fix what refused the close, then ";
25388
- const landed = writeMayHaveLanded(error) ? `${posted}, and the close may or may not have taken effect. Read the issue's status before retrying: done means it closed; otherwise retry with a reason that points at message ${closingNote.id}, since retrying this call posts its reason again` : `${posted} but the issue did not close. Retrying this call posts its reason again, so ${fix}retry with a reason that points at message ${closingNote.id}`;
25389
- if (error instanceof DispatchServiceError)
25390
- throw refusalWithCode(error, taken, landed);
25391
- throw withAccount(error, [taken, landed].filter((clause) => clause !== "").join("; "));
25392
25398
  }
25393
- refuseUnsavedRepository("updated", after, repo);
25394
- const links = after.external_links ?? [];
25395
- const linkCount = `(${links.length} ${links.length === 1 ? "link" : "links"})`;
25396
- const stated = (after.advances ?? []).filter((advance) => !advance.inherited).map((advance) => advance.id);
25397
- const changes = [
25398
- ...closingNote === undefined ? [] : [`reason posted as message ${closingNote.id} (${closingNote.ref})`],
25399
- ...status === undefined ? [] : [`status ${before.status} -> ${after.status}`],
25400
- ...title === undefined ? [] : [`title "${after.title}"`],
25401
- ...labels === undefined ? [] : [
25402
- (after.labels ?? []).length === 0 ? "labels cleared" : `labels ${(after.labels ?? []).join(", ")}`
25403
- ],
25404
- ...priority === undefined ? [] : [after.priority === null ? "priority cleared" : `priority -> P${after.priority}`],
25405
- ...assignee === undefined ? [] : [after.assignee === null ? "assignee cleared" : `assignee -> ${after.assignee}`],
25406
- ...rank === undefined ? [] : [
25407
- `rank -> ${[
25408
- ...rankAfter === undefined ? [] : [`after ${rankAfter}`],
25409
- ...rankBefore === undefined ? [] : [`before ${rankBefore}`]
25410
- ].join(", ")}`
25411
- ],
25412
- ...requestedLinks === undefined ? [] : [
25413
- requestedLinks.length === 0 ? "external links cleared" : newLinks.length === 0 ? `already linked ${requestedLinks.join(", ")} ${linkCount}` : `linked ${newLinks.join(", ")} ${linkCount}`
25414
- ],
25415
- ...route === undefined ? [] : [after.route === null ? "route cleared" : `route ${after.route}`],
25416
- ...parent === undefined ? [] : [after.parent === null ? "parent cleared" : `parent -> ${after.parent}`],
25417
- ...blockedBy === undefined ? [] : [
25418
- (after.blocked_by ?? []).length === 0 ? "blocked_by cleared" : `blocked by ${(after.blocked_by ?? []).join(", ")}`
25419
- ],
25420
- ...advances === undefined ? [] : [stated.length === 0 ? "advances cleared" : `advances ${stated.join(", ")}`],
25421
- ...components === undefined ? [] : [componentsChange(components, after.components)],
25422
- ...repo === undefined ? [] : [
25423
- after.repo === null ? `repo cleared (resolves to ${after.resolved_repo ?? "none"})` : `repo -> ${after.repo}`
25424
- ]
25425
- ];
25426
- const adviceLines = renderAdvice(input.tool, after.key, after.advice, {
25427
- setsStatus: status !== undefined
25399
+ if (removed.size === 0)
25400
+ return;
25401
+ const asks = await blockAsks(client, resolved, "open");
25402
+ const open = asks.filter((ask) => removed.has(ask.block_id));
25403
+ if (open.length === 0)
25404
+ return;
25405
+ const [what, question] = open.length === 1 ? ["a decision block whose ask is", "question"] : [`${open.length} decision blocks whose asks are`, "questions"];
25406
+ throw new Error([
25407
+ `dispatch ${commandName(tool)} was not called: it would remove ${what} still open, and the human's ${question} would leave their Inbox unanswered.`,
25408
+ ...open.map((ask) => `- ${JSON.stringify(ask.question)} (block ${ask.block_id}, ask ${ask.id})`),
25409
+ "A decision block leaves the document once its ask is answered or resolved. Until then, reword it with replace, relocate it with move, or change its question, options, urgency or multiple with dispatch edit-ask if you asked it; each keeps it."
25410
+ ].join(`
25411
+ `));
25412
+ }
25413
+ async function docEditCommand(context) {
25414
+ const { args, client, actor, input, linkBase, documentOwner, resolveDocument } = context;
25415
+ const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
25416
+ const ops = args.ops;
25417
+ const summary = optionalString(args, "summary");
25418
+ const { precondition: rawPrecondition } = args;
25419
+ const precondition = rawPrecondition;
25420
+ await refuseRemovingOpenDecisionBlocks(client, input.tool, resolved, ops);
25421
+ const edited = await client.docEdit(resolved.artifact.id, {
25422
+ ops,
25423
+ ...summary === undefined ? {} : { summary },
25424
+ ...precondition === undefined ? {} : { precondition },
25425
+ actor
25426
+ });
25427
+ const retyped = ops.filter((operation) => operation.op === "retype").length;
25428
+ const versionText = edited.version === null ? "no new version" : `version ${edited.version.number}`;
25429
+ const retypedText = retyped === 0 ? "" : `; retyped ${retyped} block${retyped === 1 ? "" : "s"}`;
25430
+ const nothingChanged = edited.changed === false;
25431
+ const head = nothingChanged ? `Applied ${edited.applied} ops${retypedText}; nothing changed (${versionText})` : `Applied ${edited.applied} ops${retypedText} (${versionText})`;
25432
+ const unchangedOps = edited.unchanged_ops ?? [];
25433
+ const unchangedText = unchangedOps.length === 0 ? "" : `; ${unchangedOps.length === 1 ? "operation" : "operations"} ${unchangedOps.join(", ")} changed nothing`;
25434
+ const lostOps = edited.lost_ops;
25435
+ const lostText = lostOps === undefined || lostOps !== null && lostOps.length === 0 ? "" : lostOps === null ? "; could not confirm this edit survived, because the live document is being reloaded or holds a tree too deep to read \u2014 re-read it" : `; ${versionText} carries text the live document no longer has: a concurrent change removed what ${lostOps.length === 1 ? "operation" : "operations"} ${lostOps.join(", ")} wrote \u2014 re-read the document`;
25436
+ const applied = `${head}${unchangedText}${lostText}`;
25437
+ const editAskText = ops.map((operation) => /^:{3,}ask\{.*\n([\s\S]*)/mu.exec(operation.markdown ?? operation.with ?? "")?.[1]).find((text) => text !== undefined) ?? resolved.issue?.title ?? "";
25438
+ const checkLines = decisionBlockLines(edited.advice, {
25439
+ project: resolved.artifact.project,
25440
+ text: editAskText,
25441
+ linkBase
25428
25442
  });
25443
+ const declinedLines = resolved.issue === undefined ? [] : declinedAskLines(edited.advice, resolved.issue.key, linkBase);
25444
+ const adviceLines = await otherAdviceLines(() => renderAdvice(input.tool, resolvedTopic(resolved).label, edited.advice, {
25445
+ isPlan: documentPlaysPlan(resolved.artifact)
25446
+ }));
25447
+ const written = edited.written;
25448
+ const writtenLines = written === undefined || written === "" ? [] : [written];
25449
+ const tokenTrailer = edited.token === undefined ? [] : [`Document token: ${edited.token}`];
25429
25450
  return {
25430
25451
  text: [
25431
- `${after.key}: ${changes.join("; ")}${await notSubscribed(issueTopic(after.key), input.subscriptions)}`,
25452
+ `${applied}${await notSubscribed(resolvedTopic(resolved), input.subscriptions)}`,
25453
+ ...checkLines,
25454
+ ...declinedLines,
25455
+ ...writtenLines,
25456
+ ...tokenTrailer,
25432
25457
  ...adviceLines
25433
25458
  ].join(`
25434
25459
  `),
25435
- details: {
25436
- issue: after.key,
25437
- status: after.status,
25438
- external_links: (after.external_links ?? []).map((link) => link.url),
25439
- ...closingNote === undefined ? {} : { message: closingNote.id },
25440
- ...after.advice === undefined ? {} : { advice: after.advice }
25441
- }
25460
+ details: writeResultDetails(resolved, {
25461
+ applied: edited.applied,
25462
+ ...edited.version === null ? {} : { version: edited.version.number },
25463
+ ...nothingChanged ? { changed: false } : {},
25464
+ ...lostOps === undefined ? {} : { lost_ops: lostOps },
25465
+ ...edited.token === undefined ? {} : { token: edited.token },
25466
+ ...edited.advice === undefined ? {} : { advice: edited.advice }
25467
+ })
25442
25468
  };
25443
25469
  }
25444
- async function claimCommand(context) {
25445
- const { args, client, actor, input, issue } = context;
25446
- const issueKey = issue();
25447
- const release = optionalBoolean(args, "release") ?? false;
25448
- let after;
25449
- try {
25450
- after = release ? await client.releaseIssueClaim(issueKey, { actor }) : await client.claimIssue(issueKey, { actor });
25451
- } catch (error) {
25452
- throw refusalWithCode(error);
25470
+ async function docReadCommand(context) {
25471
+ const { args, client, ownerArguments, shown, documentOwner, resolveDocument } = context;
25472
+ const { agentArtifact } = ownerArguments;
25473
+ if (agentArtifact !== undefined) {
25474
+ const artifact = await client.getAgentArtifact(agentArtifact.session, agentArtifact.slug);
25475
+ if (optionalBoolean(args, "blocks") === true) {
25476
+ throw new Error(`${artifact.name} is an uploaded ${artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
25477
+ }
25478
+ return readUploadedFile(client, artifact, { session: agentArtifact.session, artifact: artifact.slug }, optionalNumber(args, "version") ?? agentArtifact.version, `agent/${agentArtifact.session}`, shown);
25453
25479
  }
25454
- const held = after.claim;
25455
- const legionManaged = after.legion_managed_status === true;
25456
- let text;
25457
- if (release) {
25458
- const released = `${issueKey}: claim released; nobody is working it now. Its status is still ${after.status}`;
25459
- text = legionManaged ? `${released}; ${LEGION_OWNS_STATUS}` : `${released} \u2014 move it yourself if that is no longer where the work is.`;
25460
- } else {
25461
- if (held === null) {
25462
- throw new Error(`Dispatch claimed ${issueKey} but answered with no claim`);
25480
+ const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
25481
+ const resolved = await resolveDocument(documentOwner(), artifactReference);
25482
+ const version = optionalNumber(args, "version") ?? ownerArguments.ref?.version;
25483
+ if (optionalBoolean(args, "blocks") === true) {
25484
+ if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
25485
+ throw new Error(`${resolved.artifact.name} is an uploaded ${resolved.artifact.kind}, not a document, so it has no blocks. Read it with dispatch doc-read without --blocks.`);
25463
25486
  }
25464
- const claimed = `${issueKey}: claimed by you since ${held.at}. Its status is ${after.status}`;
25465
- const reaches = `A person's answers, comments and messages on ${issueKey} now reach you directly.`;
25466
- text = legionManaged ? `${claimed}; ${LEGION_OWNS_STATUS} Release the claim when you stop. ${reaches}` : `${claimed}; a claim moves nothing, so move it to in_progress with dispatch issue-update when you start, and release the claim when you stop. ${reaches}`;
25487
+ const listed = await listDocumentBlocks(client, resolved.artifact);
25488
+ const trailer = [
25489
+ ...listed.token === undefined ? [] : [`Document token: ${listed.token}`],
25490
+ `Document version: ${listed.version === null ? "none yet" : listed.version}`
25491
+ ];
25492
+ return {
25493
+ text: `${listed.text}
25494
+
25495
+ ${trailer.join(`
25496
+ `)}`,
25497
+ details: resolved.owner.kind === "project" ? {
25498
+ project: resolved.artifact.project,
25499
+ document: documentLabel(resolved.artifact.project, resolved.artifact.slug)
25500
+ } : { issue: resolved.issue?.key }
25501
+ };
25467
25502
  }
25503
+ if (resolved.artifact.kind === "file" || resolved.artifact.kind === "image") {
25504
+ const { artifact } = resolved;
25505
+ return readUploadedFile(client, artifact, resolved.owner.kind === "project" ? {
25506
+ project: artifact.project,
25507
+ document: documentLabel(artifact.project, artifact.slug)
25508
+ } : { issue: resolved.issue?.key }, version, resolved.owner.kind === "project" ? resolved.owner.project : resolved.owner.issue, shown);
25509
+ }
25510
+ const documentPromise = client.docRead(resolved.artifact.id, version);
25511
+ const threadsPromise = openAnchoredThreads(client, resolved);
25512
+ const threadsResultPromise = threadsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
25513
+ const document = await documentPromise;
25514
+ const threadsResult = await threadsResultPromise;
25515
+ if (threadsResult.status === "rejected")
25516
+ throw threadsResult.reason;
25517
+ const threads = threadsResult.value;
25518
+ const approval = approvalLine(resolved.artifact, typeof resolved.issue?.closed_at === "string");
25519
+ const trailer = [
25520
+ ..."token" in document && document.token !== undefined ? [`Document token: ${document.token}`] : [],
25521
+ ..."sha256" in document && document.sha256 !== undefined ? [`Content: sha256:${document.sha256}`] : [],
25522
+ ...approval === undefined ? [] : [approval]
25523
+ ];
25468
25524
  return {
25469
- text: `${text}${await notSubscribed(issueTopic(issueKey), input.subscriptions)}`,
25470
- details: { issue: issueKey, status: after.status, claim: held }
25471
- };
25472
- }
25473
- async function searchCommand(context) {
25474
- const { args, client, linkBase } = context;
25475
- const query = stringArg(args, "query");
25476
- const project = optionalString(args, "project");
25477
- const limit = optionalNumber(args, "limit");
25478
- const offset = optionalNumber(args, "offset");
25479
- const search = await client.search(query, {
25480
- ...project === undefined ? {} : { project },
25481
- ...limit === undefined ? {} : { limit },
25482
- ...offset === undefined ? {} : { offset }
25483
- });
25484
- return searchAnswer(search, query, offset, linkBase);
25485
- }
25486
- async function relatedCommand(context) {
25487
- const { args, client, linkBase } = context;
25488
- const project = stringArg(args, "project");
25489
- const title = optionalString(args, "title");
25490
- const text = optionalString(args, "text");
25491
- const excludeIssues = optionalStringArray(args, "exclude_issues");
25492
- const keywordsOnly = optionalBoolean(args, "keywords_only");
25493
- const suggestions = await client.related(project, {
25494
- ...title === undefined ? {} : { title },
25495
- ...text === undefined ? {} : { text },
25496
- ...excludeIssues === undefined ? {} : { exclude_issues: excludeIssues },
25497
- ...keywordsOnly === undefined ? {} : { keywords_only: keywordsOnly }
25498
- });
25499
- return {
25500
- text: relatedCheckLines(suggestions, {
25501
- project,
25502
- text: [title, text].filter((part) => part !== undefined).join(`
25503
- `),
25504
- linkBase
25505
- }).join(`
25525
+ text: [
25526
+ document.markdown,
25527
+ ...trailer.length === 0 ? [] : [trailer.join(`
25528
+ `)],
25529
+ ...threads.length === 0 ? [] : ["Open anchored threads:", ...threads]
25530
+ ].join(`
25531
+
25506
25532
  `),
25507
- details: { project, suggestions }
25533
+ details: resolved.owner.kind === "project" ? {
25534
+ project: resolved.artifact.project,
25535
+ document: `${resolved.artifact.project}/${resolved.artifact.slug}`
25536
+ } : { issue: resolved.issue?.key }
25508
25537
  };
25509
25538
  }
25510
- async function issuesCommand(context) {
25511
- const { args, client } = context;
25512
- const project = stringArg(args, "project");
25513
- const status = optionalString(args, "status");
25514
- const parent = optionalString(args, "parent");
25515
- const label = optionalString(args, "label");
25516
- const priority = optionalPriorityFilter(args, "priority");
25517
- const updatedSince = optionalString(args, "updated_since");
25518
- const routeStatus = optionalString(args, "route_status");
25519
- const filters = {
25520
- project,
25521
- ...status === undefined ? {} : { status },
25522
- ...parent === undefined ? {} : { parent },
25523
- ...label === undefined ? {} : { label },
25524
- ...priority === undefined ? {} : { priority },
25525
- ...updatedSince === undefined ? {} : { updated_since: updatedSince },
25526
- ...routeStatus === undefined ? {} : { route_status: routeStatus }
25527
- };
25528
- const page = optionalBoolean(args, "all") === true ? await client.listAllIssues(filters).then((issues) => ({
25529
- issues,
25530
- total: issues.length,
25531
- limit: issues.length,
25532
- offset: 0
25533
- })) : await client.listIssuePage(filters, {
25534
- limit: optionalNumber(args, "limit") ?? DEFAULT_ISSUE_PAGE_LIMIT,
25535
- offset: optionalNumber(args, "offset") ?? 0
25539
+ async function requestApprovalCommand(context) {
25540
+ const { args, client, actor, input, ownerArguments, documentOwner, resolveDocument } = context;
25541
+ const artifactReference = optionalString(args, "artifact") ?? (ownerArguments.ref?.kind === "spec" || ownerArguments.ref?.kind === "artifact" ? ownerArguments.ref.id : undefined);
25542
+ const resolved = await resolveDocument(documentOwner(), artifactReference);
25543
+ await refuseOpenDecisionBlocks(client, input.tool, resolved);
25544
+ const includeVerification = optionalBoolean(args, "include_verification") === true;
25545
+ const result = await client.requestApproval(resolved.artifact.id, {
25546
+ actor,
25547
+ summary: stringArg(args, "summary"),
25548
+ ...includeVerification ? { include_verification: true } : {}
25536
25549
  });
25537
- const { total, limit, offset } = page;
25538
- const rows = (page.issues ?? []).map((row) => ({
25539
- key: row.key,
25540
- title: row.title,
25541
- status: row.status,
25542
- priority: row.priority,
25543
- parent: row.parent,
25544
- labels: row.labels ?? [],
25545
- open_asks: row.open_asks,
25546
- claim: row.claim ?? null,
25547
- route: row.route ?? null,
25548
- route_status: row.route_status ?? null,
25549
- route_holder: row.route_holder ?? null,
25550
- route_status_reason: row.route_status_reason ?? null,
25551
- updated_at: row.updated_at,
25552
- progress: row.progress
25553
- }));
25554
- const agents = await liveAgents(client, rows.some((row) => holdsSession(row.claim)));
25555
- const isPartial = offset !== 0 || rows.length !== total;
25556
- const showing = !isPartial ? "" : rows.length === 0 ? `showing 0-0 of ${total}` : pageSummaryText(offset, rows.length, total);
25550
+ const gaps = result.coverage ?? [];
25551
+ const coverageLines = result.coverage_unread ? [
25552
+ `Coverage of ${resolved.artifact.name}: unread. Dispatch could not read what the spec's requirements lack, so no line here says there is no gap; the request is recorded either way. Read the coverage again with dispatch read --issue, and mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
25553
+ ] : gaps.length === 0 ? [] : [
25554
+ `Coverage of ${resolved.artifact.name}: ${gaps.map((gap) => `${gap}.`).join(" ")} Mark each requirement the spec states with a requirement block and write a check that serves it, in the issue's Verification document, before the work starts.`
25555
+ ];
25556
+ if (result.ask === null) {
25557
+ return {
25558
+ text: [
25559
+ `${resolved.artifact.name} (document id ${resolved.artifact.id}) is already approved at version ${result.version} by ${result.approval.by?.id ?? "unknown"}; no new request was opened. A change outside the decision blocks after approval makes it stale, so request again only for such a version, once the human has agreed to every point in it, with a --summary naming what changed since version ${result.version}; the human's own answer to a decision block carries the approval when that answer is the whole change.`,
25560
+ ...coverageLines
25561
+ ].join(`
25562
+ `),
25563
+ details: {
25564
+ ...resolved.owner.kind === "project" ? documentResultDetails(resolved.artifact) : { issue: resolved.issue?.key },
25565
+ artifact: resolved.artifact.id,
25566
+ version: result.version
25567
+ }
25568
+ };
25569
+ }
25570
+ const details = await followedAskDetails(client, result.ask, resolved.artifact);
25571
+ const outcome = result.recorded ? `Approval requested for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}).` : `The approval request for ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${result.version} (ask ${result.ask.id}) already waits on the human, so this call changed nothing: nothing since it last reached the human (a newer version, a human's reply in its thread, or your progress note) left it waiting on you.`;
25572
+ const waitsOn = waitsOnPerson(result.ask);
25557
25573
  return {
25558
- text: rows.length === 0 ? `No issues in ${project}.${isPartial ? ` (${showing})` : ""}` : [
25559
- `${rows.length} ${rows.length === 1 ? "issue" : "issues"} in ${project}` + (isPartial ? ` (${showing})` : ""),
25560
- ...rows.map((row) => {
25561
- const progress = progressText(row.progress, " \xB7 ");
25562
- return `${row.key} [${row.status}]${row.priority === null ? "" : ` P${row.priority}`} ${row.title}` + (row.open_asks === 0 ? "" : ` \xB7 ${row.open_asks} open ${row.open_asks === 1 ? "ask" : "asks"}`) + (row.claim === null ? "" : ` \xB7 claimed by ${claimText(row.claim, agents)}`) + (progress === "" ? "" : ` \xB7 ${progress}`) + (row.route === null || row.route_status === "live" || row.route_status === null ? "" : ` \xB7 route ${routeText(row)}`);
25563
- })
25574
+ text: [
25575
+ `${outcome}${waitsOn === undefined ? "" : ` It waits on ${waitsOn}.`} The human's Inbox asks: ${JSON.stringify(result.ask.question)}. The answer arrives as artifact.approved or artifact.changes_requested. An edit before the answer moves this request to the new version and leaves it waiting on you, and a change outside the decision blocks after approval makes the approval stale: either way, request again for the new version once the human has agreed to every point in it, which hands this request back or opens a new one, with a --summary naming what changed since the earlier approval. The human's own answer to a decision block carries the approval when that answer is the whole change since the approved version, and answers an open request Approve in their name: request nothing then.`,
25576
+ ...coverageLines
25564
25577
  ].join(`
25565
25578
  `),
25566
- details: { issues: rows, total, offset, limit }
25579
+ details: { ...details, artifact: resolved.artifact.id, version: result.version }
25567
25580
  };
25568
25581
  }
25569
- var BRIEF_READING_CHARACTERS = 200;
25570
- var COMPARISON_REASONS = {
25571
- no_pull_request_or_branch: "the issue has no pull request and no branch to compare with",
25572
- repository_unreadable: "Dispatch cannot read the repository",
25573
- read_failed: "a read Dispatch made did not answer"
25574
- };
25575
- function learnedText(learned) {
25576
- if (learned.kind === "read_at")
25577
- return `Dispatch read it ${learned.at}`;
25578
- return `GitHub updated it ${learned.at}`;
25579
- }
25580
- function basisText(basis) {
25581
- const learned = basis.learned_at === undefined ? "" : ` (${learnedText(basis.learned_at)})`;
25582
- if (basis.kind === "pull_request") {
25583
- const number = basis.pull_request === undefined ? "" : `#${basis.pull_request} `;
25584
- return `the head of pull request ${number}at ${basis.commit ?? "an unnamed commit"}${learned}`;
25585
- }
25586
- if (basis.kind === "branch")
25587
- return `branch ${basis.branch ?? "unnamed"}${learned}`;
25588
- return `the commit you named, ${basis.commit ?? ""}${learned}`;
25582
+ async function planApproveCommand(context) {
25583
+ const { args, client, actor, documentOwner, resolveDocument } = context;
25584
+ const planOwner = documentOwner();
25585
+ const named = optionalString(args, "artifact");
25586
+ const byRole = named === undefined && planOwner.kind === "issue" ? (await client.getIssue(planOwner.issue)).plan_artifact_id ?? "" : "";
25587
+ const resolved = await resolveDocument(planOwner, named ?? (byRole || "plan.md"));
25588
+ const version = numberArg(args, "version");
25589
+ const review = await client.planApprove(resolved.artifact.id, { actor, version });
25590
+ return {
25591
+ text: `The plan review approved ${resolved.artifact.name} (document id ${resolved.artifact.id}) at version ${review.version}; no human is asked to approve a plan. A later plan version makes this approval stale: run the review again and record it the same way.`,
25592
+ details: {
25593
+ issue: resolved.issue?.key,
25594
+ artifact: resolved.artifact.id,
25595
+ version: review.version
25596
+ }
25597
+ };
25589
25598
  }
25590
- function basisPlace(basis) {
25591
- if (basis.kind === "pull_request") {
25592
- return basis.pull_request === undefined ? "the head of a pull request" : `the head of pull request #${basis.pull_request}`;
25593
- }
25594
- if (basis.kind === "branch")
25595
- return `on branch ${basis.branch ?? "unnamed"}`;
25596
- return "the commit you named";
25599
+ function artifactUnderName(artifacts, name) {
25600
+ const written = name.trim();
25601
+ return artifacts.find((held) => held.slug === written) ?? artifacts.find((held) => held.name === written);
25597
25602
  }
25598
- function commitStandsText(stands) {
25599
- if (stands === undefined) {
25600
- return "Where that commit stands is not known: this Dispatch server does not say";
25601
- }
25602
- if (stands.answer === "at_basis") {
25603
- return stands.basis === undefined ? "That commit is one of the compared commits" : `That commit is ${basisPlace(stands.basis)}`;
25603
+ function artifactNameExistsProblem(held, owner) {
25604
+ const versions = held.versions ?? [];
25605
+ const newest = versions[versions.length - 1];
25606
+ if (newest === undefined) {
25607
+ return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}), which has no version yet and which ${actorText(held.created_by)} created. ${ARTIFACT_NAME_EXISTS_RULE}`;
25604
25608
  }
25605
- if (stands.answer === "other_commit")
25606
- return "That commit is none of the compared commits";
25607
- return stands.reason === undefined ? "Where that commit stands is not known" : `Where that commit stands is not known: ${COMPARISON_REASONS[stands.reason]}`;
25609
+ const authors = (newest.authors ?? []).map(actorText);
25610
+ const wroteIt = authors.length === 0 ? actorText(held.created_by) : authors.join(" and ");
25611
+ return `${owner} already holds ${held.name} (slug ${held.slug}, kind ${held.kind}) at version ${newest.number}, which ${wroteIt} wrote. ${ARTIFACT_NAME_EXISTS_RULE}`;
25608
25612
  }
25609
- function checkWordsText(check, result) {
25610
- const versions = `result version ${result.check_version}, check version ${check.version}`;
25611
- if (result.check_words_moved === undefined) {
25612
- return `Whether the check's words moved is not known (${versions})`;
25613
- }
25614
- return result.check_words_moved ? `The check's words moved after this result (${versions})` : `The check's words did not move after this result (${versions})`;
25613
+ var STORED_LINE_QUOTED = 200;
25614
+ function quotedStoredLine(line) {
25615
+ if (line.length <= STORED_LINE_QUOTED)
25616
+ return JSON.stringify(line);
25617
+ const head = JSON.stringify(line.slice(0, STORED_LINE_QUOTED));
25618
+ return `${head} (cut after ${STORED_LINE_QUOTED} of its ${line.length} characters)`;
25615
25619
  }
25616
- function passStandsText(pass) {
25617
- if (pass === undefined)
25618
- return "Whether a pass stands is not known: this Dispatch server does not say";
25619
- if (pass.answer === "yes") {
25620
- const roles = pass.roles ?? [];
25621
- return roles.length === 0 ? "A pass stands: yes" : `A pass stands: yes, from ${roles.join(", ")}`;
25620
+ function firstStoredDifference(given, stored) {
25621
+ const written = given.split(`
25622
+ `);
25623
+ const holds = stored.split(`
25624
+ `);
25625
+ for (let line = 0;line < Math.max(written.length, holds.length); line += 1) {
25626
+ const wrote = written[line];
25627
+ const held = holds[line];
25628
+ if (wrote === held)
25629
+ continue;
25630
+ if (wrote === undefined && held !== undefined) {
25631
+ return `the store writes a line ${line + 1}, ${quotedStoredLine(held)}`;
25632
+ }
25633
+ if (held === undefined && wrote !== undefined) {
25634
+ return `the store drops line ${line + 1}, ${quotedStoredLine(wrote)}`;
25635
+ }
25636
+ if (wrote !== undefined && held !== undefined) {
25637
+ return `line ${line + 1} reads ${quotedStoredLine(wrote)} and is stored as ${quotedStoredLine(held)}`;
25638
+ }
25622
25639
  }
25623
- if (pass.answer === "no")
25624
- return "A pass stands: no";
25625
- return "A pass stands: not known";
25640
+ return "the stored text differs from the text given";
25626
25641
  }
25627
- function readingLines(result, brief, indent = " ") {
25628
- const observed = result.observed;
25629
- if (observed === "")
25630
- return [`${indent}The role recorded no reading.`];
25631
- const cut = brief && result.commit_stands?.answer !== "at_basis";
25632
- if (cut && observed.length > BRIEF_READING_CHARACTERS) {
25633
- return [
25634
- `${indent}Reading: ${observed.slice(0, BRIEF_READING_CHARACTERS)}\u2026 (result ${result.id})`
25635
- ];
25636
- }
25637
- return [`${indent}Reading: ${observed}`];
25642
+ var STORED_TEXT_PRINTED = 2000;
25643
+ function storedTextPrinted(stored) {
25644
+ if (stored.length <= STORED_TEXT_PRINTED)
25645
+ return { text: stored, cut: "" };
25646
+ const head = stored.slice(0, STORED_TEXT_PRINTED);
25647
+ const lastLineFeed = head.lastIndexOf(`
25648
+ `);
25649
+ const text = lastLineFeed === -1 ? head : head.slice(0, lastLineFeed + 1);
25650
+ return {
25651
+ text,
25652
+ cut: ` The text below is cut after ${text.length} of its ${stored.length} characters: change the line named above and send the text again.`
25653
+ };
25638
25654
  }
25639
- function resultLines(check, result, brief) {
25640
- const lines = [
25641
- ` - ${result.verdict} by ${result.role} at ${result.commit_sha}. ${commitStandsText(result.commit_stands)}. ${checkWordsText(check, result)}. Recorded ${result.created_at}. Result ${result.id}.`
25642
- ];
25643
- const retracted = result.retracted;
25644
- if (retracted !== undefined) {
25645
- lines.push(` Retracted by ${actorText(retracted.actor)} at ${retracted.created_at}. The reason: ${retracted.reason}`);
25646
- }
25647
- return [...lines, ...readingLines(result, brief)];
25655
+ function storedTextProblem(given, stored, name) {
25656
+ const asBytes = pathKeepsBytesOf(name) ? ` To keep the text as you wrote it, send it as a file with ${PATH_KEEPS_BYTES}.` : "";
25657
+ const printed = storedTextPrinted(stored);
25658
+ return [
25659
+ `Dispatch stores this text under another spelling: ${firstStoredDifference(given, stored)}.`,
25660
+ ` Send the text Dispatch stores, which is between the two marker lines below.${asBytes}`,
25661
+ `${printed.cut}
25662
+ --- the text Dispatch stores ---
25663
+ ${printed.text}`,
25664
+ "--- end of the text Dispatch stores ---"
25665
+ ].join("");
25648
25666
  }
25649
- function ciCheckLines(check, ci, brief) {
25650
- const passStandsLine = ` ${passStandsText(check.pass_stands)}.`;
25651
- const pullRequestLine = ` Pull request line: ${ci.line}`;
25652
- const derived = check.results?.[0];
25653
- if (derived === undefined) {
25654
- return [
25655
- `- ${check.block_id} (${check.when}): no result: ${ci.detail} ${check.text}`,
25656
- passStandsLine,
25657
- pullRequestLine
25658
- ];
25667
+ function storedTextCheckFailed(error, name) {
25668
+ const failure = `Dispatch could not say how it would store this text, so nothing was uploaded: POST /api/v1/markdown/round-trip failed with ${messageFor(error)}.`;
25669
+ if (!dispatchAnswered(error, 413)) {
25670
+ return `${failure} Send the upload again once that call is answered.`;
25659
25671
  }
25660
- const stands = commitStandsText(derived.commit_stands);
25661
- return [
25662
- `- ${check.block_id} (${check.when}): ${derived.verdict} at ${derived.commit_sha} by ${derived.role} (CI run ${ci.run}, ${ci.case}), ${stands.charAt(0).toLowerCase()}${stands.slice(1)}. ${check.text}`,
25663
- passStandsLine,
25664
- pullRequestLine,
25665
- ...readingLines(derived, brief, " ")
25666
- ];
25672
+ const asBytes = pathKeepsBytesOf(name) ? ` Send it as a file with ${PATH_KEEPS_BYTES}, which asks this check nothing.` : "";
25673
+ return `${failure} This text is longer than the check reads, and sending the upload again does not change that: a markdown document is at most 1 MiB, so shorten it or split it across documents of at most that.${asBytes}`;
25667
25674
  }
25668
- function checkLines(check, brief) {
25669
- if (check.ci !== undefined)
25670
- return ciCheckLines(check, check.ci, brief);
25671
- const bases = check.compared_with ?? [];
25672
- const reason = check.compared_nothing;
25673
- const compared = bases.length > 0 ? `Compared with ${bases.map(basisText).join(", ")}` : reason === undefined ? "Compared with nothing, and this Dispatch server does not say why" : `Compared with nothing: ${COMPARISON_REASONS[reason]}`;
25674
- const results = check.results ?? [];
25675
- return [
25676
- `- ${check.block_id} (${check.when}). ${compared}. ${passStandsText(check.pass_stands)}.`,
25677
- ` The check's words: ${check.text}`,
25678
- ...results.length === 0 ? [" No result is recorded for this check."] : results.flatMap((result) => resultLines(check, result, brief))
25679
- ];
25675
+ function roundTripRouteAbsent(error) {
25676
+ return dispatchAnswered(error, 404) || dispatchAnswered(error, 405);
25680
25677
  }
25681
- function formatCheckResults(results, brief = false) {
25682
- if (results.verification_artifact_id === "") {
25683
- return `${results.issue} has no Verification document, so it has no checks. Write one (verification.md) with a check block per thing that must be proved.`;
25678
+ function withoutFinalLineFeed(text) {
25679
+ return text.endsWith(`
25680
+ `) ? text.slice(0, -1) : text;
25681
+ }
25682
+ async function artifactCommand(context) {
25683
+ const { args, client, actor, input, documentOwner, issue } = context;
25684
+ const summary = optionalString(args, "summary");
25685
+ const name = stringArg(args, "name");
25686
+ const content = optionalString(args, "content");
25687
+ const path = optionalString(args, "path");
25688
+ const options = { name, ...summary === undefined ? {} : { summary }, actor };
25689
+ const artifactOwner = documentOwner();
25690
+ const blank = content === undefined || goBlankPattern.test(content);
25691
+ if ((path !== undefined || !blank) && optionalBoolean(args, "force") !== true) {
25692
+ const held = artifactUnderName(artifactOwner.kind === "project" ? await client.listProjectArtifacts(artifactOwner.project, true) : await client.listIssueArtifacts(issue()), name);
25693
+ if (held !== undefined) {
25694
+ throw new ToolInputError(input.tool, [
25695
+ artifactNameExistsProblem(held, artifactOwner.kind === "project" ? `project ${artifactOwner.project}` : `issue ${issue()}`)
25696
+ ]);
25697
+ }
25684
25698
  }
25685
- const checks = results.checks ?? [];
25686
- if (checks.length === 0) {
25687
- return `${results.issue}'s Verification document holds no check blocks.`;
25699
+ if (!blank) {
25700
+ let stored;
25701
+ try {
25702
+ stored = await client.markdownRoundTrip(content);
25703
+ } catch (error) {
25704
+ if (!roundTripRouteAbsent(error)) {
25705
+ throw new Error(storedTextCheckFailed(error, name), { cause: error });
25706
+ }
25707
+ }
25708
+ if (stored !== undefined && withoutFinalLineFeed(stored) !== withoutFinalLineFeed(content)) {
25709
+ throw new ToolInputError(input.tool, [storedTextProblem(content, stored, name)]);
25710
+ }
25688
25711
  }
25689
- const blocks = checks.map((check) => checkLines(check, brief).join(`
25690
- `));
25691
- return [`Checks of ${results.issue}:`, ...blocks].join(`
25692
-
25693
- `);
25712
+ const artifactInput = path !== undefined ? {
25713
+ ...options,
25714
+ file: input.uploadBytes === undefined ? Bun.file(resolvePath2(input.cwd, path)) : new Blob([new Uint8Array(input.uploadBytes)], {
25715
+ type: Bun.file(resolvePath2(input.cwd, path)).type
25716
+ })
25717
+ } : content !== undefined ? { ...options, content } : options;
25718
+ const result = artifactOwner.kind === "project" ? await client.projectArtifact(artifactOwner.project, artifactInput) : await client.artifact(issue(), artifactInput);
25719
+ const artifactRef = dispatchDocumentRef(artifactOwner.kind === "project" ? artifactOwner.project : issue(), result.artifact.slug);
25720
+ const uploadOwner = artifactOwner.kind === "project" ? documentTopic(result.artifact) : issueTopic(issue());
25721
+ const adviceLines = renderAdvice(input.tool, uploadOwner.label, result.advice, {
25722
+ isPrimarySpec: result.artifact.primary || result.artifact.name === "spec.md",
25723
+ isPlan: documentPlaysPlan(result.artifact)
25724
+ });
25725
+ return {
25726
+ text: [
25727
+ path === undefined && content === undefined ? `Made ${result.artifact.name} as an empty document (artifact slug ${result.artifact.slug}; ${artifactRef}). Write in it with dispatch doc-edit.${await notSubscribed(uploadOwner, input.subscriptions)}` : `Uploaded ${result.artifact.name} as version ${result.version.number} (artifact slug ${result.artifact.slug}; ${artifactRef})${await notSubscribed(uploadOwner, input.subscriptions)}`,
25728
+ ...adviceLines
25729
+ ].join(`
25730
+ `),
25731
+ details: artifactOwner.kind === "project" ? {
25732
+ ...documentResultDetails(result.artifact),
25733
+ version: result.version.number,
25734
+ ...result.advice === undefined ? {} : { advice: result.advice }
25735
+ } : {
25736
+ issue: issue(),
25737
+ artifact: result.artifact.id,
25738
+ version: result.version.number,
25739
+ ...result.advice === undefined ? {} : { advice: result.advice }
25740
+ }
25741
+ };
25694
25742
  }
25695
- async function resultCommand(context) {
25696
- const { args, client, actor } = context;
25697
- const retract = optionalString(args, "retract");
25698
- if (retract !== undefined) {
25699
- const retraction = await client.retractResult(retract, {
25700
- actor,
25701
- reason: stringArg(args, "reason")
25702
- });
25703
- return {
25704
- text: `Retracted result ${retraction.result_id}. ${actorText(retraction.actor)} retracted it at ${retraction.created_at}. The reason: ${retraction.reason}
25705
25743
 
25706
- The result stays readable, and it proves nothing from now on. Record a new result where the check still needs one.`,
25707
- details: {
25708
- result: retraction.result_id,
25709
- reason: retraction.reason,
25710
- created_at: retraction.created_at
25711
- }
25712
- };
25744
+ // ../envoy-client/src/dispatch-commands/handoffs.ts
25745
+ async function handoffWriteCommand(context) {
25746
+ const { args, client, actor, input, issue } = context;
25747
+ if (!input.sessionId?.trim()) {
25748
+ throw new Error("host session id is required for dispatch handoff-write");
25713
25749
  }
25714
- const issue = stringArg(args, "issue");
25715
- const optional = {
25716
- ...defined("surface", optionalString(args, "surface")),
25717
- ...defined("run", optionalString(args, "run")),
25718
- ...defined("observed", optionalString(args, "observed")),
25719
- ...defined("negative_control", optionalString(args, "negative_control")),
25720
- ...defined("failed", optionalNumber(args, "failed")),
25721
- ...defined("skipped", optionalNumber(args, "skipped")),
25722
- ...defined("excluded", optionalNumber(args, "excluded")),
25723
- ...defined("screenshots", optionalStringArray(args, "screenshots"))
25724
- };
25725
25750
  let recorded;
25726
25751
  try {
25727
- recorded = await client.recordResult(issue, {
25752
+ recorded = await client.writeHandoff(issue(), stringArg(args, "phase"), {
25728
25753
  actor,
25729
- check: stringArg(args, "check"),
25730
- role: stringArg(args, "role"),
25731
- verdict: stringArg(args, "verdict"),
25732
- commit: stringArg(args, "commit"),
25733
- ...optional
25754
+ body: stringArg(args, "body")
25734
25755
  });
25735
25756
  } catch (error) {
25736
- if (dispatchAnswered(error, 409) && error.code === "CHECK_CONTENDED") {
25737
- throw refusalWithCode(error, "the check moved twice while this result was being written, and nothing was recorded: run the same dispatch result command again");
25738
- }
25739
- throw error;
25757
+ throw refusalWithCode(error);
25740
25758
  }
25741
25759
  return {
25742
- text: `Recorded ${recorded.result.verdict} for check ${recorded.result.check_block_id} of ${recorded.result.check_issue_key} at ${recorded.result.commit_sha}, as ${recorded.result.role}.
25743
-
25744
- Pull request body line:
25745
- ${recorded.line}`,
25760
+ text: `Recorded the ${recorded.phase} handoff of ${recorded.issue_key}, version ${recorded.version} (id ${recorded.id})`,
25746
25761
  details: {
25747
- issue,
25748
- result: recorded.result.id,
25749
- check: recorded.result.check_block_id,
25750
- verdict: recorded.result.verdict,
25751
- line: recorded.line
25762
+ issue: recorded.issue_key,
25763
+ phase: recorded.phase,
25764
+ version: recorded.version,
25765
+ handoff: recorded.id
25752
25766
  }
25753
25767
  };
25754
25768
  }
25755
- async function resultsCommand(context) {
25756
- const { args, client } = context;
25757
- const issue = stringArg(args, "issue");
25758
- const at = optionalString(args, "at");
25759
- const brief = optionalBoolean(args, "brief") === true;
25760
- const results = await client.issueResults(issue, at);
25761
- const checks = results.checks ?? [];
25769
+ async function handoffReadCommand(context) {
25770
+ const { args, client, issue } = context;
25771
+ const issueKey = issue();
25772
+ const phase = stringArg(args, "phase");
25773
+ const version = optionalNumber(args, "version");
25774
+ let handoff;
25775
+ try {
25776
+ if (version === undefined) {
25777
+ handoff = await client.latestHandoff(issueKey, phase);
25778
+ } else {
25779
+ const listed = await client.listHandoffs(issueKey);
25780
+ const ofPhase = listed.filter((summary) => summary.phase === phase);
25781
+ const match = ofPhase.find((summary) => summary.version === version);
25782
+ if (match === undefined) {
25783
+ const newest = Math.max(0, ...ofPhase.map((summary) => summary.version));
25784
+ throw new Error(`HANDOFF_NOT_FOUND: issue ${issueKey} has no ${phase} handoff version ${version}; ${newest === 0 ? `it has no ${phase} handoff at all` : `its newest ${phase} handoff is version ${newest}`}`);
25785
+ }
25786
+ handoff = await client.handoff(match.id);
25787
+ }
25788
+ } catch (error) {
25789
+ throw refusalWithCode(error);
25790
+ }
25762
25791
  return {
25763
- text: formatCheckResults(results, brief),
25792
+ text: `${handoff.issue_key} ${handoff.phase} handoff, version ${handoff.version} (id ${handoff.id}), written by ${actorText(handoff.author)} at ${handoff.created_at}
25793
+ ${handoff.body}`,
25764
25794
  details: {
25765
- issue,
25766
- checks: checks.length,
25767
- results: checks.reduce((total, check) => total + (check.results ?? []).length, 0)
25795
+ issue: handoff.issue_key,
25796
+ phase: handoff.phase,
25797
+ version: handoff.version,
25798
+ handoff: handoff.id
25768
25799
  }
25769
25800
  };
25770
25801
  }
@@ -26806,6 +26837,9 @@ async function executeDispatchTool(input) {
26806
26837
  });
26807
26838
  if (checked.problems.length > 0)
26808
26839
  throw new ToolInputError(input.tool, checked.problems);
26840
+ if (input.dryRun === true && !dryRunAsksDispatch(input.tool, checked.args)) {
26841
+ throw new Error(`dispatch ${input.tool}'s dry run asks Dispatch nothing`);
26842
+ }
26809
26843
  const command = dispatchCommands[input.tool];
26810
26844
  if (command === undefined)
26811
26845
  throw new Error(`Unknown Dispatch tool: ${input.tool}`);