@gumpwang/agent-workflow 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7324,7 +7324,7 @@ var require_dist = __commonJS({
7324
7324
 
7325
7325
  // src/cli/main.ts
7326
7326
  import { spawn as spawn3 } from "child_process";
7327
- import { closeSync as closeSync3, existsSync as existsSync10, mkdirSync as mkdirSync7, openSync as openSync3, readFileSync as readFileSync9 } from "fs";
7327
+ import { closeSync as closeSync3, existsSync as existsSync11, mkdirSync as mkdirSync7, openSync as openSync3, readFileSync as readFileSync9 } from "fs";
7328
7328
  import { homedir as homedir5 } from "os";
7329
7329
  import { dirname as dirname5, join as join6, relative as relative2, resolve as resolve6 } from "path";
7330
7330
  import { fileURLToPath } from "url";
@@ -7653,12 +7653,12 @@ var ID = /^[a-z][a-z0-9_-]*$/;
7653
7653
  var COMPLETION_COMMAND = /agent-workflow\s+deliver/;
7654
7654
  var DEFAULT_MAX_ATTEMPTS = 3;
7655
7655
  var FIXED_FIELDS = {
7656
- ticket: ["id", "identifier", "title", "description", "url", "state", "number", "labels", "assignee"],
7656
+ ticket: ["id", "identifier", "title", "description", "url", "state", "number", "labels", "assignee", "blocked_by", "branch", "base"],
7657
7657
  project: ["name", "root", "repo", "slug", "tracker"],
7658
- workspace: ["path", "branch"],
7658
+ workspace: ["path", "branch", "base"],
7659
7659
  rules: ["dir"]
7660
7660
  };
7661
- var SHELL_SAFE_TICKET_FIELDS = ["id", "identifier", "number", "state"];
7661
+ var SHELL_SAFE_TICKET_FIELDS = ["id", "identifier", "number", "state", "blocked_by", "branch", "base"];
7662
7662
  var DELIVERY_FIELDS = ["path", "verdict"];
7663
7663
  var STEP_FIELDS = ["outcome", "outputs"];
7664
7664
  var ROLE_FIELDS = ["agent", "session"];
@@ -7725,7 +7725,7 @@ var WorkflowChecker = class {
7725
7725
  file: this.file,
7726
7726
  rulesDir: this.rulesDir,
7727
7727
  name: "",
7728
- on: { states: [], tracked: false },
7728
+ on: { states: [], tracked: false, anyAssignee: false },
7729
7729
  onInterrupt: "cancel",
7730
7730
  inputs: {},
7731
7731
  roles: {},
@@ -7741,11 +7741,12 @@ var WorkflowChecker = class {
7741
7741
  wf.description = this.string(raw, "description", "");
7742
7742
  const on = this.map(raw, "on", "", true);
7743
7743
  if (on) {
7744
- this.unknownKeys(on, "on", ["states", "tracked"]);
7744
+ this.unknownKeys(on, "on", ["states", "tracked", "any_assignee"]);
7745
7745
  const states = this.stringList(on, "states", "on", true);
7746
7746
  if (states && !states.length) this.invalid("on.states", "list at least one ticket state");
7747
7747
  wf.on.states = states ?? [];
7748
7748
  wf.on.tracked = this.bool(on, "tracked", "on") ?? false;
7749
+ wf.on.anyAssignee = this.bool(on, "any_assignee", "on") ?? false;
7749
7750
  }
7750
7751
  const onInterrupt = this.string(raw, "on_interrupt", "");
7751
7752
  if (onInterrupt !== void 0) {
@@ -8001,8 +8002,14 @@ var WorkflowChecker = class {
8001
8002
  const t = this.map(raw, "tracker", at, true);
8002
8003
  if (!t) return void 0;
8003
8004
  const tat = join(at, "tracker");
8004
- this.unknownKeys(t, tat, ["state", "comment", "label"]);
8005
+ this.unknownKeys(t, tat, ["state", "comment", "reason", "label"]);
8005
8006
  const step = { ...base, verb, state: this.string(t, "state", tat), comment: this.string(t, "comment", tat) };
8007
+ const reason = this.string(t, "reason", tat);
8008
+ if (reason !== void 0) {
8009
+ if (reason !== "completed" && reason !== "not_planned") this.invalid(join(tat, "reason"), "use completed or not_planned");
8010
+ else if (!step.state) this.invalid(join(tat, "reason"), "reason goes with a state");
8011
+ else step.reason = reason;
8012
+ }
8006
8013
  if (t.label !== void 0) this.notImplemented(join(tat, "label"), "tracker.label");
8007
8014
  else if (!step.state && !step.comment) this.invalid(tat, "set at least one of state or comment");
8008
8015
  for (const key of ["state", "comment"]) if (step[key]) this.template(step[key], join(tat, key), inLoop);
@@ -8289,13 +8296,6 @@ function validateHome(home) {
8289
8296
  if (p) parsed.push(p);
8290
8297
  }
8291
8298
  if (!main2 || !agents || diagnostics.length) return { diagnostics };
8292
- for (const a of Object.values(agents.agents)) {
8293
- for (const [key, cmd] of [["command", a.command], ["resume_command", a.resumeCommand]]) {
8294
- if (cmd !== void 0 && !/\$\{?SESSION_ID\b/.test(cmd)) {
8295
- report("warning", agentsFile, `agents.${a.name}.${key}`, "SESSION_ID_MISSING", "the command must carry $SESSION_ID on its command line, or the agent looks dead right after it starts");
8296
- }
8297
- }
8298
- }
8299
8299
  const stateOwner = /* @__PURE__ */ new Map();
8300
8300
  for (const p of parsed) {
8301
8301
  const prev = stateOwner.get(p.stateDir);
@@ -8525,17 +8525,18 @@ var ConfigChecker = class {
8525
8525
  workspace(raw, at, projectDir) {
8526
8526
  if (raw === void 0) return void 0;
8527
8527
  if (!isObj2(raw)) {
8528
- this.invalid(at, "must be a map with optional path, branch, provision, cleanup");
8528
+ this.invalid(at, "must be a map with optional path, branch, base, provision, cleanup");
8529
8529
  return void 0;
8530
8530
  }
8531
- this.unknownKeys(raw, at, ["path", "branch", "provision", "cleanup"]);
8531
+ this.unknownKeys(raw, at, ["path", "branch", "base", "provision", "cleanup"]);
8532
8532
  const ws = {
8533
8533
  path: this.string(raw, "path", at) ?? join2(projectDir, "workspace", "${{ ticket.identifier }}"),
8534
8534
  branch: this.string(raw, "branch", at),
8535
+ base: this.string(raw, "base", at),
8535
8536
  provision: this.string(raw, "provision", at),
8536
8537
  cleanup: this.string(raw, "cleanup", at)
8537
8538
  };
8538
- for (const key of ["path", "branch"]) {
8539
+ for (const key of ["path", "branch", "base"]) {
8539
8540
  for (const src of templateExprs(ws[key] ?? "")) {
8540
8541
  let node;
8541
8542
  try {
@@ -8674,7 +8675,7 @@ function startAgent(opts) {
8674
8675
  `);
8675
8676
  const stdinFd = openSync(opts.stdinFile, "r");
8676
8677
  try {
8677
- const child = spawn("bash", ["-c", opts.command], {
8678
+ const child = spawn("bash", ["-c", 'bash -c "$1"; result=$?; exit "$result"', `agent-workflow:${opts.env.SESSION_ID}`, opts.command], {
8678
8679
  cwd: opts.cwd,
8679
8680
  detached: true,
8680
8681
  stdio: [stdinFd, logFd, logFd],
@@ -8798,6 +8799,18 @@ function releaseLock(file) {
8798
8799
  }
8799
8800
 
8800
8801
  // src/tracker/common.ts
8802
+ function branchMarkers(description) {
8803
+ const find = (key) => {
8804
+ const m = new RegExp(`^${key}:[ \\t]*(\\S+?)[ \\t\\r]*$`, "m").exec(description);
8805
+ const name = m?.[1].replace(/^`(.*)`$/, "$1");
8806
+ return name !== void 0 && isPlainRef(name) ? name : null;
8807
+ };
8808
+ return { branch: find("Branch"), base: find("Base") };
8809
+ }
8810
+ function isPlainRef(name) {
8811
+ return /^[A-Za-z0-9._/-]+$/.test(name) && !/^[-/]|[/.]$|\.\.|\/\/|(^|\/)\.|\.lock$/.test(name);
8812
+ }
8813
+ var EVIDENCE_BRANCH = "agent-evidence";
8801
8814
  var TicketError = class extends Error {
8802
8815
  code;
8803
8816
  constructor(message, code) {
@@ -8860,6 +8873,12 @@ var API_URL = () => (process.env.GITHUB_API_URL || "https://api.github.com").rep
8860
8873
  var FIXED_STATES = ["Open", "Closed"];
8861
8874
  var same = (a, b) => a.toLowerCase() === b.toLowerCase();
8862
8875
  var labelNames = (raw) => raw.labels.map((l) => typeof l === "string" ? l : l.name);
8876
+ async function openBlockers(repo, raw) {
8877
+ const summary = raw.issue_dependencies_summary?.blocked_by;
8878
+ if (typeof summary === "number") return summary;
8879
+ const { status, data } = await api("GET", `/repos/${repo}/issues/${raw.number}/dependencies/blocked_by?per_page=100`, void 0, [404, 410]);
8880
+ return status === 200 ? data.filter((i) => i.state === "open").length : 0;
8881
+ }
8863
8882
  function githubStateLabels(project) {
8864
8883
  const byPriority = Object.values(project.triggers).reverse().flatMap((states) => states.map((s) => project.tracker.stateAlias[s] ?? s));
8865
8884
  const other = [...project.tracker.otherStates, ...project.attentionState ? [project.attentionState] : []].map((s) => project.tracker.stateAlias[s] ?? s);
@@ -8948,9 +8967,12 @@ async function githubTickets(p, tracked) {
8948
8967
  state: canonical(spelledState(raw, labels)),
8949
8968
  labels: labelNames(raw),
8950
8969
  assignee: users[0] ?? null,
8951
- assignees: users
8970
+ assignees: users,
8971
+ blockedBy: 0
8952
8972
  };
8953
- if (wanted.has(ticket.state.toLowerCase()) || trackedSet.has(ticket.identifier)) tickets.push(ticket);
8973
+ if (!wanted.has(ticket.state.toLowerCase()) && !trackedSet.has(ticket.identifier)) continue;
8974
+ if (raw.state === "open") ticket.blockedBy = await openBlockers(repo, raw);
8975
+ tickets.push(ticket);
8954
8976
  }
8955
8977
  let viewer;
8956
8978
  return {
@@ -9004,10 +9026,11 @@ function githubAdapter(p) {
9004
9026
  states: catalogue,
9005
9027
  labels: labelNames(raw),
9006
9028
  assignees: (raw.assignees ?? []).map((a) => a.login),
9029
+ blocked_by: await openBlockers(repo, raw),
9007
9030
  description: raw.body ?? ""
9008
9031
  };
9009
9032
  },
9010
- async setState(identifier, wanted) {
9033
+ async setState(identifier, wanted, reason = "completed") {
9011
9034
  const state = pickState(project, catalogue, wanted);
9012
9035
  const target = project.tracker.stateAlias[state] ?? state;
9013
9036
  const { raw, path } = await load(identifier);
@@ -9018,7 +9041,7 @@ function githubAdapter(p) {
9018
9041
  const hasTarget = !isLabel || names.some((n) => same(n, target));
9019
9042
  if (stale.length === 0 && hasTarget && raw.state === "closed" === wantClosed) return { state, changed: false };
9020
9043
  if (raw.state === "closed" !== wantClosed) {
9021
- await api("PATCH", path, wantClosed ? { state: "closed", state_reason: "completed" } : { state: "open" });
9044
+ await api("PATCH", path, wantClosed ? { state: "closed", state_reason: reason } : { state: "open" });
9022
9045
  }
9023
9046
  if (!hasTarget) {
9024
9047
  const add = await api("POST", `${path}/labels`, { labels: [target] }, [404, 422]);
@@ -9030,6 +9053,34 @@ function githubAdapter(p) {
9030
9053
  for (const label of stale) await api("DELETE", `${path}/labels/${encodeURIComponent(label)}`, void 0, [404]);
9031
9054
  return { state, changed: true };
9032
9055
  },
9056
+ async addLabels(identifier, names) {
9057
+ const { raw, path } = await load(identifier);
9058
+ const have = labelNames(raw);
9059
+ const add = names.filter((n) => !have.some((h) => same(h, n)));
9060
+ if (!add.length) return have;
9061
+ const res = await api("POST", `${path}/labels`, { labels: add }, [404, 422]);
9062
+ if (res.status === 200) return res.data.map((l) => l.name);
9063
+ for (const name of add) await api("POST", `/repos/${repo}/labels`, { name }, [422]);
9064
+ return (await api("POST", `${path}/labels`, { labels: add })).data.map((l) => l.name);
9065
+ },
9066
+ async removeLabels(identifier, names) {
9067
+ const { raw, path } = await load(identifier);
9068
+ let have = labelNames(raw);
9069
+ for (const name of names) {
9070
+ const hit = have.find((h) => same(h, name));
9071
+ if (!hit) continue;
9072
+ await api("DELETE", `${path}/labels/${encodeURIComponent(hit)}`, void 0, [404]);
9073
+ have = have.filter((h) => h !== hit);
9074
+ }
9075
+ return have;
9076
+ },
9077
+ async assign(identifier, users) {
9078
+ const { path } = await load(identifier);
9079
+ const logins = [];
9080
+ for (const u of users) logins.push(u.toLowerCase() === "me" ? (await api("GET", "/user")).data.login : u);
9081
+ const { data } = await api("PATCH", path, { assignees: logins });
9082
+ return (data.assignees ?? []).map((a) => a.login);
9083
+ },
9033
9084
  async comment(identifier, body) {
9034
9085
  const { path } = await load(identifier);
9035
9086
  const { data } = await api("POST", `${path}/comments`, { body });
@@ -9054,6 +9105,32 @@ function githubAdapter(p) {
9054
9105
  async attach(identifier) {
9055
9106
  issuePath(identifier);
9056
9107
  return "unsupported";
9108
+ },
9109
+ async upload(identifier, files) {
9110
+ const { number } = issuePath(identifier);
9111
+ const issue = await getIssue(repo, number);
9112
+ if (!issue) throw new TicketError(`ticket not found: ${identifier}`, 4);
9113
+ const web = new URL(issue.html_url).origin;
9114
+ const dir = `${identifier}/${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
9115
+ const entries = [];
9116
+ for (const f of files) {
9117
+ const blob = await api("POST", `/repos/${repo}/git/blobs`, { content: f.content.toString("base64"), encoding: "base64" });
9118
+ entries.push({ name: f.name, path: `${dir}/${f.name}`, sha: blob.data.sha });
9119
+ }
9120
+ const tree = entries.map((e) => ({ path: e.path, mode: "100644", type: "blob", sha: e.sha }));
9121
+ for (let attempt = 1; ; attempt++) {
9122
+ const ref = await api("GET", `/repos/${repo}/git/ref/heads/${EVIDENCE_BRANCH}`, void 0, [404]);
9123
+ const parent = ref.status === 404 ? void 0 : ref.data.object.sha;
9124
+ const baseTree = parent && (await api("GET", `/repos/${repo}/git/commits/${parent}`)).data.tree.sha;
9125
+ const treeSha = (await api("POST", `/repos/${repo}/git/trees`, baseTree ? { base_tree: baseTree, tree } : { tree })).data.sha;
9126
+ const commit = (await api("POST", `/repos/${repo}/git/commits`, { message: `evidence for ${identifier}`, tree: treeSha, parents: parent ? [parent] : [] })).data.sha;
9127
+ const moved = parent ? await api("PATCH", `/repos/${repo}/git/refs/heads/${EVIDENCE_BRANCH}`, { sha: commit, force: false }, [422]) : await api("POST", `/repos/${repo}/git/refs`, { ref: `refs/heads/${EVIDENCE_BRANCH}`, sha: commit }, [422]);
9128
+ if (moved.status !== 422) {
9129
+ const encode = (path) => path.split("/").map(encodeURIComponent).join("/");
9130
+ return entries.map((e) => ({ name: e.name, url: `${web}/${repo}/blob/${commit}/${encode(e.path)}?raw=true` }));
9131
+ }
9132
+ if (attempt === 3) throw new TicketError(`could not update branch ${EVIDENCE_BRANCH} of ${repo}: it kept moving`, 3);
9133
+ }
9057
9134
  }
9058
9135
  };
9059
9136
  }
@@ -9063,6 +9140,10 @@ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
9063
9140
  import { homedir as homedir2 } from "os";
9064
9141
  import { join as join3 } from "path";
9065
9142
  var API_URL2 = () => process.env.LINEAR_API_URL || "https://api.linear.app/graphql";
9143
+ var TICKET_EXTRAS = `labels{ nodes{ name } } inverseRelations{ nodes{ type issue{ state{ type } } } }`;
9144
+ function openBlockers2(issue) {
9145
+ return (issue.inverseRelations?.nodes ?? []).filter((r) => r.type === "blocks" && r.issue && !["completed", "canceled"].includes(r.issue.state.type)).length;
9146
+ }
9066
9147
  async function graphql(apiKey, query, variables) {
9067
9148
  const res = await fetch(API_URL2(), {
9068
9149
  method: "POST",
@@ -9120,7 +9201,7 @@ async function linearTickets(apiKey, projects) {
9120
9201
  apiKey,
9121
9202
  `query($pids:[ID!]!, $states:[String!]!){
9122
9203
  issues(filter:{project:{id:{in:$pids}}, state:{name:{in:$states}}}, first:250){
9123
- nodes{ id identifier title description url state{name} assignee{ id name displayName email } project{id} updatedAt }
9204
+ nodes{ id identifier title description url state{name} assignee{ id name displayName email } project{id} updatedAt ${TICKET_EXTRAS} }
9124
9205
  }
9125
9206
  }`,
9126
9207
  { pids: ids, states }
@@ -9137,9 +9218,10 @@ async function linearTickets(apiKey, projects) {
9137
9218
  description: n.description ?? "",
9138
9219
  url: n.url ?? "",
9139
9220
  state: canonical(n.state.name),
9140
- labels: [],
9221
+ labels: n.labels?.nodes.map((l) => l.name) ?? [],
9141
9222
  assignee: n.assignee,
9142
- assignees: n.assignee ? [n.assignee] : []
9223
+ assignees: n.assignee ? [n.assignee] : [],
9224
+ blockedBy: openBlockers2(n)
9143
9225
  }));
9144
9226
  out.push({
9145
9227
  project,
@@ -9177,6 +9259,30 @@ function linearAdapter(project) {
9177
9259
  const canonical = canonicalizer(project);
9178
9260
  const gql = (query, variables) => graphql(linearKey(project), query, variables);
9179
9261
  const notFound = (identifier) => new TicketError(`ticket not found: ${identifier}`, 4);
9262
+ const same2 = (a, b) => a.toLowerCase() === b.toLowerCase();
9263
+ const labelled = async (identifier) => {
9264
+ const r = await gql(
9265
+ `query($id:String!){issue(id:$id){ id team{ id } labels{ nodes{ id name } } }}`,
9266
+ { id: identifier }
9267
+ );
9268
+ if (!r.issue) throw notFound(identifier);
9269
+ return { id: r.issue.id, teamId: r.issue.team.id, labels: r.issue.labels.nodes };
9270
+ };
9271
+ const teamLabel = async (teamId, name) => {
9272
+ const r = await gql(
9273
+ `query($n:String!){ issueLabels(filter:{name:{eqIgnoreCase:$n}}, first:50){ nodes{ id name team{ id } } } }`,
9274
+ { n: name }
9275
+ );
9276
+ return r.issueLabels.nodes.find((l) => !l.team || l.team.id === teamId)?.id;
9277
+ };
9278
+ const createLabel = async (teamId, name) => {
9279
+ const r = await gql(
9280
+ `mutation($t:String!,$n:String!){ issueLabelCreate(input:{teamId:$t, name:$n}){ success issueLabel{ id } } }`,
9281
+ { t: teamId, n: name }
9282
+ );
9283
+ if (!r.issueLabelCreate.success) throw new TicketError(`creating Linear label '${name}' failed`, 3);
9284
+ return r.issueLabelCreate.issueLabel.id;
9285
+ };
9180
9286
  const issueId = async (identifier) => {
9181
9287
  const r = await gql(`query($id:String!){issue(id:$id){id}}`, { id: identifier });
9182
9288
  if (!r.issue) throw notFound(identifier);
@@ -9187,7 +9293,7 @@ function linearAdapter(project) {
9187
9293
  env: () => linearEnv(project),
9188
9294
  async get(identifier) {
9189
9295
  const r = await gql(
9190
- `query($id:String!){issue(id:$id){ id identifier title url description state{name} labels{nodes{name}} assignee{displayName} }}`,
9296
+ `query($id:String!){issue(id:$id){ id identifier title url description state{name} assignee{displayName} ${TICKET_EXTRAS} }}`,
9191
9297
  { id: identifier }
9192
9298
  );
9193
9299
  if (!r.issue) throw notFound(identifier);
@@ -9200,6 +9306,7 @@ function linearAdapter(project) {
9200
9306
  states: catalogue,
9201
9307
  labels: i.labels?.nodes.map((l) => l.name) ?? [],
9202
9308
  assignees: i.assignee ? [i.assignee.displayName] : [],
9309
+ blocked_by: openBlockers2(i),
9203
9310
  description: i.description ?? ""
9204
9311
  };
9205
9312
  },
@@ -9224,6 +9331,45 @@ function linearAdapter(project) {
9224
9331
  if (!res.issueUpdate.success) throw new TicketError(`issueUpdate failed for ${identifier}`, 3);
9225
9332
  return { state, changed: true };
9226
9333
  },
9334
+ async addLabels(identifier, names) {
9335
+ const issue = await labelled(identifier);
9336
+ for (const name of names) {
9337
+ if (issue.labels.some((l) => same2(l.name, name))) continue;
9338
+ const labelId = await teamLabel(issue.teamId, name) ?? await createLabel(issue.teamId, name);
9339
+ const res = await gql(`mutation($id:String!,$l:String!){ issueAddLabel(id:$id, labelId:$l){ success } }`, { id: issue.id, l: labelId });
9340
+ if (!res.issueAddLabel.success) throw new TicketError(`adding label '${name}' failed for ${identifier}`, 3);
9341
+ }
9342
+ return (await labelled(identifier)).labels.map((l) => l.name);
9343
+ },
9344
+ async removeLabels(identifier, names) {
9345
+ const issue = await labelled(identifier);
9346
+ for (const name of names) {
9347
+ const hit = issue.labels.find((l) => same2(l.name, name));
9348
+ if (!hit) continue;
9349
+ const res = await gql(`mutation($id:String!,$l:String!){ issueRemoveLabel(id:$id, labelId:$l){ success } }`, { id: issue.id, l: hit.id });
9350
+ if (!res.issueRemoveLabel.success) throw new TicketError(`removing label '${name}' failed for ${identifier}`, 3);
9351
+ }
9352
+ return (await labelled(identifier)).labels.map((l) => l.name);
9353
+ },
9354
+ async assign(identifier, users) {
9355
+ if (users.length !== 1) throw new TicketError("a Linear issue has exactly one assignee: name one user", 2);
9356
+ const id = await issueId(identifier);
9357
+ const wanted = users[0];
9358
+ let userId;
9359
+ if (wanted.toLowerCase() === "me") userId = (await gql(`query{viewer{id}}`, {})).viewer.id;
9360
+ else {
9361
+ const r = await gql(`query{ users(first:250){ nodes{ id name displayName email } } }`, {});
9362
+ const hit = r.users.nodes.find((u) => u.id === wanted || [u.name, u.displayName, u.email].some((v) => v && same2(v, wanted)));
9363
+ if (!hit) throw new TicketError(`no Linear user matches '${wanted}'`, 4);
9364
+ userId = hit.id;
9365
+ }
9366
+ const res = await gql(
9367
+ `mutation($id:String!,$u:String!){ issueUpdate(id:$id, input:{assigneeId:$u}){ success issue{ assignee{ displayName } } } }`,
9368
+ { id, u: userId }
9369
+ );
9370
+ if (!res.issueUpdate.success) throw new TicketError(`assigning ${identifier} failed`, 3);
9371
+ return res.issueUpdate.issue.assignee ? [res.issueUpdate.issue.assignee.displayName] : [];
9372
+ },
9227
9373
  async comment(identifier, body) {
9228
9374
  const id = await issueId(identifier);
9229
9375
  const res = await gql(
@@ -9264,6 +9410,25 @@ function linearAdapter(project) {
9264
9410
  );
9265
9411
  if (!res.attachmentLinkGitHubPR.success) throw new TicketError(`attach failed for ${identifier}`, 3);
9266
9412
  return "attached";
9413
+ },
9414
+ async upload(identifier, files) {
9415
+ const r = await gql(`query($id:String!){issue(id:$id){ id }}`, { id: identifier });
9416
+ if (!r.issue) throw notFound(identifier);
9417
+ const out = [];
9418
+ for (const f of files) {
9419
+ const res = await gql(
9420
+ `mutation($t:String!,$n:String!,$s:Int!){ fileUpload(contentType:$t, filename:$n, size:$s){ success uploadFile{ uploadUrl assetUrl headers{ key value } } } }`,
9421
+ { t: f.contentType, n: f.name, s: f.content.length }
9422
+ );
9423
+ const target = res.fileUpload.uploadFile;
9424
+ if (!res.fileUpload.success || !target) throw new TicketError(`Linear refused the upload of ${f.name}`, 3);
9425
+ const headers = { "Content-Type": f.contentType, "Cache-Control": "public, max-age=31536000" };
9426
+ for (const h of target.headers) headers[h.key] = h.value;
9427
+ const put = await fetch(target.uploadUrl, { method: "PUT", headers, body: f.content });
9428
+ if (!put.ok) throw new TicketError(`uploading ${f.name} to Linear storage: HTTP ${put.status}: ${(await put.text()).slice(0, 400)}`, 3);
9429
+ out.push({ name: f.name, url: target.assetUrl });
9430
+ }
9431
+ return out;
9267
9432
  }
9268
9433
  };
9269
9434
  }
@@ -9602,6 +9767,7 @@ async function execute(e, t, wf, step) {
9602
9767
  run2.attention = `${step.at}: wait timed out after ${step.timeoutMinutes} min`;
9603
9768
  return "attention";
9604
9769
  }
9770
+ e.record({ ticket: t.identifier, action: "waiting", workflow: wf.id, detail: step.name ?? step.id ?? step.at });
9605
9771
  return "block";
9606
9772
  }
9607
9773
  case "tracker":
@@ -9698,8 +9864,8 @@ async function turn(e, t, wf, step, scope) {
9698
9864
  }
9699
9865
  const inTrigger = !t.offTrigger && (t.project.triggers[wf.id] ?? []).some((st) => st.toLowerCase() === t.ticket.state.toLowerCase());
9700
9866
  if (!inTrigger) {
9701
- if (step.id) run2.steps[step.id] = { outcome: "no-delivery", outputs: {} };
9702
- return "next";
9867
+ run2.attention = `${step.at}: agent ended without delivery '${expect.delivery}' outside the workflow trigger states`;
9868
+ return "attention";
9703
9869
  }
9704
9870
  delete run2.turn;
9705
9871
  run2.nudge = true;
@@ -9714,7 +9880,7 @@ async function turn(e, t, wf, step, scope) {
9714
9880
  const maxAttempts = wf.roles[role]?.maxAttempts ?? 3;
9715
9881
  const continues = !!session && (step.verb === "message" || !!session.session_id);
9716
9882
  const resume = continues && profile.session === "claude" && !!session.session_id;
9717
- const used = step.verb === "launch" ? session?.turns ?? 0 : run2.step_turns ?? 0;
9883
+ const used = run2.step_turns ?? 0;
9718
9884
  if (session && used >= maxAttempts) {
9719
9885
  run2.attention = expect ? `agent ended ${used} turn(s) without a delivery for '${expect.delivery}'; run still at step ${step.id ?? step.at}` : `agent exited ${used} time(s); run still at step ${step.id ?? step.at}`;
9720
9886
  return "attention";
@@ -9772,7 +9938,7 @@ ${completionInstructions(expect, !!run2.nudge)}`;
9772
9938
  ticket: t.identifier,
9773
9939
  action: kind,
9774
9940
  workflow: wf.id,
9775
- detail: kind === "enter" ? `project=${t.project.name} pid=${pid} workspace=${workspace}` : `project=${t.project.name} pid=${pid} attempt=${step.verb === "launch" ? turns : run2.step_turns}/${maxAttempts}${run2.nudge ? " (no delivery yet)" : ""}`
9941
+ detail: kind === "enter" ? `project=${t.project.name} pid=${pid} workspace=${workspace}` : `project=${t.project.name} pid=${pid} attempt=${run2.step_turns}/${maxAttempts}${run2.nudge ? " (no delivery yet)" : ""}`
9776
9942
  });
9777
9943
  return "block";
9778
9944
  }
@@ -9826,7 +9992,8 @@ async function trackerStep(e, t, wf, step, scope) {
9826
9992
  }
9827
9993
  if (step.state) {
9828
9994
  const state = String(interpolate(step.state, scope));
9829
- ops.push({ what: `state \u2192 ${state}`, apply: () => tracker.setState(t.identifier, state) });
9995
+ const why = step.reason ? ` (${step.reason})` : "";
9996
+ ops.push({ what: `state \u2192 ${state}${why}`, apply: () => tracker.setState(t.identifier, state, step.reason) });
9830
9997
  }
9831
9998
  for (const op of ops) {
9832
9999
  if (e.dryRun) {
@@ -9882,11 +10049,13 @@ function workspaceOf(project, ticket) {
9882
10049
  const def = project.workspace;
9883
10050
  if (!def) return { path: project.root, ready: true };
9884
10051
  const scope = { ticket: ticketView(ticket), project: projectView(project) };
9885
- return {
10052
+ const ws = {
9886
10053
  path: resolve4(project.dir, expandHome2(String(interpolate(def.path, scope)))),
9887
10054
  branch: def.branch ? String(interpolate(def.branch, scope)) : void 0,
9888
10055
  ready: false
9889
10056
  };
10057
+ if (def.base) ws.base = String(interpolate(def.base, scope));
10058
+ return ws;
9890
10059
  }
9891
10060
  function ticketView(ticket) {
9892
10061
  return {
@@ -9898,7 +10067,10 @@ function ticketView(ticket) {
9898
10067
  state: ticket.state,
9899
10068
  number: ticket.number ?? null,
9900
10069
  labels: ticket.labels,
9901
- assignee: ticket.assignee
10070
+ assignee: ticket.assignee,
10071
+ // Absent in tickets a ledger saved before blockers were read.
10072
+ blocked_by: ticket.blockedBy ?? 0,
10073
+ ...branchMarkers(ticket.description)
9902
10074
  };
9903
10075
  }
9904
10076
  function projectView(project) {
@@ -9921,7 +10093,7 @@ function scopeOf(e, t, wf) {
9921
10093
  state: run2.state,
9922
10094
  ticket: ticketView(t.ticket),
9923
10095
  project: projectView(t.project),
9924
- workspace: { path: t.ctx.workspace?.path ?? t.project.root, branch: t.ctx.workspace?.branch ?? "" },
10096
+ workspace: { path: t.ctx.workspace?.path ?? t.project.root, branch: t.ctx.workspace?.branch ?? "", base: t.ctx.workspace?.base ?? "" },
9925
10097
  rules: { dir: wf.rulesDir },
9926
10098
  deliveries: Object.fromEntries(Object.entries(t.ctx.deliveries ?? {}).map(([k, d]) => [k, { path: d.path, verdict: d.verdict ?? null }])),
9927
10099
  steps: run2.steps,
@@ -9947,6 +10119,7 @@ function baseEnv(e, t, wf) {
9947
10119
  WORKSPACE: ws.path,
9948
10120
  WORKSPACE_ROOT: ws.path,
9949
10121
  WORKSPACE_BRANCH: t.ctx.workspace?.branch ?? "",
10122
+ WORKSPACE_BASE: t.ctx.workspace?.base ?? "",
9950
10123
  ISSUE_ID: t.ticket.id,
9951
10124
  ISSUE_IDENTIFIER: t.identifier,
9952
10125
  ISSUE_TITLE: t.ticket.title,
@@ -10162,16 +10335,11 @@ async function advanceOne(paths2, config, identifier, opts) {
10162
10335
  const project = ctx && config.projects[ctx.project];
10163
10336
  if (!ctx || !project || !isActive(ctx)) return;
10164
10337
  const engine = engineFor(paths2, config, ledger, opts);
10165
- let ticket = ctx.ticket;
10166
- let offTrigger = false;
10167
10338
  const tracker = adapterFor(project);
10168
- try {
10169
- const state = await tracker.refresh(ticket);
10170
- if (state) ticket = { ...ticket, state };
10171
- offTrigger = !desiredWorkflow(project, ticket);
10172
- } catch (err) {
10173
- console.warn(`could not read ${identifier} from the tracker, using the last snapshot: ${err instanceof Error ? err.message : err}`);
10174
- }
10339
+ const state = await tracker.refresh(ctx.ticket);
10340
+ if (!state) throw new Error(`could not read ${identifier} from the tracker; run was not advanced`);
10341
+ const ticket = { ...ctx.ticket, state };
10342
+ const offTrigger = !desiredWorkflow(project, ticket);
10175
10343
  ctx.ticket = ticket;
10176
10344
  const work = { identifier, ctx, project, ticket, trackerEnv: tracker.env(ticket), offTrigger };
10177
10345
  await advanceActive(engine, ledger, work);
@@ -10188,7 +10356,7 @@ function workOf(identifier, ctx, pt, ticket) {
10188
10356
  async function handleTicket(e, ledger, pt, ticket, desired) {
10189
10357
  const id = ticket.identifier;
10190
10358
  let ctx = ledger.tickets[id];
10191
- if (desired && !desired.on.tracked && !pt.isMine(ticket)) {
10359
+ if (desired && !desired.on.tracked && !desired.on.anyAssignee && !pt.isMine(ticket)) {
10192
10360
  if (!ctx) return;
10193
10361
  const to = ticket.assignee?.displayName || ticket.assignee?.name || "nobody";
10194
10362
  if (e.dryRun) {
@@ -10294,13 +10462,45 @@ function statusReport(paths2, config) {
10294
10462
  }
10295
10463
 
10296
10464
  // src/cli/ticket.ts
10297
- import { readFileSync as readFileSync8 } from "fs";
10465
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync } from "fs";
10466
+ import { basename as basename2, extname as extname2 } from "path";
10298
10467
  var TICKET_USAGE = ` agent-workflow ticket <ID> get
10299
- agent-workflow ticket <ID> state <State>
10468
+ agent-workflow ticket <ID> state <State> [--reason completed|not_planned]
10469
+ agent-workflow ticket <ID> label add|remove <name>...
10470
+ agent-workflow ticket <ID> assign <user>...
10300
10471
  agent-workflow ticket <ID> comment [body|-]
10301
10472
  agent-workflow ticket <ID> comments
10302
10473
  agent-workflow ticket <ID> comment-update <comment-id> [body|-] [--final]
10303
- agent-workflow ticket <ID> attach <pr-url>`;
10474
+ agent-workflow ticket <ID> attach <pr-url>
10475
+ agent-workflow ticket <ID> upload <file>...`;
10476
+ var CONTENT_TYPES = {
10477
+ ".png": "image/png",
10478
+ ".jpg": "image/jpeg",
10479
+ ".jpeg": "image/jpeg",
10480
+ ".gif": "image/gif",
10481
+ ".webp": "image/webp",
10482
+ ".svg": "image/svg+xml",
10483
+ ".mp4": "video/mp4",
10484
+ ".mov": "video/quicktime",
10485
+ ".webm": "video/webm",
10486
+ ".pdf": "application/pdf",
10487
+ ".txt": "text/plain",
10488
+ ".log": "text/plain"
10489
+ };
10490
+ var MAX_UPLOAD = 25 * 1024 * 1024;
10491
+ function readUploads(paths2) {
10492
+ const seen = /* @__PURE__ */ new Set();
10493
+ return paths2.map((path) => {
10494
+ if (!existsSync8(path) || !statSync(path).isFile()) throw new TicketError(`no such file: ${path}`, 2);
10495
+ const size = statSync(path).size;
10496
+ if (size === 0) throw new TicketError(`refusing to upload an empty file: ${path}`, 2);
10497
+ if (size > MAX_UPLOAD) throw new TicketError(`${path} is larger than 25 MB`, 2);
10498
+ let name = basename2(path).replace(/[^\w.-]+/g, "-");
10499
+ for (let i = 2; seen.has(name); i++) name = `${basename2(path, extname2(path))}-${i}${extname2(path)}`.replace(/[^\w.-]+/g, "-");
10500
+ seen.add(name);
10501
+ return { name, contentType: CONTENT_TYPES[extname2(path).toLowerCase()] ?? "application/octet-stream", content: readFileSync8(path) };
10502
+ });
10503
+ }
10304
10504
  function checkboxTally(body) {
10305
10505
  const checked = body.match(/^\s*[-*+] \[[xX]\]/gm)?.length ?? 0;
10306
10506
  const unchecked = body.match(/^\s*[-*+] \[ \]/gm)?.length ?? 0;
@@ -10324,16 +10524,29 @@ async function ticketCommand(args, loadConfig2) {
10324
10524
  }
10325
10525
  async function run(args, loadConfig2) {
10326
10526
  const final = args.includes("--final");
10527
+ let reason;
10528
+ const reasonAt = args.indexOf("--reason");
10529
+ if (reasonAt >= 0) {
10530
+ const value = args[reasonAt + 1];
10531
+ if (value !== "completed" && value !== "not_planned") throw usage("--reason takes completed or not_planned");
10532
+ reason = value;
10533
+ args = [...args.slice(0, reasonAt), ...args.slice(reasonAt + 2)];
10534
+ }
10327
10535
  const [id, sub, ...rest] = args.filter((a) => a !== "--final");
10328
10536
  if (!id || !sub) throw usage("ticket needs an ID and a subcommand");
10329
10537
  if (final && sub !== "comment-update") throw usage("--final only applies to comment-update");
10538
+ if (reason && sub !== "state") throw usage("--reason only applies to state");
10539
+ if (sub === "label" && rest[0] !== "add" && rest[0] !== "remove") throw usage("label takes add or remove");
10330
10540
  const arity = {
10331
10541
  get: [0, 0],
10332
10542
  state: [1, 1],
10543
+ label: [2, Infinity],
10544
+ assign: [1, Infinity],
10333
10545
  comment: [0, 1],
10334
10546
  comments: [0, 0],
10335
10547
  "comment-update": [1, 2],
10336
- attach: [1, 1]
10548
+ attach: [1, 1],
10549
+ upload: [1, Infinity]
10337
10550
  };
10338
10551
  const range = arity[sub];
10339
10552
  if (!range) throw usage(`unknown ticket subcommand '${sub}'`);
@@ -10347,6 +10560,7 @@ async function run(args, loadConfig2) {
10347
10560
  throw new TicketError(`--final: ${unchecked} unchecked item(s) remain; finish them or report the block instead (comment not updated)`, 5);
10348
10561
  }
10349
10562
  }
10563
+ const uploads = sub === "upload" ? readUploads(rest) : [];
10350
10564
  const config = loadConfig2();
10351
10565
  if (!config) return 1;
10352
10566
  const tracker = adapterFor(await resolveProject(config, id));
@@ -10355,10 +10569,19 @@ async function run(args, loadConfig2) {
10355
10569
  console.log(JSON.stringify(await tracker.get(id), null, 2));
10356
10570
  break;
10357
10571
  case "state": {
10358
- const { state, changed } = await tracker.setState(id, rest[0]);
10572
+ const { state, changed } = await tracker.setState(id, rest[0], reason);
10359
10573
  console.log(changed ? `${id} \u2192 ${state}` : `${id} already in '${state}', no change`);
10360
10574
  break;
10361
10575
  }
10576
+ case "label": {
10577
+ const [op, ...names] = rest;
10578
+ const labels = op === "add" ? await tracker.addLabels(id, names) : await tracker.removeLabels(id, names);
10579
+ console.log(`${id} labels: ${labels.join(", ") || "(none)"}`);
10580
+ break;
10581
+ }
10582
+ case "assign":
10583
+ console.log(`${id} assignees: ${(await tracker.assign(id, rest)).join(", ") || "(none)"}`);
10584
+ break;
10362
10585
  case "comment":
10363
10586
  console.log(JSON.stringify(await tracker.comment(id, body)));
10364
10587
  break;
@@ -10378,12 +10601,17 @@ async function run(args, loadConfig2) {
10378
10601
  );
10379
10602
  break;
10380
10603
  }
10604
+ case "upload": {
10605
+ const done = await tracker.upload(id, uploads);
10606
+ uploads.forEach((f, i) => console.log(`${f.contentType.startsWith("image/") ? "!" : ""}[${f.name}](${done[i].url})`));
10607
+ break;
10608
+ }
10381
10609
  }
10382
10610
  return 0;
10383
10611
  }
10384
10612
 
10385
10613
  // src/cli/briefing.ts
10386
- import { closeSync as closeSync2, existsSync as existsSync8, fstatSync, openSync as openSync2, readSync } from "fs";
10614
+ import { closeSync as closeSync2, existsSync as existsSync9, fstatSync, openSync as openSync2, readSync } from "fs";
10387
10615
  var MAX_EXCERPT = 200;
10388
10616
  var TAIL_BYTES = 256 * 1024;
10389
10617
  var ERROR_LINE = /\b(error|fatal|panic)\b/i;
@@ -10407,7 +10635,7 @@ function roleLog(ctx) {
10407
10635
  }
10408
10636
  function logExcerpt(file) {
10409
10637
  if (!file) return "no agent log";
10410
- if (!existsSync8(file)) return `agent log ${file} is missing`;
10638
+ if (!existsSync9(file)) return `agent log ${file} is missing`;
10411
10639
  const lines = tail(file).split("\n");
10412
10640
  for (let i = lines.length - 1; i >= 0; i--) {
10413
10641
  const line = lines[i].trim();
@@ -10452,20 +10680,20 @@ function short(text) {
10452
10680
  }
10453
10681
 
10454
10682
  // src/cli/init.ts
10455
- import { copyFileSync, existsSync as existsSync9, mkdirSync as mkdirSync6, readdirSync } from "fs";
10683
+ import { copyFileSync, existsSync as existsSync10, mkdirSync as mkdirSync6, readdirSync } from "fs";
10456
10684
  import { homedir as homedir4 } from "os";
10457
10685
  import { dirname as dirname4, join as join5, relative } from "path";
10458
10686
  var defaultHome = () => join5(homedir4(), ".agent-workflow");
10459
10687
  function legacyHome(home) {
10460
10688
  const legacy = join5(homedir4(), ".task-dispatch");
10461
- return home === defaultHome() && existsSync9(legacy) && !existsSync9(home) ? legacy : void 0;
10689
+ return home === defaultHome() && existsSync10(legacy) && !existsSync10(home) ? legacy : void 0;
10462
10690
  }
10463
10691
  function initRuleSet(templates, home, force) {
10464
10692
  const result = { created: [], overwritten: [], kept: [] };
10465
10693
  for (const file of filesUnder(templates)) {
10466
10694
  const rel = relative(templates, file);
10467
10695
  const target = join5(home, rel);
10468
- const exists = existsSync9(target);
10696
+ const exists = existsSync10(target);
10469
10697
  if (exists && !force) {
10470
10698
  result.kept.push(rel);
10471
10699
  continue;
@@ -10766,7 +10994,7 @@ function displayPath(file) {
10766
10994
  }
10767
10995
  function packageRoot(from) {
10768
10996
  for (let dir = from; ; dir = dirname5(dir)) {
10769
- if (existsSync10(join6(dir, "package.json"))) return dir;
10997
+ if (existsSync11(join6(dir, "package.json"))) return dir;
10770
10998
  if (dirname5(dir) === dir) throw new Error(`no package.json above ${from}`);
10771
10999
  }
10772
11000
  }