@hasna/loops 0.4.5 → 0.4.6

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.
package/dist/sdk/index.js CHANGED
@@ -1491,11 +1491,14 @@ function ensurePrivateStorePath(file) {
1491
1491
  class Store {
1492
1492
  db;
1493
1493
  rootDir;
1494
+ memoryRootDir;
1494
1495
  constructor(path) {
1495
1496
  const file = path ?? dbPath();
1496
1497
  if (file !== ":memory:")
1497
1498
  ensurePrivateStorePath(file);
1498
1499
  this.rootDir = file === ":memory:" ? mkdtempSync(join3(tmpdir(), "open-loops-store-")) : dirname2(file);
1500
+ if (file === ":memory:")
1501
+ this.memoryRootDir = this.rootDir;
1499
1502
  this.db = new Database(file);
1500
1503
  this.db.exec("PRAGMA foreign_keys = ON;");
1501
1504
  this.db.exec("PRAGMA busy_timeout = 5000;");
@@ -1948,9 +1951,12 @@ class Store {
1948
1951
  const rows = this.db.query("SELECT * FROM loops WHERE name = ? ORDER BY created_at DESC LIMIT 2").all(idOrName);
1949
1952
  if (rows.length === 0)
1950
1953
  throw new LoopNotFoundError(idOrName);
1951
- if (rows.length > 1)
1954
+ if (rows.length === 1)
1955
+ return rowToLoop(rows[0]);
1956
+ const active = this.db.query("SELECT * FROM loops WHERE name = ? AND archived_at IS NULL ORDER BY created_at DESC LIMIT 2").all(idOrName);
1957
+ if (active.length !== 1)
1952
1958
  throw new AmbiguousNameError(idOrName);
1953
- return rowToLoop(rows[0]);
1959
+ return rowToLoop(active[0]);
1954
1960
  }
1955
1961
  requireLoop(idOrName) {
1956
1962
  return this.getLoop(idOrName) ?? this.findLoopByName(idOrName) ?? (() => {
@@ -2291,6 +2297,7 @@ class Store {
2291
2297
  return this.transact(() => {
2292
2298
  const loop = this.requireLoop(idOrName);
2293
2299
  this.setWorkflowWorkItemsForLoop(loop.id, "cancelled", "loop deleted", nowIso());
2300
+ this.db.query("DELETE FROM loop_runs WHERE loop_id = ?").run(loop.id);
2294
2301
  const res = this.db.query("DELETE FROM loops WHERE id = ?").run(loop.id);
2295
2302
  return res.changes > 0;
2296
2303
  });
@@ -2775,7 +2782,10 @@ class Store {
2775
2782
  return rowToGoal(row);
2776
2783
  }
2777
2784
  if (context.sourceType && context.sourceId) {
2778
- const row = this.db.query("SELECT * FROM goals WHERE source_type = ? AND source_id = ? ORDER BY created_at DESC LIMIT 1").get(context.sourceType, context.sourceId);
2785
+ const terminalPlaceholders = GOAL_TERMINAL.map(() => "?").join(", ");
2786
+ const row = this.db.query(`SELECT * FROM goals
2787
+ WHERE source_type = ? AND source_id = ? AND status NOT IN (${terminalPlaceholders})
2788
+ ORDER BY created_at DESC LIMIT 1`).get(context.sourceType, context.sourceId, ...GOAL_TERMINAL);
2779
2789
  if (row)
2780
2790
  return rowToGoal(row);
2781
2791
  }
@@ -3195,6 +3205,41 @@ class Store {
3195
3205
  throw new Error(`workflow step run not found after pid update: ${workflowRunId}/${stepId}`);
3196
3206
  return run;
3197
3207
  }
3208
+ recordWorkflowStepProgress(workflowRunId, stepId, progress, opts = {}) {
3209
+ const now = (opts.now ?? new Date).toISOString();
3210
+ this.db.exec("BEGIN IMMEDIATE");
3211
+ try {
3212
+ const res = this.db.query(`UPDATE workflow_step_runs
3213
+ SET stdout=COALESCE($stdout, stdout),
3214
+ stderr=COALESCE($stderr, stderr),
3215
+ updated_at=$updated
3216
+ WHERE workflow_run_id=$workflowRunId AND step_id=$stepId AND status='running'
3217
+ AND ($daemonLeaseId IS NULL OR EXISTS (
3218
+ SELECT 1 FROM daemon_lease WHERE id=$daemonLeaseId AND expires_at > $now
3219
+ ))`).run({
3220
+ $workflowRunId: workflowRunId,
3221
+ $stepId: stepId,
3222
+ $stdout: progress.stdout === undefined ? null : scrubbedOrNull(progress.stdout),
3223
+ $stderr: progress.stderr === undefined ? null : scrubbedOrNull(progress.stderr),
3224
+ $updated: now,
3225
+ $daemonLeaseId: opts.daemonLeaseId ?? null,
3226
+ $now: now
3227
+ });
3228
+ if (res.changes === 1) {
3229
+ this.appendWorkflowEvent(workflowRunId, "step_progress", stepId, progress.payload);
3230
+ }
3231
+ this.db.exec("COMMIT");
3232
+ } catch (error) {
3233
+ try {
3234
+ this.db.exec("ROLLBACK");
3235
+ } catch {}
3236
+ throw error;
3237
+ }
3238
+ const run = this.getWorkflowStepRun(workflowRunId, stepId);
3239
+ if (!run)
3240
+ throw new Error(`workflow step run not found after progress update: ${workflowRunId}/${stepId}`);
3241
+ return run;
3242
+ }
3198
3243
  recoverWorkflowRun(workflowRunId, reason = "workflow run recovered for retry") {
3199
3244
  return this.transact(() => {
3200
3245
  const now = nowIso();
@@ -3632,7 +3677,8 @@ class Store {
3632
3677
  AND ($daemonLeaseId IS NULL OR EXISTS (
3633
3678
  SELECT 1 FROM daemon_lease WHERE id=$daemonLeaseId AND expires_at > $now
3634
3679
  ))`).run(params) : this.db.query(`UPDATE loop_runs SET status=$status, finished_at=$finished, claim_token=NULL, lease_expires_at=NULL, pid=$pid, exit_code=$exitCode,
3635
- duration_ms=$durationMs, stdout=$stdout, stderr=$stderr, error=$error, updated_at=$updated WHERE id=$id`).run(params);
3680
+ duration_ms=$durationMs, stdout=$stdout, stderr=$stderr, error=$error, updated_at=$updated
3681
+ WHERE id=$id AND status='running'`).run(params);
3636
3682
  const run = this.getRun(id);
3637
3683
  if (!run)
3638
3684
  throw new Error(`run not found after finalize: ${id}`);
@@ -4160,12 +4206,18 @@ class Store {
4160
4206
  }
4161
4207
  close() {
4162
4208
  this.db.close();
4209
+ if (this.memoryRootDir) {
4210
+ try {
4211
+ rmSync2(this.memoryRootDir, { recursive: true, force: true });
4212
+ } catch {}
4213
+ this.memoryRootDir = undefined;
4214
+ }
4163
4215
  }
4164
4216
  }
4165
4217
  // package.json
4166
4218
  var package_default = {
4167
4219
  name: "@hasna/loops",
4168
- version: "0.4.5",
4220
+ version: "0.4.6",
4169
4221
  description: "Persistent local loop and workflow runner for deterministic commands and headless AI coding agents",
4170
4222
  type: "module",
4171
4223
  main: "dist/index.js",
@@ -4623,10 +4675,7 @@ async function stopDaemon(opts = {}) {
4623
4675
  const store = new Store(join4(dirname3(path), "loops.db"));
4624
4676
  try {
4625
4677
  const lease = store.getDaemonLease();
4626
- if (!lease || lease.pid !== state.pid || new Date(lease.expiresAt).getTime() <= Date.now()) {
4627
- removePid(path);
4628
- return { wasRunning: false, stopped: false, forced: false, pid: state.pid };
4629
- }
4678
+ const leaseVerified = Boolean(lease && lease.pid === state.pid && new Date(lease.expiresAt).getTime() > Date.now());
4630
4679
  try {
4631
4680
  process.kill(state.pid, "SIGTERM");
4632
4681
  } catch {
@@ -4646,11 +4695,14 @@ async function stopDaemon(opts = {}) {
4646
4695
  } catch {}
4647
4696
  await sleep(150);
4648
4697
  removePid(path);
4649
- const ownedRuns = store.listRuns({ status: "running", limit: 1000 }).filter((run) => run.claimedBy !== undefined && run.claimedBy.endsWith(`:${lease.id}`));
4650
- const reapedPgids = await reapProcessGroups(ownedRuns.map(toReapableProcess), {
4651
- sleep,
4652
- graceMs: opts.reapGraceMs
4653
- });
4698
+ let reapedPgids = [];
4699
+ if (leaseVerified && lease) {
4700
+ const ownedRuns = store.listRuns({ status: "running", limit: 1000 }).filter((run) => run.claimedBy !== undefined && run.claimedBy.endsWith(`:${lease.id}`));
4701
+ reapedPgids = await reapProcessGroups(ownedRuns.map(toReapableProcess), {
4702
+ sleep,
4703
+ graceMs: opts.reapGraceMs
4704
+ });
4705
+ }
4654
4706
  return { wasRunning: true, stopped: !isAlive(state.pid, record?.startedAt), forced: true, pid: state.pid, reapedPgids };
4655
4707
  } finally {
4656
4708
  store.close();
@@ -4984,7 +5036,12 @@ function notifySpawn(pid, opts) {
4984
5036
  if (!pid)
4985
5037
  return;
4986
5038
  opts.onSpawn?.(pid);
4987
- opts.onSpawnProcess?.({ pid, pgid: pid, processStartedAt: nowIso() });
5039
+ const startedMs = processStartTimeMs(pid);
5040
+ opts.onSpawnProcess?.({
5041
+ pid,
5042
+ pgid: pid,
5043
+ processStartedAt: startedMs !== undefined ? new Date(startedMs).toISOString() : nowIso()
5044
+ });
4988
5045
  }
4989
5046
  function shellQuote(value) {
4990
5047
  return `'${value.replace(/'/g, `'\\''`)}'`;
@@ -5339,6 +5396,13 @@ function numberField(value, key) {
5339
5396
  function codewithAgentStatus(readJson) {
5340
5397
  return stringField(recordField(readJson, "agent"), "status") ?? stringField(recordField(readJson, "statusSnapshot"), "status");
5341
5398
  }
5399
+ function codewithAgentLastEventSeq(readJson) {
5400
+ const agentSeq = numberField(recordField(readJson, "agent"), "lastEventSeq");
5401
+ const snapshotSeq = numberField(recordField(readJson, "statusSnapshot"), "lastEventSeq");
5402
+ if (agentSeq !== undefined && snapshotSeq !== undefined)
5403
+ return Math.max(agentSeq, snapshotSeq);
5404
+ return agentSeq ?? snapshotSeq;
5405
+ }
5342
5406
  function codewithAgentEvidence(startJson, readJson, logsJson) {
5343
5407
  const agent = recordField(readJson, "agent") ?? recordField(startJson, "agent");
5344
5408
  const statusSnapshot = recordField(readJson, "statusSnapshot");
@@ -5369,6 +5433,21 @@ function codewithAgentEvidence(startJson, readJson, logsJson) {
5369
5433
  events
5370
5434
  }, null, 2);
5371
5435
  }
5436
+ function codewithAgentProgress(readJson) {
5437
+ const agent = recordField(readJson, "agent");
5438
+ const statusSnapshot = recordField(readJson, "statusSnapshot");
5439
+ return {
5440
+ provider: "codewith",
5441
+ agentId: stringField(agent, "agentId"),
5442
+ status: stringField(agent, "status") ?? stringField(statusSnapshot, "status"),
5443
+ summary: stringField(statusSnapshot, "summary"),
5444
+ statusReason: stringField(agent, "statusReason"),
5445
+ threadId: stringField(agent, "threadId"),
5446
+ rolloutPath: stringField(agent, "rolloutPath"),
5447
+ pid: numberField(agent, "pid"),
5448
+ lastEventSeq: codewithAgentLastEventSeq(readJson)
5449
+ };
5450
+ }
5372
5451
  function sleep(ms) {
5373
5452
  return new Promise((resolve3) => setTimeout(resolve3, ms));
5374
5453
  }
@@ -5403,6 +5482,7 @@ async function executeCodewithDurableAgent(spec, metadata, opts, env, startedAt)
5403
5482
  if (!agentId) {
5404
5483
  return failureResult(startedAt, "codewith agent start did not return agent.agentId", { stdout: start.stdout, stderr: stderr.value() });
5405
5484
  }
5485
+ opts.onAgentProgress?.(codewithAgentProgress(startJson));
5406
5486
  const stopAgent = async () => {
5407
5487
  await spawnCapture(spec.command, codewithAgentControlArgs(target, "stop", agentId), {
5408
5488
  cwd: spec.cwd,
@@ -5445,10 +5525,15 @@ async function executeCodewithDurableAgent(spec, metadata, opts, env, startedAt)
5445
5525
  });
5446
5526
  }
5447
5527
  const status = codewithAgentStatus(lastReadJson);
5448
- const fingerprint = JSON.stringify({ status, snapshot: recordField(lastReadJson, "statusSnapshot") ?? null });
5528
+ const fingerprint = JSON.stringify({
5529
+ status,
5530
+ agentLastEventSeq: numberField(recordField(lastReadJson, "agent"), "lastEventSeq"),
5531
+ snapshot: recordField(lastReadJson, "statusSnapshot") ?? null
5532
+ });
5449
5533
  if (fingerprint !== lastFingerprint) {
5450
5534
  lastFingerprint = fingerprint;
5451
5535
  lastProgressAt = Date.now();
5536
+ opts.onAgentProgress?.(codewithAgentProgress(lastReadJson));
5452
5537
  }
5453
5538
  if (status === "completed" || status === "failed" || status === "cancelled") {
5454
5539
  const logs = await spawnCapture(spec.command, codewithAgentControlArgs(target, "logs", agentId), {
@@ -6376,7 +6461,7 @@ ${failure.evidence.stderr}` : undefined
6376
6461
 
6377
6462
  `);
6378
6463
  const dedupeKey = `openloops:${loop.id}:${failure.fingerprint}`;
6379
- const tags = ["bug", "openloops", "loop-health", failure.classification];
6464
+ const tags = ["bug", "openloops", "loops", "loop-health", failure.classification];
6380
6465
  const priority = failure.classification === "auth" || failure.classification === "rate_limit" ? "high" : "medium";
6381
6466
  return {
6382
6467
  title,
@@ -6391,7 +6476,7 @@ ${failure.evidence.stderr}` : undefined
6391
6476
  comment: ["todos", "comment", "<task-id>", description]
6392
6477
  },
6393
6478
  futureNativeUpsert: {
6394
- command: "todos upsert",
6479
+ command: "todos task upsert",
6395
6480
  fields: {
6396
6481
  title,
6397
6482
  description,
@@ -7595,173 +7680,213 @@ async function executeWorkflow(store, workflow, opts = {}) {
7595
7680
  if (run.status === "succeeded" || run.status === "failed" || run.status === "timed_out" || run.status === "cancelled") {
7596
7681
  return workflowResult(run, run.status, startedAt, run.finishedAt ?? nowIso(), store.listWorkflowStepRuns(run.id), run.error);
7597
7682
  }
7683
+ const resumedRunningSteps = store.listWorkflowStepRuns(run.id).filter((step) => step.status === "running");
7684
+ if (resumedRunningSteps.length > 0 && resumedRunningSteps.every((step) => step.pid !== undefined)) {
7685
+ try {
7686
+ store.recoverWorkflowRun(run.id, "workflow run resumed after lease takeover");
7687
+ } catch {}
7688
+ }
7598
7689
  const ordered = workflowExecutionOrder(workflow);
7599
7690
  const byId = new Map(workflow.steps.map((step) => [step.id, step]));
7600
7691
  let blockingError;
7601
7692
  let terminalStatus = "succeeded";
7602
- for (const step of ordered) {
7603
- if (store.isWorkflowRunTerminal(run.id)) {
7604
- terminalStatus = store.requireWorkflowRun(run.id).status;
7605
- blockingError = "workflow run was cancelled";
7606
- break;
7607
- }
7608
- const pendingTimeout = opts.signal?.aborted ? opts.signalTimeoutMessage?.() : undefined;
7609
- if (pendingTimeout) {
7610
- terminalStatus = "timed_out";
7611
- blockingError = pendingTimeout;
7612
- break;
7613
- }
7614
- const existing = store.getWorkflowStepRun(run.id, step.id);
7615
- if (existing?.status === "succeeded" || existing?.status === "skipped" || existing?.status === "cancelled")
7616
- continue;
7617
- const blockedBy = (step.dependsOn ?? []).find((dependencyId) => {
7618
- const dependencyRun = store.getWorkflowStepRun(run.id, dependencyId);
7619
- const dependencyStep = byId.get(dependencyId);
7620
- if (dependencyRun?.status === "succeeded")
7621
- return false;
7622
- return !dependencyStep?.continueOnFailure;
7623
- });
7624
- if (blockedBy) {
7625
- opts.beforePersist?.();
7626
- if (isBlockedStepRun(store.getWorkflowStepRun(run.id, blockedBy))) {
7627
- store.skipWorkflowStepRun(run.id, step.id, `${BLOCKED_STEP_ERROR_PREFIX} upstream step ${blockedBy} was blocked`, {
7628
- daemonLeaseId: opts.daemonLeaseId
7629
- });
7693
+ try {
7694
+ for (const step of ordered) {
7695
+ if (store.isWorkflowRunTerminal(run.id)) {
7696
+ terminalStatus = store.requireWorkflowRun(run.id).status;
7697
+ blockingError = "workflow run was cancelled";
7698
+ break;
7699
+ }
7700
+ const pendingTimeout = opts.signal?.aborted ? opts.signalTimeoutMessage?.() : undefined;
7701
+ if (pendingTimeout) {
7702
+ terminalStatus = "timed_out";
7703
+ blockingError = pendingTimeout;
7704
+ break;
7705
+ }
7706
+ const existing = store.getWorkflowStepRun(run.id, step.id);
7707
+ if (existing?.status === "succeeded" || existing?.status === "skipped" || existing?.status === "cancelled")
7708
+ continue;
7709
+ const blockedBy = (step.dependsOn ?? []).find((dependencyId) => {
7710
+ const dependencyRun = store.getWorkflowStepRun(run.id, dependencyId);
7711
+ const dependencyStep = byId.get(dependencyId);
7712
+ if (dependencyRun?.status === "succeeded")
7713
+ return false;
7714
+ return !dependencyStep?.continueOnFailure;
7715
+ });
7716
+ if (blockedBy) {
7717
+ opts.beforePersist?.();
7718
+ if (isBlockedStepRun(store.getWorkflowStepRun(run.id, blockedBy))) {
7719
+ store.skipWorkflowStepRun(run.id, step.id, `${BLOCKED_STEP_ERROR_PREFIX} upstream step ${blockedBy} was blocked`, {
7720
+ daemonLeaseId: opts.daemonLeaseId
7721
+ });
7722
+ continue;
7723
+ }
7724
+ store.skipWorkflowStepRun(run.id, step.id, `dependency did not succeed: ${blockedBy}`, { daemonLeaseId: opts.daemonLeaseId });
7725
+ blockingError ??= `step ${step.id} blocked by dependency ${blockedBy}`;
7726
+ terminalStatus = "failed";
7630
7727
  continue;
7631
7728
  }
7632
- store.skipWorkflowStepRun(run.id, step.id, `dependency did not succeed: ${blockedBy}`, { daemonLeaseId: opts.daemonLeaseId });
7633
- blockingError ??= `step ${step.id} blocked by dependency ${blockedBy}`;
7634
- terminalStatus = "failed";
7635
- continue;
7636
- }
7637
- opts.beforePersist?.();
7638
- const startedStep = store.startWorkflowStepRun(run.id, step.id, { daemonLeaseId: opts.daemonLeaseId });
7639
- if (startedStep.status !== "running") {
7640
- terminalStatus = "failed";
7641
- blockingError = `step ${step.id} could not start because workflow is no longer running`;
7642
- break;
7643
- }
7644
- const stepContext = goalExecutionContext({
7645
- loop: opts.loop,
7646
- loopRun: opts.loopRun,
7647
- scheduledFor: opts.scheduledFor,
7648
- workflow,
7649
- workflowRunId: run.id,
7650
- workflowStepId: step.id
7651
- });
7652
- let result;
7653
- const controller = new AbortController;
7654
- const externalAbort = () => controller.abort();
7655
- if (opts.signal?.aborted)
7656
- controller.abort();
7657
- opts.signal?.addEventListener("abort", externalAbort, { once: true });
7658
- const cancelTimer = setInterval(() => {
7659
- if (store.getWorkflowRun(run.id)?.status === "cancelled")
7729
+ opts.beforePersist?.();
7730
+ const startedStep = store.startWorkflowStepRun(run.id, step.id, { daemonLeaseId: opts.daemonLeaseId });
7731
+ if (startedStep.status !== "running") {
7732
+ terminalStatus = "failed";
7733
+ blockingError = `step ${step.id} could not start because workflow is no longer running`;
7734
+ break;
7735
+ }
7736
+ const stepContext = goalExecutionContext({
7737
+ loop: opts.loop,
7738
+ loopRun: opts.loopRun,
7739
+ scheduledFor: opts.scheduledFor,
7740
+ workflow,
7741
+ workflowRunId: run.id,
7742
+ workflowStepId: step.id
7743
+ });
7744
+ let result;
7745
+ const controller = new AbortController;
7746
+ const externalAbort = () => controller.abort();
7747
+ if (opts.signal?.aborted)
7660
7748
  controller.abort();
7661
- }, opts.cancelPollMs ?? 500);
7662
- cancelTimer.unref();
7663
- try {
7664
- if (step.goal) {
7665
- result = await runGoal(store, step.goal, {
7666
- ...opts,
7667
- model: opts.goalModel,
7668
- target: targetWithStepAccount(step),
7669
- signal: controller.signal,
7670
- context: stepContext
7671
- });
7672
- } else {
7673
- result = await executeTarget(targetWithStepAccount(step, opts.goalNodePrompt), executionMetadata(stepContext), {
7674
- ...opts,
7675
- machine: opts.machine ?? opts.loop?.machine,
7676
- signal: controller.signal,
7677
- onSpawn: (pid) => {
7678
- opts.beforePersist?.();
7679
- store.markWorkflowStepPid(run.id, step.id, pid, { daemonLeaseId: opts.daemonLeaseId });
7680
- opts.onSpawn?.(pid);
7681
- }
7749
+ opts.signal?.addEventListener("abort", externalAbort, { once: true });
7750
+ const cancelTimer = setInterval(() => {
7751
+ if (store.getWorkflowRun(run.id)?.status === "cancelled")
7752
+ controller.abort();
7753
+ }, opts.cancelPollMs ?? 500);
7754
+ cancelTimer.unref();
7755
+ try {
7756
+ if (step.goal) {
7757
+ result = await runGoal(store, step.goal, {
7758
+ ...opts,
7759
+ model: opts.goalModel,
7760
+ target: targetWithStepAccount(step),
7761
+ signal: controller.signal,
7762
+ context: stepContext
7763
+ });
7764
+ } else {
7765
+ result = await executeTarget(targetWithStepAccount(step, opts.goalNodePrompt), executionMetadata(stepContext), {
7766
+ ...opts,
7767
+ machine: opts.machine ?? opts.loop?.machine,
7768
+ signal: controller.signal,
7769
+ onAgentProgress: (progress) => {
7770
+ const stdout = JSON.stringify({ agentProgress: progress }, null, 2);
7771
+ opts.beforePersist?.();
7772
+ store.recordWorkflowStepProgress(run.id, step.id, {
7773
+ stdout,
7774
+ payload: progress
7775
+ }, {
7776
+ daemonLeaseId: opts.daemonLeaseId
7777
+ });
7778
+ opts.onAgentProgress?.(progress);
7779
+ },
7780
+ onSpawn: (pid) => {
7781
+ opts.beforePersist?.();
7782
+ store.markWorkflowStepPid(run.id, step.id, pid, { daemonLeaseId: opts.daemonLeaseId });
7783
+ opts.onSpawn?.(pid);
7784
+ }
7785
+ });
7786
+ }
7787
+ } catch (error) {
7788
+ const finishedAt2 = nowIso();
7789
+ result = {
7790
+ status: "failed",
7791
+ stdout: "",
7792
+ stderr: "",
7793
+ error: error instanceof Error ? error.message : String(error),
7794
+ startedAt: startedStep.startedAt ?? finishedAt2,
7795
+ finishedAt: finishedAt2,
7796
+ durationMs: new Date(finishedAt2).getTime() - new Date(startedStep.startedAt ?? finishedAt2).getTime()
7797
+ };
7798
+ } finally {
7799
+ clearInterval(cancelTimer);
7800
+ opts.signal?.removeEventListener("abort", externalAbort);
7801
+ }
7802
+ const timeoutMessage = opts.signal?.aborted ? opts.signalTimeoutMessage?.() : undefined;
7803
+ if (timeoutMessage && result.status === "failed") {
7804
+ result = { ...result, status: "timed_out", error: timeoutMessage };
7805
+ }
7806
+ if (store.isWorkflowRunTerminal(run.id)) {
7807
+ terminalStatus = store.requireWorkflowRun(run.id).status;
7808
+ blockingError = "workflow run was cancelled";
7809
+ break;
7810
+ }
7811
+ opts.beforePersist?.();
7812
+ const blockedExit = result.status === "failed" && result.exitCode !== undefined && blockedExitCodesForStep(step).includes(result.exitCode);
7813
+ if (blockedExit) {
7814
+ store.finalizeWorkflowStepRun(run.id, step.id, {
7815
+ status: "skipped",
7816
+ finishedAt: result.finishedAt,
7817
+ durationMs: result.durationMs,
7818
+ stdout: result.stdout,
7819
+ stderr: result.stderr,
7820
+ exitCode: result.exitCode,
7821
+ error: `${BLOCKED_STEP_ERROR_PREFIX} step ${step.id} exited with blocked exit code ${result.exitCode}`
7822
+ }, {
7823
+ daemonLeaseId: opts.daemonLeaseId
7682
7824
  });
7825
+ continue;
7683
7826
  }
7684
- } catch (error) {
7685
- const finishedAt2 = nowIso();
7686
- result = {
7687
- status: "failed",
7688
- stdout: "",
7689
- stderr: "",
7690
- error: error instanceof Error ? error.message : String(error),
7691
- startedAt: startedStep.startedAt ?? finishedAt2,
7692
- finishedAt: finishedAt2,
7693
- durationMs: new Date(finishedAt2).getTime() - new Date(startedStep.startedAt ?? finishedAt2).getTime()
7694
- };
7695
- } finally {
7696
- clearInterval(cancelTimer);
7697
- opts.signal?.removeEventListener("abort", externalAbort);
7698
- }
7699
- const timeoutMessage = opts.signal?.aborted ? opts.signalTimeoutMessage?.() : undefined;
7700
- if (timeoutMessage && result.status === "failed") {
7701
- result = { ...result, status: "timed_out", error: timeoutMessage };
7702
- }
7703
- if (store.isWorkflowRunTerminal(run.id)) {
7704
- terminalStatus = store.requireWorkflowRun(run.id).status;
7705
- blockingError = "workflow run was cancelled";
7706
- break;
7707
- }
7708
- opts.beforePersist?.();
7709
- const blockedExit = result.status === "failed" && result.exitCode !== undefined && blockedExitCodesForStep(step).includes(result.exitCode);
7710
- if (blockedExit) {
7711
7827
  store.finalizeWorkflowStepRun(run.id, step.id, {
7712
- status: "skipped",
7828
+ status: result.status,
7713
7829
  finishedAt: result.finishedAt,
7714
7830
  durationMs: result.durationMs,
7715
7831
  stdout: result.stdout,
7716
7832
  stderr: result.stderr,
7717
7833
  exitCode: result.exitCode,
7718
- error: `${BLOCKED_STEP_ERROR_PREFIX} step ${step.id} exited with blocked exit code ${result.exitCode}`
7834
+ error: result.error
7719
7835
  }, {
7720
7836
  daemonLeaseId: opts.daemonLeaseId
7721
7837
  });
7722
- continue;
7838
+ if (result.status !== "succeeded" && !step.continueOnFailure) {
7839
+ terminalStatus = result.status;
7840
+ blockingError = `step ${step.id} ${result.status}${result.error ? `: ${result.error}` : ""}`;
7841
+ break;
7842
+ }
7723
7843
  }
7724
- store.finalizeWorkflowStepRun(run.id, step.id, {
7725
- status: result.status,
7726
- finishedAt: result.finishedAt,
7727
- durationMs: result.durationMs,
7728
- stdout: result.stdout,
7729
- stderr: result.stderr,
7730
- exitCode: result.exitCode,
7731
- error: result.error
7844
+ if (terminalStatus !== "succeeded") {
7845
+ for (const step of ordered) {
7846
+ const existing = store.getWorkflowStepRun(run.id, step.id);
7847
+ if (existing?.status === "pending" || existing?.status === "running") {
7848
+ store.skipWorkflowStepRun(run.id, step.id, blockingError ?? "workflow stopped before step could run", {
7849
+ daemonLeaseId: opts.daemonLeaseId
7850
+ });
7851
+ }
7852
+ }
7853
+ }
7854
+ const finishedAt = nowIso();
7855
+ if (store.isWorkflowRunTerminal(run.id)) {
7856
+ const terminalRun = store.requireWorkflowRun(run.id);
7857
+ return workflowResult(terminalRun, terminalRun.status, startedAt, terminalRun.finishedAt ?? finishedAt, store.listWorkflowStepRuns(run.id), terminalRun.error ?? blockingError);
7858
+ }
7859
+ opts.beforePersist?.();
7860
+ const finalRun = store.finalizeWorkflowRun(run.id, terminalStatus, {
7861
+ finishedAt,
7862
+ durationMs: new Date(finishedAt).getTime() - new Date(startedAt).getTime(),
7863
+ error: blockingError
7732
7864
  }, {
7733
7865
  daemonLeaseId: opts.daemonLeaseId
7734
7866
  });
7735
- if (result.status !== "succeeded" && !step.continueOnFailure) {
7736
- terminalStatus = result.status;
7737
- blockingError = `step ${step.id} ${result.status}${result.error ? `: ${result.error}` : ""}`;
7738
- break;
7739
- }
7740
- }
7741
- if (terminalStatus !== "succeeded") {
7742
- for (const step of ordered) {
7743
- const existing = store.getWorkflowStepRun(run.id, step.id);
7744
- if (existing?.status === "pending" || existing?.status === "running") {
7745
- store.skipWorkflowStepRun(run.id, step.id, blockingError ?? "workflow stopped before step could run", {
7867
+ return workflowResult(finalRun, terminalStatus, startedAt, finishedAt, store.listWorkflowStepRuns(run.id), blockingError);
7868
+ } catch (error) {
7869
+ if (opts.daemonLeaseId && error instanceof Error && error.message === "daemon lease lost")
7870
+ throw error;
7871
+ if (error instanceof Error && error.message.includes("workflow step is not claimable"))
7872
+ throw error;
7873
+ const message = error instanceof Error ? error.message : String(error);
7874
+ const finishedAt = nowIso();
7875
+ try {
7876
+ if (!store.isWorkflowRunTerminal(run.id)) {
7877
+ store.finalizeWorkflowRun(run.id, "failed", {
7878
+ finishedAt,
7879
+ durationMs: new Date(finishedAt).getTime() - new Date(startedAt).getTime(),
7880
+ error: message
7881
+ }, {
7746
7882
  daemonLeaseId: opts.daemonLeaseId
7747
7883
  });
7748
7884
  }
7749
- }
7750
- }
7751
- const finishedAt = nowIso();
7752
- if (store.isWorkflowRunTerminal(run.id)) {
7753
- const terminalRun = store.requireWorkflowRun(run.id);
7754
- return workflowResult(terminalRun, terminalRun.status, startedAt, terminalRun.finishedAt ?? finishedAt, store.listWorkflowStepRuns(run.id), terminalRun.error ?? blockingError);
7885
+ } catch {}
7886
+ const current = store.getWorkflowRun(run.id) ?? run;
7887
+ const resultStatus = current.status === "running" ? "failed" : current.status;
7888
+ return workflowResult(current, resultStatus, startedAt, finishedAt, store.listWorkflowStepRuns(run.id), current.error ?? message);
7755
7889
  }
7756
- opts.beforePersist?.();
7757
- const finalRun = store.finalizeWorkflowRun(run.id, terminalStatus, {
7758
- finishedAt,
7759
- durationMs: new Date(finishedAt).getTime() - new Date(startedAt).getTime(),
7760
- error: blockingError
7761
- }, {
7762
- daemonLeaseId: opts.daemonLeaseId
7763
- });
7764
- return workflowResult(finalRun, terminalStatus, startedAt, finishedAt, store.listWorkflowStepRuns(run.id), blockingError);
7765
7890
  }
7766
7891
  function preflightWorkflow(workflow, opts = {}) {
7767
7892
  return workflowExecutionOrder(workflow).map((step) => {
@@ -8132,6 +8257,25 @@ function advanceOptions(deps) {
8132
8257
  onRun: deps.onRun
8133
8258
  };
8134
8259
  }
8260
+ var TERMINAL_RUN_STATUSES2 = new Set([
8261
+ "succeeded",
8262
+ "failed",
8263
+ "timed_out",
8264
+ "abandoned",
8265
+ "skipped"
8266
+ ]);
8267
+ function repairWedgedTerminalSlot(deps, loop, scheduledFor, now) {
8268
+ const existing = deps.store.getRunBySlot(loop.id, scheduledFor);
8269
+ if (!existing || !TERMINAL_RUN_STATUSES2.has(existing.status))
8270
+ return;
8271
+ try {
8272
+ advanceLoop(deps.store, loop, existing, new Date(existing.finishedAt ?? now), existing.status === "succeeded", advanceOptions(deps));
8273
+ } catch (error) {
8274
+ if (deps.daemonLeaseId && isDaemonLeaseLost(error))
8275
+ return;
8276
+ throw error;
8277
+ }
8278
+ }
8135
8279
  async function runSlot(deps, loop, scheduledFor) {
8136
8280
  const now = deps.now?.() ?? new Date;
8137
8281
  deps.beforeRun?.(loop, scheduledFor);
@@ -8158,8 +8302,10 @@ async function runSlot(deps, loop, scheduledFor) {
8158
8302
  return;
8159
8303
  throw error;
8160
8304
  }
8161
- if (!claim)
8305
+ if (!claim) {
8306
+ repairWedgedTerminalSlot(deps, loop, scheduledFor, now);
8162
8307
  return;
8308
+ }
8163
8309
  deps.beforeRun?.(claim.loop, claim.run.scheduledFor);
8164
8310
  deps.onRun?.(claim.run);
8165
8311
  const finalRun = await executeClaimedRun({
@@ -8205,8 +8351,10 @@ function claimSlot(deps, loop, scheduledFor) {
8205
8351
  return;
8206
8352
  throw error;
8207
8353
  }
8208
- if (!claim)
8354
+ if (!claim) {
8355
+ repairWedgedTerminalSlot(deps, loop, scheduledFor, now);
8209
8356
  return;
8357
+ }
8210
8358
  deps.beforeRun?.(claim.loop, claim.run.scheduledFor);
8211
8359
  deps.onRun?.(claim.run);
8212
8360
  return claim;
@@ -8323,13 +8471,19 @@ class LoopsClient {
8323
8471
  return this.store.requireLoop(idOrName);
8324
8472
  }
8325
8473
  pause(idOrName) {
8326
- return this.store.updateLoop(this.get(idOrName).id, { status: "paused" });
8474
+ return this.store.updateLoop(this.store.requireUniqueLoop(idOrName).id, { status: "paused" });
8327
8475
  }
8328
8476
  resume(idOrName) {
8329
- return this.store.updateLoop(this.get(idOrName).id, { status: "active" });
8477
+ const loop = this.store.requireUniqueLoop(idOrName);
8478
+ let nextRunAt = loop.nextRunAt;
8479
+ if (!nextRunAt) {
8480
+ const now = new Date;
8481
+ nextRunAt = computeNextAfter(loop.schedule, now, now);
8482
+ }
8483
+ return this.store.updateLoop(loop.id, { status: "active", nextRunAt });
8330
8484
  }
8331
8485
  stop(idOrName) {
8332
- return this.store.updateLoop(this.get(idOrName).id, { status: "stopped", nextRunAt: undefined });
8486
+ return this.store.updateLoop(this.store.requireUniqueLoop(idOrName).id, { status: "stopped", nextRunAt: undefined });
8333
8487
  }
8334
8488
  archive(idOrName) {
8335
8489
  return this.store.archiveLoop(idOrName);
@@ -8338,7 +8492,7 @@ class LoopsClient {
8338
8492
  return this.store.unarchiveLoop(idOrName);
8339
8493
  }
8340
8494
  delete(idOrName) {
8341
- return this.store.deleteLoop(idOrName);
8495
+ return this.store.deleteLoop(this.store.requireUniqueLoop(idOrName).id);
8342
8496
  }
8343
8497
  runs(idOrName, filters = {}) {
8344
8498
  let loopId;
@@ -8370,7 +8524,7 @@ class LoopsClient {
8370
8524
  return tick({ store: this.store, runnerId: this.runnerId });
8371
8525
  }
8372
8526
  async runNow(idOrName) {
8373
- const result = await runLoopNow({ store: this.store, idOrName, runnerId: this.runnerId });
8527
+ const result = await runLoopNow({ store: this.store, idOrName: this.store.requireUniqueLoop(idOrName).id, runnerId: this.runnerId });
8374
8528
  return result.run;
8375
8529
  }
8376
8530
  exportBundle(opts = {}) {