@gumpwang/agent-workflow 0.1.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,16 +7653,19 @@ 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"];
7665
7665
  var RULE_SET_PATH = /^(\s*)([A-Za-z0-9_@+-][^\s'"`;&|<>()$]*\/[^\s'"`;&|<>()$]*)/;
7666
+ function ruleSetPath(command) {
7667
+ return RULE_SET_PATH.exec(command)?.[2];
7668
+ }
7666
7669
  function resolveRunCommand(command, rulesDir) {
7667
7670
  const m = RULE_SET_PATH.exec(command);
7668
7671
  if (!m) return command;
@@ -7722,7 +7725,7 @@ var WorkflowChecker = class {
7722
7725
  file: this.file,
7723
7726
  rulesDir: this.rulesDir,
7724
7727
  name: "",
7725
- on: { states: [], tracked: false },
7728
+ on: { states: [], tracked: false, anyAssignee: false },
7726
7729
  onInterrupt: "cancel",
7727
7730
  inputs: {},
7728
7731
  roles: {},
@@ -7738,11 +7741,12 @@ var WorkflowChecker = class {
7738
7741
  wf.description = this.string(raw, "description", "");
7739
7742
  const on = this.map(raw, "on", "", true);
7740
7743
  if (on) {
7741
- this.unknownKeys(on, "on", ["states", "tracked"]);
7744
+ this.unknownKeys(on, "on", ["states", "tracked", "any_assignee"]);
7742
7745
  const states = this.stringList(on, "states", "on", true);
7743
7746
  if (states && !states.length) this.invalid("on.states", "list at least one ticket state");
7744
7747
  wf.on.states = states ?? [];
7745
7748
  wf.on.tracked = this.bool(on, "tracked", "on") ?? false;
7749
+ wf.on.anyAssignee = this.bool(on, "any_assignee", "on") ?? false;
7746
7750
  }
7747
7751
  const onInterrupt = this.string(raw, "on_interrupt", "");
7748
7752
  if (onInterrupt !== void 0) {
@@ -7965,7 +7969,7 @@ var WorkflowChecker = class {
7965
7969
  this.unknownKeys(raw, at, [...common, "run", "working-directory", "env"]);
7966
7970
  const run2 = this.string(raw, "run", at, true) ?? "";
7967
7971
  this.template(run2, join(at, "run"), inLoop, true);
7968
- const handler = RULE_SET_PATH.exec(run2)?.[2];
7972
+ const handler = ruleSetPath(run2);
7969
7973
  if (handler && !existsSync(resolve(this.rulesDir, handler))) {
7970
7974
  this.report("error", join(at, "run"), "RUN_NOT_FOUND", `no file ${handler} in the rule set ${this.rulesDir}`);
7971
7975
  }
@@ -7998,8 +8002,14 @@ var WorkflowChecker = class {
7998
8002
  const t = this.map(raw, "tracker", at, true);
7999
8003
  if (!t) return void 0;
8000
8004
  const tat = join(at, "tracker");
8001
- this.unknownKeys(t, tat, ["state", "comment", "label"]);
8005
+ this.unknownKeys(t, tat, ["state", "comment", "reason", "label"]);
8002
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
+ }
8003
8013
  if (t.label !== void 0) this.notImplemented(join(tat, "label"), "tracker.label");
8004
8014
  else if (!step.state && !step.comment) this.invalid(tat, "set at least one of state or comment");
8005
8015
  for (const key of ["state", "comment"]) if (step[key]) this.template(step[key], join(tat, key), inLoop);
@@ -8264,57 +8274,72 @@ function resolveWorkflowFile(id, home) {
8264
8274
  }
8265
8275
  function validateHome(home) {
8266
8276
  const file = resolve2(home, "config.yaml");
8277
+ const agentsFile = resolve2(home, "agents.yaml");
8267
8278
  const diagnostics = [];
8268
- const report = (level, at, code, message, inFile = file) => diagnostics.push({ level, file: inFile, at, code, message });
8269
- if (!existsSync2(file)) {
8270
- report("error", "", "CONFIG_NOT_FOUND", `no config.yaml in ${home}`);
8271
- return { diagnostics };
8279
+ const report = (level, inFile, at, code, message) => diagnostics.push({ level, file: inFile, at, code, message });
8280
+ const checker = (inFile) => new ConfigChecker((at, msg) => report("error", inFile, at, "CONFIG_INVALID", msg));
8281
+ const mainRaw = readYaml(file, report);
8282
+ if (!mainRaw) return { diagnostics };
8283
+ const main2 = checker(file).main(mainRaw.raw, file);
8284
+ const agentsRaw = readYaml(agentsFile, report);
8285
+ const agents = agentsRaw && checker(agentsFile).agentsFile(agentsRaw.raw, agentsFile);
8286
+ const parsed = [];
8287
+ for (const [i, name] of (main2?.projects ?? []).entries()) {
8288
+ const dir = resolve2(home, "projects", name);
8289
+ const projectFile = join2(dir, "project.yaml");
8290
+ if (!existsSync2(projectFile)) {
8291
+ report("error", file, `projects[${i}]`, "CONFIG_NOT_FOUND", `project '${name}' has no ${projectFile}`);
8292
+ continue;
8293
+ }
8294
+ const raw = readYaml(projectFile, report);
8295
+ const p = raw && checker(projectFile).project(raw.raw, projectFile, name, dir);
8296
+ if (p) parsed.push(p);
8272
8297
  }
8273
- let raw;
8274
- try {
8275
- raw = (0, import_yaml2.parse)(readFileSync2(file, "utf8"));
8276
- } catch (e) {
8277
- report("error", "", "CONFIG_INVALID", e instanceof Error ? e.message.split("\n")[0] : String(e));
8278
- return { diagnostics };
8279
- }
8280
- const parsed = new ConfigChecker((at, msg) => report("error", at, "CONFIG_INVALID", msg)).check(raw, file);
8281
- if (!parsed || diagnostics.length) return { diagnostics };
8282
- for (const a of Object.values(parsed.agents)) {
8283
- for (const [key, cmd] of [["command", a.command], ["resume_command", a.resumeCommand]]) {
8284
- if (cmd !== void 0 && !/\$\{?SESSION_ID\b/.test(cmd)) {
8285
- report("warning", `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");
8286
- }
8287
- }
8288
- }
8289
- const config = {
8290
- file,
8291
- maxConcurrent: parsed.maxConcurrent,
8292
- workspace: parsed.workspace,
8293
- attentionState: parsed.attentionState,
8294
- defaultAgent: parsed.defaultAgent,
8295
- agents: parsed.agents,
8296
- projects: {}
8297
- };
8298
+ if (!main2 || !agents || diagnostics.length) return { diagnostics };
8299
+ const stateOwner = /* @__PURE__ */ new Map();
8300
+ for (const p of parsed) {
8301
+ const prev = stateOwner.get(p.stateDir);
8302
+ if (prev) report("error", p.file, "state.path", "CONFIG_INVALID", `${p.stateDir} is already the state dir of project '${prev}'`);
8303
+ else stateOwner.set(p.stateDir, p.name);
8304
+ }
8305
+ const config = { file, maxConcurrent: main2.maxConcurrent, defaultAgent: agents.defaultAgent, agents: agents.agents, projects: {} };
8298
8306
  let failed = false;
8299
- for (const p of parsed.projects) {
8300
- const project = checkProject(
8301
- { ...p, workspace: p.workspace ?? parsed.workspace, attentionState: p.attentionState ?? parsed.attentionState },
8302
- config.agents,
8303
- parsed.defaultAgent,
8304
- home,
8305
- report,
8306
- diagnostics
8307
- );
8307
+ for (const p of parsed) {
8308
+ const project = checkProject(p, config.agents, config.defaultAgent, home, (level, at, code, message) => report(level, p.file, at, code, message), diagnostics);
8308
8309
  if (project) config.projects[p.name] = project;
8309
8310
  else failed = true;
8310
8311
  }
8311
8312
  return failed || diagnostics.some((d) => d.level === "error") ? { diagnostics } : { config, diagnostics };
8312
8313
  }
8314
+ function readYaml(file, report) {
8315
+ if (!existsSync2(file)) {
8316
+ report("error", file, "", "CONFIG_NOT_FOUND", `no ${file}`);
8317
+ return void 0;
8318
+ }
8319
+ try {
8320
+ return { raw: (0, import_yaml2.parse)(readFileSync2(file, "utf8")) };
8321
+ } catch (e) {
8322
+ report("error", file, "", "CONFIG_INVALID", e instanceof Error ? e.message.split("\n")[0] : String(e));
8323
+ return void 0;
8324
+ }
8325
+ }
8313
8326
  function checkProject(p, agents, defaultAgent, home, report, diagnostics) {
8314
- const at = join22("projects", p.name);
8315
8327
  const errorsBefore = diagnostics.filter((d) => d.level === "error").length;
8316
- const project = { name: p.name, root: p.root, tracker: p.tracker, workspace: p.workspace, attentionState: p.attentionState, workflows: {}, triggers: {}, roleAgents: {}, inputs: {} };
8317
- const wat = (i) => join22(join22(at, "workflows"), i);
8328
+ const project = {
8329
+ name: p.name,
8330
+ dir: p.dir,
8331
+ file: p.file,
8332
+ stateDir: p.stateDir,
8333
+ root: p.root,
8334
+ tracker: p.tracker,
8335
+ workspace: p.workspace,
8336
+ attentionState: p.attentionState,
8337
+ workflows: {},
8338
+ triggers: {},
8339
+ roleAgents: {},
8340
+ inputs: {}
8341
+ };
8342
+ const wat = (i) => join22("workflows", i);
8318
8343
  const loaded = [];
8319
8344
  p.workflowIds.forEach((id, i) => {
8320
8345
  const file = resolveWorkflowFile(id, home);
@@ -8339,27 +8364,24 @@ function checkProject(p, agents, defaultAgent, home, report, diagnostics) {
8339
8364
  }
8340
8365
  }
8341
8366
  if (p.attentionState && owner.has(p.attentionState.toLowerCase())) {
8342
- report("error", join22(at, "attention_state"), "CONFIG_INVALID", `'${p.attentionState}' starts workflow '${owner.get(p.attentionState.toLowerCase())}'; pick a state no workflow triggers on`);
8367
+ report("error", "attention_state", "CONFIG_INVALID", `'${p.attentionState}' starts workflow '${owner.get(p.attentionState.toLowerCase())}'; pick a state no workflow triggers on`);
8343
8368
  }
8344
- const usedRoles = /* @__PURE__ */ new Set();
8345
8369
  const profiles = Object.keys(agents);
8346
8370
  for (const { index, wf } of loaded) {
8347
8371
  const bound = {};
8348
8372
  for (const [role, def] of Object.entries(wf.roles)) {
8349
- usedRoles.add(role);
8350
- const override = p.roles[role];
8351
- const name = override ?? def.agent ?? defaultAgent ?? (profiles.length === 1 ? profiles[0] : void 0);
8352
- const where = override ? join22(join22(join22(at, "roles"), role), "agent") : wat(index);
8373
+ const name = def.agent ?? defaultAgent ?? (profiles.length === 1 ? profiles[0] : void 0);
8353
8374
  if (!name) {
8354
- report("error", where, "PROFILE_REQUIRED", `role '${role}' of '${wf.id}' needs an agent: set default_agent, or roles.${role}.agent in the project or the workflow`);
8375
+ report("error", wat(index), "PROFILE_REQUIRED", `role '${role}' of '${wf.id}' needs an agent: set default_agent in agents.yaml, or roles.${role}.agent in the workflow`);
8355
8376
  } else if (!agents[name]) {
8356
- report("error", where, "PROFILE_NOT_FOUND", `role '${role}' of '${wf.id}' names agent '${name}', which is not under agents`);
8377
+ report("error", wat(index), "PROFILE_NOT_FOUND", `role '${role}' of '${wf.id}' names agent '${name}', which is not in agents.yaml`);
8357
8378
  } else bound[role] = name;
8358
8379
  }
8359
8380
  project.roleAgents[wf.id] = bound;
8360
8381
  }
8361
- for (const role of Object.keys(p.roles)) {
8362
- if (!usedRoles.has(role)) report("warning", join22(join22(at, "roles"), role), "ROLE_UNUSED", `no enabled workflow declares role '${role}'`);
8382
+ for (const key of ["provision", "cleanup"]) {
8383
+ const script = ruleSetPath(p.workspace?.[key] ?? "");
8384
+ if (script && !existsSync2(resolve2(home, script))) report("error", join22("workspace", key), "RUN_NOT_FOUND", `no file ${script} in the rule set ${home}`);
8363
8385
  }
8364
8386
  const projectScope = { project: { name: p.name, root: p.root, tracker: p.tracker.kind, repo: "", slug: "" } };
8365
8387
  for (const { index, wf } of loaded) {
@@ -8380,7 +8402,7 @@ function checkProject(p, agents, defaultAgent, home, report, diagnostics) {
8380
8402
  }
8381
8403
  for (const { wf } of loaded) {
8382
8404
  const given = p.inputs[wf.id] ?? {};
8383
- const iat = join22(join22(at, "inputs"), wf.id);
8405
+ const iat = join22("inputs", wf.id);
8384
8406
  const values = {};
8385
8407
  for (const [name, def] of Object.entries(wf.inputs)) {
8386
8408
  if (name in given) continue;
@@ -8398,7 +8420,7 @@ function checkProject(p, agents, defaultAgent, home, report, diagnostics) {
8398
8420
  }
8399
8421
  for (const [key, map] of [["inputs", p.inputs], ["states", p.states]]) {
8400
8422
  for (const id of Object.keys(map)) {
8401
- if (!p.workflowIds.includes(id)) report("error", join22(join22(at, key), id), "CONFIG_INVALID", `workflow '${id}' is not enabled for this project`);
8423
+ if (!p.workflowIds.includes(id)) report("error", join22(key, id), "CONFIG_INVALID", `workflow '${id}' is not enabled for this project`);
8402
8424
  }
8403
8425
  }
8404
8426
  return diagnostics.filter((d) => d.level === "error").length === errorsBefore ? project : void 0;
@@ -8418,34 +8440,97 @@ var ConfigChecker = class {
8418
8440
  report(at, msg);
8419
8441
  };
8420
8442
  }
8421
- check(raw, file) {
8443
+ // config.yaml: the cap and the project registry.
8444
+ main(raw, file) {
8422
8445
  if (!isObj2(raw)) {
8423
8446
  this.invalid("", `${file} must be a YAML map`);
8424
8447
  return void 0;
8425
8448
  }
8426
- this.unknownKeys(raw, "", ["max_concurrent", "workspace", "attention_state", "default_agent", "agents", "projects"]);
8449
+ const moved = {
8450
+ agents: "agents.yaml",
8451
+ default_agent: "agents.yaml",
8452
+ workspace: "projects/<name>/project.yaml",
8453
+ attention_state: "projects/<name>/project.yaml"
8454
+ };
8455
+ for (const k of Object.keys(raw)) {
8456
+ if (moved[k]) this.invalid(k, `'${k}' moved to ${moved[k]} (ADR 0008)`);
8457
+ else if (k !== "max_concurrent" && k !== "projects") this.invalid(k, `unknown key '${k}'`);
8458
+ }
8427
8459
  let maxConcurrent;
8428
8460
  if (raw.max_concurrent !== void 0) {
8429
8461
  if (Number.isInteger(raw.max_concurrent) && raw.max_concurrent > 0) maxConcurrent = raw.max_concurrent;
8430
8462
  else this.invalid("max_concurrent", "must be a positive integer");
8431
8463
  }
8432
- const workspace = this.workspace(raw.workspace, "workspace");
8433
- const attentionState = this.string(raw, "attention_state", "");
8464
+ if (isObj2(raw.projects)) {
8465
+ this.invalid("projects", "list the project names; each project lives in projects/<name>/project.yaml (ADR 0008)");
8466
+ return void 0;
8467
+ }
8468
+ const projects = this.stringList(raw, "projects", "") ?? [];
8469
+ if (Array.isArray(raw.projects) && !projects.length) this.invalid("projects", "list at least one project");
8470
+ const seen = /* @__PURE__ */ new Set();
8471
+ projects.forEach((name, i) => {
8472
+ if (!PROJECT_NAME.test(name)) this.invalid(`projects[${i}]`, "project names use only [A-Za-z0-9_.-]");
8473
+ else if (seen.has(name)) this.invalid(`projects[${i}]`, `project '${name}' is listed twice`);
8474
+ seen.add(name);
8475
+ });
8476
+ return this.ok ? { maxConcurrent, projects } : void 0;
8477
+ }
8478
+ // agents.yaml: the agent profiles.
8479
+ agentsFile(raw, file) {
8480
+ if (!isObj2(raw)) {
8481
+ this.invalid("", `${file} must be a YAML map`);
8482
+ return void 0;
8483
+ }
8484
+ this.unknownKeys(raw, "", ["default_agent", "agents"]);
8434
8485
  const agents = this.agents(raw.agents);
8435
8486
  const defaultAgent = this.string(raw, "default_agent", "");
8436
8487
  if (defaultAgent !== void 0 && !agents[defaultAgent]) this.invalid("default_agent", `'${defaultAgent}' is not under agents`);
8437
- const projects = this.projects(raw.projects);
8438
- return this.ok ? { maxConcurrent, workspace, attentionState, defaultAgent, agents, projects } : void 0;
8488
+ return this.ok ? { defaultAgent, agents } : void 0;
8439
8489
  }
8440
- workspace(raw, at) {
8490
+ // projects/<name>/project.yaml.
8491
+ project(raw, file, name, dir) {
8492
+ if (!isObj2(raw)) {
8493
+ this.invalid("", `${file} must be a YAML map`);
8494
+ return void 0;
8495
+ }
8496
+ this.unknownKeys(raw, "", ["tracker", "root", "attention_state", "workspace", "state", "workflows", "states", "inputs"]);
8497
+ const tracker = this.tracker(raw.tracker, "tracker");
8498
+ const root = this.string(raw, "root", "", true);
8499
+ const attentionState = this.string(raw, "attention_state", "");
8500
+ const workspace = this.workspace(raw.workspace, "workspace", dir);
8501
+ let stateDir = join2(dir, "state");
8502
+ const state = this.map(raw, "state", "");
8503
+ if (state) {
8504
+ this.unknownKeys(state, "state", ["path"]);
8505
+ const path = this.string(state, "path", "state");
8506
+ if (path !== void 0) stateDir = resolve2(dir, expandHome(path));
8507
+ }
8508
+ const workflowIds = this.workflowIds(raw);
8509
+ const states = {};
8510
+ const rawStates = this.map(raw, "states", "") ?? {};
8511
+ for (const wf of Object.keys(rawStates)) {
8512
+ const list = this.stringList(rawStates, wf, "states");
8513
+ if (list && !list.length) this.invalid(join22("states", wf), "list at least one ticket state");
8514
+ else if (list) states[wf] = list;
8515
+ }
8516
+ const inputs = {};
8517
+ for (const [wf, values] of Object.entries(this.map(raw, "inputs", "") ?? {})) {
8518
+ if (isObj2(values)) inputs[wf] = values;
8519
+ else this.invalid(join22("inputs", wf), "must be a map of input values");
8520
+ }
8521
+ if (!this.ok || !tracker || root === void 0 || !workflowIds) return void 0;
8522
+ return { name, dir, file, stateDir, root: expandHome(root), tracker, workspace, attentionState, workflowIds, states, inputs };
8523
+ }
8524
+ // Without a path, each ticket gets <project dir>/workspace/<identifier>.
8525
+ workspace(raw, at, projectDir) {
8441
8526
  if (raw === void 0) return void 0;
8442
8527
  if (!isObj2(raw)) {
8443
- this.invalid(at, "must be a map with path, and optional branch, provision, cleanup");
8528
+ this.invalid(at, "must be a map with optional path, branch, provision, cleanup");
8444
8529
  return void 0;
8445
8530
  }
8446
8531
  this.unknownKeys(raw, at, ["path", "branch", "provision", "cleanup"]);
8447
8532
  const ws = {
8448
- path: this.string(raw, "path", at, true) ?? "",
8533
+ path: this.string(raw, "path", at) ?? join2(projectDir, "workspace", "${{ ticket.identifier }}"),
8449
8534
  branch: this.string(raw, "branch", at),
8450
8535
  provision: this.string(raw, "provision", at),
8451
8536
  cleanup: this.string(raw, "cleanup", at)
@@ -8493,59 +8578,13 @@ var ConfigChecker = class {
8493
8578
  }
8494
8579
  return out;
8495
8580
  }
8496
- projects(raw) {
8497
- const out = [];
8498
- if (!isObj2(raw) || !Object.keys(raw).length) {
8499
- this.invalid("projects", "declare at least one project");
8500
- return out;
8501
- }
8502
- for (const [name, def] of Object.entries(raw)) {
8503
- const at = join22("projects", name);
8504
- if (!PROJECT_NAME.test(name)) this.invalid(at, "project names use only [A-Za-z0-9_.-]");
8505
- if (!isObj2(def)) {
8506
- this.invalid(at, "must be a map");
8507
- continue;
8508
- }
8509
- this.unknownKeys(def, at, ["tracker", "root", "workspace", "attention_state", "workflows", "states", "roles", "inputs"]);
8510
- const tracker = this.tracker(def.tracker, join22(at, "tracker"));
8511
- const root = this.string(def, "root", at, true);
8512
- const workspace = this.workspace(def.workspace, join22(at, "workspace"));
8513
- const workflowIds = this.workflowIds(def, at);
8514
- const roles = {};
8515
- for (const [role, r] of Object.entries(this.map(def, "roles", at) ?? {})) {
8516
- const rat = join22(join22(at, "roles"), role);
8517
- if (!isObj2(r)) {
8518
- this.invalid(rat, "must be a map with agent");
8519
- continue;
8520
- }
8521
- const agent = this.string(r, "agent", rat, true);
8522
- if (agent) roles[role] = agent;
8523
- }
8524
- const states = {};
8525
- const rawStates = this.map(def, "states", at) ?? {};
8526
- for (const wf of Object.keys(rawStates)) {
8527
- const list = this.stringList(rawStates, wf, join22(at, "states"));
8528
- if (list && !list.length) this.invalid(join22(join22(at, "states"), wf), "list at least one ticket state");
8529
- else if (list) states[wf] = list;
8530
- }
8531
- const inputs = {};
8532
- for (const [wf, values] of Object.entries(this.map(def, "inputs", at) ?? {})) {
8533
- if (isObj2(values)) inputs[wf] = values;
8534
- else this.invalid(join22(join22(at, "inputs"), wf), "must be a map of input values");
8535
- }
8536
- if (tracker && root !== void 0 && workflowIds) {
8537
- out.push({ name, root: expandHome(root), tracker, workspace, attentionState: this.string(def, "attention_state", at), workflowIds, states, roles, inputs });
8538
- }
8539
- }
8540
- return out;
8541
- }
8542
8581
  // No default list: the rule set alone says what a project runs.
8543
- workflowIds(def, at) {
8582
+ workflowIds(def) {
8544
8583
  if (def.workflows === void 0) {
8545
- this.invalid(join22(at, "workflows"), "is required: list the workflows this project enables (ids of files in workflows/)");
8584
+ this.invalid("workflows", "is required: list the workflows this project enables (ids of files in workflows/)");
8546
8585
  return void 0;
8547
8586
  }
8548
- return this.stringList(def, "workflows", at);
8587
+ return this.stringList(def, "workflows", "");
8549
8588
  }
8550
8589
  tracker(raw, at) {
8551
8590
  if (!isObj2(raw)) {
@@ -8635,7 +8674,7 @@ function startAgent(opts) {
8635
8674
  `);
8636
8675
  const stdinFd = openSync(opts.stdinFile, "r");
8637
8676
  try {
8638
- 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], {
8639
8678
  cwd: opts.cwd,
8640
8679
  detached: true,
8641
8680
  stdio: [stdinFd, logFd, logFd],
@@ -8759,6 +8798,29 @@ function releaseLock(file) {
8759
8798
  }
8760
8799
 
8761
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
+ };
8762
8824
  var TicketError = class extends Error {
8763
8825
  code;
8764
8826
  constructor(message, code) {
@@ -8821,6 +8883,12 @@ var API_URL = () => (process.env.GITHUB_API_URL || "https://api.github.com").rep
8821
8883
  var FIXED_STATES = ["Open", "Closed"];
8822
8884
  var same = (a, b) => a.toLowerCase() === b.toLowerCase();
8823
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
+ }
8824
8892
  function githubStateLabels(project) {
8825
8893
  const byPriority = Object.values(project.triggers).reverse().flatMap((states) => states.map((s) => project.tracker.stateAlias[s] ?? s));
8826
8894
  const other = [...project.tracker.otherStates, ...project.attentionState ? [project.attentionState] : []].map((s) => project.tracker.stateAlias[s] ?? s);
@@ -8909,9 +8977,12 @@ async function githubTickets(p, tracked) {
8909
8977
  state: canonical(spelledState(raw, labels)),
8910
8978
  labels: labelNames(raw),
8911
8979
  assignee: users[0] ?? null,
8912
- assignees: users
8980
+ assignees: users,
8981
+ blockedBy: 0
8913
8982
  };
8914
- 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);
8915
8986
  }
8916
8987
  let viewer;
8917
8988
  return {
@@ -8965,10 +9036,11 @@ function githubAdapter(p) {
8965
9036
  states: catalogue,
8966
9037
  labels: labelNames(raw),
8967
9038
  assignees: (raw.assignees ?? []).map((a) => a.login),
9039
+ blocked_by: await openBlockers(repo, raw),
8968
9040
  description: raw.body ?? ""
8969
9041
  };
8970
9042
  },
8971
- async setState(identifier, wanted) {
9043
+ async setState(identifier, wanted, reason = "completed") {
8972
9044
  const state = pickState(project, catalogue, wanted);
8973
9045
  const target = project.tracker.stateAlias[state] ?? state;
8974
9046
  const { raw, path } = await load(identifier);
@@ -8979,7 +9051,7 @@ function githubAdapter(p) {
8979
9051
  const hasTarget = !isLabel || names.some((n) => same(n, target));
8980
9052
  if (stale.length === 0 && hasTarget && raw.state === "closed" === wantClosed) return { state, changed: false };
8981
9053
  if (raw.state === "closed" !== wantClosed) {
8982
- 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" });
8983
9055
  }
8984
9056
  if (!hasTarget) {
8985
9057
  const add = await api("POST", `${path}/labels`, { labels: [target] }, [404, 422]);
@@ -8991,6 +9063,34 @@ function githubAdapter(p) {
8991
9063
  for (const label of stale) await api("DELETE", `${path}/labels/${encodeURIComponent(label)}`, void 0, [404]);
8992
9064
  return { state, changed: true };
8993
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
+ },
8994
9094
  async comment(identifier, body) {
8995
9095
  const { path } = await load(identifier);
8996
9096
  const { data } = await api("POST", `${path}/comments`, { body });
@@ -9015,6 +9115,58 @@ function githubAdapter(p) {
9015
9115
  async attach(identifier) {
9016
9116
  issuePath(identifier);
9017
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]);
9018
9170
  }
9019
9171
  };
9020
9172
  }
@@ -9024,6 +9176,10 @@ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
9024
9176
  import { homedir as homedir2 } from "os";
9025
9177
  import { join as join3 } from "path";
9026
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
+ }
9027
9183
  async function graphql(apiKey, query, variables) {
9028
9184
  const res = await fetch(API_URL2(), {
9029
9185
  method: "POST",
@@ -9081,7 +9237,7 @@ async function linearTickets(apiKey, projects) {
9081
9237
  apiKey,
9082
9238
  `query($pids:[ID!]!, $states:[String!]!){
9083
9239
  issues(filter:{project:{id:{in:$pids}}, state:{name:{in:$states}}}, first:250){
9084
- 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} }
9085
9241
  }
9086
9242
  }`,
9087
9243
  { pids: ids, states }
@@ -9098,9 +9254,10 @@ async function linearTickets(apiKey, projects) {
9098
9254
  description: n.description ?? "",
9099
9255
  url: n.url ?? "",
9100
9256
  state: canonical(n.state.name),
9101
- labels: [],
9257
+ labels: n.labels?.nodes.map((l) => l.name) ?? [],
9102
9258
  assignee: n.assignee,
9103
- assignees: n.assignee ? [n.assignee] : []
9259
+ assignees: n.assignee ? [n.assignee] : [],
9260
+ blockedBy: openBlockers2(n)
9104
9261
  }));
9105
9262
  out.push({
9106
9263
  project,
@@ -9138,6 +9295,30 @@ function linearAdapter(project) {
9138
9295
  const canonical = canonicalizer(project);
9139
9296
  const gql = (query, variables) => graphql(linearKey(project), query, variables);
9140
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
+ };
9141
9322
  const issueId = async (identifier) => {
9142
9323
  const r = await gql(`query($id:String!){issue(id:$id){id}}`, { id: identifier });
9143
9324
  if (!r.issue) throw notFound(identifier);
@@ -9148,7 +9329,7 @@ function linearAdapter(project) {
9148
9329
  env: () => linearEnv(project),
9149
9330
  async get(identifier) {
9150
9331
  const r = await gql(
9151
- `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} }}`,
9152
9333
  { id: identifier }
9153
9334
  );
9154
9335
  if (!r.issue) throw notFound(identifier);
@@ -9161,6 +9342,7 @@ function linearAdapter(project) {
9161
9342
  states: catalogue,
9162
9343
  labels: i.labels?.nodes.map((l) => l.name) ?? [],
9163
9344
  assignees: i.assignee ? [i.assignee.displayName] : [],
9345
+ blocked_by: openBlockers2(i),
9164
9346
  description: i.description ?? ""
9165
9347
  };
9166
9348
  },
@@ -9185,6 +9367,45 @@ function linearAdapter(project) {
9185
9367
  if (!res.issueUpdate.success) throw new TicketError(`issueUpdate failed for ${identifier}`, 3);
9186
9368
  return { state, changed: true };
9187
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
+ },
9188
9409
  async comment(identifier, body) {
9189
9410
  const id = await issueId(identifier);
9190
9411
  const res = await gql(
@@ -9225,6 +9446,86 @@ function linearAdapter(project) {
9225
9446
  );
9226
9447
  if (!res.attachmentLinkGitHubPR.success) throw new TicketError(`attach failed for ${identifier}`, 3);
9227
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);
9228
9529
  }
9229
9530
  };
9230
9531
  }
@@ -9241,6 +9542,9 @@ async function fetchTickets(projects, tracked) {
9241
9542
  for (const p of projects.filter((p2) => p2.tracker.kind === "github")) out.push(await githubTickets(p, tracked.get(p.name) ?? []));
9242
9543
  return projects.map((p) => out.find((t) => t.project === p));
9243
9544
  }
9545
+ function trackerSetup(project) {
9546
+ return project.tracker.kind === "github" ? githubSetup(project) : linearSetup(project);
9547
+ }
9244
9548
  function adapterFor(project) {
9245
9549
  return project.tracker.kind === "github" ? githubAdapter(project) : linearAdapter(project);
9246
9550
  }
@@ -9255,9 +9559,9 @@ async function resolveProject(config, identifier) {
9255
9559
  if (slugId === void 0) continue;
9256
9560
  const project = linear.find((p) => linearSlugId(p) === slugId);
9257
9561
  if (project) return project;
9258
- throw new TicketError(`${identifier} belongs to Linear project ${slugId}, which no project in config.yaml tracks`, 4);
9562
+ throw new TicketError(`${identifier} belongs to Linear project ${slugId}, which no registered project tracks`, 4);
9259
9563
  }
9260
- throw new TicketError(`no project in config.yaml has ticket ${identifier}`, 4);
9564
+ throw new TicketError(`no registered project has ticket ${identifier}`, 4);
9261
9565
  }
9262
9566
 
9263
9567
  // src/engine/delivery.ts
@@ -9531,7 +9835,7 @@ function completeDeliveryWaiting(e, t, wf) {
9531
9835
  return false;
9532
9836
  }
9533
9837
  if (!step || step.verb !== "launch" && step.verb !== "message" || !step.expect || run2.turn !== step.role) return false;
9534
- const meta = readMeta(e.stateDir, run2.id, step.expect.delivery);
9838
+ const meta = readMeta(t.project.stateDir, run2.id, step.expect.delivery);
9535
9839
  return !!meta && !meta.provisional && meta.token === t.ctx.roles[step.role]?.token;
9536
9840
  }
9537
9841
  function locate(wf, cursor) {
@@ -9563,6 +9867,7 @@ async function execute(e, t, wf, step) {
9563
9867
  run2.attention = `${step.at}: wait timed out after ${step.timeoutMinutes} min`;
9564
9868
  return "attention";
9565
9869
  }
9870
+ e.record({ ticket: t.identifier, action: "waiting", workflow: wf.id, detail: step.name ?? step.id ?? step.at });
9566
9871
  return "block";
9567
9872
  }
9568
9873
  case "tracker":
@@ -9610,14 +9915,14 @@ async function turn(e, t, wf, step, scope) {
9610
9915
  if (run2.turn === role && session) {
9611
9916
  const alive = isAgentAlive(session.pid, session.session_id);
9612
9917
  if (expect) {
9613
- const meta = readMeta(e.stateDir, run2.id, expect.delivery);
9918
+ const meta = readMeta(t.project.stateDir, run2.id, expect.delivery);
9614
9919
  if (meta && session.token && meta.token === session.token) {
9615
9920
  if (meta.provisional) {
9616
9921
  run2.attention = `${step.at}: delivery '${expect.delivery}' is incomplete (${meta.problems.join("; ")}); accept it with \`agent-workflow resolve ${t.identifier} accept [--verdict <v>]\`, or retry`;
9617
9922
  run2.attention_kind = "incomplete_delivery";
9618
9923
  return "attention";
9619
9924
  }
9620
- const path = deliveryPath(e.stateDir, run2.id, expect.delivery);
9925
+ const path = deliveryPath(t.project.stateDir, run2.id, expect.delivery);
9621
9926
  t.ctx.deliveries = { ...t.ctx.deliveries, [expect.delivery]: { path, verdict: meta.verdict, run: run2.id, at: meta.at } };
9622
9927
  if (step.id) run2.steps[step.id] = { outcome: meta.verdict ?? "success", outputs: { verdict: meta.verdict ?? null, path } };
9623
9928
  session.turns = 0;
@@ -9659,8 +9964,8 @@ async function turn(e, t, wf, step, scope) {
9659
9964
  }
9660
9965
  const inTrigger = !t.offTrigger && (t.project.triggers[wf.id] ?? []).some((st) => st.toLowerCase() === t.ticket.state.toLowerCase());
9661
9966
  if (!inTrigger) {
9662
- if (step.id) run2.steps[step.id] = { outcome: "no-delivery", outputs: {} };
9663
- return "next";
9967
+ run2.attention = `${step.at}: agent ended without delivery '${expect.delivery}' outside the workflow trigger states`;
9968
+ return "attention";
9664
9969
  }
9665
9970
  delete run2.turn;
9666
9971
  run2.nudge = true;
@@ -9675,7 +9980,7 @@ async function turn(e, t, wf, step, scope) {
9675
9980
  const maxAttempts = wf.roles[role]?.maxAttempts ?? 3;
9676
9981
  const continues = !!session && (step.verb === "message" || !!session.session_id);
9677
9982
  const resume = continues && profile.session === "claude" && !!session.session_id;
9678
- const used = step.verb === "launch" ? session?.turns ?? 0 : run2.step_turns ?? 0;
9983
+ const used = run2.step_turns ?? 0;
9679
9984
  if (session && used >= maxAttempts) {
9680
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}`;
9681
9986
  return "attention";
@@ -9695,7 +10000,7 @@ ${completionInstructions(expect, !!run2.nudge)}`;
9695
10000
  prompt += "\n";
9696
10001
  const kind = continues ? "resume" : "enter";
9697
10002
  const sessionId = resume ? session.session_id : randomUUID();
9698
- const log = session?.log ?? resolve4(e.stateDir, "logs", `${t.identifier}.${role}.log`);
10003
+ const log = session?.log ?? resolve4(t.project.stateDir, "logs", `${t.identifier}.${role}.log`);
9699
10004
  const workspace = t.ctx.workspace.path;
9700
10005
  if (e.dryRun) {
9701
10006
  console.log(`--- DRY-RUN ${kind} ${t.identifier} [${wf.id}] role=${role} agent=${profile.name} workspace=${workspace} ---`);
@@ -9704,7 +10009,7 @@ ${completionInstructions(expect, !!run2.nudge)}`;
9704
10009
  return "block";
9705
10010
  }
9706
10011
  const provisioned = await ensureWorkspace(e, t, wf);
9707
- const promptFile = resolve4(e.stateDir, "prompts", `${t.identifier}.${role}${kind === "resume" ? ".resume" : ""}.md`);
10012
+ const promptFile = resolve4(t.project.stateDir, "prompts", `${t.identifier}.${role}${kind === "resume" ? ".resume" : ""}.md`);
9708
10013
  mkdirSync4(dirname3(promptFile), { recursive: true });
9709
10014
  writeFileSync3(promptFile, prompt);
9710
10015
  const token2 = randomUUID();
@@ -9733,7 +10038,7 @@ ${completionInstructions(expect, !!run2.nudge)}`;
9733
10038
  ticket: t.identifier,
9734
10039
  action: kind,
9735
10040
  workflow: wf.id,
9736
- 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)" : ""}`
9737
10042
  });
9738
10043
  return "block";
9739
10044
  }
@@ -9787,7 +10092,8 @@ async function trackerStep(e, t, wf, step, scope) {
9787
10092
  }
9788
10093
  if (step.state) {
9789
10094
  const state = String(interpolate(step.state, scope));
9790
- 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) });
9791
10097
  }
9792
10098
  for (const op of ops) {
9793
10099
  if (e.dryRun) {
@@ -9827,7 +10133,7 @@ async function ensureWorkspace(e, t, wf) {
9827
10133
  const ws = t.ctx.workspace;
9828
10134
  const def = t.project.workspace;
9829
10135
  if (!def?.provision || ws.ready && existsSync6(ws.path)) return false;
9830
- const r = await shell(def.provision, t.project.root, baseEnv(e, t, wf));
10136
+ const r = await shell(resolveRunCommand(def.provision, e.home), t.project.root, baseEnv(e, t, wf));
9831
10137
  if (r.code !== 0) throw new Error(`workspace provision failed: ${r.lastErr || `exit ${r.code}`}`);
9832
10138
  ws.ready = true;
9833
10139
  return true;
@@ -9835,7 +10141,7 @@ async function ensureWorkspace(e, t, wf) {
9835
10141
  async function cleanupWorkspace(e, t, wf) {
9836
10142
  const def = t.project.workspace;
9837
10143
  if (!def?.cleanup) return;
9838
- const r = await shell(def.cleanup, t.project.root, baseEnv(e, t, wf));
10144
+ const r = await shell(resolveRunCommand(def.cleanup, e.home), t.project.root, baseEnv(e, t, wf));
9839
10145
  if (r.code !== 0) console.warn(`cleanup hook for ${t.identifier} failed: ${r.lastErr || `exit ${r.code}`}`);
9840
10146
  if (t.ctx.workspace) t.ctx.workspace.ready = false;
9841
10147
  }
@@ -9844,7 +10150,7 @@ function workspaceOf(project, ticket) {
9844
10150
  if (!def) return { path: project.root, ready: true };
9845
10151
  const scope = { ticket: ticketView(ticket), project: projectView(project) };
9846
10152
  return {
9847
- path: expandHome2(String(interpolate(def.path, scope))),
10153
+ path: resolve4(project.dir, expandHome2(String(interpolate(def.path, scope)))),
9848
10154
  branch: def.branch ? String(interpolate(def.branch, scope)) : void 0,
9849
10155
  ready: false
9850
10156
  };
@@ -9859,7 +10165,9 @@ function ticketView(ticket) {
9859
10165
  state: ticket.state,
9860
10166
  number: ticket.number ?? null,
9861
10167
  labels: ticket.labels,
9862
- assignee: ticket.assignee
10168
+ assignee: ticket.assignee,
10169
+ // Absent in tickets a ledger saved before blockers were read.
10170
+ blocked_by: ticket.blockedBy ?? 0
9863
10171
  };
9864
10172
  }
9865
10173
  function projectView(project) {
@@ -9989,28 +10297,49 @@ function pathsOf(home, packageDir) {
9989
10297
  home,
9990
10298
  packageDir,
9991
10299
  stateDir,
9992
- ledger: resolve5(stateDir, "ledger.json"),
9993
10300
  lastRun: resolve5(stateDir, "last-run.json"),
9994
10301
  lock: resolve5(stateDir, "dispatch.lock"),
9995
10302
  tickets: resolve5(stateDir, "issues.json")
9996
10303
  };
9997
10304
  }
10305
+ function ledgerFile(project) {
10306
+ return resolve5(project.stateDir, "ledger.json");
10307
+ }
9998
10308
  function loadConfig(paths2) {
9999
10309
  const { config, diagnostics } = validateHome(paths2.home);
10000
10310
  for (const d of diagnostics) console.error(`${d.level}: ${d.file}: ${d.at || "-"}: ${d.code}: ${d.message}`);
10001
10311
  return config;
10002
10312
  }
10003
- function openLedger(paths2) {
10004
- const ledger = loadLedger(paths2.ledger);
10313
+ function openLedger(config) {
10314
+ const ledger = { version: 2, tickets: {} };
10315
+ for (const p of Object.values(config.projects)) {
10316
+ for (const [id, ctx] of Object.entries(loadLedger(ledgerFile(p)).tickets)) {
10317
+ const prev = ledger.tickets[id];
10318
+ if (prev) console.warn(`${id} is in the ledgers of '${prev.project}' and '${p.name}'; using the one of '${prev.project}'`);
10319
+ else ledger.tickets[id] = ctx;
10320
+ }
10321
+ }
10005
10322
  for (const ctx of Object.values(ledger.tickets)) {
10006
10323
  for (const s of Object.values(ctx.roles)) s.status = isAgentAlive(s.pid, s.session_id) ? "running" : "exited";
10007
10324
  }
10008
10325
  return ledger;
10009
10326
  }
10327
+ function saveLedgers(config, ledger) {
10328
+ for (const p of Object.values(config.projects)) {
10329
+ const file = ledgerFile(p);
10330
+ const tickets = Object.fromEntries(Object.entries(ledger.tickets).filter(([, c]) => c.project === p.name));
10331
+ if (Object.keys(tickets).length || existsSync7(file)) saveLedger(file, { version: 2, tickets });
10332
+ }
10333
+ }
10010
10334
  var TICKET_LOCK_WAIT_MS = 15 * 6e4;
10011
10335
  async function reconcile(paths2, opts) {
10012
10336
  const config = loadConfig(paths2);
10013
10337
  if (!config) return false;
10338
+ const unknown = opts.projects?.filter((name) => !config.projects[name]) ?? [];
10339
+ if (unknown.length) {
10340
+ console.error(`no project ${unknown.map((n) => `'${n}'`).join(", ")} in ${config.file}; registered: ${Object.keys(config.projects).join(", ")}`);
10341
+ return false;
10342
+ }
10014
10343
  mkdirSync5(paths2.stateDir, { recursive: true });
10015
10344
  if (!opts.dryRun && !(opts.ticket ? await acquireLockWaiting(paths2.lock, TICKET_LOCK_WAIT_MS) : acquireLock(paths2.lock))) return true;
10016
10345
  try {
@@ -10024,8 +10353,8 @@ async function reconcile(paths2, opts) {
10024
10353
  async function reconcileLocked(paths2, config, opts) {
10025
10354
  const { dryRun } = opts;
10026
10355
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
10027
- const ledger = openLedger(paths2);
10028
- const projects = Object.values(config.projects);
10356
+ const ledger = openLedger(config);
10357
+ const projects = Object.values(config.projects).filter((p) => !opts.projects || opts.projects.includes(p.name));
10029
10358
  const tracked = /* @__PURE__ */ new Map();
10030
10359
  for (const [id, ctx] of Object.entries(ledger.tickets)) tracked.set(ctx.project, [...tracked.get(ctx.project) ?? [], id]);
10031
10360
  const fetched = await fetchTickets(projects, tracked);
@@ -10068,7 +10397,7 @@ async function reconcileLocked(paths2, config, opts) {
10068
10397
  console.log(`dry_run=true tracked=${Object.keys(ledger.tickets).length} running=${engine.slots.used}`);
10069
10398
  return;
10070
10399
  }
10071
- saveLedger(paths2.ledger, ledger);
10400
+ saveLedgers(config, ledger);
10072
10401
  const count = (a) => actions.filter((x) => x.action === a).length;
10073
10402
  const summary = `entered=${count("enter")} resumed=${count("resume")} ran=${count("run")} waiting=${count("waiting")} closed=${count("close")} released=${count("release")} interrupted=${count("interrupt")} attention=${count("attention")} deferred=${count("deferred")} failed=${count("failed")} running=${engine.slots.used}`;
10074
10403
  writeFileSync4(paths2.lastRun, JSON.stringify({ started_at: startedAt, finished_at: (/* @__PURE__ */ new Date()).toISOString(), summary, actions }, null, 2) + "\n");
@@ -10079,7 +10408,6 @@ function engineFor(paths2, config, ledger, opts, actions) {
10079
10408
  return {
10080
10409
  home: paths2.home,
10081
10410
  packageDir: paths2.packageDir,
10082
- stateDir: paths2.stateDir,
10083
10411
  config,
10084
10412
  dryRun,
10085
10413
  slots: {
@@ -10092,31 +10420,26 @@ function engineFor(paths2, config, ledger, opts, actions) {
10092
10420
  for (const line of opts.brief?.(a, ledger.tickets[a.ticket]) ?? []) console.log(line);
10093
10421
  },
10094
10422
  persist() {
10095
- if (!dryRun) saveLedger(paths2.ledger, ledger);
10423
+ if (!dryRun) saveLedgers(config, ledger);
10096
10424
  }
10097
10425
  };
10098
10426
  }
10099
10427
  async function advanceOne(paths2, config, identifier, opts) {
10100
10428
  const { dryRun } = opts;
10101
- const ledger = openLedger(paths2);
10429
+ const ledger = openLedger(config);
10102
10430
  const ctx = ledger.tickets[identifier];
10103
10431
  const project = ctx && config.projects[ctx.project];
10104
10432
  if (!ctx || !project || !isActive(ctx)) return;
10105
10433
  const engine = engineFor(paths2, config, ledger, opts);
10106
- let ticket = ctx.ticket;
10107
- let offTrigger = false;
10108
10434
  const tracker = adapterFor(project);
10109
- try {
10110
- const state = await tracker.refresh(ticket);
10111
- if (state) ticket = { ...ticket, state };
10112
- offTrigger = !desiredWorkflow(project, ticket);
10113
- } catch (err) {
10114
- console.warn(`could not read ${identifier} from the tracker, using the last snapshot: ${err instanceof Error ? err.message : err}`);
10115
- }
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);
10116
10439
  ctx.ticket = ticket;
10117
10440
  const work = { identifier, ctx, project, ticket, trackerEnv: tracker.env(ticket), offTrigger };
10118
10441
  await advanceActive(engine, ledger, work);
10119
- if (!dryRun) saveLedger(paths2.ledger, ledger);
10442
+ if (!dryRun) saveLedgers(config, ledger);
10120
10443
  }
10121
10444
  function desiredWorkflow(project, ticket) {
10122
10445
  const state = ticket.state.toLowerCase();
@@ -10129,7 +10452,7 @@ function workOf(identifier, ctx, pt, ticket) {
10129
10452
  async function handleTicket(e, ledger, pt, ticket, desired) {
10130
10453
  const id = ticket.identifier;
10131
10454
  let ctx = ledger.tickets[id];
10132
- if (desired && !desired.on.tracked && !pt.isMine(ticket)) {
10455
+ if (desired && !desired.on.tracked && !desired.on.anyAssignee && !pt.isMine(ticket)) {
10133
10456
  if (!ctx) return;
10134
10457
  const to = ticket.assignee?.displayName || ticket.assignee?.name || "nobody";
10135
10458
  if (e.dryRun) {
@@ -10219,32 +10542,61 @@ function withLedger(paths2, fn) {
10219
10542
  if (!acquireLock(paths2.lock)) return Promise.resolve(false);
10220
10543
  return (async () => {
10221
10544
  try {
10222
- const ledger = openLedger(paths2);
10545
+ const ledger = openLedger(config);
10223
10546
  await fn(ledger, config);
10224
- saveLedger(paths2.ledger, ledger);
10547
+ saveLedgers(config, ledger);
10225
10548
  return true;
10226
10549
  } finally {
10227
10550
  releaseLock(paths2.lock);
10228
10551
  }
10229
10552
  })();
10230
10553
  }
10231
- function statusReport(paths2) {
10232
- const ledger = existsSync7(paths2.ledger) ? loadLedger(paths2.ledger) : { version: 2, tickets: {} };
10233
- for (const ctx of Object.values(ledger.tickets)) {
10234
- for (const s of Object.values(ctx.roles)) s.status = isAgentAlive(s.pid, s.session_id) ? "running" : "exited";
10235
- }
10554
+ function statusReport(paths2, config) {
10555
+ const ledger = openLedger(config);
10236
10556
  const lastRun = existsSync7(paths2.lastRun) ? JSON.parse(readFileSync7(paths2.lastRun, "utf8")) : null;
10237
10557
  return { home: paths2.home, tickets: ledger.tickets, last_run: lastRun };
10238
10558
  }
10239
10559
 
10240
10560
  // src/cli/ticket.ts
10241
- 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";
10242
10563
  var TICKET_USAGE = ` agent-workflow ticket <ID> get
10243
- 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>...
10244
10567
  agent-workflow ticket <ID> comment [body|-]
10245
10568
  agent-workflow ticket <ID> comments
10246
10569
  agent-workflow ticket <ID> comment-update <comment-id> [body|-] [--final]
10247
- 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
+ }
10248
10600
  function checkboxTally(body) {
10249
10601
  const checked = body.match(/^\s*[-*+] \[[xX]\]/gm)?.length ?? 0;
10250
10602
  const unchecked = body.match(/^\s*[-*+] \[ \]/gm)?.length ?? 0;
@@ -10268,16 +10620,29 @@ async function ticketCommand(args, loadConfig2) {
10268
10620
  }
10269
10621
  async function run(args, loadConfig2) {
10270
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
+ }
10271
10631
  const [id, sub, ...rest] = args.filter((a) => a !== "--final");
10272
10632
  if (!id || !sub) throw usage("ticket needs an ID and a subcommand");
10273
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");
10274
10636
  const arity = {
10275
10637
  get: [0, 0],
10276
10638
  state: [1, 1],
10639
+ label: [2, Infinity],
10640
+ assign: [1, Infinity],
10277
10641
  comment: [0, 1],
10278
10642
  comments: [0, 0],
10279
10643
  "comment-update": [1, 2],
10280
- attach: [1, 1]
10644
+ attach: [1, 1],
10645
+ upload: [1, Infinity]
10281
10646
  };
10282
10647
  const range = arity[sub];
10283
10648
  if (!range) throw usage(`unknown ticket subcommand '${sub}'`);
@@ -10291,6 +10656,7 @@ async function run(args, loadConfig2) {
10291
10656
  throw new TicketError(`--final: ${unchecked} unchecked item(s) remain; finish them or report the block instead (comment not updated)`, 5);
10292
10657
  }
10293
10658
  }
10659
+ const uploads = sub === "upload" ? readUploads(rest) : [];
10294
10660
  const config = loadConfig2();
10295
10661
  if (!config) return 1;
10296
10662
  const tracker = adapterFor(await resolveProject(config, id));
@@ -10299,10 +10665,19 @@ async function run(args, loadConfig2) {
10299
10665
  console.log(JSON.stringify(await tracker.get(id), null, 2));
10300
10666
  break;
10301
10667
  case "state": {
10302
- const { state, changed } = await tracker.setState(id, rest[0]);
10668
+ const { state, changed } = await tracker.setState(id, rest[0], reason);
10303
10669
  console.log(changed ? `${id} \u2192 ${state}` : `${id} already in '${state}', no change`);
10304
10670
  break;
10305
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;
10306
10681
  case "comment":
10307
10682
  console.log(JSON.stringify(await tracker.comment(id, body)));
10308
10683
  break;
@@ -10322,12 +10697,144 @@ async function run(args, loadConfig2) {
10322
10697
  );
10323
10698
  break;
10324
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
+ }
10325
10705
  }
10326
10706
  return 0;
10327
10707
  }
10328
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
+
10329
10836
  // src/cli/briefing.ts
10330
- 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";
10331
10838
  var MAX_EXCERPT = 200;
10332
10839
  var TAIL_BYTES = 256 * 1024;
10333
10840
  var ERROR_LINE = /\b(error|fatal|panic)\b/i;
@@ -10351,7 +10858,7 @@ function roleLog(ctx) {
10351
10858
  }
10352
10859
  function logExcerpt(file) {
10353
10860
  if (!file) return "no agent log";
10354
- if (!existsSync8(file)) return `agent log ${file} is missing`;
10861
+ if (!existsSync10(file)) return `agent log ${file} is missing`;
10355
10862
  const lines = tail(file).split("\n");
10356
10863
  for (let i = lines.length - 1; i >= 0; i--) {
10357
10864
  const line = lines[i].trim();
@@ -10396,32 +10903,32 @@ function short(text) {
10396
10903
  }
10397
10904
 
10398
10905
  // src/cli/init.ts
10399
- import { copyFileSync, existsSync as existsSync9, mkdirSync as mkdirSync6, readdirSync } from "fs";
10906
+ import { copyFileSync, existsSync as existsSync11, mkdirSync as mkdirSync7, readdirSync } from "fs";
10400
10907
  import { homedir as homedir4 } from "os";
10401
- import { dirname as dirname4, join as join5, relative } from "path";
10402
- var defaultHome = () => join5(homedir4(), ".agent-workflow");
10908
+ import { dirname as dirname4, join as join6, relative } from "path";
10909
+ var defaultHome = () => join6(homedir4(), ".agent-workflow");
10403
10910
  function legacyHome(home) {
10404
- const legacy = join5(homedir4(), ".task-dispatch");
10405
- 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;
10406
10913
  }
10407
10914
  function initRuleSet(templates, home, force) {
10408
10915
  const result = { created: [], overwritten: [], kept: [] };
10409
10916
  for (const file of filesUnder(templates)) {
10410
10917
  const rel = relative(templates, file);
10411
- const target = join5(home, rel);
10412
- const exists = existsSync9(target);
10918
+ const target = join6(home, rel);
10919
+ const exists = existsSync11(target);
10413
10920
  if (exists && !force) {
10414
10921
  result.kept.push(rel);
10415
10922
  continue;
10416
10923
  }
10417
- mkdirSync6(dirname4(target), { recursive: true });
10924
+ mkdirSync7(dirname4(target), { recursive: true });
10418
10925
  copyFileSync(file, target);
10419
10926
  (exists ? result.overwritten : result.created).push(rel);
10420
10927
  }
10421
10928
  return result;
10422
10929
  }
10423
10930
  function filesUnder(dir) {
10424
- 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)] : []);
10425
10932
  }
10426
10933
 
10427
10934
  // src/cli/main.ts
@@ -10429,7 +10936,9 @@ var PACKAGE_DIR = packageRoot(dirname5(fileURLToPath(import.meta.url)));
10429
10936
  var HOME_DIR = expandHome3(process.env.AGENT_WORKFLOW_HOME || "~/.agent-workflow");
10430
10937
  var USAGE = `usage:
10431
10938
  agent-workflow init [--home DIR] [--force]
10432
- agent-workflow dispatch [--dry-run] [--ticket <id>]
10939
+ ${SETUP_USAGE}
10940
+ agent-workflow dispatch [<project>...] [--dry-run]
10941
+ agent-workflow dispatch --ticket <id> [--dry-run]
10433
10942
  agent-workflow status
10434
10943
  agent-workflow deliver [--verdict <v>] [--force] [- | --file <f>]
10435
10944
  agent-workflow resolve <ticket> retry|accept [--verdict <v>]|skip|cancel
@@ -10443,16 +10952,36 @@ async function main(argv) {
10443
10952
  switch (command) {
10444
10953
  case "init":
10445
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
+ }
10446
10970
  case "dispatch": {
10447
- const opts = parseFlags(rest, ["--dry-run"], ["--ticket"]);
10971
+ const projects = [];
10972
+ const opts = parseFlags(rest, ["--dry-run"], ["--ticket"], projects);
10448
10973
  if (typeof opts === "string") return usage2(opts);
10449
10974
  const ticket = opts["--ticket"];
10450
- return await reconcile(paths(), { dryRun: !!opts["--dry-run"], ticket, brief: briefing }) ? 0 : 1;
10975
+ if (ticket && projects.length) return usage2("--ticket finds the project itself; give no project names with it");
10976
+ return await reconcile(paths(), { dryRun: !!opts["--dry-run"], ticket, projects: projects.length ? projects : void 0, brief: briefing }) ? 0 : 1;
10451
10977
  }
10452
- case "status":
10978
+ case "status": {
10453
10979
  if (rest.length) return usage2();
10454
- console.log(JSON.stringify(process.env.AGENT_WORKFLOW_TOKEN ? selfStatus() : statusReport(paths()), null, 2));
10980
+ const config = loadConfig(paths());
10981
+ if (!config) return 1;
10982
+ console.log(JSON.stringify(process.env.AGENT_WORKFLOW_TOKEN ? selfStatus(config) : statusReport(paths(), config), null, 2));
10455
10983
  return 0;
10984
+ }
10456
10985
  case "deliver":
10457
10986
  return deliverCommand(rest);
10458
10987
  case "resolve":
@@ -10504,7 +11033,8 @@ or run init --force to start a fresh home and leave ${legacy} as it is`
10504
11033
  const env = home === defaultHome() ? "" : `AGENT_WORKFLOW_HOME=${home} `;
10505
11034
  console.log(`
10506
11035
  rule set ready in ${home}. Next:
10507
- 1. edit ${join6(home, "config.yaml")}: agents, projects and their workflows
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)
10508
11038
  2. ${env}agent-workflow validate
10509
11039
  3. ${env}agent-workflow dispatch --dry-run`);
10510
11040
  return 0;
@@ -10512,12 +11042,12 @@ rule set ready in ${home}. Next:
10512
11042
  function contractCommand(args) {
10513
11043
  const unknown = args.filter((a) => a !== "--path");
10514
11044
  if (unknown.length) return usage2(`unknown argument '${unknown[0]}'`);
10515
- const file = join6(PACKAGE_DIR, "docs", "contract.md");
11045
+ const file = join7(PACKAGE_DIR, "docs", "contract.md");
10516
11046
  if (args.includes("--path")) console.log(file);
10517
- else process.stdout.write(readFileSync9(file, "utf8"));
11047
+ else process.stdout.write(readFileSync10(file, "utf8"));
10518
11048
  return 0;
10519
11049
  }
10520
- function parseFlags(args, bool, value) {
11050
+ function parseFlags(args, bool, value, positional) {
10521
11051
  const out = {};
10522
11052
  for (let i = 0; i < args.length; i++) {
10523
11053
  const a = args[i];
@@ -10526,26 +11056,27 @@ function parseFlags(args, bool, value) {
10526
11056
  const v = args[++i];
10527
11057
  if (v === void 0 || v.startsWith("--")) return `${a} needs a value`;
10528
11058
  out[a] = v;
10529
- } else return `unknown argument '${a}'`;
11059
+ } else if (positional && !a.startsWith("-")) positional.push(a);
11060
+ else return `unknown argument '${a}'`;
10530
11061
  }
10531
11062
  return out;
10532
11063
  }
10533
- function caller() {
11064
+ function caller(config) {
10534
11065
  const runId = process.env.AGENT_WORKFLOW_RUN;
10535
11066
  const role = process.env.AGENT_WORKFLOW_ROLE;
10536
11067
  const token2 = process.env.AGENT_WORKFLOW_TOKEN;
10537
11068
  if (!runId || !role || !token2) {
10538
11069
  return { code: "TOKEN_REQUIRED", error: "not inside an agent turn: AGENT_WORKFLOW_RUN, AGENT_WORKFLOW_ROLE and AGENT_WORKFLOW_TOKEN must be set" };
10539
11070
  }
10540
- const ledger = loadLedger(paths().ledger);
11071
+ const ledger = openLedger(config);
10541
11072
  const found = Object.entries(ledger.tickets).find(([, c]) => c.run?.id === runId);
10542
11073
  if (!found) return { code: "RUN_NOT_FOUND", error: `run ${runId} is not active` };
10543
11074
  const [id, ctx] = found;
10544
11075
  if (ctx.roles[role]?.token !== token2) return { code: "TOKEN_INVALID", error: "the token does not belong to the current turn of this role" };
10545
11076
  return { id, ctx, role, token: token2 };
10546
11077
  }
10547
- function selfStatus() {
10548
- const c = caller();
11078
+ function selfStatus(config) {
11079
+ const c = caller(config);
10549
11080
  if (c.error !== void 0) return { error: c.code, message: c.error };
10550
11081
  const run2 = c.ctx.run;
10551
11082
  return { ticket: c.id, run: run2.id, workflow: run2.workflow, role: c.role, status: run2.status, cursor: run2.cursor, waiting_on: run2.turn ?? null };
@@ -10553,29 +11084,30 @@ function selfStatus() {
10553
11084
  async function deliverCommand(args) {
10554
11085
  const opts = parseFlags(args, ["--force", "-"], ["--verdict", "--file"]);
10555
11086
  if (typeof opts === "string") return usage2(opts);
10556
- const fail = (code, msg) => {
11087
+ const fail2 = (code, msg) => {
10557
11088
  console.error(`deliver: ${code}: ${msg}`);
10558
11089
  return 1;
10559
11090
  };
10560
- const c = caller();
10561
- if (c.error !== void 0) return fail(c.code, c.error);
10562
11091
  const config = loadConfig(paths());
10563
- if (!config) return fail("CONFIG_INVALID", "config.yaml does not validate");
11092
+ if (!config) return fail2("CONFIG_INVALID", "the configuration does not validate");
11093
+ const c = caller(config);
11094
+ if (c.error !== void 0) return fail2(c.code, c.error);
10564
11095
  const run2 = c.ctx.run;
10565
- const wf = config.projects[c.ctx.project]?.workflows[run2.workflow];
11096
+ const project = config.projects[c.ctx.project];
11097
+ const wf = project?.workflows[run2.workflow];
10566
11098
  const step = wf && locate(wf, run2.cursor).step;
10567
11099
  if (!step || step.verb !== "launch" && step.verb !== "message" || step.role !== c.role || !step.expect || run2.turn !== c.role) {
10568
- 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}`);
10569
11101
  }
10570
- const body = (opts["--file"] ? readFileSync9(String(opts["--file"]), "utf8") : readFileSync9(0, "utf8")).trim();
10571
- 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");
10572
11104
  const verdict = opts["--verdict"];
10573
11105
  const problems = deliveryProblems(step.expect, body, verdict);
10574
11106
  if (problems.length && step.expect.strict && !opts["--force"]) {
10575
11107
  for (const p of problems) console.error(` - ${p}`);
10576
- 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)");
10577
11109
  }
10578
- const path = writeDelivery(paths().stateDir, run2.id, step.expect.delivery, body, {
11110
+ const path = writeDelivery(project.stateDir, run2.id, step.expect.delivery, body, {
10579
11111
  token: c.token,
10580
11112
  verdict,
10581
11113
  provisional: problems.length > 0,
@@ -10591,7 +11123,7 @@ async function deliverCommand(args) {
10591
11123
  console.log(`delivered '${step.expect.delivery}'${verdict ? ` (verdict ${verdict})` : ""} \u2192 ${path}`);
10592
11124
  }
10593
11125
  const logDir = resolve6(paths().stateDir, "logs");
10594
- mkdirSync7(logDir, { recursive: true });
11126
+ mkdirSync8(logDir, { recursive: true });
10595
11127
  const out = openSync3(resolve6(logDir, "deliveries.log"), "a");
10596
11128
  const { AGENT_WORKFLOW_TOKEN, AGENT_WORKFLOW_ROLE, AGENT_WORKFLOW_RUN, SESSION_ID, LOG_FILE, PROMPT_FILE, ...env } = process.env;
10597
11129
  const child = spawn3(resolve6(PACKAGE_DIR, "bin", "agent-workflow"), ["dispatch", "--ticket", c.id], { detached: true, stdio: ["ignore", out, out], env });
@@ -10616,7 +11148,7 @@ async function resolveCommand(args) {
10616
11148
  if (action === "accept" || action === "skip") {
10617
11149
  try {
10618
11150
  if (!wf) throw new Error("no active run of an enabled workflow");
10619
- if (action === "accept") console.log(`accepted delivery '${acceptDelivery(paths().stateDir, ctx, wf, flags["--verdict"])}' of ${id}`);
11151
+ if (action === "accept") console.log(`accepted delivery '${acceptDelivery(config.projects[ctx.project].stateDir, ctx, wf, flags["--verdict"])}' of ${id}`);
10620
11152
  else console.log(`skipped ${skipStep(ctx, wf)} of ${id}`);
10621
11153
  } catch (err) {
10622
11154
  console.error(`${id}: ${err instanceof Error ? err.message : err}`);
@@ -10701,12 +11233,12 @@ function displayPath(file) {
10701
11233
  }
10702
11234
  function packageRoot(from) {
10703
11235
  for (let dir = from; ; dir = dirname5(dir)) {
10704
- if (existsSync10(join6(dir, "package.json"))) return dir;
11236
+ if (existsSync12(join7(dir, "package.json"))) return dir;
10705
11237
  if (dirname5(dir) === dir) throw new Error(`no package.json above ${from}`);
10706
11238
  }
10707
11239
  }
10708
11240
  function expandHome3(p) {
10709
- return p === "~" || p.startsWith("~/") ? join6(homedir5(), p.slice(1)) : p;
11241
+ return p === "~" || p.startsWith("~/") ? join7(homedir5(), p.slice(1)) : p;
10710
11242
  }
10711
11243
  main(process.argv.slice(2)).then(
10712
11244
  (code) => {