@gumpwang/agent-workflow 0.1.0 → 0.2.1

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.
@@ -7663,6 +7663,9 @@ 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;
@@ -7965,7 +7968,7 @@ var WorkflowChecker = class {
7965
7968
  this.unknownKeys(raw, at, [...common, "run", "working-directory", "env"]);
7966
7969
  const run2 = this.string(raw, "run", at, true) ?? "";
7967
7970
  this.template(run2, join(at, "run"), inLoop, true);
7968
- const handler = RULE_SET_PATH.exec(run2)?.[2];
7971
+ const handler = ruleSetPath(run2);
7969
7972
  if (handler && !existsSync(resolve(this.rulesDir, handler))) {
7970
7973
  this.report("error", join(at, "run"), "RUN_NOT_FOUND", `no file ${handler} in the rule set ${this.rulesDir}`);
7971
7974
  }
@@ -8264,57 +8267,79 @@ function resolveWorkflowFile(id, home) {
8264
8267
  }
8265
8268
  function validateHome(home) {
8266
8269
  const file = resolve2(home, "config.yaml");
8270
+ const agentsFile = resolve2(home, "agents.yaml");
8267
8271
  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 };
8272
- }
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 };
8272
+ const report = (level, inFile, at, code, message) => diagnostics.push({ level, file: inFile, at, code, message });
8273
+ const checker = (inFile) => new ConfigChecker((at, msg) => report("error", inFile, at, "CONFIG_INVALID", msg));
8274
+ const mainRaw = readYaml(file, report);
8275
+ if (!mainRaw) return { diagnostics };
8276
+ const main2 = checker(file).main(mainRaw.raw, file);
8277
+ const agentsRaw = readYaml(agentsFile, report);
8278
+ const agents = agentsRaw && checker(agentsFile).agentsFile(agentsRaw.raw, agentsFile);
8279
+ const parsed = [];
8280
+ for (const [i, name] of (main2?.projects ?? []).entries()) {
8281
+ const dir = resolve2(home, "projects", name);
8282
+ const projectFile = join2(dir, "project.yaml");
8283
+ if (!existsSync2(projectFile)) {
8284
+ report("error", file, `projects[${i}]`, "CONFIG_NOT_FOUND", `project '${name}' has no ${projectFile}`);
8285
+ continue;
8286
+ }
8287
+ const raw = readYaml(projectFile, report);
8288
+ const p = raw && checker(projectFile).project(raw.raw, projectFile, name, dir);
8289
+ if (p) parsed.push(p);
8279
8290
  }
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)) {
8291
+ if (!main2 || !agents || diagnostics.length) return { diagnostics };
8292
+ for (const a of Object.values(agents.agents)) {
8283
8293
  for (const [key, cmd] of [["command", a.command], ["resume_command", a.resumeCommand]]) {
8284
8294
  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");
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");
8286
8296
  }
8287
8297
  }
8288
8298
  }
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
- };
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)) {
@@ -9255,9 +9294,9 @@ async function resolveProject(config, identifier) {
9255
9294
  if (slugId === void 0) continue;
9256
9295
  const project = linear.find((p) => linearSlugId(p) === slugId);
9257
9296
  if (project) return project;
9258
- throw new TicketError(`${identifier} belongs to Linear project ${slugId}, which no project in config.yaml tracks`, 4);
9297
+ throw new TicketError(`${identifier} belongs to Linear project ${slugId}, which no registered project tracks`, 4);
9259
9298
  }
9260
- throw new TicketError(`no project in config.yaml has ticket ${identifier}`, 4);
9299
+ throw new TicketError(`no registered project has ticket ${identifier}`, 4);
9261
9300
  }
9262
9301
 
9263
9302
  // src/engine/delivery.ts
@@ -9531,7 +9570,7 @@ function completeDeliveryWaiting(e, t, wf) {
9531
9570
  return false;
9532
9571
  }
9533
9572
  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);
9573
+ const meta = readMeta(t.project.stateDir, run2.id, step.expect.delivery);
9535
9574
  return !!meta && !meta.provisional && meta.token === t.ctx.roles[step.role]?.token;
9536
9575
  }
