@gumpwang/agent-workflow 0.2.1 → 0.3.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.
@@ -7203,7 +7203,7 @@ var require_public_api = __commonJS({
7203
7203
  return docs;
7204
7204
  return Object.assign([], { empty: true }, composer$1.streamInfo());
7205
7205
  }
7206
- function parseDocument(source, options = {}) {
7206
+ function parseDocument2(source, options = {}) {
7207
7207
  const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
7208
7208
  const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
7209
7209
  const composer$1 = new composer.Composer(options);
@@ -7229,7 +7229,7 @@ var require_public_api = __commonJS({
7229
7229
  } else if (options === void 0 && reviver && typeof reviver === "object") {
7230
7230
  options = reviver;
7231
7231
  }
7232
- const doc = parseDocument(src, options);
7232
+ const doc = parseDocument2(src, options);
7233
7233
  if (!doc)
7234
7234
  return null;
7235
7235
  doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
@@ -7265,7 +7265,7 @@ var require_public_api = __commonJS({
7265
7265
  }
7266
7266
  exports.parse = parse;
7267
7267
  exports.parseAllDocuments = parseAllDocuments;
7268
- exports.parseDocument = parseDocument;
7268
+ exports.parseDocument = parseDocument2;
7269
7269
  exports.stringify = stringify;
7270
7270
  }
7271
7271
  });
@@ -7324,9 +7324,9 @@ 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 existsSync12, mkdirSync as mkdirSync8, openSync as openSync3, readFileSync as readFileSync10 } from "fs";
7328
7328
  import { homedir as homedir5 } from "os";
7329
- import { dirname as dirname5, join as join6, relative as relative2, resolve as resolve6 } from "path";
7329
+ import { dirname as dirname5, join as join7, relative as relative2, resolve as resolve6 } from "path";
7330
7330
  import { fileURLToPath } from "url";
7331
7331
 
7332
7332
  // src/rules/config.ts
@@ -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"],
7657
7657
  project: ["name", "root", "repo", "slug", "tracker"],
7658
7658
  workspace: ["path", "branch"],
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"];
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);
@@ -8674,7 +8674,7 @@ function startAgent(opts) {
8674
8674
  `);
8675
8675
  const stdinFd = openSync(opts.stdinFile, "r");
8676
8676
  try {
8677
- const child = spawn("bash", ["-c", opts.command], {
8677
+ const child = spawn("bash", ["-c", 'bash -c "$1"; result=$?; exit "$result"', `agent-workflow:${opts.env.SESSION_ID}`, opts.command], {
8678
8678
  cwd: opts.cwd,
8679
8679
  detached: true,
8680
8680
  stdio: [stdinFd, logFd, logFd],
@@ -8798,6 +8798,29 @@ function releaseLock(file) {
8798
8798
  }
8799
8799
 
8800
8800
  // src/tracker/common.ts
8801
+ var EVIDENCE_BRANCH = "agent-evidence";
8802
+ var TYPE_LABELS = [
8803
+ { name: "bug", color: "d73a4a", description: "Something isn't working" },
8804
+ { name: "documentation", color: "0075ca", description: "Improvements or additions to documentation" },
8805
+ { name: "duplicate", color: "cfd3d7", description: "This issue or pull request already exists" },
8806
+ { name: "enhancement", color: "a2eeef", description: "New feature or request" },
8807
+ { name: "help wanted", color: "008672", description: "Extra attention is needed" },
8808
+ { name: "invalid", color: "e4e669", description: "This doesn't seem right" },
8809
+ { name: "question", color: "d876e3", description: "Further information is requested" },
8810
+ { name: "wontfix", color: "ffffff", description: "This will not be worked on" }
8811
+ ];
8812
+ var STATE_COLORS = {
8813
+ triage: "fbca04",
8814
+ backlog: "ededed",
8815
+ "needs info": "d876e3",
8816
+ todo: "c5def5",
8817
+ "in progress": "1d76db",
8818
+ "in review": "fbca04",
8819
+ reviewed: "0e8a16",
8820
+ merging: "5319e7",
8821
+ done: "0e8a16",
8822
+ canceled: "cfd3d7"
8823
+ };
8801
8824
  var TicketError = class extends Error {
8802
8825
  code;
8803
8826
  constructor(message, code) {
@@ -8860,6 +8883,12 @@ var API_URL = () => (process.env.GITHUB_API_URL || "https://api.github.com").rep
8860
8883
  var FIXED_STATES = ["Open", "Closed"];
8861
8884
  var same = (a, b) => a.toLowerCase() === b.toLowerCase();
8862
8885
  var labelNames = (raw) => raw.labels.map((l) => typeof l === "string" ? l : l.name);
8886
+ async function openBlockers(repo, raw) {
8887
+ const summary = raw.issue_dependencies_summary?.blocked_by;
8888
+ if (typeof summary === "number") return summary;
8889
+ const { status, data } = await api("GET", `/repos/${repo}/issues/${raw.number}/dependencies/blocked_by?per_page=100`, void 0, [404, 410]);
8890
+ return status === 200 ? data.filter((i) => i.state === "open").length : 0;
8891
+ }
8863
8892
  function githubStateLabels(project) {
8864
8893
  const byPriority = Object.values(project.triggers).reverse().flatMap((states) => states.map((s) => project.tracker.stateAlias[s] ?? s));
8865
8894
  const other = [...project.tracker.otherStates, ...project.attentionState ? [project.attentionState] : []].map((s) => project.tracker.stateAlias[s] ?? s);
@@ -8948,9 +8977,12 @@ async function githubTickets(p, tracked) {
8948
8977
  state: canonical(spelledState(raw, labels)),
8949
8978
  labels: labelNames(raw),
8950
8979
  assignee: users[0] ?? null,
8951
- assignees: users
8980
+ assignees: users,
8981
+ blockedBy: 0
8952
8982
  };
8953
- if (wanted.has(ticket.state.toLowerCase()) || trackedSet.has(ticket.identifier)) tickets.push(ticket);
8983
+ if (!wanted.has(ticket.state.toLowerCase()) && !trackedSet.has(ticket.identifier)) continue;
8984
+ if (raw.state === "open") ticket.blockedBy = await openBlockers(repo, raw);
8985
+ tickets.push(ticket);
8954
8986
  }
8955
8987
  let viewer;
8956
8988
  return {
@@ -9004,10 +9036,11 @@ function githubAdapter(p) {
9004
9036
  states: catalogue,
9005
9037
  labels: labelNames(raw),
9006
9038
  assignees: (raw.assignees ?? []).map((a) => a.login),
9039
+ blocked_by: await openBlockers(repo, raw),
9007
9040
  description: raw.body ?? ""
9008
9041
  };
9009
9042
  },
9010
- async setState(identifier, wanted) {
9043
+ async setState(identifier, wanted, reason = "completed") {
9011
9044
  const state = pickState(project, catalogue, wanted);
9012
9045
  const target = project.tracker.stateAlias[state] ?? state;
9013
9046
  const { raw, path } = await load(identifier);
@@ -9018,7 +9051,7 @@ function githubAdapter(p) {
9018
9051
  const hasTarget = !isLabel || names.some((n) => same(n, target));
9019
9052
  if (stale.length === 0 && hasTarget && raw.state === "closed" === wantClosed) return { state, changed: false };
9020
9053
  if (raw.state === "closed" !== wantClosed) {
9021
- await api("PATCH", path, wantClosed ? { state: "closed", state_reason: "completed" } : { state: "open" });
9054
+ await api("PATCH", path, wantClosed ? { state: "closed", state_reason: reason } : { state: "open" });
9022
9055
  }
9023
9056
  if (!hasTarget) {
9024
9057
  const add = await api("POST", `${path}/labels`, { labels: [target] }, [404, 422]);
@@ -9030,6 +9063,34 @@ function githubAdapter(p) {
9030
9063
  for (const label of stale) await api("DELETE", `${path}/labels/${encodeURIComponent(label)}`, void 0, [404]);
9031
9064
  return { state, changed: true };
9032
9065
  },
9066
+ async addLabels(identifier, names) {
9067
+ const { raw, path } = await load(identifier);
9068
+ const have = labelNames(raw);
9069
+ const add = names.filter((n) => !have.some((h) => same(h, n)));
9070
+ if (!add.length) return have;
9071
+ const res = await api("POST", `${path}/labels`, { labels: add }, [404, 422]);
9072
+ if (res.status === 200) return res.data.map((l) => l.name);
9073
+ for (const name of add) await api("POST", `/repos/${repo}/labels`, { name }, [422]);
9074
+ return (await api("POST", `${path}/labels`, { labels: add })).data.map((l) => l.name);
9075
+ },
9076
+ async removeLabels(identifier, names) {
9077
+ const { raw, path } = await load(identifier);
9078
+ let have = labelNames(raw);
9079
+ for (const name of names) {
9080
+ const hit = have.find((h) => same(h, name));
9081
+ if (!hit) continue;
9082
+ await api("DELETE", `${path}/labels/${encodeURIComponent(hit)}`, void 0, [404]);
9083
+ have = have.filter((h) => h !== hit);
9084
+ }
9085
+ return have;
9086
+ },
9087
+ async assign(identifier, users) {
9088
+ const { path } = await load(identifier);
9089
+ const logins = [];
9090
+ for (const u of users) logins.push(u.toLowerCase() === "me" ? (await api("GET", "/user")).data.login : u);
9091
+ const { data } = await api("PATCH", path, { assignees: logins });
9092
+ return (data.assignees ?? []).map((a) => a.login);
9093
+ },
9033
9094
  async comment(identifier, body) {
9034
9095
  const { path } = await load(identifier);
9035
9096
  const { data } = await api("POST", `${path}/comments`, { body });
@@ -9054,6 +9115,58 @@ function githubAdapter(p) {
9054
9115
  async attach(identifier) {
9055
9116
  issuePath(identifier);
9056
9117
  return "unsupported";
9118
+ },
9119
+ async upload(identifier, files) {
9120
+ const { number } = issuePath(identifier);
9121
+ const issue = await getIssue(repo, number);
9122
+ if (!issue) throw new TicketError(`ticket not found: ${identifier}`, 4);
9123
+ const web = new URL(issue.html_url).origin;
9124
+ const dir = `${identifier}/${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
9125
+ const entries = [];
9126
+ for (const f of files) {
9127
+ const blob = await api("POST", `/repos/${repo}/git/blobs`, { content: f.content.toString("base64"), encoding: "base64" });
9128
+ entries.push({ name: f.name, path: `${dir}/${f.name}`, sha: blob.data.sha });
9129
+ }
9130
+ const tree = entries.map((e) => ({ path: e.path, mode: "100644", type: "blob", sha: e.sha }));
9131
+ for (let attempt = 1; ; attempt++) {
9132
+ const ref = await api("GET", `/repos/${repo}/git/ref/heads/${EVIDENCE_BRANCH}`, void 0, [404]);
9133
+ const parent = ref.status === 404 ? void 0 : ref.data.object.sha;
9134
+ const baseTree = parent && (await api("GET", `/repos/${repo}/git/commits/${parent}`)).data.tree.sha;
9135
+ const treeSha = (await api("POST", `/repos/${repo}/git/trees`, baseTree ? { base_tree: baseTree, tree } : { tree })).data.sha;
9136
+ const commit = (await api("POST", `/repos/${repo}/git/commits`, { message: `evidence for ${identifier}`, tree: treeSha, parents: parent ? [parent] : [] })).data.sha;
9137
+ 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]);
9138
+ if (moved.status !== 422) {
9139
+ const encode = (path) => path.split("/").map(encodeURIComponent).join("/");
9140
+ return entries.map((e) => ({ name: e.name, url: `${web}/${repo}/blob/${commit}/${encode(e.path)}?raw=true` }));
9141
+ }
9142
+ if (attempt === 3) throw new TicketError(`could not update branch ${EVIDENCE_BRANCH} of ${repo}: it kept moving`, 3);
9143
+ }
9144
+ }
9145
+ };
9146
+ }
9147
+ async function githubSetup(p) {
9148
+ const project = asGitHub(p);
9149
+ const repo = project.tracker.repo;
9150
+ const { status, data } = await api("GET", `/repos/${repo}`, void 0, [404]);
9151
+ if (status === 404) throw new TicketError(`GitHub repository ${repo} not found, or the token cannot see it`, 4);
9152
+ const have = [];
9153
+ for (let page = 1; ; page++) {
9154
+ const batch = (await api("GET", `/repos/${repo}/labels?per_page=100&page=${page}`)).data;
9155
+ have.push(...batch.map((l) => l.name));
9156
+ if (batch.length < 100) break;
9157
+ }
9158
+ const lacks = (name) => !have.some((h) => same(h, name));
9159
+ const stateItems = githubStateLabels(project).filter(lacks).map((name) => ({ kind: "state", name, detail: "state label" }));
9160
+ const labelItems = TYPE_LABELS.filter((l) => lacks(l.name)).map((l) => ({ kind: "label", name: l.name, detail: l.description }));
9161
+ return {
9162
+ target: data.full_name,
9163
+ missing: [...stateItems, ...labelItems],
9164
+ manual: [],
9165
+ async create(item) {
9166
+ const type = TYPE_LABELS.find((l) => same(l.name, item.name));
9167
+ const color = type?.color ?? STATE_COLORS[item.name.toLowerCase()] ?? "bfd4f2";
9168
+ const description = type?.description ?? `agent-workflow state: ${item.name}`;
9169
+ await api("POST", `/repos/${repo}/labels`, { name: item.name, color, description }, [422]);
9057
9170
  }
9058
9171
  };
9059
9172
  }
