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