9537
9576
  function locate(wf, cursor) {
@@ -9610,14 +9649,14 @@ async function turn(e, t, wf, step, scope) {
9610
9649
  if (run2.turn === role && session) {
9611
9650
  const alive = isAgentAlive(session.pid, session.session_id);
9612
9651
  if (expect) {
9613
- const meta = readMeta(e.stateDir, run2.id, expect.delivery);
9652
+ const meta = readMeta(t.project.stateDir, run2.id, expect.delivery);
9614
9653
  if (meta && session.token && meta.token === session.token) {
9615
9654
  if (meta.provisional) {
9616
9655
  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
9656
  run2.attention_kind = "incomplete_delivery";
9618
9657
  return "attention";
9619
9658
  }
9620
- const path = deliveryPath(e.stateDir, run2.id, expect.delivery);
9659
+ const path = deliveryPath(t.project.stateDir, run2.id, expect.delivery);
9621
9660
  t.ctx.deliveries = { ...t.ctx.deliveries, [expect.delivery]: { path, verdict: meta.verdict, run: run2.id, at: meta.at } };
9622
9661
  if (step.id) run2.steps[step.id] = { outcome: meta.verdict ?? "success", outputs: { verdict: meta.verdict ?? null, path } };
9623
9662
  session.turns = 0;
@@ -9695,7 +9734,7 @@ ${completionInstructions(expect, !!run2.nudge)}`;
9695
9734
  prompt += "\n";
9696
9735
  const kind = continues ? "resume" : "enter";
9697
9736
  const sessionId = resume ? session.session_id : randomUUID();
9698
- const log = session?.log ?? resolve4(e.stateDir, "logs", `${t.identifier}.${role}.log`);
9737
+ const log = session?.log ?? resolve4(t.project.stateDir, "logs", `${t.identifier}.${role}.log`);
9699
9738
  const workspace = t.ctx.workspace.path;
9700
9739
  if (e.dryRun) {
9701
9740
  console.log(`--- DRY-RUN ${kind} ${t.identifier} [${wf.id}] role=${role} agent=${profile.name} workspace=${workspace} ---`);
@@ -9704,7 +9743,7 @@ ${completionInstructions(expect, !!run2.nudge)}`;
9704
9743
  return "block";
9705
9744
  }
9706
9745
  const provisioned = await ensureWorkspace(e, t, wf);
9707
- const promptFile = resolve4(e.stateDir, "prompts", `${t.identifier}.${role}${kind === "resume" ? ".resume" : ""}.md`);
9746
+ const promptFile = resolve4(t.project.stateDir, "prompts", `${t.identifier}.${role}${kind === "resume" ? ".resume" : ""}.md`);
9708
9747
  mkdirSync4(dirname3(promptFile), { recursive: true });
9709
9748
  writeFileSync3(promptFile, prompt);
9710
9749
  const token2 = randomUUID();
@@ -9827,7 +9866,7 @@ async function ensureWorkspace(e, t, wf) {
9827
9866
  const ws = t.ctx.workspace;
9828
9867
  const def = t.project.workspace;
9829
9868
  if (!def?.provision || ws.ready && existsSync6(ws.path)) return false;
9830
- const r = await shell(def.provision, t.project.root, baseEnv(e, t, wf));
9869
+ const r = await shell(resolveRunCommand(def.provision, e.home), t.project.root, baseEnv(e, t, wf));
9831
9870
  if (r.code !== 0) throw new Error(`workspace provision failed: ${r.lastErr || `exit ${r.code}`}`);
9832
9871
  ws.ready = true;
9833
9872
  return true;
@@ -9835,7 +9874,7 @@ async function ensureWorkspace(e, t, wf) {
9835
9874
  async function cleanupWorkspace(e, t, wf) {
9836
9875
  const def = t.project.workspace;
9837
9876
  if (!def?.cleanup) return;
9838
- const r = await shell(def.cleanup, t.project.root, baseEnv(e, t, wf));
9877
+ const r = await shell(resolveRunCommand(def.cleanup, e.home), t.project.root, baseEnv(e, t, wf));
9839
9878
  if (r.code !== 0) console.warn(`cleanup hook for ${t.identifier} failed: ${r.lastErr || `exit ${r.code}`}`);
9840
9879
  if (t.ctx.workspace) t.ctx.workspace.ready = false;
9841
9880
  }
@@ -9844,7 +9883,7 @@ function workspaceOf(project, ticket) {
9844
9883
  if (!def) return { path: project.root, ready: true };
9845
9884
  const scope = { ticket: ticketView(ticket), project: projectView(project) };
9846
9885
  return {
9847
- path: expandHome2(String(interpolate(def.path, scope))),
9886
+ path: resolve4(project.dir, expandHome2(String(interpolate(def.path, scope)))),
9848
9887
  branch: def.branch ? String(interpolate(def.branch, scope)) : void 0,
9849
9888
  ready: false
9850
9889
  };
@@ -9989,28 +10028,49 @@ function pathsOf(home, packageDir) {
9989
10028
  home,
9990
10029
  packageDir,
9991
10030
  stateDir,
9992
- ledger: resolve5(stateDir, "ledger.json"),
9993
10031
  lastRun: resolve5(stateDir, "last-run.json"),
9994
10032
  lock: resolve5(stateDir, "dispatch.lock"),
9995
10033
  tickets: resolve5(stateDir, "issues.json")
9996
10034
  };
9997
10035
  }
10036
+ function ledgerFile(project) {
10037
+ return resolve5(project.stateDir, "ledger.json");
10038
+ }
9998
10039
  function loadConfig(paths2) {
9999
10040
  const { config, diagnostics } = validateHome(paths2.home);
10000
10041
  for (const d of diagnostics) console.error(`${d.level}: ${d.file}: ${d.at || "-"}: ${d.code}: ${d.message}`);
10001
10042
  return config;
10002
10043
  }
10003
- function openLedger(paths2) {
10004
- const ledger = loadLedger(paths2.ledger);
10044
+ function openLedger(config) {
10045
+ const ledger = { version: 2, tickets: {} };
10046
+ for (const p of Object.values(config.projects)) {
10047
+ for (const [id, ctx] of Object.entries(loadLedger(ledgerFile(p)).tickets)) {
10048
+ const prev = ledger.tickets[id];
10049
+ if (prev) console.warn(`${id} is in the ledgers of '${prev.project}' and '${p.name}'; using the one of '${prev.project}'`);
10050
+ else ledger.tickets[id] = ctx;
10051
+ }
10052
+ }
10005
10053
  for (const ctx of Object.values(ledger.tickets)) {
10006
10054
  for (const s of Object.values(ctx.roles)) s.status = isAgentAlive(s.pid, s.session_id) ? "running" : "exited";
10007
10055
  }
10008
10056
  return ledger;
10009
10057
  }
10058
+ function saveLedgers(config, ledger) {
10059
+ for (const p of Object.values(config.projects)) {
10060
+ const file = ledgerFile(p);
10061
+ const tickets = Object.fromEntries(Object.entries(ledger.tickets).filter(([, c]) => c.project === p.name));
10062
+ if (Object.keys(tickets).length || existsSync7(file)) saveLedger(file, { version: 2, tickets });
10063
+ }
10064
+ }
10010
10065
  var TICKET_LOCK_WAIT_MS = 15 * 6e4;
10011
10066
  async function reconcile(paths2, opts) {
10012
10067
  const config = loadConfig(paths2);
10013
10068
  if (!config) return false;
10069
+ const unknown = opts.projects?.filter((name) => !config.projects[name]) ?? [];
10070
+ if (unknown.length) {
10071
+ console.error(`no project ${unknown.map((n) => `'${n}'`).join(", ")} in ${config.file}; registered: ${Object.keys(config.projects).join(", ")}`);
10072
+ return false;
10073
+ }
10014
10074
  mkdirSync5(paths2.stateDir, { recursive: true });
10015
10075
  if (!opts.dryRun && !(opts.ticket ? await acquireLockWaiting(paths2.lock, TICKET_LOCK_WAIT_MS) : acquireLock(paths2.lock))) return true;
10016
10076
  try {
@@ -10024,8 +10084,8 @@ async function reconcile(paths2, opts) {
10024
10084
  async function reconcileLocked(paths2, config, opts) {
10025
10085
  const { dryRun } = opts;
10026
10086
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
10027
- const ledger = openLedger(paths2);
10028
- const projects = Object.values(config.projects);
10087
+ const ledger = openLedger(config);
10088
+ const projects = Object.values(config.projects).filter((p) => !opts.projects || opts.projects.includes(p.name));
10029
10089
  const tracked = /* @__PURE__ */ new Map();
10030
10090
  for (const [id, ctx] of Object.entries(ledger.tickets)) tracked.set(ctx.project, [...tracked.get(ctx.project) ?? [], id]);
10031
10091
  const fetched = await fetchTickets(projects, tracked);
@@ -10068,7 +10128,7 @@ async function reconcileLocked(paths2, config, opts) {
10068
10128
  console.log(`dry_run=true tracked=${Object.keys(ledger.tickets).length} running=${engine.slots.used}`);
10069
10129
  return;
10070
10130
  }
10071
- saveLedger(paths2.ledger, ledger);
10131
+ saveLedgers(config, ledger);
10072
10132
  const count = (a) => actions.filter((x) => x.action === a).length;
10073
10133
  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
10134
  writeFileSync4(paths2.lastRun, JSON.stringify({ started_at: startedAt, finished_at: (/* @__PURE__ */ new Date()).toISOString(), summary, actions }, null, 2) + "\n");
@@ -10079,7 +10139,6 @@ function engineFor(paths2, config, ledger, opts, actions) {
10079
10139
  return {
10080
10140
  home: paths2.home,
10081
10141
  packageDir: paths2.packageDir,
10082
- stateDir: paths2.stateDir,
10083
10142
  config,
10084
10143
  dryRun,
10085
10144
  slots: {
@@ -10092,13 +10151,13 @@ function engineFor(paths2, config, ledger, opts, actions) {
10092
10151
  for (const line of opts.brief?.(a, ledger.tickets[a.ticket]) ?? []) console.log(line);
10093
10152
  },
10094
10153
  persist() {
10095
- if (!dryRun) saveLedger(paths2.ledger, ledger);
10154
+ if (!dryRun) saveLedgers(config, ledger);
10096
10155
  }
10097
10156
  };
10098
10157
  }
10099
10158
  async function advanceOne(paths2, config, identifier, opts) {
10100
10159
  const { dryRun } = opts;
10101
- const ledger = openLedger(paths2);
10160
+ const ledger = openLedger(config);
10102
10161
  const ctx = ledger.tickets[identifier];
10103
10162
  const project = ctx && config.projects[ctx.project];
10104
10163
  if (!ctx || !project || !isActive(ctx)) return;
@@ -10116,7 +10175,7 @@ async function advanceOne(paths2, config, identifier, opts) {
10116
10175
  ctx.ticket = ticket;
10117
10176
  const work = { identifier, ctx, project, ticket, trackerEnv: tracker.env(ticket), offTrigger };
10118
10177
  await advanceActive(engine, ledger, work);
10119
- if (!dryRun) saveLedger(paths2.ledger, ledger);
10178
+ if (!dryRun) saveLedgers(config, ledger);
10120
10179
  }
10121
10180
  function desiredWorkflow(project, ticket) {
10122
10181
  const state = ticket.state.toLowerCase();
@@ -10219,20 +10278,17 @@ function withLedger(paths2, fn) {
10219
10278
  if (!acquireLock(paths2.lock)) return Promise.resolve(false);
10220
10279
  return (async () => {
10221
10280
  try {
10222
- const ledger = openLedger(paths2);
10281
+ const ledger = openLedger(config);
10223
10282
  await fn(ledger, config);
10224
- saveLedger(paths2.ledger, ledger);
10283
+ saveLedgers(config, ledger);
10225
10284
  return true;
10226
10285
  } finally {
10227
10286
  releaseLock(paths2.lock);
10228
10287
  }
10229
10288
  })();
10230
10289
  }
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
- }
10290
+ function statusReport(paths2, config) {
10291
+ const ledger = openLedger(config);
10236
10292
  const lastRun = existsSync7(paths2.lastRun) ? JSON.parse(readFileSync7(paths2.lastRun, "utf8")) : null;
10237
10293
  return { home: paths2.home, tickets: ledger.tickets, last_run: lastRun };
10238
10294
  }
@@ -10429,7 +10485,8 @@ var PACKAGE_DIR = packageRoot(dirname5(fileURLToPath(import.meta.url)));
10429
10485
  var HOME_DIR = expandHome3(process.env.AGENT_WORKFLOW_HOME || "~/.agent-workflow");
10430
10486
  var USAGE = `usage:
10431
10487
  agent-workflow init [--home DIR] [--force]
10432
- agent-workflow dispatch [--dry-run] [--ticket <id>]
10488
+ agent-workflow dispatch [<project>...] [--dry-run]
10489
+ agent-workflow dispatch --ticket <id> [--dry-run]
10433
10490
  agent-workflow status
10434
10491
  agent-workflow deliver [--verdict <v>] [--force] [- | --file <f>]
10435
10492
  agent-workflow resolve <ticket> retry|accept [--verdict <v>]|skip|cancel
@@ -10444,15 +10501,20 @@ async function main(argv) {
10444
10501
  case "init":
10445
10502
  return initCommand(rest);
10446
10503
  case "dispatch": {
10447
- const opts = parseFlags(rest, ["--dry-run"], ["--ticket"]);
10504
+ const projects = [];
10505
+ const opts = parseFlags(rest, ["--dry-run"], ["--ticket"], projects);
10448
10506
  if (typeof opts === "string") return usage2(opts);
10449
10507
  const ticket = opts["--ticket"];
10450
- return await reconcile(paths(), { dryRun: !!opts["--dry-run"], ticket, brief: briefing }) ? 0 : 1;
10508
+ if (ticket && projects.length) return usage2("--ticket finds the project itself; give no project names with it");
10509
+ return await reconcile(paths(), { dryRun: !!opts["--dry-run"], ticket, projects: projects.length ? projects : void 0, brief: briefing }) ? 0 : 1;
10451
10510
  }
10452
- case "status":
10511
+ case "status": {
10453
10512
  if (rest.length) return usage2();
10454
- console.log(JSON.stringify(process.env.AGENT_WORKFLOW_TOKEN ? selfStatus() : statusReport(paths()), null, 2));
10513
+ const config = loadConfig(paths());
10514
+ if (!config) return 1;
10515
+ console.log(JSON.stringify(process.env.AGENT_WORKFLOW_TOKEN ? selfStatus(config) : statusReport(paths(), config), null, 2));
10455
10516
  return 0;
10517
+ }
10456
10518
  case "deliver":
10457
10519
  return deliverCommand(rest);
10458
10520
  case "resolve":
@@ -10504,7 +10566,8 @@ or run init --force to start a fresh home and leave ${legacy} as it is`
10504
10566
  const env = home === defaultHome() ? "" : `AGENT_WORKFLOW_HOME=${home} `;
10505
10567
  console.log(`
10506
10568
  rule set ready in ${home}. Next:
10507
- 1. edit ${join6(home, "config.yaml")}: agents, projects and their workflows
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)
10508
10571
  2. ${env}agent-workflow validate
10509
10572
  3. ${env}agent-workflow dispatch --dry-run`);
10510
10573
  return 0;
@@ -10517,7 +10580,7 @@ function contractCommand(args) {
10517
10580
  else process.stdout.write(readFileSync9(file, "utf8"));
10518
10581
  return 0;
10519
10582
  }
10520
- function parseFlags(args, bool, value) {
10583
+ function parseFlags(args, bool, value, positional) {
10521
10584
  const out = {};
10522
10585
  for (let i = 0; i < args.length; i++) {
10523
10586
  const a = args[i];
@@ -10526,26 +10589,27 @@ function parseFlags(args, bool, value) {
10526
10589
  const v = args[++i];
10527
10590
  if (v === void 0 || v.startsWith("--")) return `${a} needs a value`;
10528
10591
  out[a] = v;
10529
- } else return `unknown argument '${a}'`;
10592
+ } else if (positional && !a.startsWith("-")) positional.push(a);
10593
+ else return `unknown argument '${a}'`;
10530
10594
  }
10531
10595
  return out;
10532
10596
  }
10533
- function caller() {
10597
+ function caller(config) {
10534
10598
  const runId = process.env.AGENT_WORKFLOW_RUN;
10535
10599
  const role = process.env.AGENT_WORKFLOW_ROLE;
10536
10600
  const token2 = process.env.AGENT_WORKFLOW_TOKEN;
10537
10601
  if (!runId || !role || !token2) {
10538
10602
  return { code: "TOKEN_REQUIRED", error: "not inside an agent turn: AGENT_WORKFLOW_RUN, AGENT_WORKFLOW_ROLE and AGENT_WORKFLOW_TOKEN must be set" };
10539
10603
  }
10540
- const ledger = loadLedger(paths().ledger);
10604
+ const ledger = openLedger(config);
10541
10605
  const found = Object.entries(ledger.tickets).find(([, c]) => c.run?.id === runId);
10542
10606
  if (!found) return { code: "RUN_NOT_FOUND", error: `run ${runId} is not active` };
10543
10607
  const [id, ctx] = found;
10544
10608
  if (ctx.roles[role]?.token !== token2) return { code: "TOKEN_INVALID", error: "the token does not belong to the current turn of this role" };
10545
10609
  return { id, ctx, role, token: token2 };
10546
10610
  }
10547
- function selfStatus() {
10548
- const c = caller();
10611
+ function selfStatus(config) {
10612
+ const c = caller(config);
10549
10613
  if (c.error !== void 0) return { error: c.code, message: c.error };
10550
10614
  const run2 = c.ctx.run;
10551
10615
  return { ticket: c.id, run: run2.id, workflow: run2.workflow, role: c.role, status: run2.status, cursor: run2.cursor, waiting_on: run2.turn ?? null };
@@ -10557,12 +10621,13 @@ async function deliverCommand(args) {
10557
10621
  console.error(`deliver: ${code}: ${msg}`);
10558
10622
  return 1;
10559
10623
  };
10560
- const c = caller();
10561
- if (c.error !== void 0) return fail(c.code, c.error);
10562
10624
  const config = loadConfig(paths());
10563
- if (!config) return fail("CONFIG_INVALID", "config.yaml does not validate");
10625
+ if (!config) return fail("CONFIG_INVALID", "the configuration does not validate");
10626
+ const c = caller(config);
10627
+ if (c.error !== void 0) return fail(c.code, c.error);
10564
10628
  const run2 = c.ctx.run;
10565
- const wf = config.projects[c.ctx.project]?.workflows[run2.workflow];
10629
+ const project = config.projects[c.ctx.project];
10630
+ const wf = project?.workflows[run2.workflow];
10566
10631
  const step = wf && locate(wf, run2.cursor).step;
10567
10632
  if (!step || step.verb !== "launch" && step.verb !== "message" || step.role !== c.role || !step.expect || run2.turn !== c.role) {
10568
10633
  return fail("STEP_NOT_EXPECTING", `run ${run2.id} is not waiting for a delivery from ${c.role}`);
@@ -10575,7 +10640,7 @@ async function deliverCommand(args) {
10575
10640
  for (const p of problems) console.error(` - ${p}`);
10576
10641
  return fail("DELIVERY_INCOMPLETE", "fix the body and deliver again (this step is strict)");
10577
10642
  }
10578
- const path = writeDelivery(paths().stateDir, run2.id, step.expect.delivery, body, {
10643
+ const path = writeDelivery(project.stateDir, run2.id, step.expect.delivery, body, {
10579
10644
  token: c.token,
10580
10645
  verdict,
10581
10646
  provisional: problems.length > 0,
@@ -10616,7 +10681,7 @@ async function resolveCommand(args) {
10616
10681
  if (action === "accept" || action === "skip") {
10617
10682
  try {
10618
10683
  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}`);
10684
+ if (action === "accept") console.log(`accepted delivery '${acceptDelivery(config.projects[ctx.project].stateDir, ctx, wf, flags["--verdict"])}' of ${id}`);
10620
10685
  else console.log(`skipped ${skipStep(ctx, wf)} of ${id}`);
10621
10686
  } catch (err) {
10622
10687
  console.error(`${id}: ${err instanceof Error ? err.message : err}`);