@@ -9063,6 +9176,10 @@ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
9063
9176
  import { homedir as homedir2 } from "os";
9064
9177
  import { join as join3 } from "path";
9065
9178
  var API_URL2 = () => process.env.LINEAR_API_URL || "https://api.linear.app/graphql";
9179
+ var TICKET_EXTRAS = `labels{ nodes{ name } } inverseRelations{ nodes{ type issue{ state{ type } } } }`;
9180
+ function openBlockers2(issue) {
9181
+ return (issue.inverseRelations?.nodes ?? []).filter((r) => r.type === "blocks" && r.issue && !["completed", "canceled"].includes(r.issue.state.type)).length;
9182
+ }
9066
9183
  async function graphql(apiKey, query, variables) {
9067
9184
  const res = await fetch(API_URL2(), {
9068
9185
  method: "POST",
@@ -9120,7 +9237,7 @@ async function linearTickets(apiKey, projects) {
9120
9237
  apiKey,
9121
9238
  `query($pids:[ID!]!, $states:[String!]!){
9122
9239
  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 }
9240
+ nodes{ id identifier title description url state{name} assignee{ id name displayName email } project{id} updatedAt ${TICKET_EXTRAS} }
9124
9241
  }
9125
9242
  }`,
9126
9243
  { pids: ids, states }
@@ -9137,9 +9254,10 @@ async function linearTickets(apiKey, projects) {
9137
9254
  description: n.description ?? "",
9138
9255
  url: n.url ?? "",
9139
9256
  state: canonical(n.state.name),
9140
- labels: [],
9257
+ labels: n.labels?.nodes.map((l) => l.name) ?? [],
9141
9258
  assignee: n.assignee,
9142
- assignees: n.assignee ? [n.assignee] : []
9259
+ assignees: n.assignee ? [n.assignee] : [],
9260
+ blockedBy: openBlockers2(n)
9143
9261
  }));
9144
9262
  out.push({
9145
9263
  project,
@@ -9177,6 +9295,30 @@ function linearAdapter(project) {
9177
9295
  const canonical = canonicalizer(project);
9178
9296
  const gql = (query, variables) => graphql(linearKey(project), query, variables);
9179
9297
  const notFound = (identifier) => new TicketError(`ticket not found: ${identifier}`, 4);
9298
+ const same2 = (a, b) => a.toLowerCase() === b.toLowerCase();
9299
+ const labelled = async (identifier) => {
9300
+ const r = await gql(
9301
+ `query($id:String!){issue(id:$id){ id team{ id } labels{ nodes{ id name } } }}`,
9302
+ { id: identifier }
9303
+ );
9304
+ if (!r.issue) throw notFound(identifier);
9305
+ return { id: r.issue.id, teamId: r.issue.team.id, labels: r.issue.labels.nodes };
9306
+ };
9307
+ const teamLabel = async (teamId, name) => {
9308
+ const r = await gql(
9309
+ `query($n:String!){ issueLabels(filter:{name:{eqIgnoreCase:$n}}, first:50){ nodes{ id name team{ id } } } }`,
9310
+ { n: name }
9311
+ );
9312
+ return r.issueLabels.nodes.find((l) => !l.team || l.team.id === teamId)?.id;
9313
+ };
9314
+ const createLabel = async (teamId, name) => {
9315
+ const r = await gql(
9316
+ `mutation($t:String!,$n:String!){ issueLabelCreate(input:{teamId:$t, name:$n}){ success issueLabel{ id } } }`,
9317
+ { t: teamId, n: name }
9318
+ );
9319
+ if (!r.issueLabelCreate.success) throw new TicketError(`creating Linear label '${name}' failed`, 3);
9320
+ return r.issueLabelCreate.issueLabel.id;
9321
+ };
9180
9322
  const issueId = async (identifier) => {
9181
9323
  const r = await gql(`query($id:String!){issue(id:$id){id}}`, { id: identifier });
9182
9324
  if (!r.issue) throw notFound(identifier);
@@ -9187,7 +9329,7 @@ function linearAdapter(project) {
9187
9329
  env: () => linearEnv(project),
9188
9330
  async get(identifier) {
9189
9331
  const r = await gql(
9190
- `query($id:String!){issue(id:$id){ id identifier title url description state{name} labels{nodes{name}} assignee{displayName} }}`,
9332
+ `query($id:String!){issue(id:$id){ id identifier title url description state{name} assignee{displayName} ${TICKET_EXTRAS} }}`,
9191
9333
  { id: identifier }
9192
9334
  );
9193
9335
  if (!r.issue) throw notFound(identifier);
@@ -9200,6 +9342,7 @@ function linearAdapter(project) {
9200
9342
  states: catalogue,
9201
9343
  labels: i.labels?.nodes.map((l) => l.name) ?? [],
9202
9344
  assignees: i.assignee ? [i.assignee.displayName] : [],
9345
+ blocked_by: openBlockers2(i),
9203
9346
  description: i.description ?? ""
9204
9347
  };
9205
9348
  },
@@ -9224,6 +9367,45 @@ function linearAdapter(project) {
9224
9367
  if (!res.issueUpdate.success) throw new TicketError(`issueUpdate failed for ${identifier}`, 3);
9225
9368
  return { state, changed: true };
9226
9369
  },
9370
+ async addLabels(identifier, names) {
9371
+ const issue = await labelled(identifier);
9372
+ for (const name of names) {
9373
+ if (issue.labels.some((l) => same2(l.name, name))) continue;
9374
+ const labelId = await teamLabel(issue.teamId, name) ?? await createLabel(issue.teamId, name);
9375
+ const res = await gql(`mutation($id:String!,$l:String!){ issueAddLabel(id:$id, labelId:$l){ success } }`, { id: issue.id, l: labelId });
9376
+ if (!res.issueAddLabel.success) throw new TicketError(`adding label '${name}' failed for ${identifier}`, 3);
9377
+ }
9378
+ return (await labelled(identifier)).labels.map((l) => l.name);
9379
+ },
9380
+ async removeLabels(identifier, names) {
9381
+ const issue = await labelled(identifier);
9382
+ for (const name of names) {
9383
+ const hit = issue.labels.find((l) => same2(l.name, name));
9384
+ if (!hit) continue;
9385
+ const res = await gql(`mutation($id:String!,$l:String!){ issueRemoveLabel(id:$id, labelId:$l){ success } }`, { id: issue.id, l: hit.id });
9386
+ if (!res.issueRemoveLabel.success) throw new TicketError(`removing label '${name}' failed for ${identifier}`, 3);
9387
+ }
9388
+ return (await labelled(identifier)).labels.map((l) => l.name);
9389
+ },
9390
+ async assign(identifier, users) {
9391
+ if (users.length !== 1) throw new TicketError("a Linear issue has exactly one assignee: name one user", 2);
9392
+ const id = await issueId(identifier);
9393
+ const wanted = users[0];
9394
+ let userId;
9395
+ if (wanted.toLowerCase() === "me") userId = (await gql(`query{viewer{id}}`, {})).viewer.id;
9396
+ else {
9397
+ const r = await gql(`query{ users(first:250){ nodes{ id name displayName email } } }`, {});
9398
+ const hit = r.users.nodes.find((u) => u.id === wanted || [u.name, u.displayName, u.email].some((v) => v && same2(v, wanted)));
9399
+ if (!hit) throw new TicketError(`no Linear user matches '${wanted}'`, 4);
9400
+ userId = hit.id;
9401
+ }
9402
+ const res = await gql(
9403
+ `mutation($id:String!,$u:String!){ issueUpdate(id:$id, input:{assigneeId:$u}){ success issue{ assignee{ displayName } } } }`,
9404
+ { id, u: userId }
9405
+ );
9406
+ if (!res.issueUpdate.success) throw new TicketError(`assigning ${identifier} failed`, 3);
9407
+ return res.issueUpdate.issue.assignee ? [res.issueUpdate.issue.assignee.displayName] : [];
9408
+ },
9227
9409
  async comment(identifier, body) {
9228
9410
  const id = await issueId(identifier);
9229
9411
  const res = await gql(
@@ -9264,6 +9446,86 @@ function linearAdapter(project) {
9264
9446
  );
9265
9447
  if (!res.attachmentLinkGitHubPR.success) throw new TicketError(`attach failed for ${identifier}`, 3);
9266
9448
  return "attached";
9449
+ },
9450
+ async upload(identifier, files) {
9451
+ const r = await gql(`query($id:String!){issue(id:$id){ id }}`, { id: identifier });
9452
+ if (!r.issue) throw notFound(identifier);
9453
+ const out = [];
9454
+ for (const f of files) {
9455
+ const res = await gql(
9456
+ `mutation($t:String!,$n:String!,$s:Int!){ fileUpload(contentType:$t, filename:$n, size:$s){ success uploadFile{ uploadUrl assetUrl headers{ key value } } } }`,
9457
+ { t: f.contentType, n: f.name, s: f.content.length }
9458
+ );
9459
+ const target = res.fileUpload.uploadFile;
9460
+ if (!res.fileUpload.success || !target) throw new TicketError(`Linear refused the upload of ${f.name}`, 3);
9461
+ const headers = { "Content-Type": f.contentType, "Cache-Control": "public, max-age=31536000" };
9462
+ for (const h of target.headers) headers[h.key] = h.value;
9463
+ const put = await fetch(target.uploadUrl, { method: "PUT", headers, body: f.content });
9464
+ if (!put.ok) throw new TicketError(`uploading ${f.name} to Linear storage: HTTP ${put.status}: ${(await put.text()).slice(0, 400)}`, 3);
9465
+ out.push({ name: f.name, url: target.assetUrl });
9466
+ }
9467
+ return out;
9468
+ }
9469
+ };
9470
+ }
9471
+ var STATE_TYPES = {
9472
+ backlog: "backlog",
9473
+ "needs info": "backlog",
9474
+ todo: "unstarted",
9475
+ "in progress": "started",
9476
+ "in review": "started",
9477
+ reviewed: "started",
9478
+ merging: "started",
9479
+ done: "completed",
9480
+ canceled: "canceled"
9481
+ };
9482
+ var SPELLING_ONLY = ["cancelled", "duplicate", "closed"];
9483
+ async function linearSetup(project) {
9484
+ if (project.tracker.kind !== "linear") throw new Error(`projects.${project.name} is not a Linear project`);
9485
+ const apiKey = linearKey(project);
9486
+ const r = await graphql(
9487
+ apiKey,
9488
+ `query($s:[String!]!){projects(filter:{slugId:{in:$s}}){nodes{ name teams{ nodes{ id name states{ nodes{ name } } } } }}}`,
9489
+ { s: [linearSlugId(project)] }
9490
+ );
9491
+ const found = r.projects.nodes[0];
9492
+ if (!found) throw new TicketError(`Linear project ${project.tracker.slug} not found, or the API key cannot see it`, 4);
9493
+ const teams = found.teams.nodes;
9494
+ const wanted = stateCatalogue(project).map((s) => project.tracker.stateAlias[s] ?? s);
9495
+ const missing = [];
9496
+ const manual = [];
9497
+ const teamOf = /* @__PURE__ */ new Map();
9498
+ for (const team of teams) {
9499
+ for (const name of wanted) {
9500
+ if (team.states.nodes.some((s) => s.name.toLowerCase() === name.toLowerCase())) continue;
9501
+ if (SPELLING_ONLY.includes(name.toLowerCase())) continue;
9502
+ if (name.toLowerCase() === "triage") {
9503
+ manual.push(`state Triage of team ${team.name}: turn on Triage in the team's settings`);
9504
+ continue;
9505
+ }
9506
+ const type = STATE_TYPES[name.toLowerCase()];
9507
+ if (!type) {
9508
+ manual.push(`state ${name} of team ${team.name}: its type is unknown to setup-project`);
9509
+ continue;
9510
+ }
9511
+ const label = teams.length > 1 ? `${name} (${team.name})` : name;
9512
+ missing.push({ kind: "state", name: label, detail: `${type} state of team ${team.name}` });
9513
+ teamOf.set(label, team);
9514
+ }
9515
+ }
9516
+ return {
9517
+ target: `${found.name} (team ${teams.map((t) => t.name).join(", ")})`,
9518
+ missing,
9519
+ manual,
9520
+ async create(item) {
9521
+ const team = teamOf.get(item.name);
9522
+ const name = teams.length > 1 ? item.name.slice(0, item.name.lastIndexOf(" (")) : item.name;
9523
+ const res = await graphql(
9524
+ apiKey,
9525
+ `mutation($t:String!,$n:String!,$y:String!,$c:String!){ workflowStateCreate(input:{teamId:$t, name:$n, type:$y, color:$c}){ success } }`,
9526
+ { t: team.id, n: name, y: STATE_TYPES[name.toLowerCase()], c: `#${STATE_COLORS[name.toLowerCase()] ?? "bfd4f2"}` }
9527
+ );
9528
+ if (!res.workflowStateCreate.success) throw new TicketError(`creating state '${name}' in team ${team.name} failed`, 3);
9267
9529
  }
9268
9530
  };
9269
9531
  }
@@ -9280,6 +9542,9 @@ async function fetchTickets(projects, tracked) {
9280
9542
  for (const p of projects.filter((p2) => p2.tracker.kind === "github")) out.push(await githubTickets(p, tracked.get(p.name) ?? []));
9281
9543
  return projects.map((p) => out.find((t) => t.project === p));
9282
9544
  }
9545
+ function trackerSetup(project) {
9546
+ return project.tracker.kind === "github" ? githubSetup(project) : linearSetup(project);
9547
+ }
9283
9548
  function adapterFor(project) {
9284
9549
  return project.tracker.kind === "github" ? githubAdapter(project) : linearAdapter(project);
9285
9550
  }
@@ -9602,6 +9867,7 @@ async function execute(e, t, wf, step) {
9602
9867
  run2.attention = `${step.at}: wait timed out after ${step.timeoutMinutes} min`;
9603
9868
  return "attention";
9604
9869
  }
9870
+ e.record({ ticket: t.identifier, action: "waiting", workflow: wf.id, detail: step.name ?? step.id ?? step.at });
9605
9871
  return "block";
9606
9872
  }
9607
9873
  case "tracker":
@@ -9698,8 +9964,8 @@ async function turn(e, t, wf, step, scope) {
9698
9964
  }
9699
9965
  const inTrigger = !t.offTrigger && (t.project.triggers[wf.id] ?? []).some((st) => st.toLowerCase() === t.ticket.state.toLowerCase());
9700
9966
  if (!inTrigger) {
9701
- if (step.id) run2.steps[step.id] = { outcome: "no-delivery", outputs: {} };
9702
- return "next";
9967
+ run2.attention = `${step.at}: agent ended without delivery '${expect.delivery}' outside the workflow trigger states`;
9968
+ return "attention";
9703
9969
  }
9704
9970
  delete run2.turn;
9705
9971
  run2.nudge = true;
@@ -9714,7 +9980,7 @@ async function turn(e, t, wf, step, scope) {
9714
9980
  const maxAttempts = wf.roles[role]?.maxAttempts ?? 3;
9715
9981
  const continues = !!session && (step.verb === "message" || !!session.session_id);
9716
9982
  const resume = continues && profile.session === "claude" && !!session.session_id;
9717
- const used = step.verb === "launch" ? session?.turns ?? 0 : run2.step_turns ?? 0;
9983
+ const used = run2.step_turns ?? 0;
9718
9984
  if (session && used >= maxAttempts) {
9719
9985
  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
9986
  return "attention";
@@ -9772,7 +10038,7 @@ ${completionInstructions(expect, !!run2.nudge)}`;
9772
10038
  ticket: t.identifier,
9773
10039
  action: kind,
9774
10040
  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)" : ""}`
10041
+ 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
10042
  });
9777
10043
  return "block";
9778
10044
  }
@@ -9826,7 +10092,8 @@ async function trackerStep(e, t, wf, step, scope) {
9826
10092
  }
9827
10093
  if (step.state) {
9828
10094
  const state = String(interpolate(step.state, scope));
9829
- ops.push({ what: `state \u2192 ${state}`, apply: () => tracker.setState(t.identifier, state) });
10095
+ const why = step.reason ? ` (${step.reason})` : "";
10096
+ ops.push({ what: `state \u2192 ${state}${why}`, apply: () => tracker.setState(t.identifier, state, step.reason) });
9830
10097
  }
9831
10098
  for (const op of ops) {
9832
10099
  if (e.dryRun) {
@@ -9898,7 +10165,9 @@ function ticketView(ticket) {
9898
10165
  state: ticket.state,
9899
10166
  number: ticket.number ?? null,
9900
10167
  labels: ticket.labels,
9901
- assignee: ticket.assignee
10168
+ assignee: ticket.assignee,
10169
+ // Absent in tickets a ledger saved before blockers were read.
10170
+ blocked_by: ticket.blockedBy ?? 0
9902
10171
  };
9903
10172
  }
9904
10173
  function projectView(project) {
@@ -10162,16 +10431,11 @@ async function advanceOne(paths2, config, identifier, opts) {
10162
10431
  const project = ctx && config.projects[ctx.project];
10163
10432
  if (!ctx || !project || !isActive(ctx)) return;
10164
10433
  const engine = engineFor(paths2, config, ledger, opts);
10165
- let ticket = ctx.ticket;
10166
- let offTrigger = false;
10167
10434
  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
- }
10435
+ const state = await tracker.refresh(ctx.ticket);
10436
+ if (!state) throw new Error(`could not read ${identifier} from the tracker; run was not advanced`);
10437
+ const ticket = { ...ctx.ticket, state };
10438
+ const offTrigger = !desiredWorkflow(project, ticket);
10175
10439
  ctx.ticket = ticket;
10176
10440
  const work = { identifier, ctx, project, ticket, trackerEnv: tracker.env(ticket), offTrigger };
10177
10441
  await advanceActive(engine, ledger, work);
@@ -10188,7 +10452,7 @@ function workOf(identifier, ctx, pt, ticket) {
10188
10452
  async function handleTicket(e, ledger, pt, ticket, desired) {
10189
10453
  const id = ticket.identifier;
10190
10454
  let ctx = ledger.tickets[id];
10191
- if (desired && !desired.on.tracked && !pt.isMine(ticket)) {
10455
+ if (desired && !desired.on.tracked && !desired.on.anyAssignee && !pt.isMine(ticket)) {
10192
10456
  if (!ctx) return;
10193
10457
  const to = ticket.assignee?.displayName || ticket.assignee?.name || "nobody";
10194
10458
  if (e.dryRun) {
@@ -10294,13 +10558,45 @@ function statusReport(paths2, config) {
10294
10558
  }
10295
10559
 
10296
10560
  // src/cli/ticket.ts
10297
- import { readFileSync as readFileSync8 } from "fs";
10561
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync } from "fs";
10562
+ import { basename as basename2, extname as extname2 } from "path";
10298
10563
  var TICKET_USAGE = ` agent-workflow ticket <ID> get
10299
- agent-workflow ticket <ID> state <State>
10564
+ agent-workflow ticket <ID> state <State> [--reason completed|not_planned]
10565
+ agent-workflow ticket <ID> label add|remove <name>...
10566
+ agent-workflow ticket <ID> assign <user>...
10300
10567
  agent-workflow ticket <ID> comment [body|-]
10301
10568
  agent-workflow ticket <ID> comments
10302
10569
  agent-workflow ticket <ID> comment-update <comment-id> [body|-] [--final]
10303
- agent-workflow ticket <ID> attach <pr-url>`;
10570
+ agent-workflow ticket <ID> attach <pr-url>
10571
+ agent-workflow ticket <ID> upload <file>...`;
10572
+ var CONTENT_TYPES = {
10573
+ ".png": "image/png",
10574
+ ".jpg": "image/jpeg",
10575
+ ".jpeg": "image/jpeg",
10576
+ ".gif": "image/gif",
10577
+ ".webp": "image/webp",
10578
+ ".svg": "image/svg+xml",
10579
+ ".mp4": "video/mp4",
10580
+ ".mov": "video/quicktime",
10581
+ ".webm": "video/webm",
10582
+ ".pdf": "application/pdf",
10583
+ ".txt": "text/plain",
10584
+ ".log": "text/plain"
10585
+ };
10586
+ var MAX_UPLOAD = 25 * 1024 * 1024;
10587
+ function readUploads(paths2) {
10588
+ const seen = /* @__PURE__ */ new Set();
10589
+ return paths2.map((path) => {
10590
+ if (!existsSync8(path) || !statSync(path).isFile()) throw new TicketError(`no such file: ${path}`, 2);
10591
+ const size = statSync(path).size;
10592
+ if (size === 0) throw new TicketError(`refusing to upload an empty file: ${path}`, 2);
10593
+ if (size > MAX_UPLOAD) throw new TicketError(`${path} is larger than 25 MB`, 2);
10594
+ let name = basename2(path).replace(/[^\w.-]+/g, "-");
10595
+ for (let i = 2; seen.has(name); i++) name = `${basename2(path, extname2(path))}-${i}${extname2(path)}`.replace(/[^\w.-]+/g, "-");
10596
+ seen.add(name);
10597
+ return { name, contentType: CONTENT_TYPES[extname2(path).toLowerCase()] ?? "application/octet-stream", content: readFileSync8(path) };
10598
+ });
10599
+ }
10304
10600
  function checkboxTally(body) {
10305
10601
  const checked = body.match(/^\s*[-*+] \[[xX]\]/gm)?.length ?? 0;
10306
10602
  const unchecked = body.match(/^\s*[-*+] \[ \]/gm)?.length ?? 0;
@@ -10324,16 +10620,29 @@ async function ticketCommand(args, loadConfig2) {
10324
10620
  }
10325
10621
  async function run(args, loadConfig2) {
10326
10622
  const final = args.includes("--final");
10623
+ let reason;
10624
+ const reasonAt = args.indexOf("--reason");
10625
+ if (reasonAt >= 0) {
10626
+ const value = args[reasonAt + 1];
10627
+ if (value !== "completed" && value !== "not_planned") throw usage("--reason takes completed or not_planned");
10628
+ reason = value;
10629
+ args = [...args.slice(0, reasonAt), ...args.slice(reasonAt + 2)];
10630
+ }
10327
10631
  const [id, sub, ...rest] = args.filter((a) => a !== "--final");
10328
10632
  if (!id || !sub) throw usage("ticket needs an ID and a subcommand");
10329
10633
  if (final && sub !== "comment-update") throw usage("--final only applies to comment-update");
10634
+ if (reason && sub !== "state") throw usage("--reason only applies to state");
10635
+ if (sub === "label" && rest[0] !== "add" && rest[0] !== "remove") throw usage("label takes add or remove");
10330
10636
  const arity = {
10331
10637
  get: [0, 0],
10332
10638
  state: [1, 1],
10639
+ label: [2, Infinity],
10640
+ assign: [1, Infinity],
10333
10641
  comment: [0, 1],
10334
10642
  comments: [0, 0],
10335
10643
  "comment-update": [1, 2],
10336
- attach: [1, 1]
10644
+ attach: [1, 1],
10645
+ upload: [1, Infinity]
10337
10646
  };
10338
10647
  const range = arity[sub];
10339
10648
  if (!range) throw usage(`unknown ticket subcommand '${sub}'`);
@@ -10347,6 +10656,7 @@ async function run(args, loadConfig2) {
10347
10656
  throw new TicketError(`--final: ${unchecked} unchecked item(s) remain; finish them or report the block instead (comment not updated)`, 5);
10348
10657
  }
10349
10658
  }
10659
+ const uploads = sub === "upload" ? readUploads(rest) : [];
10350
10660
  const config = loadConfig2();
10351
10661
  if (!config) return 1;
10352
10662
  const tracker = adapterFor(await resolveProject(config, id));
@@ -10355,10 +10665,19 @@ async function run(args, loadConfig2) {
10355
10665
  console.log(JSON.stringify(await tracker.get(id), null, 2));
10356
10666
  break;
10357
10667
  case "state": {
10358
- const { state, changed } = await tracker.setState(id, rest[0]);
10668
+ const { state, changed } = await tracker.setState(id, rest[0], reason);
10359
10669
  console.log(changed ? `${id} \u2192 ${state}` : `${id} already in '${state}', no change`);
10360
10670
  break;
10361
10671
  }
10672
+ case "label": {
10673
+ const [op, ...names] = rest;
10674
+ const labels = op === "add" ? await tracker.addLabels(id, names) : await tracker.removeLabels(id, names);
10675
+ console.log(`${id} labels: ${labels.join(", ") || "(none)"}`);
10676
+ break;
10677
+ }
10678
+ case "assign":
10679
+ console.log(`${id} assignees: ${(await tracker.assign(id, rest)).join(", ") || "(none)"}`);
10680
+ break;
10362
10681
  case "comment":
10363
10682
  console.log(JSON.stringify(await tracker.comment(id, body)));
10364
10683
  break;
@@ -10378,12 +10697,144 @@ async function run(args, loadConfig2) {
10378
10697
  );
10379
10698
  break;
10380
10699
  }
10700
+ case "upload": {
10701
+ const done = await tracker.upload(id, uploads);
10702
+ uploads.forEach((f, i) => console.log(`${f.contentType.startsWith("image/") ? "!" : ""}[${f.name}](${done[i].url})`));
10703
+ break;
10704
+ }
10381
10705
  }
10382
10706
  return 0;
10383
10707
  }
10384
10708
 
10709
+ // src/cli/setup.ts
10710
+ var import_yaml3 = __toESM(require_dist(), 1);
10711
+ import { existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
10712
+ import { join as join5 } from "path";
10713
+ import { createInterface } from "readline/promises";
10714
+ var SETUP_USAGE = ` agent-workflow setup-project <name> --github <owner/repo> --root <dir> [--assignee <login>] [--yes]
10715
+ agent-workflow setup-project <name> --linear <project-slug> --root <dir> [--assignee <user>] [--yes]
10716
+ agent-workflow setup-project <name> [--yes]`;
10717
+ async function setupProject(home, opts) {
10718
+ if (!/^[A-Za-z0-9_.-]+$/.test(opts.name)) return fail(`project name '${opts.name}' may only use letters, digits, '_', '.' and '-'`);
10719
+ const configFile = join5(home, "config.yaml");
10720
+ if (!existsSync9(configFile)) return fail(`no rule set at ${home}: run \`agent-workflow init\` first`);
10721
+ const projectFile = join5(home, "projects", opts.name, "project.yaml");
10722
+ if (existsSync9(projectFile)) {
10723
+ if (opts.github || opts.linear || opts.root || opts.assignee) {
10724
+ console.log(`${projectFile} exists; kept as it is (edit it to change the tracker, root or assignee)`);
10725
+ }
10726
+ } else {
10727
+ if (!!opts.github === !!opts.linear) return fail("a new project needs exactly one of --github <owner/repo> or --linear <project-slug>");
10728
+ if (!opts.root) return fail("a new project needs --root <dir>, its canonical repository");
10729
+ if (opts.github && !/^[^/\s]+\/[^/\s]+$/.test(opts.github)) return fail(`--github takes owner/repo, not '${opts.github}'`);
10730
+ mkdirSync6(join5(home, "projects", opts.name), { recursive: true });
10731
+ writeFileSync5(projectFile, projectYaml(opts));
10732
+ console.log(`wrote ${projectFile}`);
10733
+ }
10734
+ if (register(configFile, opts.name)) console.log(`registered ${opts.name} in ${configFile}`);
10735
+ const { config, diagnostics } = validateHome(home);
10736
+ for (const d of diagnostics) console.error(`${d.level}: ${d.file}: ${d.at || "-"}: ${d.code}: ${d.message}`);
10737
+ const project = config?.projects[opts.name];
10738
+ if (!project) return fail("fix the configuration errors above, then run setup-project again");
10739
+ let setup;
10740
+ try {
10741
+ setup = await trackerSetup(project);
10742
+ } catch (err) {
10743
+ return fail(err instanceof Error ? err.message : String(err), err instanceof TicketError ? err.code : 1);
10744
+ }
10745
+ console.log(`tracker: ${setup.target}`);
10746
+ for (const m of setup.manual) console.log(` add by hand: ${m}`);
10747
+ if (!setup.missing.length) {
10748
+ console.log("tracker has every state and label the workflows use");
10749
+ return setup.manual.length ? 1 : 0;
10750
+ }
10751
+ console.log("missing on the tracker:");
10752
+ for (const item of setup.missing) console.log(` ${item.kind} ${item.name} \u2014 ${item.detail}`);
10753
+ if (!await confirm(opts.yes, `create ${setup.missing.length} item(s) now?`)) {
10754
+ console.log("nothing created; run again with --yes to create them");
10755
+ return 0;
10756
+ }
10757
+ let failed = 0;
10758
+ for (const item of setup.missing) {
10759
+ try {
10760
+ await setup.create(item);
10761
+ console.log(` created ${item.kind} ${item.name}`);
10762
+ } catch (err) {
10763
+ failed++;
10764
+ console.error(` could not create ${item.kind} ${item.name}: ${err instanceof Error ? err.message : err}`);
10765
+ }
10766
+ }
10767
+ return failed || setup.manual.length ? 1 : 0;
10768
+ }
10769
+ function fail(message, code = 1) {
10770
+ console.error(`agent-workflow setup-project: ${message}`);
10771
+ return code;
10772
+ }
10773
+ async function confirm(yes, question) {
10774
+ if (yes) return true;
10775
+ if (!process.stdin.isTTY) return false;
10776
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
10777
+ try {
10778
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
10779
+ } finally {
10780
+ rl.close();
10781
+ }
10782
+ }
10783
+ function register(file, name) {
10784
+ const doc = (0, import_yaml3.parseDocument)(readFileSync9(file, "utf8"));
10785
+ const list = doc.get("projects");
10786
+ const names = list && typeof list.toJSON === "function" ? list.toJSON() : [];
10787
+ if (Array.isArray(names) && names.includes(name)) return false;
10788
+ if (list && list.add) list.add(name);
10789
+ else doc.set("projects", [name]);
10790
+ writeFileSync5(file, doc.toString());
10791
+ return true;
10792
+ }
10793
+ function projectYaml(o) {
10794
+ const tracker = o.github ? `tracker:
10795
+ kind: github
10796
+ repo: ${o.github}
10797
+ # Only issues assigned to these logins; triage assigns new issues to the same login.
10798
+ assignee: [${o.assignee ?? "me"}]
10799
+ other_states: [Backlog, Reviewed, Needs Info]` : `tracker:
10800
+ kind: linear
10801
+ slug: ${o.linear}
10802
+ api_key: $LINEAR_API_KEY
10803
+ # Only issues assigned to this user; triage assigns new issues to the same user.
10804
+ assignee: ${o.assignee ?? "me"}
10805
+ other_states: [Backlog, Reviewed, Needs Info]`;
10806
+ const states = o.github ? `# GitHub has no Done / Canceled: tear down on a closed issue only.
10807
+ states: { teardown: [Closed] }` : `# New issues are triaged in the team's Triage state (turn on Triage in the team settings).
10808
+ states: { triage: [Triage] }`;
10809
+ return `# project.yaml \u2014 written by \`agent-workflow setup-project\`; edit it freely.
10810
+ # Every key is explained in the template, templates/projects/your-repo/project.yaml,
10811
+ # and in \`agent-workflow contract\`.
10812
+
10813
+ ${tracker}
10814
+
10815
+ # The canonical repo: $ROOT in hooks and steps.
10816
+ root: ${o.root}
10817
+
10818
+ workspace:
10819
+ branch: agent/\${{ ticket.identifier }}
10820
+ provision: handlers/workspace-provision.sh
10821
+ cleanup: handlers/workspace-cleanup.sh
10822
+
10823
+ # triage new ticket \u2192 Todo, Backlog, Needs Info or closed
10824
+ # implement Todo / In Progress \u2192 In Review
10825
+ # review-loop In Review \u2192 Reviewed
10826
+ # a human Reviewed \u2192 Merging
10827
+ # merge Merging \u2192 Done / Closed
10828
+ workflows: [triage, implement, review-loop, merge, teardown]
10829
+ ${states}
10830
+
10831
+ inputs:
10832
+ triage: { assignee: ${o.assignee ?? "me"} }
10833
+ `;
10834
+ }
10835
+
10385
10836
  // src/cli/briefing.ts
10386
- import { closeSync as closeSync2, existsSync as existsSync8, fstatSync, openSync as openSync2, readSync } from "fs";
10837
+ import { closeSync as closeSync2, existsSync as existsSync10, fstatSync, openSync as openSync2, readSync } from "fs";
10387
10838
  var MAX_EXCERPT = 200;
10388
10839
  var TAIL_BYTES = 256 * 1024;
10389
10840
  var ERROR_LINE = /\b(error|fatal|panic)\b/i;
@@ -10407,7 +10858,7 @@ function roleLog(ctx) {
10407
10858
  }
10408
10859
  function logExcerpt(file) {
10409
10860
  if (!file) return "no agent log";
10410
- if (!existsSync8(file)) return `agent log ${file} is missing`;
10861
+ if (!existsSync10(file)) return `agent log ${file} is missing`;
10411
10862
  const lines = tail(file).split("\n");
10412
10863
  for (let i = lines.length - 1; i >= 0; i--) {
10413
10864
  const line = lines[i].trim();
@@ -10452,32 +10903,32 @@ function short(text) {
10452
10903
  }
10453
10904
 
10454
10905
  // src/cli/init.ts
10455
- import { copyFileSync, existsSync as existsSync9, mkdirSync as mkdirSync6, readdirSync } from "fs";
10906
+ import { copyFileSync, existsSync as existsSync11, mkdirSync as mkdirSync7, readdirSync } from "fs";
10456
10907
  import { homedir as homedir4 } from "os";
10457
- import { dirname as dirname4, join as join5, relative } from "path";
10458
- var defaultHome = () => join5(homedir4(), ".agent-workflow");
10908
+ import { dirname as dirname4, join as join6, relative } from "path";
10909
+ var defaultHome = () => join6(homedir4(), ".agent-workflow");
10459
10910
  function legacyHome(home) {
10460
- const legacy = join5(homedir4(), ".task-dispatch");
10461
- return home === defaultHome() && existsSync9(legacy) && !existsSync9(home) ? legacy : void 0;
10911
+ const legacy = join6(homedir4(), ".task-dispatch");
10912
+ return home === defaultHome() && existsSync11(legacy) && !existsSync11(home) ? legacy : void 0;
10462
10913
  }
10463
10914
  function initRuleSet(templates, home, force) {
10464
10915
  const result = { created: [], overwritten: [], kept: [] };
10465
10916
  for (const file of filesUnder(templates)) {
10466
10917
  const rel = relative(templates, file);
10467
- const target = join5(home, rel);
10468
- const exists = existsSync9(target);
10918
+ const target = join6(home, rel);
10919
+ const exists = existsSync11(target);
10469
10920
  if (exists && !force) {
10470
10921
  result.kept.push(rel);
10471
10922
  continue;
10472
10923
  }
10473
- mkdirSync6(dirname4(target), { recursive: true });
10924
+ mkdirSync7(dirname4(target), { recursive: true });
10474
10925
  copyFileSync(file, target);
10475
10926
  (exists ? result.overwritten : result.created).push(rel);
10476
10927
  }
10477
10928
  return result;
10478
10929
  }
10479
10930
  function filesUnder(dir) {
10480
- return readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap((e) => e.isDirectory() ? filesUnder(join5(dir, e.name)) : e.isFile() ? [join5(dir, e.name)] : []);
10931
+ return readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap((e) => e.isDirectory() ? filesUnder(join6(dir, e.name)) : e.isFile() ? [join6(dir, e.name)] : []);
10481
10932
  }
10482
10933
 
10483
10934
  // src/cli/main.ts
@@ -10485,6 +10936,7 @@ var PACKAGE_DIR = packageRoot(dirname5(fileURLToPath(import.meta.url)));
10485
10936
  var HOME_DIR = expandHome3(process.env.AGENT_WORKFLOW_HOME || "~/.agent-workflow");
10486
10937
  var USAGE = `usage:
10487
10938
  agent-workflow init [--home DIR] [--force]
10939
+ ${SETUP_USAGE}
10488
10940
  agent-workflow dispatch [<project>...] [--dry-run]
10489
10941
  agent-workflow dispatch --ticket <id> [--dry-run]
10490
10942
  agent-workflow status
@@ -10500,6 +10952,21 @@ async function main(argv) {
10500
10952
  switch (command) {
10501
10953
  case "init":
10502
10954
  return initCommand(rest);
10955
+ case "setup-project": {
10956
+ const names = [];
10957
+ const opts = parseFlags(rest, ["--yes"], ["--github", "--linear", "--root", "--assignee"], names);
10958
+ if (typeof opts === "string") return usage2(opts);
10959
+ if (names.length !== 1) return usage2("setup-project takes one project name");
10960
+ const root = opts["--root"];
10961
+ return setupProject(HOME_DIR, {
10962
+ name: names[0],
10963
+ github: opts["--github"],
10964
+ linear: opts["--linear"],
10965
+ root: root ? resolve6(expandHome3(root)) : void 0,
10966
+ assignee: opts["--assignee"],
10967
+ yes: !!opts["--yes"]
10968
+ });
10969
+ }
10503
10970
  case "dispatch": {
10504
10971
  const projects = [];
10505
10972
  const opts = parseFlags(rest, ["--dry-run"], ["--ticket"], projects);
@@ -10566,8 +11033,8 @@ or run init --force to start a fresh home and leave ${legacy} as it is`
10566
11033
  const env = home === defaultHome() ? "" : `AGENT_WORKFLOW_HOME=${home} `;
10567
11034
  console.log(`
10568
11035
  rule set ready in ${home}. Next:
10569
- 1. edit ${join6(home, "agents.yaml")} (agent profiles), ${join6(home, "config.yaml")} (registered projects)
10570
- and ${join6(home, "projects", "<name>", "project.yaml")} (tracker, root and workflows of each project)
11036
+ 1. edit ${join7(home, "agents.yaml")} (agent profiles), ${join7(home, "config.yaml")} (registered projects)
11037
+ and ${join7(home, "projects", "<name>", "project.yaml")} (tracker, root and workflows of each project)
10571
11038
  2. ${env}agent-workflow validate
10572
11039
  3. ${env}agent-workflow dispatch --dry-run`);
10573
11040
  return 0;
@@ -10575,9 +11042,9 @@ rule set ready in ${home}. Next:
10575
11042
  function contractCommand(args) {
10576
11043
  const unknown = args.filter((a) => a !== "--path");
10577
11044
  if (unknown.length) return usage2(`unknown argument '${unknown[0]}'`);
10578
- const file = join6(PACKAGE_DIR, "docs", "contract.md");
11045
+ const file = join7(PACKAGE_DIR, "docs", "contract.md");
10579
11046
  if (args.includes("--path")) console.log(file);
10580
- else process.stdout.write(readFileSync9(file, "utf8"));
11047
+ else process.stdout.write(readFileSync10(file, "utf8"));
10581
11048
  return 0;
10582
11049
  }
10583
11050
  function parseFlags(args, bool, value, positional) {
@@ -10617,28 +11084,28 @@ function selfStatus(config) {
10617
11084
  async function deliverCommand(args) {
10618
11085
  const opts = parseFlags(args, ["--force", "-"], ["--verdict", "--file"]);
10619
11086
  if (typeof opts === "string") return usage2(opts);
10620
- const fail = (code, msg) => {
11087
+ const fail2 = (code, msg) => {
10621
11088
  console.error(`deliver: ${code}: ${msg}`);
10622
11089
  return 1;
10623
11090
  };
10624
11091
  const config = loadConfig(paths());
10625
- if (!config) return fail("CONFIG_INVALID", "the configuration does not validate");
11092
+ if (!config) return fail2("CONFIG_INVALID", "the configuration does not validate");
10626
11093
  const c = caller(config);
10627
- if (c.error !== void 0) return fail(c.code, c.error);
11094
+ if (c.error !== void 0) return fail2(c.code, c.error);
10628
11095
  const run2 = c.ctx.run;
10629
11096
  const project = config.projects[c.ctx.project];
10630
11097
  const wf = project?.workflows[run2.workflow];
10631
11098
  const step = wf && locate(wf, run2.cursor).step;
10632
11099
  if (!step || step.verb !== "launch" && step.verb !== "message" || step.role !== c.role || !step.expect || run2.turn !== c.role) {
10633
- return fail("STEP_NOT_EXPECTING", `run ${run2.id} is not waiting for a delivery from ${c.role}`);
11100
+ return fail2("STEP_NOT_EXPECTING", `run ${run2.id} is not waiting for a delivery from ${c.role}`);
10634
11101
  }
10635
- const body = (opts["--file"] ? readFileSync9(String(opts["--file"]), "utf8") : readFileSync9(0, "utf8")).trim();
10636
- if (!body) return fail("DELIVERY_EMPTY", "the delivery body is empty");
11102
+ const body = (opts["--file"] ? readFileSync10(String(opts["--file"]), "utf8") : readFileSync10(0, "utf8")).trim();
11103
+ if (!body) return fail2("DELIVERY_EMPTY", "the delivery body is empty");
10637
11104
  const verdict = opts["--verdict"];
10638
11105
  const problems = deliveryProblems(step.expect, body, verdict);
10639
11106
  if (problems.length && step.expect.strict && !opts["--force"]) {
10640
11107
  for (const p of problems) console.error(` - ${p}`);
10641
- return fail("DELIVERY_INCOMPLETE", "fix the body and deliver again (this step is strict)");
11108
+ return fail2("DELIVERY_INCOMPLETE", "fix the body and deliver again (this step is strict)");
10642
11109
  }
10643
11110
  const path = writeDelivery(project.stateDir, run2.id, step.expect.delivery, body, {
10644
11111
  token: c.token,
@@ -10656,7 +11123,7 @@ async function deliverCommand(args) {
10656
11123
  console.log(`delivered '${step.expect.delivery}'${verdict ? ` (verdict ${verdict})` : ""} \u2192 ${path}`);
10657
11124
  }
10658
11125
  const logDir = resolve6(paths().stateDir, "logs");
10659
- mkdirSync7(logDir, { recursive: true });
11126
+ mkdirSync8(logDir, { recursive: true });
10660
11127
  const out = openSync3(resolve6(logDir, "deliveries.log"), "a");
10661
11128
  const { AGENT_WORKFLOW_TOKEN, AGENT_WORKFLOW_ROLE, AGENT_WORKFLOW_RUN, SESSION_ID, LOG_FILE, PROMPT_FILE, ...env } = process.env;
10662
11129
  const child = spawn3(resolve6(PACKAGE_DIR, "bin", "agent-workflow"), ["dispatch", "--ticket", c.id], { detached: true, stdio: ["ignore", out, out], env });
@@ -10766,12 +11233,12 @@ function displayPath(file) {
10766
11233
  }
10767
11234
  function packageRoot(from) {
10768
11235
  for (let dir = from; ; dir = dirname5(dir)) {
10769
- if (existsSync10(join6(dir, "package.json"))) return dir;
11236
+ if (existsSync12(join7(dir, "package.json"))) return dir;
10770
11237
  if (dirname5(dir) === dir) throw new Error(`no package.json above ${from}`);
10771
11238
  }
10772
11239
  }
10773
11240
  function expandHome3(p) {
10774
- return p === "~" || p.startsWith("~/") ? join6(homedir5(), p.slice(1)) : p;
11241
+ return p === "~" || p.startsWith("~/") ? join7(homedir5(), p.slice(1)) : p;
10775
11242
  }
10776
11243
  main(process.argv.slice(2)).then(
10777
11244
  (code) => {