agent-valley 4.1.0 → 4.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "av",
4
- "version": "4.1.0",
4
+ "version": "4.2.1",
5
5
  "description": "Delegate repository goals to Agent Valley and inspect mission progress and verification evidence.",
6
6
  "author": {
7
7
  "name": "Agent Valley"
package/dist/index.js CHANGED
@@ -7091,6 +7091,7 @@ var init_contracts = __esm(() => {
7091
7091
  "unknown-effect",
7092
7092
  "budget",
7093
7093
  "interrupted",
7094
+ "service-shutdown",
7094
7095
  "chief-wait",
7095
7096
  "chief-unavailable",
7096
7097
  "integrity"
@@ -7264,7 +7265,7 @@ function recordPause(mission, pause) {
7264
7265
  state.failureKind = pause.kind;
7265
7266
  if (pause.nextRunAt)
7266
7267
  state.nextRunAt = pause.nextRunAt;
7267
- else
7268
+ else if (pause.kind !== "service-shutdown")
7268
7269
  delete state.nextRunAt;
7269
7270
  mission.status = pause.nextRunAt ? "waiting" : "paused";
7270
7271
  mission.error = pause.message;
@@ -69239,7 +69240,8 @@ var codeDeliveryPolicySchema = strictObject({
69239
69240
  remote: string2().min(1).max(100).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
69240
69241
  paths: array(string2().refine(codeDeliveryPath, "Select exact product paths; private/runtime paths cannot be delivered.")).min(1).max(100).refine((paths) => new Set(paths).size === paths.length, "Select each delivery path once."),
69241
69242
  message: string2().trim().min(1).max(8000),
69242
- baseSha: sha
69243
+ baseSha: sha,
69244
+ skipPrePush: boolean2().optional()
69243
69245
  });
69244
69246
  var codeDeliverySchema = strictObject({
69245
69247
  policy: codeDeliveryPolicySchema,
@@ -70783,6 +70785,7 @@ function validateResumeOptions(goal, options) {
70783
70785
  "resume",
70784
70786
  "worker",
70785
70787
  "supervise",
70788
+ "service",
70786
70789
  "retry",
70787
70790
  "runs",
70788
70791
  "duration",
@@ -71067,7 +71070,7 @@ var operationSchema = strictObject({
71067
71070
  charter: string2().trim().min(1).max(32000),
71068
71071
  settings: record(string2().min(1).max(80), union([string2().max(32000), boolean2()])),
71069
71072
  phase: _enum(["deciding", "running", "accepting", "waiting", "paused", "completed"]),
71070
- pauseKind: _enum(["interrupted", "blocked"]).optional(),
71073
+ pauseKind: _enum(["interrupted", "blocked", "service-shutdown"]).optional(),
71071
71074
  createdAt: timestampSchema,
71072
71075
  updatedAt: timestampSchema,
71073
71076
  completedCycles: number2().int().min(0),
@@ -71698,6 +71701,67 @@ async function collectContainerObservation(input, previous, dependencies = {}) {
71698
71701
  // ../../packages/core/src/chief/continuous-operation.ts
71699
71702
  import { createHash as createHash18, randomUUID as randomUUID12 } from "node:crypto";
71700
71703
  init_execution();
71704
+
71705
+ // ../../packages/core/src/chief/service-shutdown.ts
71706
+ init_execution();
71707
+ function serviceShutdownPause() {
71708
+ return new MissionPause("The OS-owned service is shutting down. Re-observe the saved execution before continuing the same goal within its original limits.", "service-shutdown");
71709
+ }
71710
+ function isServiceShutdown(signal) {
71711
+ return signal?.reason instanceof MissionPause && signal.reason.kind === "service-shutdown";
71712
+ }
71713
+ function interruptionPause(signal, fallback) {
71714
+ return signal?.reason instanceof MissionPause ? signal.reason : new MissionPause(fallback, "interrupted");
71715
+ }
71716
+ function recordServiceShutdown(mission, unconfirmedTermination) {
71717
+ const pause = serviceShutdownPause();
71718
+ if (mission.history.at(-1)?.stage !== "service-shutdown")
71719
+ mission.history.push({ at: new Date().toISOString(), stage: "service-shutdown", message: pause.message });
71720
+ const protectedKinds = ["interrupted", "budget", "integrity", "unknown-effect", "chief-unavailable"];
71721
+ if (protectedKinds.includes(mission.execution?.failureKind ?? ""))
71722
+ return;
71723
+ if (mission.status === "paused" && mission.execution?.failureKind && mission.execution.failureKind !== "service-shutdown")
71724
+ return;
71725
+ if (mission.status === "failed" && mission.execution?.failureKind !== "service-shutdown")
71726
+ return;
71727
+ if (unconfirmedTermination) {
71728
+ recordPause(mission, new MissionPause(unconfirmedTermination.message, "unknown-effect"));
71729
+ return;
71730
+ }
71731
+ if (mission.status === "completed") {
71732
+ if (pendingCodeDelivery(mission)) {
71733
+ try {
71734
+ assertExecutionDeadline(mission);
71735
+ } catch (error) {
71736
+ if (!(error instanceof MissionPause))
71737
+ throw error;
71738
+ if (mission.codeDelivery) {
71739
+ mission.codeDelivery.phase = "blocked";
71740
+ mission.codeDelivery.error = error.message;
71741
+ delete mission.codeDelivery.nextRunAt;
71742
+ }
71743
+ }
71744
+ }
71745
+ } else {
71746
+ for (const run of mission.operations?.runs ?? []) {
71747
+ if (!run.finishedAt && run.executionState !== "settled")
71748
+ markOperatingRunUnknown(run, "Service shutdown interrupted this execution. Matching process-guard proof is required before recovery.");
71749
+ }
71750
+ let disposition = pause;
71751
+ try {
71752
+ assertExecutionBudget(mission);
71753
+ } catch (error) {
71754
+ if (!(error instanceof MissionPause))
71755
+ throw error;
71756
+ disposition = error;
71757
+ }
71758
+ recordPause(mission, disposition);
71759
+ if (disposition.kind === "service-shutdown" && mission.supervision)
71760
+ mission.supervision.pendingRecovery ??= { reason: pause.message };
71761
+ }
71762
+ }
71763
+
71764
+ // ../../packages/core/src/chief/continuous-operation.ts
71701
71765
  function continuousDecisionKey(decision, observationFingerprint, observationRevision) {
71702
71766
  return createHash18("sha256").update(JSON.stringify({ goal: decision.goal, evidence: decision.evidence, observationFingerprint, observationRevision })).digest("hex");
71703
71767
  }
@@ -71712,8 +71776,9 @@ async function runContinuousOperation(operation, ports) {
71712
71776
  if (operation.phase !== "paused" && operation.phase !== "completed")
71713
71777
  operation.resumePhase = operation.phase;
71714
71778
  operation.phase = "paused";
71715
- operation.pauseKind = ports.signal?.aborted ? "interrupted" : "blocked";
71716
- operation.error = message.slice(0, 16000);
71779
+ const shutdown = isServiceShutdown(ports.signal);
71780
+ operation.pauseKind = shutdown ? "service-shutdown" : ports.signal?.aborted ? "interrupted" : "blocked";
71781
+ operation.error = (shutdown ? "The OS-owned service is shutting down. The operation retained its child, decision and recovery checkpoints for automatic resumption within their original limits." : message).slice(0, 16000);
71717
71782
  await save();
71718
71783
  return operation;
71719
71784
  };
@@ -71740,12 +71805,22 @@ async function runContinuousOperation(operation, ports) {
71740
71805
  if (mission)
71741
71806
  assertExecutionDeadline(mission, Date.parse(now()));
71742
71807
  const remaining = mission?.executionPolicy && mission.execution ? Date.parse(mission.execution.startedAt) + mission.executionPolicy.maxDurationSec * 1000 - Date.parse(now()) : Infinity;
71743
- await ports.delay(Math.min(Date.parse(nextRunAt) - Date.parse(now()), remaining, 30000), ports.signal);
71808
+ try {
71809
+ await ports.delay(Math.min(Date.parse(nextRunAt) - Date.parse(now()), remaining, 30000), ports.signal);
71810
+ } catch (error) {
71811
+ if (mission)
71812
+ assertExecutionDeadline(mission, Date.parse(now()));
71813
+ if (error instanceof MissionPause && error.kind !== "interrupted" && error.kind !== "service-shutdown")
71814
+ throw error;
71815
+ if (ports.signal?.aborted)
71816
+ throw interruptionPause(ports.signal, "Operation recovery interrupted.");
71817
+ throw error;
71818
+ }
71744
71819
  }
71745
71820
  if (mission)
71746
71821
  assertExecutionDeadline(mission, Date.parse(now()));
71747
71822
  if (ports.signal?.aborted)
71748
- throw new MissionPause("Operation recovery interrupted.", "interrupted");
71823
+ throw interruptionPause(ports.signal, "Operation recovery interrupted.");
71749
71824
  };
71750
71825
  const recoverChild = async (mission, context) => {
71751
71826
  const disposition = automaticMissionRecovery(mission, Date.parse(now()), context);
@@ -71776,6 +71851,7 @@ async function runContinuousOperation(operation, ports) {
71776
71851
  }
71777
71852
  await save();
71778
71853
  await waitForRecovery(disposition.waitUntil, mission);
71854
+ const pendingRecovery = structuredClone(operation.recovery);
71779
71855
  operation.recovery.attempts += 1;
71780
71856
  if (!continuation)
71781
71857
  operation.recovery.failedAttempts = failedAttempts + 1;
@@ -71784,11 +71860,22 @@ async function runContinuousOperation(operation, ports) {
71784
71860
  await save();
71785
71861
  if (!operation.baseline)
71786
71862
  throw new Error("The original accepted baseline is missing from the recovery checkpoint.");
71787
- await ports.runMission(operation, mission.id, mission.goal, operation.baseline.path);
71863
+ try {
71864
+ const resumed = await ports.runMission(operation, mission.id, mission.goal, operation.baseline.path);
71865
+ if (isServiceShutdown(ports.signal) && resumed.execution?.failureKind === "service-shutdown") {
71866
+ operation.recovery = pendingRecovery;
71867
+ throw interruptionPause(ports.signal, "Operation child recovery interrupted.");
71868
+ }
71869
+ } catch (error) {
71870
+ if (error instanceof MissionPause && error.kind === "service-shutdown")
71871
+ operation.recovery = pendingRecovery;
71872
+ throw error;
71873
+ }
71788
71874
  return true;
71789
71875
  };
71790
71876
  const selectDecision = async (id) => {
71791
71877
  while (true) {
71878
+ const previous = operation.recovery?.target === "decision" && operation.recovery.checkpointId === id ? structuredClone(operation.recovery) : undefined;
71792
71879
  const prior = operation.recovery?.target === "decision" && operation.recovery.checkpointId === id ? operation.recovery.attempts : 0;
71793
71880
  if (prior >= automaticRecoveryLimit)
71794
71881
  throw new Error("Bounded automatic goal-selection recovery exhausted its attempts; the saved decision remains unresolved.");
@@ -71804,6 +71891,16 @@ async function runContinuousOperation(operation, ports) {
71804
71891
  try {
71805
71892
  return continuousDecisionSchema.parse(await ports.decide(operation, id));
71806
71893
  } catch (error) {
71894
+ if (error instanceof MissionPause && error.kind === "service-shutdown") {
71895
+ operation.recovery = previous ?? {
71896
+ target: "decision",
71897
+ checkpointId: id,
71898
+ attempts: prior,
71899
+ disposition: "waiting",
71900
+ reason: error.message.slice(0, 16000)
71901
+ };
71902
+ throw error;
71903
+ }
71807
71904
  const reason = error instanceof Error ? error.message : String(error);
71808
71905
  const kind = error instanceof MissionPause ? error.kind : classifyFailure(reason);
71809
71906
  const invalid = error instanceof Error && (error.name === "ZodError" || reason.startsWith("Invalid Chief decision"));
@@ -71996,7 +72093,7 @@ async function runContinuousOperation(operation, ports) {
71996
72093
  await save();
71997
72094
  }
71998
72095
  } catch (error) {
71999
- if (operation.recovery && error instanceof MissionPause) {
72096
+ if (operation.recovery && error instanceof MissionPause && error.kind !== "service-shutdown") {
72000
72097
  operation.recovery.disposition = "protected";
72001
72098
  operation.recovery.reason = error.message.slice(0, 16000);
72002
72099
  }
@@ -73913,13 +74010,15 @@ import { createHash as createHash21 } from "node:crypto";
73913
74010
  class ContractViolation extends Error {
73914
74011
  }
73915
74012
  function createMissionContract(mission) {
74013
+ const originalDelivery = mission.codeDelivery ? structuredClone(mission.codeDelivery) : undefined;
73916
74014
  const immutable = {
73917
74015
  goal: mission.goal,
73918
74016
  verifyCommand: mission.verifyCommand,
73919
74017
  operatingPolicy: JSON.stringify(mission.operatingPolicy),
73920
74018
  executionPolicy: JSON.stringify(mission.executionPolicy),
73921
74019
  metricSourcePolicy: JSON.stringify(mission.metricSourcePolicy),
73922
- containerObservationPolicy: JSON.stringify(mission.containerObservationPolicy)
74020
+ containerObservationPolicy: JSON.stringify(mission.containerObservationPolicy),
74021
+ codeDeliveryPolicy: JSON.stringify(mission.codeDelivery?.policy)
73923
74022
  };
73924
74023
  let brief = mission.goalBrief ? JSON.stringify(mission.goalBrief) : undefined;
73925
74024
  let checks = mission.verificationContract ? JSON.stringify(mission.verificationContract) : undefined;
@@ -73931,7 +74030,7 @@ function createMissionContract(mission) {
73931
74030
  digest = mission.verificationContractSha256;
73932
74031
  },
73933
74032
  assert() {
73934
- if (mission.goal === immutable.goal && mission.verifyCommand === immutable.verifyCommand && JSON.stringify(mission.operatingPolicy) === immutable.operatingPolicy && JSON.stringify(mission.executionPolicy) === immutable.executionPolicy && JSON.stringify(mission.metricSourcePolicy) === immutable.metricSourcePolicy && JSON.stringify(mission.containerObservationPolicy) === immutable.containerObservationPolicy && (!brief || JSON.stringify(mission.goalBrief) === brief) && (!checks || JSON.stringify(mission.verificationContract) === checks) && mission.verificationContractSha256 === digest)
74033
+ if (mission.goal === immutable.goal && mission.verifyCommand === immutable.verifyCommand && JSON.stringify(mission.operatingPolicy) === immutable.operatingPolicy && JSON.stringify(mission.executionPolicy) === immutable.executionPolicy && JSON.stringify(mission.metricSourcePolicy) === immutable.metricSourcePolicy && JSON.stringify(mission.containerObservationPolicy) === immutable.containerObservationPolicy && JSON.stringify(mission.codeDelivery?.policy) === immutable.codeDeliveryPolicy && (!brief || JSON.stringify(mission.goalBrief) === brief) && (!checks || JSON.stringify(mission.verificationContract) === checks) && mission.verificationContractSha256 === digest)
73935
74034
  return;
73936
74035
  mission.goal = immutable.goal;
73937
74036
  mission.verifyCommand = immutable.verifyCommand;
@@ -73939,6 +74038,11 @@ function createMissionContract(mission) {
73939
74038
  mission.executionPolicy = immutable.executionPolicy ? JSON.parse(immutable.executionPolicy) : undefined;
73940
74039
  mission.metricSourcePolicy = immutable.metricSourcePolicy ? JSON.parse(immutable.metricSourcePolicy) : undefined;
73941
74040
  mission.containerObservationPolicy = immutable.containerObservationPolicy ? JSON.parse(immutable.containerObservationPolicy) : undefined;
74041
+ if (originalDelivery && immutable.codeDeliveryPolicy) {
74042
+ mission.codeDelivery ??= structuredClone(originalDelivery);
74043
+ mission.codeDelivery.policy = JSON.parse(immutable.codeDeliveryPolicy);
74044
+ } else
74045
+ delete mission.codeDelivery;
73942
74046
  if (brief)
73943
74047
  mission.goalBrief = JSON.parse(brief);
73944
74048
  if (checks)
@@ -75157,7 +75261,7 @@ function abortableDelay(ms, signal) {
75157
75261
  const abort = () => {
75158
75262
  clearTimeout(timer);
75159
75263
  signal?.removeEventListener("abort", abort);
75160
- reject(new Error("Order supervision interrupted."));
75264
+ reject(signal?.reason instanceof MissionPause ? signal.reason : new Error("Order supervision interrupted."));
75161
75265
  };
75162
75266
  const timer = setTimeout(() => {
75163
75267
  signal?.removeEventListener("abort", abort);
@@ -75173,17 +75277,23 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75173
75277
  const id = options.resume ?? options.missionId ?? randomUUID15();
75174
75278
  const store = new MissionStore(join36(root, ".agent-valley/missions"));
75175
75279
  const controller = new AbortController;
75176
- const interrupt = () => controller.abort();
75280
+ const interrupt = () => controller.abort(dependencies.signal?.reason);
75281
+ const terminate = () => controller.abort(options.service ? serviceShutdownPause() : undefined);
75177
75282
  dependencies.signal?.addEventListener("abort", interrupt, { once: true });
75178
75283
  if (dependencies.signal?.aborted)
75179
75284
  interrupt();
75180
75285
  if (!dependencies.signal) {
75181
75286
  process.once("SIGINT", interrupt);
75182
- process.once("SIGTERM", interrupt);
75287
+ process.once("SIGTERM", terminate);
75183
75288
  }
75184
75289
  const runWorker = createDeadlineWorkerRunner(store, id, controller.signal);
75185
- let args = orderWorkerArgs(goal, options, id);
75290
+ const workerArgs = (goal, current) => orderWorkerArgs(goal, {
75291
+ ...current,
75292
+ ...options.service ? { service: true } : {}
75293
+ }, id);
75294
+ let args = workerArgs(goal, options);
75186
75295
  let returned;
75296
+ let terminationFailure;
75187
75297
  const waitForOwner = async () => {
75188
75298
  let observed = false;
75189
75299
  while (await store.isLocked(id)) {
@@ -75206,7 +75316,7 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75206
75316
  returned = current;
75207
75317
  if (controller.signal.aborted || current.status === "completed" && !pendingCodeDelivery(current) || ["paused", "failed"].includes(current.status) && !automaticMissionRecovery(current).retry)
75208
75318
  return current;
75209
- args = orderWorkerArgs(undefined, { resume: id }, id);
75319
+ args = workerArgs(undefined, { resume: id });
75210
75320
  }
75211
75321
  if (controller.signal.aborted)
75212
75322
  break;
@@ -75255,7 +75365,7 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75255
75365
  await (dependencies.delay ?? abortableDelay)(Math.min(Date.parse(mission.codeDelivery.nextRunAt) - Date.now(), 30000), controller.signal);
75256
75366
  }
75257
75367
  assertExecutionDeadline(mission);
75258
- args = orderWorkerArgs(undefined, { resume: id }, id);
75368
+ args = workerArgs(undefined, { resume: id });
75259
75369
  continue;
75260
75370
  }
75261
75371
  const recovery = automaticMissionRecovery(mission);
@@ -75294,13 +75404,15 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75294
75404
  await (dependencies.delay ?? abortableDelay)(Math.min(1000, remainingTime()), controller.signal);
75295
75405
  }
75296
75406
  assertExecutionDeadline(mission);
75297
- args = orderWorkerArgs(undefined, { resume: id }, id);
75407
+ args = workerArgs(undefined, { resume: id });
75298
75408
  }
75299
75409
  returned = await store.load(id);
75300
75410
  return returned;
75301
75411
  } catch (error) {
75302
- if (error instanceof WorkerTerminationError)
75412
+ if (error instanceof WorkerTerminationError) {
75413
+ terminationFailure = error;
75303
75414
  throw error;
75415
+ }
75304
75416
  if (await store.isLocked(id)) {
75305
75417
  if (!controller.signal.aborted)
75306
75418
  await waitForOwner();
@@ -75363,7 +75475,18 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75363
75475
  const existing = await store.load(id).catch(() => {
75364
75476
  return;
75365
75477
  });
75366
- if (existing?.status === "completed" && existing.codeDelivery && pendingCodeDelivery(existing)) {
75478
+ if (existing && isServiceShutdown(controller.signal)) {
75479
+ const unlock = await store.lock(id);
75480
+ try {
75481
+ const latest = await store.load(id);
75482
+ recordServiceShutdown(latest, terminationFailure);
75483
+ await store.save(latest);
75484
+ if (returned)
75485
+ Object.assign(returned, latest);
75486
+ } finally {
75487
+ await unlock();
75488
+ }
75489
+ } else if (existing?.status === "completed" && existing.codeDelivery && pendingCodeDelivery(existing)) {
75367
75490
  const unlock = await store.lock(id);
75368
75491
  try {
75369
75492
  const latest = await store.load(id);
@@ -75401,7 +75524,7 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75401
75524
  dependencies.signal?.removeEventListener("abort", interrupt);
75402
75525
  if (!dependencies.signal) {
75403
75526
  process.removeListener("SIGINT", interrupt);
75404
- process.removeListener("SIGTERM", interrupt);
75527
+ process.removeListener("SIGTERM", terminate);
75405
75528
  }
75406
75529
  }
75407
75530
  }
@@ -75409,13 +75532,13 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75409
75532
  // src/chief-continuous-recovery.ts
75410
75533
  function assertContinuousDecisionRecovery(mission) {
75411
75534
  const state = executionState(mission);
75412
- if (mission.status === "paused" && state.failureKind !== "implementation" && state.failureKind !== "provider" && state.failureKind !== "rate-limit")
75535
+ if (mission.status === "paused" && state.failureKind !== "implementation" && state.failureKind !== "provider" && state.failureKind !== "rate-limit" && state.failureKind !== "service-shutdown")
75413
75536
  throw new MissionPause(mission.error ?? state.pauseReason ?? "The saved decision remains unresolved.", state.failureKind ?? "implementation");
75414
75537
  }
75415
75538
  async function runContinuousDecision(mission, prompt, run, store, signal, delay = abortableDelay) {
75416
75539
  assertContinuousDecisionRecovery(mission);
75417
75540
  const state = executionState(mission);
75418
- if (mission.status === "paused" && state.retries >= (mission.executionPolicy?.maxRetries ?? 0))
75541
+ if (mission.status === "paused" && state.failureKind !== "service-shutdown" && state.retries >= (mission.executionPolicy?.maxRetries ?? 0))
75419
75542
  throw new MissionPause(mission.error ?? "Bounded Chief decision recovery exhausted its attempts.", state.failureKind ?? "implementation");
75420
75543
  let correction = mission.history.findLast((entry) => entry.stage === "continuous-decision-invalid")?.message;
75421
75544
  while (true) {
@@ -75425,7 +75548,7 @@ async function runContinuousDecision(mission, prompt, run, store, signal, delay
75425
75548
  await delay(Math.min(Date.parse(state.nextRunAt) - Date.now(), remaining, 30000), signal);
75426
75549
  }
75427
75550
  if (signal?.aborted)
75428
- throw new MissionPause("Operation decision interrupted.", "interrupted");
75551
+ throw interruptionPause(signal, "Operation decision interrupted.");
75429
75552
  mission.status = "planning";
75430
75553
  delete mission.error;
75431
75554
  delete state.pauseReason;
@@ -76306,8 +76429,12 @@ async function decideContinuousGoal(operation, decisionId, root, dependencies =
76306
76429
  return parseContinuousDecision(result.message);
76307
76430
  }
76308
76431
  if (mission) {
76432
+ const serviceRuns = mission.history.at(-1)?.stage === "service-shutdown" && mission.execution?.failureKind === "unknown-effect" ? mission.operations?.runs.filter((run) => run.executionState === "unknown") ?? [] : [];
76309
76433
  await store.recoverProcesses(decisionId, mission);
76310
76434
  finalizeAbandonedRuns(mission);
76435
+ if (serviceRuns.length && serviceRuns.every((run) => run.executionRecovery === "local-process" && run.executionState === "settled") && !mission.tasks.some((task) => task.effectState === "unknown") && mission.execution) {
76436
+ mission.execution.failureKind = "service-shutdown";
76437
+ }
76311
76438
  assertContinuousDecisionRecovery(mission);
76312
76439
  await store.save(mission);
76313
76440
  } else {
@@ -76375,7 +76502,7 @@ async function decideContinuousGoal(operation, decisionId, root, dependencies =
76375
76502
  throw new MissionPause("Decision stage changed its saved charter, workspace, Chief Director or pinned evidence.", "integrity");
76376
76503
  }, () => {
76377
76504
  if (dependencies.signal?.aborted)
76378
- throw new MissionPause("Operation decision interrupted.", "interrupted");
76505
+ throw interruptionPause(dependencies.signal, "Operation decision interrupted.");
76379
76506
  });
76380
76507
  await consultContinuousDirectors(mission, ports, run);
76381
76508
  const tools = await (dependencies.tools ?? discoverTools)(operation.repositoryRoot);
@@ -76405,7 +76532,14 @@ async function decideContinuousGoal(operation, decisionId, root, dependencies =
76405
76532
  throw error;
76406
76533
  } finally {
76407
76534
  try {
76408
- await runtime.close();
76535
+ try {
76536
+ await runtime.close();
76537
+ } finally {
76538
+ if (mission && isServiceShutdown(dependencies.signal)) {
76539
+ recordServiceShutdown(mission);
76540
+ await store.save(mission);
76541
+ }
76542
+ }
76409
76543
  } finally {
76410
76544
  await unlock();
76411
76545
  }
@@ -76433,7 +76567,8 @@ var orderKeys = [
76433
76567
  "deliver",
76434
76568
  "deliveryPaths",
76435
76569
  "deliveryMessage",
76436
- "deliveryRemote"
76570
+ "deliveryRemote",
76571
+ "deliverySkipPrePush"
76437
76572
  ];
76438
76573
  var decisionBudgetKeys = ["runs", "duration", "cost", "accountRun", "accountCost"];
76439
76574
  function integerOption(value, name, maximum) {
@@ -76470,6 +76605,8 @@ async function restoreOperationOrigin(repository, workspace) {
76470
76605
  }
76471
76606
  }
76472
76607
  async function newOperation(charter, options, root, id) {
76608
+ if (options.deliverySkipPrePush !== undefined && !options.deliver)
76609
+ throw new Error("Set --deliver <branch> with --delivery-skip-pre-push before starting an order.");
76473
76610
  if (options.accountRun !== undefined || options.accountCost !== undefined)
76474
76611
  throw new Error("Use --resume <operation-id> to reconcile an active decision run's observed cost.");
76475
76612
  if (!charter?.trim() || charter.length > 32000)
@@ -76574,13 +76711,14 @@ async function runOperation(charter, options, root = process.cwd(), dependencies
76574
76711
  const storage = operationStore(root);
76575
76712
  const unlock = await storage.lock(id);
76576
76713
  const controller = new AbortController;
76577
- const stop = () => controller.abort();
76714
+ const stop = () => controller.abort(dependencies.signal?.reason);
76715
+ const terminate = () => controller.abort(options.service ? serviceShutdownPause() : undefined);
76578
76716
  dependencies.signal?.addEventListener("abort", stop, { once: true });
76579
76717
  if (dependencies.signal?.aborted)
76580
76718
  stop();
76581
76719
  if (!dependencies.signal) {
76582
76720
  process.once("SIGINT", stop);
76583
- process.once("SIGTERM", stop);
76721
+ process.once("SIGTERM", terminate);
76584
76722
  }
76585
76723
  try {
76586
76724
  let operation;
@@ -76666,12 +76804,13 @@ Resume: av order --resume ${id}`);
76666
76804
  return;
76667
76805
  throw error;
76668
76806
  });
76669
- return superviseOrder(saved ? undefined : goal, saved ? { resume: missionId, once: true } : {
76807
+ return superviseOrder(saved ? undefined : goal, saved ? { resume: missionId, once: true, ...options.service ? { service: true } : {} } : {
76670
76808
  ...current.settings,
76671
76809
  once: true,
76672
76810
  missionId,
76673
76811
  baselineWorkspace: baselinePath,
76674
- operationId: current.id
76812
+ operationId: current.id,
76813
+ ...options.service ? { service: true } : {}
76675
76814
  }, root, { signal: controller.signal });
76676
76815
  }),
76677
76816
  accept: async (current, mission) => {
@@ -76687,13 +76826,13 @@ Resume: av order --resume ${id}`);
76687
76826
  dependencies.signal?.removeEventListener("abort", stop);
76688
76827
  if (!dependencies.signal) {
76689
76828
  process.removeListener("SIGINT", stop);
76690
- process.removeListener("SIGTERM", stop);
76829
+ process.removeListener("SIGTERM", terminate);
76691
76830
  }
76692
76831
  await unlock();
76693
76832
  }
76694
76833
  }
76695
76834
  function registerContinuousCommands(program) {
76696
- program.command("operate [charter]", { hidden: true }).description("Deprecated alias for av order; resume existing operating charters").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check for each improvement").option("--actor <type>", "Pinned Chief Director CLI").option("--model <id>", "Pinned Chief Director model").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Configured YAML Actor roster").option("--oma", "Require OMA completion receipts for workers").option("--timeout <seconds>", "Timeout per Actor/check").option("--repairs <count>", "Repair limit per task/final review").option("--rounds <count>", "Recovery decision limit per improvement").option("--parallel <count>", "Actor concurrency per improvement").option("--runs <count>", "Initial Actor call limit; on resume, increase the active decision checkpoint limit").option("--duration <seconds>", "Initial wall-time limit; on resume, increase the active decision checkpoint limit").option("--cost <usd>", "Initial estimated cost limit; on resume, increase the active decision checkpoint limit").option("--account-run <run-id>", "On resume, reconcile an active decision run whose usage/cost was lost").option("--account-cost <usd>", "Observed USD cost for the decision --account-run after inspecting billing").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--resume <id>", "Resume the saved charter and accepted work").addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).action(async (charter, options) => {
76835
+ program.command("operate [charter]", { hidden: true }).description("Deprecated alias for av order; resume existing operating charters").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check for each improvement").option("--actor <type>", "Pinned Chief Director CLI").option("--model <id>", "Pinned Chief Director model").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Configured YAML Actor roster").option("--oma", "Require OMA completion receipts for workers").option("--service", "Resume after OS service SIGTERM within saved limits; SIGINT still cancels").option("--timeout <seconds>", "Timeout per Actor/check").option("--repairs <count>", "Repair limit per task/final review").option("--rounds <count>", "Recovery decision limit per improvement").option("--parallel <count>", "Actor concurrency per improvement").option("--runs <count>", "Initial Actor call limit; on resume, increase the active decision checkpoint limit").option("--duration <seconds>", "Initial wall-time limit; on resume, increase the active decision checkpoint limit").option("--cost <usd>", "Initial estimated cost limit; on resume, increase the active decision checkpoint limit").option("--account-run <run-id>", "On resume, reconcile an active decision run whose usage/cost was lost").option("--account-cost <usd>", "Observed USD cost for the decision --account-run after inspecting billing").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--resume <id>", "Resume the saved charter and accepted work").addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).action(async (charter, options) => {
76697
76836
  const operation = await runOperation(charter, options);
76698
76837
  console.log(`Operation ${operation.id}: ${operation.phase}; ${operation.completedCycles} verified improvements.`);
76699
76838
  if (operation.error)
@@ -76820,7 +76959,7 @@ class OperationApi {
76820
76959
  if (checked === "unknown")
76821
76960
  throw new Error("Operation process identity changed. No signal was sent.");
76822
76961
  if (checked === "running")
76823
- (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGTERM")))(job.pid);
76962
+ (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGINT")))(job.pid);
76824
76963
  }
76825
76964
  return { ...await this.status(id), cancelRequested: current === "running" };
76826
76965
  });
@@ -77111,7 +77250,7 @@ class MissionApi {
77111
77250
  throw new Error("Supervisor identity changed during cancellation. Inspect the original process; no signal was sent.");
77112
77251
  if (current === "stopped")
77113
77252
  return { ...await this.status(id), cancelRequested: false };
77114
- (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGTERM")))(job.pid);
77253
+ (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGINT")))(job.pid);
77115
77254
  }
77116
77255
  return { ...await this.status(id), cancelRequested: liveness === "running" };
77117
77256
  });
@@ -129744,7 +129883,7 @@ async function artifact(path, content) {
129744
129883
  }
129745
129884
  async function prepareCodeDelivery(repository, options) {
129746
129885
  if (!options.deliver) {
129747
- if (options.deliveryPaths || options.deliveryMessage || options.deliveryRemote)
129886
+ if (options.deliveryPaths || options.deliveryMessage || options.deliveryRemote || options.deliverySkipPrePush !== undefined)
129748
129887
  throw new Error("Set --deliver <branch> with explicit --delivery-paths before requesting code delivery.");
129749
129888
  return;
129750
129889
  }
@@ -129761,7 +129900,8 @@ async function prepareCodeDelivery(repository, options) {
129761
129900
  remote,
129762
129901
  paths: options.deliveryPaths,
129763
129902
  message: options.deliveryMessage ?? "fix: apply verified Agent Valley mission",
129764
- baseSha: (await gitRead(root, ["rev-parse", "HEAD"])).trim()
129903
+ baseSha: (await gitRead(root, ["rev-parse", "HEAD"])).trim(),
129904
+ ...options.deliverySkipPrePush !== undefined ? { skipPrePush: options.deliverySkipPrePush } : {}
129765
129905
  });
129766
129906
  await gitRead(root, ["remote", "get-url", policy.remote]);
129767
129907
  return { policy, phase: "pending", attempts: 0, updatedAt: new Date().toISOString() };
@@ -129780,6 +129920,10 @@ async function privateDirectory(root, id) {
129780
129920
  return current;
129781
129921
  }
129782
129922
  function assertLive(mission, signal) {
129923
+ if (isServiceShutdown(signal)) {
129924
+ assertExecutionDeadline(mission);
129925
+ throw interruptionPause(signal, "Code delivery service is shutting down.");
129926
+ }
129783
129927
  if (signal?.aborted)
129784
129928
  throw new DeliveryBlocked("Code delivery was explicitly interrupted. Preserve its checkpoint and inspect the target before resuming.");
129785
129929
  assertExecutionDeadline(mission);
@@ -129964,8 +130108,21 @@ AV-Delivery: ${delivery.nonce}
129964
130108
  await save();
129965
130109
  }
129966
130110
  if (await remoteState(mission, store, root, delivery, signal) !== "delivered") {
130111
+ if (delivery.policy.skipPrePush) {
130112
+ mission.history.push({
130113
+ at: new Date().toISOString(),
130114
+ stage: "code-delivery-pre-push",
130115
+ message: "The operator authorized --delivery-skip-pre-push. This push attempt omits the pre-push hook; no pre-push check result is claimed. Commit hooks remain enabled."
130116
+ });
130117
+ await save();
130118
+ }
129967
130119
  try {
129968
- await managedGit(mission, store, root, ["push", delivery.policy.remote, `${delivery.commitSha}:refs/heads/${delivery.policy.branch}`], signal);
130120
+ await managedGit(mission, store, root, [
130121
+ "push",
130122
+ ...delivery.policy.skipPrePush ? ["--no-verify"] : [],
130123
+ delivery.policy.remote,
130124
+ `${delivery.commitSha}:refs/heads/${delivery.policy.branch}`
130125
+ ], signal);
129969
130126
  } catch (error) {
129970
130127
  if (signal?.aborted || error instanceof MissionPause)
129971
130128
  throw error;
@@ -129979,9 +130136,14 @@ AV-Delivery: ${delivery.nonce}
129979
130136
  delete delivery.error;
129980
130137
  await save();
129981
130138
  } catch (error) {
130139
+ const deadline = mission.execution && mission.executionPolicy && Date.now() >= Date.parse(mission.execution.startedAt) + mission.executionPolicy.maxDurationSec * 1000;
130140
+ if (error instanceof MissionPause && error.kind === "service-shutdown" && !deadline) {
130141
+ delivery.error = error.message;
130142
+ await save();
130143
+ return;
130144
+ }
129982
130145
  if (delivery.attempts === previousAttempts)
129983
130146
  delivery.attempts = Math.min(3, previousAttempts + 1);
129984
- const deadline = mission.execution && mission.executionPolicy && Date.now() >= Date.parse(mission.execution.startedAt) + mission.executionPolicy.maxDurationSec * 1000;
129985
130147
  const blocked = error instanceof DeliveryBlocked || error instanceof MissionPause || signal?.aborted || deadline;
129986
130148
  if (blocked || delivery.attempts >= 3)
129987
130149
  delivery.phase = "blocked";
@@ -130047,13 +130209,14 @@ import { join as join49 } from "node:path";
130047
130209
  async function watchOrders(root = process.cwd(), dependencies = {}) {
130048
130210
  assertNotManagedRun();
130049
130211
  const controller = new AbortController;
130050
- const stop = () => controller.abort();
130212
+ const stop = () => controller.abort(dependencies.signal?.reason);
130213
+ const terminate = () => controller.abort(dependencies.service ? serviceShutdownPause() : undefined);
130051
130214
  dependencies.signal?.addEventListener("abort", stop, { once: true });
130052
130215
  if (dependencies.signal?.aborted)
130053
130216
  stop();
130054
130217
  if (!dependencies.signal) {
130055
130218
  process.once("SIGINT", stop);
130056
- process.once("SIGTERM", stop);
130219
+ process.once("SIGTERM", terminate);
130057
130220
  }
130058
130221
  const missions = new MissionStore(join49(root, ".agent-valley", "missions"));
130059
130222
  try {
@@ -130072,7 +130235,7 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130072
130235
  if (mission.status === "completed") {
130073
130236
  if (!pendingCodeDelivery(mission) || mission.codeDelivery?.nextRunAt && Date.parse(mission.codeDelivery.nextRunAt) > Date.now())
130074
130237
  continue;
130075
- await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id }, root, {
130238
+ await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id, ...dependencies.service ? { service: true } : {} }, root, {
130076
130239
  signal: controller.signal
130077
130240
  }).then(printOrderOutcome);
130078
130241
  continue;
@@ -130080,7 +130243,7 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130080
130243
  const recovery = automaticMissionRecovery(mission);
130081
130244
  if (!recovery.retry || recovery.waitUntil && Date.parse(recovery.waitUntil) > Date.now())
130082
130245
  continue;
130083
- await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id }, root, {
130246
+ await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id, ...dependencies.service ? { service: true } : {} }, root, {
130084
130247
  signal: controller.signal
130085
130248
  }).then(printOrderOutcome);
130086
130249
  } catch (error) {
@@ -130095,21 +130258,23 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130095
130258
  if (operation.currentMissionId && await missions.isLocked(operation.currentMissionId))
130096
130259
  continue;
130097
130260
  if (operation.phase === "paused") {
130098
- if (operation.pauseKind !== "blocked" || !operation.currentMissionId)
130261
+ if (operation.pauseKind !== "service-shutdown" && (operation.pauseKind !== "blocked" || !operation.currentMissionId))
130099
130262
  continue;
130100
- try {
130101
- const child = await reobserveLocalExecutions(await missions.load(operation.currentMissionId), missions);
130102
- if (child.codeDelivery?.phase === "blocked")
130103
- continue;
130104
- if (!automaticMissionRecovery(child).retry && !(child.status === "completed" && verifiedMissionEvidence(child)))
130263
+ if (operation.currentMissionId) {
130264
+ try {
130265
+ const child = await reobserveLocalExecutions(await missions.load(operation.currentMissionId), missions);
130266
+ if (child.codeDelivery?.phase === "blocked")
130267
+ continue;
130268
+ if (!automaticMissionRecovery(child).retry && !(child.status === "completed" && verifiedMissionEvidence(child)))
130269
+ continue;
130270
+ } catch (error) {
130271
+ console.error(String(error));
130105
130272
  continue;
130106
- } catch (error) {
130107
- console.error(String(error));
130108
- continue;
130273
+ }
130109
130274
  }
130110
130275
  }
130111
130276
  try {
130112
- await (dependencies.operation ?? runOperation)(undefined, { resume: operation.id }, root, {
130277
+ await (dependencies.operation ?? runOperation)(undefined, { resume: operation.id, ...dependencies.service ? { service: true } : {} }, root, {
130113
130278
  signal: controller.signal
130114
130279
  });
130115
130280
  } catch (error) {
@@ -130125,7 +130290,7 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130125
130290
  dependencies.signal?.removeEventListener("abort", stop);
130126
130291
  if (!dependencies.signal) {
130127
130292
  process.removeListener("SIGINT", stop);
130128
- process.removeListener("SIGTERM", stop);
130293
+ process.removeListener("SIGTERM", terminate);
130129
130294
  }
130130
130295
  }
130131
130296
  }
@@ -130260,8 +130425,14 @@ async function organizationContext2(repository, mission) {
130260
130425
  }
130261
130426
  async function runOrder(goal, options, root = process.cwd()) {
130262
130427
  assertNotManagedRun();
130263
- if (options.resume && [options.deliver, options.deliveryPaths, options.deliveryMessage, options.deliveryRemote].some((value) => value !== undefined))
130264
- throw new Error("Code delivery retains its saved branch, paths and commit message. Resume without replacement delivery options.");
130428
+ if (options.resume && [
130429
+ options.deliver,
130430
+ options.deliveryPaths,
130431
+ options.deliveryMessage,
130432
+ options.deliveryRemote,
130433
+ options.deliverySkipPrePush
130434
+ ].some((value) => value !== undefined))
130435
+ throw new Error("Code delivery retains its saved branch, paths, commit message and hook policy. Resume without replacement delivery options.");
130265
130436
  if (!options.resume && [options.retry, options.resolveEffect, options.effectResult, options.accountRun, options.accountCost].some((value) => value !== undefined && value !== false))
130266
130437
  throw new Error("Use --resume <id> for retry, external-effect resolution or cost reconciliation.");
130267
130438
  const store = new MissionStore(join51(root, ".agent-valley/missions"));
@@ -130269,9 +130440,10 @@ async function runOrder(goal, options, root = process.cwd()) {
130269
130440
  const unlock = await store.lock(id);
130270
130441
  const abortController = new AbortController;
130271
130442
  const interrupt = () => abortController.abort(new MissionPause("Operator stopped the order. Its checks and worktree were retained; repair any interrupted effects before resuming with --retry.", "interrupted"));
130443
+ const terminate = () => options.service ? abortController.abort(serviceShutdownPause()) : interrupt();
130272
130444
  const runtime = new ChiefRuntime(store, abortController.signal, (stage, persona) => console.log(`[${stage}] ${persona.name} (${persona.agentType})`));
130273
130445
  process.once("SIGINT", interrupt);
130274
- process.once("SIGTERM", interrupt);
130446
+ process.once("SIGTERM", terminate);
130275
130447
  let mission;
130276
130448
  let capture;
130277
130449
  let reportSaved = false;
@@ -130442,12 +130614,19 @@ Resume: bun av order --resume ${id}`);
130442
130614
  } finally {
130443
130615
  clearTimeout(deadlineTimer);
130444
130616
  process.removeListener("SIGINT", interrupt);
130445
- process.removeListener("SIGTERM", interrupt);
130617
+ process.removeListener("SIGTERM", terminate);
130446
130618
  try {
130447
130619
  try {
130448
130620
  await finishCapture();
130449
130621
  } finally {
130450
- await runtime.close();
130622
+ try {
130623
+ await runtime.close();
130624
+ } finally {
130625
+ if (mission && isServiceShutdown(abortController.signal)) {
130626
+ recordServiceShutdown(mission);
130627
+ await store.save(mission);
130628
+ }
130629
+ }
130451
130630
  }
130452
130631
  } finally {
130453
130632
  await unlock();
@@ -130502,7 +130681,7 @@ async function dispatchOrder(goal, options, root = process.cwd(), dependencies =
130502
130681
  }
130503
130682
  function registerChiefCommands(program) {
130504
130683
  registerContinuousCommands(program);
130505
- program.command("order [goal]").description("Give the Chief Director a goal; continuously select, execute, review and verify improvements").option("--once", "Stop after one verified goal instead of continuing improvements").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check (defaults to av.yaml)").option("--deliver <branch>", "Commit and push only verified, reviewed work to the selected source branch").option("--delivery-paths <json>", "JSON array of exact product files allowed for code delivery").option("--delivery-message <text>", "Commit message for the approved delivery, including required repository trailers").option("--delivery-remote <name>", "Configured Git remote for code delivery (default origin)").option("--actor <type>", "Chief Director CLI (default: saved actor.type, otherwise an authenticated CLI)").option("--model <id>", "Chief Director model (default: actor.model from config, otherwise the CLI default)").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Use a configured YAML Actor roster instead of generating goal-specific Actors").addOption(new Option("--agent <type>", "Legacy alias for --actor").hideHelp()).addOption(new Option("--chief <id>", "Legacy alias for --director").hideHelp()).addOption(new Option("--personas <file>", "Legacy alias for --actors").hideHelp()).option("--oma", "Require OMA completion receipts for workers (installed skill selection is automatic)").option("--timeout <seconds>", "Timeout per actor/check (default 600 or actor.timeout)").option("--repairs <count>", "Repair limit per task/final review (default 2)").option("--rounds <count>", "Chief Director recovery decision limit, preserved on resume (default 8, maximum 50)").option("--parallel <count>", "Independent Actor concurrency (default 3, maximum 8)").option("--runs <count>", "Actor call limit per goal/decision; may be increased on saved checkpoint resume (default 200)").option("--duration <seconds>", "Wall-time limit per goal/decision; may be increased on resume (default 86400)").option("--cost <usd>", "Configured-price estimated cost limit; unknown cost pauses further calls").option("--account-run <run-id>", "Reconcile a finished run whose usage/cost was lost").option("--account-cost <usd>", "Operator-observed USD cost for --account-run; stored separately from native usage").option("--retry", "Resume after repairing a blocker; retain prior evidence and spent budget").option("--resolve-effect <task-id>", "Reconcile an interrupted external action before resuming").option("--effect-result <result>", "External destination inspection result: completed or not-applied").option("--no-supervise", "With --once, run directly without worker crash restart or observation polling").addOption(new Option("--worker", "Internal supervised worker").hideHelp()).addOption(new Option("--mission-id <id>", "Internal mission identity").hideHelp()).addOption(new Option("--baseline-workspace <path>", "Internal accepted operation snapshot").hideHelp()).addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).addOption(new Option("--native-model", "Internal pinned Chief native model default").hideHelp()).option("--resume <id>", "Resume the saved continuing order or single mission with its original contract").action(async (goal, options) => {
130684
+ program.command("order [goal]").description("Give the Chief Director a goal; continuously select, execute, review and verify improvements").option("--once", "Stop after one verified goal instead of continuing improvements").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check (defaults to av.yaml)").option("--deliver <branch>", "Commit and push only verified, reviewed work to the selected source branch").option("--delivery-paths <json>", "JSON array of exact product files allowed for code delivery").option("--delivery-message <text>", "Commit message for the approved delivery, including required repository trailers").option("--delivery-remote <name>", "Configured Git remote for code delivery (default origin)").option("--delivery-skip-pre-push", "Authorize git push --no-verify for this delivery; commit hooks remain enabled").option("--actor <type>", "Chief Director CLI (default: saved actor.type, otherwise an authenticated CLI)").option("--model <id>", "Chief Director model (default: actor.model from config, otherwise the CLI default)").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Use a configured YAML Actor roster instead of generating goal-specific Actors").addOption(new Option("--agent <type>", "Legacy alias for --actor").hideHelp()).addOption(new Option("--chief <id>", "Legacy alias for --director").hideHelp()).addOption(new Option("--personas <file>", "Legacy alias for --actors").hideHelp()).option("--oma", "Require OMA completion receipts for workers (installed skill selection is automatic)").option("--timeout <seconds>", "Timeout per actor/check (default 600 or actor.timeout)").option("--repairs <count>", "Repair limit per task/final review (default 2)").option("--rounds <count>", "Chief Director recovery decision limit, preserved on resume (default 8, maximum 50)").option("--parallel <count>", "Independent Actor concurrency (default 3, maximum 8)").option("--runs <count>", "Actor call limit per goal/decision; may be increased on saved checkpoint resume (default 200)").option("--duration <seconds>", "Wall-time limit per goal/decision; may be increased on resume (default 86400)").option("--cost <usd>", "Configured-price estimated cost limit; unknown cost pauses further calls").option("--account-run <run-id>", "Reconcile a finished run whose usage/cost was lost").option("--account-cost <usd>", "Operator-observed USD cost for --account-run; stored separately from native usage").option("--retry", "Resume after repairing a blocker; retain prior evidence and spent budget").option("--resolve-effect <task-id>", "Reconcile an interrupted external action before resuming").option("--effect-result <result>", "External destination inspection result: completed or not-applied").option("--no-supervise", "With --once, run directly without worker crash restart or observation polling").option("--service", "Resume after OS service SIGTERM within saved limits; SIGINT still cancels").addOption(new Option("--worker", "Internal supervised worker").hideHelp()).addOption(new Option("--mission-id <id>", "Internal mission identity").hideHelp()).addOption(new Option("--baseline-workspace <path>", "Internal accepted operation snapshot").hideHelp()).addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).addOption(new Option("--native-model", "Internal pinned Chief native model default").hideHelp()).option("--resume <id>", "Resume the saved continuing order or single mission with its original contract").action(async (goal, options) => {
130506
130685
  const result = await dispatchOrder(goal, options);
130507
130686
  if ("phase" in result) {
130508
130687
  console.log(`Order ${result.id}: ${result.phase}; ${result.completedCycles} verified improvements.`);
@@ -130515,9 +130694,11 @@ function registerChiefCommands(program) {
130515
130694
  process.exitCode = orderExitCode(result);
130516
130695
  }
130517
130696
  });
130518
- const missions = program.command("missions").description("List saved Chief Director orders and their workspaces").option("--watch", "Resume due or interrupted orders from their saved checkpoints").action(async (options) => {
130697
+ const missions = program.command("missions").description("List saved Chief Director orders and their workspaces").option("--watch", "Resume due or interrupted orders from their saved checkpoints").option("--service", "Treat watcher SIGTERM as recoverable service shutdown; requires --watch").action(async (options) => {
130698
+ if (options.service && !options.watch)
130699
+ throw new Error("Use --service with av missions --watch.");
130519
130700
  if (options.watch) {
130520
- await watchOrders(process.cwd());
130701
+ await watchOrders(process.cwd(), { service: options.service });
130521
130702
  return;
130522
130703
  }
130523
130704
  const missions = await new MissionStore(join51(process.cwd(), ".agent-valley/missions")).list();
@@ -7083,6 +7083,7 @@ var init_contracts = __esm(() => {
7083
7083
  "unknown-effect",
7084
7084
  "budget",
7085
7085
  "interrupted",
7086
+ "service-shutdown",
7086
7087
  "chief-wait",
7087
7088
  "chief-unavailable",
7088
7089
  "integrity"
@@ -7256,7 +7257,7 @@ function recordPause(mission, pause) {
7256
7257
  state.failureKind = pause.kind;
7257
7258
  if (pause.nextRunAt)
7258
7259
  state.nextRunAt = pause.nextRunAt;
7259
- else
7260
+ else if (pause.kind !== "service-shutdown")
7260
7261
  delete state.nextRunAt;
7261
7262
  mission.status = pause.nextRunAt ? "waiting" : "paused";
7262
7263
  mission.error = pause.message;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-valley",
3
- "version": "4.1.0",
3
+ "version": "4.2.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=26.10.0",