@fro.bot/systematic 3.22.0 → 3.22.2

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/index.js CHANGED
@@ -754,10 +754,12 @@ import { createHash } from "crypto";
754
754
  import fs6 from "fs";
755
755
  import path5 from "path";
756
756
  var DEFAULT_LIMITS = {
757
- maxCommandOutputBytes: 1048576,
757
+ maxCommandOutputBytes: 8388608,
758
758
  maxCommandTimeoutMs: 5000,
759
- maxFiles: 4096,
760
- maxTotalFileBytes: 16777216,
759
+ maxFiles: 20000,
760
+ maxRemoteCommandOutputBytes: 1048576,
761
+ maxRemoteItems: 4096,
762
+ maxTotalFileBytes: 134217728,
761
763
  maxPathBytes: 4096
762
764
  };
763
765
  var UNTRACKED_FILES_ARGS = [
@@ -836,6 +838,8 @@ function mergeLimits(input) {
836
838
  maxCommandOutputBytes: input?.maxCommandOutputBytes ?? DEFAULT_LIMITS.maxCommandOutputBytes,
837
839
  maxCommandTimeoutMs: input?.maxCommandTimeoutMs ?? DEFAULT_LIMITS.maxCommandTimeoutMs,
838
840
  maxFiles: input?.maxFiles ?? DEFAULT_LIMITS.maxFiles,
841
+ maxRemoteCommandOutputBytes: input?.maxRemoteCommandOutputBytes ?? DEFAULT_LIMITS.maxRemoteCommandOutputBytes,
842
+ maxRemoteItems: input?.maxRemoteItems ?? DEFAULT_LIMITS.maxRemoteItems,
839
843
  maxTotalFileBytes: input?.maxTotalFileBytes ?? DEFAULT_LIMITS.maxTotalFileBytes,
840
844
  maxPathBytes: input?.maxPathBytes ?? DEFAULT_LIMITS.maxPathBytes
841
845
  };
@@ -1198,14 +1202,14 @@ function readCommitClosure(runner, context, limits) {
1198
1202
  function runRemoteCommand(runner, executable, args2, root, limits) {
1199
1203
  let result;
1200
1204
  try {
1201
- result = runner(executable, args2, root, limits.maxCommandOutputBytes, limits.maxCommandTimeoutMs);
1205
+ result = runner(executable, args2, root, limits.maxRemoteCommandOutputBytes, limits.maxCommandTimeoutMs);
1202
1206
  } catch {
1203
1207
  return { status: "error", reasonCode: "remote-command-failed" };
1204
1208
  }
1205
1209
  if (result.timedOut) {
1206
1210
  return { status: "error", reasonCode: "command-timeout" };
1207
1211
  }
1208
- if (outputBytes(result.stdout) > limits.maxCommandOutputBytes || outputBytes(result.stderr) > limits.maxCommandOutputBytes) {
1212
+ if (outputBytes(result.stdout) > limits.maxRemoteCommandOutputBytes || outputBytes(result.stderr) > limits.maxRemoteCommandOutputBytes) {
1209
1213
  return { status: "error", reasonCode: "remote-command-output-limit" };
1210
1214
  }
1211
1215
  if (result.status !== 0) {
@@ -1250,7 +1254,7 @@ function parsePullRequest(value, limits) {
1250
1254
  const number = record.number;
1251
1255
  const state = remoteState(record.state);
1252
1256
  const headRefOid = record.headRefOid;
1253
- if (typeof number !== "number" || !Number.isSafeInteger(number) || number <= 0 || state === undefined || typeof headRefOid !== "string" || !isHexRevision(headRefOid) || Object.keys(record).length > limits.maxFiles) {
1257
+ if (typeof number !== "number" || !Number.isSafeInteger(number) || number <= 0 || state === undefined || typeof headRefOid !== "string" || !isHexRevision(headRefOid) || Object.keys(record).length > limits.maxRemoteItems) {
1254
1258
  return { status: "error", reasonCode: "remote-missing-field" };
1255
1259
  }
1256
1260
  return {
@@ -1273,7 +1277,7 @@ function reviewState(value) {
1273
1277
  return;
1274
1278
  }
1275
1279
  function checkState(value, limits) {
1276
- if (!Array.isArray(value) || value.length === 0 || value.length > limits.maxFiles)
1280
+ if (!Array.isArray(value) || value.length === 0 || value.length > limits.maxRemoteItems)
1277
1281
  return;
1278
1282
  let pending = false;
1279
1283
  let failed = false;
@@ -3997,7 +4001,7 @@ import { randomBytes as randomBytes3 } from "crypto";
3997
4001
  import fs7 from "fs";
3998
4002
  import { fileURLToPath } from "url";
3999
4003
 
4000
- // node_modules/.bun/web-tree-sitter@0.27.0/node_modules/web-tree-sitter/web-tree-sitter.js
4004
+ // node_modules/.bun/web-tree-sitter@0.27.1/node_modules/web-tree-sitter/web-tree-sitter.js
4001
4005
  var __defProp = Object.defineProperty;
4002
4006
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4003
4007
  var Edit = class {
@@ -10377,6 +10381,23 @@ function observerReadbackFailedCause(reasonCode, site = "refresh-readback") {
10377
10381
  timedOut: reasonCode === "command-timeout"
10378
10382
  };
10379
10383
  }
10384
+ function hookCause(site, kind, reasonCode) {
10385
+ return {
10386
+ site,
10387
+ kind,
10388
+ ...reasonCode !== undefined ? { reasonCode } : {},
10389
+ timedOut: reasonCode === "command-timeout"
10390
+ };
10391
+ }
10392
+ function beforeCause(kind, reasonCode) {
10393
+ return hookCause("tool-before", kind, reasonCode);
10394
+ }
10395
+ function afterCause(kind, reasonCode) {
10396
+ return hookCause("tool-after", kind, reasonCode);
10397
+ }
10398
+ function afterFailure(kind, reasonCode) {
10399
+ return { status: "unavailable", cause: afterCause(kind, reasonCode) };
10400
+ }
10380
10401
  function remoteFailureReason(result) {
10381
10402
  if (result?.status === "missing-resource")
10382
10403
  return "missing-resource";
@@ -10472,20 +10493,21 @@ function parseHostOutput(output, options) {
10472
10493
  metadata: output.metadata
10473
10494
  };
10474
10495
  }
10496
+ var GUARDED_SKILL_ALIASES = new Map([
10497
+ ["ce:work", "ce-work"],
10498
+ ["systematic:ce:work", "ce-work"],
10499
+ ["git-commit", "git-commit"],
10500
+ ["systematic:git-commit", "git-commit"],
10501
+ ["git-commit-push-pr", "git-commit-push-pr"],
10502
+ ["systematic:git-commit-push-pr", "git-commit-push-pr"]
10503
+ ]);
10475
10504
  function normalizeSkill(tool, args2) {
10476
10505
  if (tool !== "systematic_skill" && tool !== "skill")
10477
10506
  return;
10478
10507
  if (!isRecord7(args2) || !boundedString(args2.name, MAX_SKILL_LENGTH)) {
10479
10508
  return;
10480
10509
  }
10481
- const names = {
10482
- "ce:work": "ce-work",
10483
- "git-commit": "git-commit",
10484
- "systematic:git-commit": "git-commit",
10485
- "git-commit-push-pr": "git-commit-push-pr",
10486
- "systematic:git-commit-push-pr": "git-commit-push-pr"
10487
- };
10488
- return names[args2.name] ?? "ce-work";
10510
+ return GUARDED_SKILL_ALIASES.get(args2.name);
10489
10511
  }
10490
10512
  function trustedSkillPolicy(skill, additional = []) {
10491
10513
  const requiredOperations = [
@@ -11088,10 +11110,11 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11088
11110
  const blockedQuestionCalls = new Map;
11089
11111
  const consumedQuestionTargets = new Set;
11090
11112
  let firstUnavailableCause;
11113
+ let pendingUnavailableCause;
11091
11114
  let seedDeferralRecord;
11092
11115
  let unitStartGeneration = 0;
11093
11116
  function startFreshUnit(input, policy) {
11094
- const result = guard.startUnit(input, policy);
11117
+ const result = requireGuard().startUnit(input, policy);
11095
11118
  if (result.status === "started") {
11096
11119
  unitStartGeneration += 1;
11097
11120
  firstUnavailableCause = undefined;
@@ -11101,7 +11124,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11101
11124
  }
11102
11125
  function recordUnavailable(target, cause) {
11103
11126
  const result = target.setMode({ mode: "unavailable" });
11104
- if (cause && result.status === "changed" && !firstUnavailableCause) {
11127
+ if (result.status === "changed" && !firstUnavailableCause) {
11105
11128
  firstUnavailableCause = cause;
11106
11129
  }
11107
11130
  }
@@ -11154,7 +11177,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11154
11177
  const parentObserver = options.observer;
11155
11178
  if (!parentObserver)
11156
11179
  return { status: "fatal" };
11157
- const pinnedTargetIdentity = guard.status().unit?.pinnedOperationTargetIdentity;
11180
+ const pinnedTargetIdentity = requireGuard().status().unit?.pinnedOperationTargetIdentity;
11158
11181
  if (pinnedTargetIdentity === undefined || pinnedTargetIdentity === options.workspaceIdentity) {
11159
11182
  return {
11160
11183
  status: "ok",
@@ -11195,7 +11218,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11195
11218
  };
11196
11219
  }
11197
11220
  function questionResource(target) {
11198
- const status = guard.status();
11221
+ const status = requireGuard().status();
11199
11222
  return `workflow/${target}/${status.unit?.unitId ?? status.epoch?.epochId ?? "unknown"}`;
11200
11223
  }
11201
11224
  function questionProjection() {
@@ -11446,16 +11469,26 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11446
11469
  }
11447
11470
  function publishUnavailable(cause, reusableLedger) {
11448
11471
  ledger = reusableLedger ?? mintLedger();
11449
- guard = createGuard(ledger);
11450
- if (options.config.mode !== "disabled") {
11451
- recordUnavailable(guard, cause);
11452
- }
11472
+ const published = createGuard(ledger);
11473
+ guard = published;
11474
+ if (options.config.mode !== "disabled")
11475
+ recordUnavailable(published, cause);
11476
+ pendingUnavailableCause = undefined;
11453
11477
  initialized = true;
11454
11478
  }
11479
+ function commitPendingUnavailable() {
11480
+ const cause = pendingUnavailableCause;
11481
+ pendingUnavailableCause = undefined;
11482
+ if (cause && options.config.mode !== "disabled") {
11483
+ recordUnavailable(requireGuard(), cause);
11484
+ retryableEmptyHistory = false;
11485
+ }
11486
+ }
11455
11487
  function publishFresh(reusableLedger) {
11456
11488
  ledger = reusableLedger ?? mintLedger();
11457
11489
  guard = createGuard(ledger);
11458
11490
  firstUnavailableCause = undefined;
11491
+ commitPendingUnavailable();
11459
11492
  initialized = true;
11460
11493
  }
11461
11494
  function ensureSynchronousRuntime() {
@@ -11542,6 +11575,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11542
11575
  ledger = recoveredLedger;
11543
11576
  guard = recoveredGuard;
11544
11577
  firstUnavailableCause = undefined;
11578
+ commitPendingUnavailable();
11545
11579
  initialized = true;
11546
11580
  return;
11547
11581
  }
@@ -11585,6 +11619,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11585
11619
  publishFresh(reusableLedger);
11586
11620
  }
11587
11621
  async function initializeSession(sessionID, allowFresh) {
11622
+ try {
11623
+ await initializeSessionSteps(sessionID, allowFresh);
11624
+ } catch {
11625
+ retryableEmptyHistory = false;
11626
+ publishUnavailable(initializationCause("initialization-threw"));
11627
+ }
11628
+ }
11629
+ async function initializeSessionSteps(sessionID, allowFresh) {
11588
11630
  const reader = options.hostReadback?.readSessionPartsStrict ?? options.hostReadback?.readSessionParts;
11589
11631
  if (!reader) {
11590
11632
  publishFresh();
@@ -11640,30 +11682,30 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11640
11682
  const rollupKey = `${host.sessionID}:${host.callID}:${childSessionID}`;
11641
11683
  if (rolledUpChildren.has(rollupKey))
11642
11684
  return;
11643
- const parentBefore = guard.currentOperationContext();
11685
+ const parentBefore = requireGuard().currentOperationContext();
11644
11686
  const children = await options.hostReadback.listChildren(host.sessionID);
11645
11687
  if (!children.some((child) => child.sessionId === childSessionID && child.parentID === host.sessionID)) {
11646
- markUnavailable();
11688
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
11647
11689
  return;
11648
11690
  }
11649
11691
  let parts2;
11650
11692
  try {
11651
11693
  parts2 = await options.hostReadback.readSessionParts(childSessionID);
11652
11694
  } catch {
11653
- markUnavailable();
11695
+ markUnavailable(afterCause("history-read-failed"));
11654
11696
  return;
11655
11697
  }
11656
11698
  const classification = classifyMarkersFromParts(parts2);
11657
11699
  if (classification.kind === "foreign-empty")
11658
11700
  return;
11659
11701
  if (classification.kind === "ambiguous") {
11660
- markUnavailable();
11702
+ markUnavailable(afterCause("markers-ambiguous"));
11661
11703
  return;
11662
11704
  }
11663
11705
  const ownMarkers = classification.markers;
11664
11706
  const seed = extractReceiptReadbackSeed(ownMarkers);
11665
11707
  if (seed.status !== "ready") {
11666
- markUnavailable();
11708
+ markUnavailable(afterCause("recovery-rejected"));
11667
11709
  return;
11668
11710
  }
11669
11711
  const childLedger = createReceiptLedger({
@@ -11672,18 +11714,18 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11672
11714
  sessionSalt: seed.sessionSalt
11673
11715
  });
11674
11716
  if (!seedAgrees(childLedger, seed)) {
11675
- markUnavailable();
11717
+ markUnavailable(afterCause("recovery-rejected"));
11676
11718
  return;
11677
11719
  }
11678
11720
  const recovered = childLedger.recoverReadback(ownMarkers);
11679
11721
  if (recovered.status === "rejected") {
11680
- markUnavailable();
11722
+ markUnavailable(afterCause("recovery-rejected"));
11681
11723
  return;
11682
11724
  }
11683
11725
  try {
11684
11726
  await options.observer?.snapshot();
11685
11727
  } catch {}
11686
- const currentStatus = guard.status();
11728
+ const currentStatus = requireGuard().status();
11687
11729
  if (!currentStatus.epoch || !currentStatus.unit)
11688
11730
  return;
11689
11731
  const expectedWorkspace = childLedger.digestIdentity("workspace", parentBefore.workspaceIdentity);
@@ -11694,49 +11736,53 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11694
11736
  if (!localOperation(operation))
11695
11737
  continue;
11696
11738
  if (childReceipt.canonical.workspaceDigest !== expectedWorkspace) {
11697
- markUnavailable();
11739
+ markUnavailable(afterCause("operation-observation-rejected"));
11698
11740
  return;
11699
11741
  }
11700
11742
  const targetIdentity = childReceipt.canonical.operationTargetIdentity;
11701
11743
  if (!targetIdentity) {
11702
- markUnavailable();
11744
+ markUnavailable(afterCause("operation-input-invalid"));
11703
11745
  return;
11704
11746
  }
11705
11747
  if (batchTargetIdentity !== undefined && targetIdentity !== batchTargetIdentity) {
11706
- markUnavailable();
11748
+ markUnavailable(afterCause("operation-target-mismatch"));
11707
11749
  return;
11708
11750
  }
11709
11751
  batchTargetIdentity = targetIdentity;
11710
11752
  const registration = operationObserverRegistration(targetIdentity);
11711
11753
  if (!registration || !options.observer) {
11712
- markUnavailable();
11754
+ markUnavailable(afterCause("operation-input-invalid"));
11713
11755
  return;
11714
11756
  }
11715
11757
  let validation;
11716
11758
  try {
11717
11759
  validation = options.observer.validateRegisteredWorktree(registration.targetRoot);
11718
11760
  } catch {
11719
- markUnavailable();
11761
+ markUnavailable(afterCause("operation-input-invalid"));
11720
11762
  return;
11721
11763
  }
11722
11764
  if (validation.status === "error" || validation.targetRoot !== registration.targetRoot || registeredWorktreeIdentity(validation) !== registration.registeredWorktreeIdentity || registration.observer.targetDigest !== targetIdentity) {
11723
- markUnavailable();
11765
+ markUnavailable(afterCause("operation-input-invalid", validation.status === "error" ? validation.reasonCode : undefined));
11724
11766
  return;
11725
11767
  }
11726
11768
  let targetResult;
11727
11769
  try {
11728
11770
  targetResult = await registration.observer.snapshot();
11729
11771
  } catch {
11730
- markUnavailable();
11772
+ markUnavailable(afterCause("local-snapshot-error"));
11731
11773
  return;
11732
11774
  }
11733
- if (targetResult.status === "unavailable" || targetResult.snapshot.targetDigest !== targetIdentity) {
11734
- markUnavailable();
11775
+ if (targetResult.status === "unavailable") {
11776
+ markUnavailable(afterCause("local-snapshot-unavailable", targetResult.reasonCode));
11777
+ return;
11778
+ }
11779
+ if (targetResult.snapshot.targetDigest !== targetIdentity) {
11780
+ markUnavailable(afterCause("operation-target-mismatch"));
11735
11781
  return;
11736
11782
  }
11737
11783
  const recoveredContext = recoveredOperationContexts.get(childReceipt.canonical.receiptId);
11738
11784
  if (recoveredContext && recoveredContext.targetIdentity !== targetIdentity || targetIdentity !== options.observer.targetDigest && !recoveredContext) {
11739
- markUnavailable();
11785
+ markUnavailable(afterCause("operation-target-mismatch"));
11740
11786
  return;
11741
11787
  }
11742
11788
  const expectedRepository = childLedger.digestIdentity("repository", targetResult.snapshot.repositoryRevisionDigest);
@@ -11755,7 +11801,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11755
11801
  const childReceipt = candidate.receipt;
11756
11802
  const targetSnapshot = candidate.snapshot;
11757
11803
  const operation = childReceipt.canonical.operation;
11758
- const parentContext = guard.currentOperationContext();
11804
+ const parentContext = requireGuard().currentOperationContext();
11759
11805
  const beforeSnapshot = candidate.before;
11760
11806
  const callID = `task-${host.callID}-${childReceipt.canonical.receiptId}`;
11761
11807
  const observation = {
@@ -11782,7 +11828,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11782
11828
  noOp: false
11783
11829
  }
11784
11830
  };
11785
- const result = await guard.observeTrustedRecoveredOperation(observation);
11831
+ const result = await requireGuard().observeTrustedRecoveredOperation(observation);
11786
11832
  if (result.status === "accepted") {
11787
11833
  const receipt = receiptForOperation(callID, operation);
11788
11834
  if (receipt)
@@ -11797,7 +11843,20 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11797
11843
  function markUnavailable(cause) {
11798
11844
  if (options.config.mode === "disabled")
11799
11845
  return;
11800
- recordUnavailable(guard, cause);
11846
+ const published = guard;
11847
+ if (!published) {
11848
+ pendingUnavailableCause ??= cause;
11849
+ return;
11850
+ }
11851
+ recordUnavailable(published, cause);
11852
+ }
11853
+ function guardPublished() {
11854
+ return guard !== undefined;
11855
+ }
11856
+ function requireGuard() {
11857
+ if (!guard)
11858
+ throw new Error("workflow guard used before it was published");
11859
+ return guard;
11801
11860
  }
11802
11861
  function bindCall(callDigest, kind, fingerprint) {
11803
11862
  const existing = callBindings.get(callDigest);
@@ -11808,12 +11867,12 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11808
11867
  if (existing.kind === kind && existing.fingerprint === fingerprint) {
11809
11868
  return "duplicate";
11810
11869
  }
11811
- markUnavailable();
11870
+ markUnavailable(beforeCause("call-lifecycle-mismatch"));
11812
11871
  return "conflict";
11813
11872
  }
11814
11873
  function abandonPending() {
11815
11874
  for (const [callDigest, pending] of pendingCompletes) {
11816
- guard.abandonTransition({
11875
+ requireGuard().abandonTransition({
11817
11876
  callId: pending.callID,
11818
11877
  transitionId: pending.transitionId
11819
11878
  });
@@ -11831,7 +11890,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11831
11890
  }
11832
11891
  }
11833
11892
  function readStatus() {
11834
- return guard.status();
11893
+ return guard ? guard.status() : unavailableWorkflowStatus();
11835
11894
  }
11836
11895
  function control(sessionID, input) {
11837
11896
  if (!isRecord7(input) || input.mode !== "disabled") {
@@ -11854,7 +11913,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11854
11913
  return questionUnavailableResult();
11855
11914
  if (pending.requestID && questionProjection().status === "attested") {
11856
11915
  if (consumeQuestion(pending)) {
11857
- guard.setMode({ mode: "disabled" });
11916
+ requireGuard().setMode({ mode: "disabled" });
11858
11917
  return {
11859
11918
  title: "Workflow guard disabled",
11860
11919
  output: JSON.stringify({ status: "disabled" })
@@ -11873,12 +11932,12 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11873
11932
  };
11874
11933
  }
11875
11934
  function observerReadbackApplies() {
11876
- return options.observer !== undefined && guard.status().epoch !== null;
11935
+ return options.observer !== undefined && requireGuard().status().epoch !== null;
11877
11936
  }
11878
11937
  function skippedWithRemoteTail(head) {
11879
11938
  return [
11880
11939
  unconfirmedReadback(head),
11881
- ...guard.status().satisfiedOperations.filter(remoteOperation).map((operation) => unconfirmedReadback(operation))
11940
+ ...requireGuard().status().satisfiedOperations.filter(remoteOperation).map((operation) => unconfirmedReadback(operation))
11882
11941
  ];
11883
11942
  }
11884
11943
  async function refreshReadback() {
@@ -11903,7 +11962,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11903
11962
  return applyReadbackAndProbeRemote(effective, read.value);
11904
11963
  }
11905
11964
  async function applyReadbackAndProbeRemote(effective, snapshot) {
11906
- const observed = guard.observeReadback({
11965
+ const observed = requireGuard().observeReadback({
11907
11966
  workspaceIdentity: options.workspaceIdentity,
11908
11967
  repositoryIdentity: snapshot.repositoryRevisionDigest,
11909
11968
  worktreeIdentity: snapshot.worktreeRevisionDigest,
@@ -11920,7 +11979,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11920
11979
  return remote.unconfirmed;
11921
11980
  }
11922
11981
  async function refreshRemoteReadbacks(observer, local) {
11923
- const remoteOperations = guard.status().satisfiedOperations.filter(remoteOperation);
11982
+ const remoteOperations = requireGuard().status().satisfiedOperations.filter(remoteOperation);
11924
11983
  if (remoteOperations.length === 0)
11925
11984
  return { kind: "ok", unconfirmed: [] };
11926
11985
  const remoteSnapshot = observer.remoteSnapshot;
@@ -11940,14 +11999,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
11940
11999
  reasonCode: remoteFailureReason(result)
11941
12000
  };
11942
12001
  }
11943
- const observed = guard.observeReadback(remoteReadbackInput(operation, local, options.workspaceIdentity, result.snapshot));
12002
+ const observed = requireGuard().observeReadback(remoteReadbackInput(operation, local, options.workspaceIdentity, result.snapshot));
11944
12003
  if (observed.status === "rejected")
11945
12004
  return { kind: "fatal", unconfirmed };
11946
12005
  }
11947
12006
  return { kind: "ok", unconfirmed };
11948
12007
  }
11949
12008
  function currentMarkerSource() {
11950
- const status = guard.status();
12009
+ const status = requireGuard().status();
11951
12010
  const statusDigest = ledger.digestIdentity("resource", JSON.stringify({
11952
12011
  state: status.state,
11953
12012
  reasonCode: status.reasonCode,
@@ -12084,7 +12143,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12084
12143
  };
12085
12144
  }
12086
12145
  function writeNoEpochBlockedResult(callDigest, output, target) {
12087
- const current = guard.status();
12146
+ const current = requireGuard().status();
12088
12147
  const terminal = !current.epoch ? {
12089
12148
  target,
12090
12149
  status: "rejected",
@@ -12150,7 +12209,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12150
12209
  }
12151
12210
  const challenge = challengeForTransition(host.sessionID, target);
12152
12211
  if (!challenge) {
12153
- markUnavailable();
12212
+ markUnavailable(hookCause("tool-before", "call-lifecycle-mismatch"));
12154
12213
  return true;
12155
12214
  }
12156
12215
  if (options.config.mode === "protected") {
@@ -12174,10 +12233,13 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12174
12233
  }
12175
12234
  return;
12176
12235
  }
12177
- const status = guard.status();
12236
+ const status = requireGuard().status();
12178
12237
  if (gateCompleteWithQuestion(host, target, callDigest, status))
12179
12238
  return;
12180
- const prepared = guard.prepareTransition({ callId: host.callID, target });
12239
+ const prepared = requireGuard().prepareTransition({
12240
+ callId: host.callID,
12241
+ target
12242
+ });
12181
12243
  if (prepared.status === "allowed") {
12182
12244
  pendingCompletes.set(callDigest, {
12183
12245
  callID: host.callID,
@@ -12223,7 +12285,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12223
12285
  const { parentTargetRoot, sessionLocation } = effectiveTargetContext();
12224
12286
  const fingerprint = argsFingerprint(ledger, host.tool, args2, sessionLocation);
12225
12287
  if (!fingerprint) {
12226
- markUnavailable();
12288
+ markUnavailable(beforeCause("operation-input-invalid"));
12227
12289
  return;
12228
12290
  }
12229
12291
  const callDigest = digestCall(ledger, host.callID);
@@ -12236,24 +12298,24 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12236
12298
  validateRegisteredWorktree: options.observer.validateRegisteredWorktree
12237
12299
  });
12238
12300
  if (target.status === "unavailable") {
12239
- markUnavailable();
12301
+ markUnavailable(beforeCause("operation-input-invalid", target.reasonCode));
12240
12302
  return;
12241
12303
  }
12242
12304
  let registeredTarget;
12243
12305
  try {
12244
12306
  registeredTarget = options.observer.validateRegisteredWorktree(target.targetRoot);
12245
12307
  } catch {
12246
- markUnavailable();
12308
+ markUnavailable(beforeCause("operation-input-invalid"));
12247
12309
  return;
12248
12310
  }
12249
12311
  const registeredIdentity = registeredWorktreeIdentity(registeredTarget);
12250
12312
  if (registeredTarget.status !== "ok" || registeredIdentity === undefined || registeredTarget.targetRoot !== target.targetRoot) {
12251
- markUnavailable();
12313
+ markUnavailable(beforeCause("operation-input-invalid", registeredTarget.status === "error" ? registeredTarget.reasonCode : undefined));
12252
12314
  return;
12253
12315
  }
12254
12316
  const canonicalParentTargetRoot = canonicalExistingPath(parentTargetRoot, fs8.realpathSync);
12255
12317
  if (!canonicalParentTargetRoot) {
12256
- markUnavailable();
12318
+ markUnavailable(beforeCause("operation-input-invalid"));
12257
12319
  return;
12258
12320
  }
12259
12321
  const operationObserver = target.targetRoot === canonicalParentTargetRoot ? options.observer : [...operationObservers.values()].find((registration) => registration.targetRoot === target.targetRoot)?.observer ?? (options.createTargetObserver ?? defaultTargetObserver)(target.targetRoot);
@@ -12261,15 +12323,15 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12261
12323
  try {
12262
12324
  result = await operationObserver.snapshot();
12263
12325
  } catch {
12264
- markUnavailable();
12326
+ markUnavailable(beforeCause("local-snapshot-error"));
12265
12327
  return;
12266
12328
  }
12267
12329
  if (result.status === "unavailable") {
12268
- markUnavailable();
12330
+ markUnavailable(beforeCause("local-snapshot-unavailable", result.reasonCode));
12269
12331
  return;
12270
12332
  }
12271
12333
  if (result.snapshot.targetDigest !== operationObserver.targetDigest) {
12272
- markUnavailable();
12334
+ markUnavailable(beforeCause("operation-target-mismatch"));
12273
12335
  return;
12274
12336
  }
12275
12337
  rememberOperationObserver({
@@ -12387,7 +12449,10 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12387
12449
  } catch (error) {
12388
12450
  if (isWorkflowGuardBlockedError(error))
12389
12451
  throw error;
12390
- markUnavailable();
12452
+ markUnavailable(hookCause("tool-before", "hook-threw"));
12453
+ if (options.config.mode === "protected" && !guardPublished()) {
12454
+ throw createWorkflowGuardBlockedError("guard-unavailable");
12455
+ }
12391
12456
  }
12392
12457
  }
12393
12458
  async function seedRemoteScopes(operations) {
@@ -12434,7 +12499,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12434
12499
  return;
12435
12500
  }
12436
12501
  function recordSeedDeferral(operation, reasonCode) {
12437
- if (guard.hasResourceBaseline(operation))
12502
+ if (requireGuard().hasResourceBaseline(operation))
12438
12503
  return;
12439
12504
  const observer = options.observer;
12440
12505
  if (!observer)
@@ -12447,7 +12512,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12447
12512
  });
12448
12513
  }
12449
12514
  function seedDeferralEntries(reset = false) {
12450
- const unitId = guard.status().unit?.unitId;
12515
+ const unitId = requireGuard().status().unit?.unitId;
12451
12516
  if (!unitId)
12452
12517
  return [];
12453
12518
  if (seedDeferralRecord?.unitId === unitId)
@@ -12473,7 +12538,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12473
12538
  const deferred = deferredSeedFor(operation);
12474
12539
  if (!deferred)
12475
12540
  return;
12476
- if (guard.hasResourceBaseline(operation)) {
12541
+ if (requireGuard().hasResourceBaseline(operation)) {
12477
12542
  clearSeedDeferral(operation);
12478
12543
  return;
12479
12544
  }
@@ -12489,12 +12554,12 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12489
12554
  }
12490
12555
  if (before.status !== "available")
12491
12556
  return;
12492
- const observed = guard.observeReadback(deferredBaselineReadback(operation, before.snapshot));
12557
+ const observed = requireGuard().observeReadback(deferredBaselineReadback(operation, before.snapshot));
12493
12558
  if (observed.status !== "rejected")
12494
12559
  clearSeedDeferral(operation);
12495
12560
  }
12496
12561
  function currentInitiator() {
12497
- const current = guard.status();
12562
+ const current = requireGuard().status();
12498
12563
  return current.epoch && current.unit ? {
12499
12564
  epochId: current.epoch.epochId,
12500
12565
  unitId: current.unit.unitId,
@@ -12554,7 +12619,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12554
12619
  timedOut: false
12555
12620
  });
12556
12621
  }
12557
- const observed = guard.observeReadback(remoteReadbackInput(operation, local, options.workspaceIdentity, result.snapshot, operation !== "pr-creation"));
12622
+ const observed = requireGuard().observeReadback(remoteReadbackInput(operation, local, options.workspaceIdentity, result.snapshot, operation !== "pr-creation"));
12558
12623
  if (observed.status === "rejected") {
12559
12624
  return fatalSeed({
12560
12625
  site: "seed-remote-scope",
@@ -12571,8 +12636,9 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12571
12636
  const finalSkill = normalizeSkill(host.tool, host.args);
12572
12637
  const completedSkill = completedSkillCalls.get(callDigest);
12573
12638
  if (completedSkill) {
12574
- if (completedSkill !== finalSkill)
12575
- markUnavailable();
12639
+ if (completedSkill !== finalSkill) {
12640
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12641
+ }
12576
12642
  return;
12577
12643
  }
12578
12644
  const pending = pendingSkills.get(callDigest);
@@ -12580,14 +12646,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12580
12646
  return;
12581
12647
  pendingSkills.delete(callDigest);
12582
12648
  if (!finalSkill || finalSkill !== pending.skill) {
12583
- markUnavailable();
12649
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12584
12650
  return;
12585
12651
  }
12586
12652
  if (!isSuccessfulSkillAfter(output))
12587
12653
  return;
12588
12654
  completedSkillCalls.set(callDigest, pending.skill);
12589
12655
  await activateCompletedSkill(pending.skill);
12590
- const status = guard.status();
12656
+ const status = requireGuard().status();
12591
12657
  if (status.epoch) {
12592
12658
  mergeProgressionMarker(output, projectReceiptProgressionMarker(ledger, {
12593
12659
  target: "epoch",
@@ -12611,14 +12677,14 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12611
12677
  }
12612
12678
  }
12613
12679
  async function activateCompletedSkill(skill) {
12614
- const activation = guard.activate({
12680
+ const activation = requireGuard().activate({
12615
12681
  event: "guarded-skill",
12616
12682
  skill,
12617
12683
  outcome: "success"
12618
12684
  });
12619
12685
  if (activation.status === "activated" || activation.status === "reused" || activation.status === "attached") {
12620
12686
  runtimePolicy = trustedSkillPolicy(skill, options.runtimeRequiredOperations ?? []);
12621
- const status = guard.status();
12687
+ const status = requireGuard().status();
12622
12688
  if (!status.unit || status.unit.status === "completed") {
12623
12689
  startFreshUnit({}, runtimePolicy);
12624
12690
  const cause = await seedRemoteScopes(runtimePolicy.requiredOperations ?? []);
@@ -12632,19 +12698,19 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12632
12698
  const pending = pendingStarts.get(callDigest);
12633
12699
  pendingStarts.delete(callDigest);
12634
12700
  if (!pending) {
12635
- markUnavailable();
12701
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12636
12702
  return;
12637
12703
  }
12638
12704
  const normalized = normalizeStartInput(host.args);
12639
12705
  if (normalized === undefined || JSON.stringify(normalized) !== pending.fingerprint) {
12640
- markUnavailable();
12706
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12641
12707
  return;
12642
12708
  }
12643
12709
  if (!isSuccessfulAfter(output))
12644
12710
  return;
12645
12711
  const result = startFreshUnit(pending.input, runtimePolicy);
12646
12712
  if (result.status === "rejected" && (result.reasonCode === "guard-unavailable" || result.reasonCode === "invalid-configuration")) {
12647
- markUnavailable();
12713
+ markUnavailable(afterCause("unit-start-rejected", result.reasonCode));
12648
12714
  }
12649
12715
  if (result.status === "started") {
12650
12716
  const cause = await seedRemoteScopes(runtimePolicy.requiredOperations ?? []);
@@ -12652,7 +12718,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12652
12718
  markUnavailable(cause);
12653
12719
  }
12654
12720
  if (result.status === "started") {
12655
- const startedStatus = guard.status();
12721
+ const startedStatus = requireGuard().status();
12656
12722
  const epoch = startedStatus.epoch;
12657
12723
  const unit = startedStatus.unit;
12658
12724
  if (!epoch || !unit)
@@ -12674,7 +12740,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12674
12740
  const replay = finalizedCompletes.get(callDigest);
12675
12741
  if (!replay)
12676
12742
  return false;
12677
- guard.finalizeTransition({
12743
+ requireGuard().finalizeTransition({
12678
12744
  callId: replay.callID,
12679
12745
  transitionId: replay.transitionId
12680
12746
  });
@@ -12683,7 +12749,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12683
12749
  function finalizeComplete(callDigest, pending, output, readbacks) {
12684
12750
  pendingCompletes.delete(callDigest);
12685
12751
  if (!isSuccessfulAfter(output)) {
12686
- guard.abandonTransition({
12752
+ requireGuard().abandonTransition({
12687
12753
  callId: pending.callID,
12688
12754
  transitionId: pending.transitionId
12689
12755
  });
@@ -12697,7 +12763,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12697
12763
  });
12698
12764
  return;
12699
12765
  }
12700
- const result = guard.finalizeTransition({
12766
+ const result = requireGuard().finalizeTransition({
12701
12767
  callId: pending.callID,
12702
12768
  transitionId: pending.transitionId,
12703
12769
  ...readbacks ? { readbacks } : {}
@@ -12707,8 +12773,8 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12707
12773
  writeSuccessfulCompletionResult(output, pending.target);
12708
12774
  return;
12709
12775
  }
12710
- markUnavailable();
12711
12776
  const reasonCode = "reasonCode" in result ? result.reasonCode : "guard-unavailable";
12777
+ markUnavailable(afterCause("transition-finalize-rejected", reasonCode));
12712
12778
  const terminal = {
12713
12779
  target: pending.target,
12714
12780
  status: result.status === "waiting" ? "unavailable" : result.status,
@@ -12747,7 +12813,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12747
12813
  if (!expectedTarget)
12748
12814
  return false;
12749
12815
  if (finalTarget !== expectedTarget) {
12750
- markUnavailable();
12816
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12751
12817
  return true;
12752
12818
  }
12753
12819
  if (replay)
@@ -12758,7 +12824,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12758
12824
  }
12759
12825
  function abandonComplete(callDigest, pending, remember) {
12760
12826
  pendingCompletes.delete(callDigest);
12761
- guard.abandonTransition({
12827
+ requireGuard().abandonTransition({
12762
12828
  callId: pending.callID,
12763
12829
  transitionId: pending.transitionId
12764
12830
  });
@@ -12832,7 +12898,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12832
12898
  };
12833
12899
  }
12834
12900
  async function completionRemoteReadbacks(observer) {
12835
- const remoteOperations = guard.status().satisfiedOperations.filter(remoteOperation);
12901
+ const remoteOperations = requireGuard().status().satisfiedOperations.filter(remoteOperation);
12836
12902
  if (remoteOperations.length === 0)
12837
12903
  return { status: "ready", readbacks: [] };
12838
12904
  const remoteSnapshot = observer.remoteSnapshot;
@@ -12857,11 +12923,11 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12857
12923
  status: "unavailable",
12858
12924
  reasonCode: "invalid-transition"
12859
12925
  });
12860
- markUnavailable();
12926
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12861
12927
  writeAbandonedCompletionResult(output, pending.target, "invalid-transition");
12862
12928
  }
12863
12929
  function finishUnreplayableComplete(finalTarget, output) {
12864
- markUnavailable();
12930
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12865
12931
  writeAbandonedCompletionResult(output, finalTarget, "guard-unavailable");
12866
12932
  }
12867
12933
  function finishUnavailableReadback(callDigest, pending, output, reasonCode) {
@@ -12875,7 +12941,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12875
12941
  writeAbandonedCompletionResult(output, pending.target, "finalization-failed");
12876
12942
  }
12877
12943
  function finishReadbackTimeout(callDigest, pending, output) {
12878
- if (guard.status().state === "unavailable") {
12944
+ if (requireGuard().status().state === "unavailable") {
12879
12945
  finishUnavailableReadback(callDigest, pending, output, "command-timeout");
12880
12946
  } else {
12881
12947
  finishRetryableReadback(callDigest, pending, output);
@@ -12936,48 +13002,57 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
12936
13002
  function takePendingOperation(callDigest, host, fingerprint) {
12937
13003
  const pending = pendingOperations.get(callDigest);
12938
13004
  if (!pending) {
12939
- markUnavailable();
13005
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12940
13006
  return;
12941
13007
  }
12942
13008
  pendingOperations.delete(callDigest);
12943
13009
  if (pending.tool !== host.tool || fingerprint === undefined || fingerprint !== pending.argsFingerprint) {
12944
13010
  sealOperation(callDigest, pending, true);
12945
- markUnavailable();
13011
+ markUnavailable(afterCause("call-lifecycle-mismatch"));
12946
13012
  return;
12947
13013
  }
12948
13014
  return pending;
12949
13015
  }
12950
- async function captureAfterOperation(pending) {
12951
- if (!options.observer)
12952
- return;
13016
+ function afterTargetFailure(observer, pending) {
12953
13017
  let validation;
12954
13018
  try {
12955
- validation = options.observer.validateRegisteredWorktree(pending.targetRoot);
13019
+ validation = observer.validateRegisteredWorktree(pending.targetRoot);
12956
13020
  } catch {
12957
- return;
13021
+ return afterFailure("operation-input-invalid");
12958
13022
  }
12959
13023
  if (validation.status === "error" || validation.targetRoot !== pending.targetRoot || registeredWorktreeIdentity(validation) !== pending.registeredWorktreeIdentity) {
12960
- return;
13024
+ return afterFailure("operation-input-invalid", validation.status === "error" ? validation.reasonCode : undefined);
12961
13025
  }
13026
+ return;
13027
+ }
13028
+ async function captureAfterOperation(pending) {
13029
+ if (!options.observer)
13030
+ return afterFailure("operation-input-invalid");
13031
+ const targetFailure = afterTargetFailure(options.observer, pending);
13032
+ if (targetFailure)
13033
+ return targetFailure;
12962
13034
  let result;
12963
13035
  try {
12964
13036
  result = await pending.observer.snapshot();
12965
13037
  } catch {
12966
- return;
13038
+ return afterFailure("local-snapshot-error");
13039
+ }
13040
+ if (result.status === "unavailable") {
13041
+ return afterFailure("local-snapshot-unavailable", result.reasonCode);
12967
13042
  }
12968
- return result.status === "available" && result.snapshot.targetDigest === pending.targetIdentity ? result.snapshot : undefined;
13043
+ return result.snapshot.targetDigest === pending.targetIdentity ? { status: "available", snapshot: result.snapshot } : afterFailure("operation-target-mismatch");
12969
13044
  }
12970
13045
  async function captureRemoteAfter(operation, observer) {
12971
13046
  const remoteSnapshot = observer.remoteSnapshot;
12972
13047
  if (!remoteSnapshot)
12973
- return;
13048
+ return afterFailure("operation-observation-rejected");
12974
13049
  let result;
12975
13050
  try {
12976
13051
  result = await remoteSnapshot(operation, "after");
12977
13052
  } catch {
12978
- return;
13053
+ return afterFailure("operation-observation-rejected");
12979
13054
  }
12980
- return result.status === "available" ? result.snapshot : undefined;
13055
+ return result.status === "available" ? { status: "available", snapshot: result.snapshot } : afterFailure("operation-observation-rejected", remoteFailureReason(result));
12981
13056
  }
12982
13057
  async function readRemoteScope(reader, operation, phase = "after") {
12983
13058
  try {
@@ -13028,12 +13103,12 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13028
13103
  async function classifyLocalObservation(observation) {
13029
13104
  const classify = options.classifier?.classifyOperation;
13030
13105
  if (!classify)
13031
- return { status: "unavailable" };
13106
+ return afterFailure("operation-classifier-unavailable");
13032
13107
  let classification;
13033
13108
  try {
13034
13109
  classification = await classify(observation);
13035
13110
  } catch {
13036
- return { status: "unavailable" };
13111
+ return afterFailure("operation-classifier-unavailable");
13037
13112
  }
13038
13113
  if (!localOperation(classification.category)) {
13039
13114
  if (remoteOperation(classification.category)) {
@@ -13045,7 +13120,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13045
13120
  }
13046
13121
  };
13047
13122
  }
13048
- return classification.category === null ? { status: "deferred" } : { status: "unavailable" };
13123
+ return classification.category === null ? { status: "deferred" } : afterFailure("operation-classifier-unavailable");
13049
13124
  }
13050
13125
  return {
13051
13126
  status: "ready",
@@ -13054,7 +13129,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13054
13129
  }
13055
13130
  async function observeClassifiedOperation(observation) {
13056
13131
  try {
13057
- return await guard.observeOperation(observation);
13132
+ return await requireGuard().observeOperation(observation);
13058
13133
  } catch {
13059
13134
  return;
13060
13135
  }
@@ -13072,16 +13147,17 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13072
13147
  const parsedOutput = parseHostOutput(output);
13073
13148
  if (!parsedOutput) {
13074
13149
  sealOperation(callDigest, pending, true);
13075
- return { status: "unavailable" };
13150
+ return afterFailure("operation-input-invalid");
13076
13151
  }
13077
- const afterSnapshot = await captureAfterOperation(pending);
13152
+ const capture = await captureAfterOperation(pending);
13078
13153
  if (!ownsOperation(pending))
13079
13154
  return sealLostOperation(callDigest, pending);
13080
- if (!afterSnapshot) {
13155
+ if (capture.status === "unavailable") {
13081
13156
  sealOperation(callDigest, pending, true);
13082
- return { status: "unavailable" };
13157
+ return capture;
13083
13158
  }
13084
- const observation = buildOperationObservation(host, pending, afterSnapshot, guard.status(), parsedOutput);
13159
+ const afterSnapshot = capture.snapshot;
13160
+ const observation = buildOperationObservation(host, pending, afterSnapshot, requireGuard().status(), parsedOutput);
13085
13161
  if (!observation) {
13086
13162
  sealOperation(callDigest, pending, true);
13087
13163
  return { status: "ignored" };
@@ -13091,26 +13167,27 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13091
13167
  return sealLostOperation(callDigest, pending);
13092
13168
  if (classification.status !== "ready") {
13093
13169
  sealOperation(callDigest, pending, true);
13094
- return { status: classification.status };
13170
+ return classification;
13095
13171
  }
13096
13172
  let finalObservation = classification.observation;
13097
13173
  if (remoteOperation(finalObservation.operation)) {
13098
- const remoteAfter = await captureRemoteAfter(finalObservation.operation, pending.observer);
13174
+ const remoteCapture = await captureRemoteAfter(finalObservation.operation, pending.observer);
13099
13175
  if (!ownsOperation(pending)) {
13100
13176
  return sealLostOperation(callDigest, pending);
13101
13177
  }
13102
- if (!remoteAfter) {
13178
+ if (remoteCapture.status === "unavailable") {
13103
13179
  sealOperation(callDigest, pending, true);
13104
- return { status: "unavailable" };
13180
+ return remoteCapture;
13105
13181
  }
13106
- const rebuilt = buildOperationObservation(host, pending, afterSnapshot, guard.status(), parsedOutput, finalObservation.operation, remoteAfter);
13182
+ const remoteAfter = remoteCapture.snapshot;
13183
+ const rebuilt = buildOperationObservation(host, pending, afterSnapshot, requireGuard().status(), parsedOutput, finalObservation.operation, remoteAfter);
13107
13184
  if (!rebuilt) {
13108
13185
  sealOperation(callDigest, pending, true);
13109
13186
  return { status: "ignored" };
13110
13187
  }
13111
13188
  finalObservation = rebuilt;
13112
13189
  if (finalObservation.operation === "pr-creation" && pending.remoteBefore?.status === "missing-resource") {
13113
- const seeded = guard.observeReadback({
13190
+ const seeded = requireGuard().observeReadback({
13114
13191
  operation: "pr-creation",
13115
13192
  workspaceIdentity: options.workspaceIdentity,
13116
13193
  repositoryIdentity: afterSnapshot.repositoryRevisionDigest,
@@ -13120,7 +13197,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13120
13197
  });
13121
13198
  if (seeded.status === "rejected") {
13122
13199
  sealOperation(callDigest, pending, true);
13123
- return { status: "unavailable" };
13200
+ return afterFailure("operation-observation-rejected", seeded.reasonCode);
13124
13201
  }
13125
13202
  }
13126
13203
  }
@@ -13129,11 +13206,11 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13129
13206
  const observed = await observeClassifiedOperation(finalObservation);
13130
13207
  if (!observed) {
13131
13208
  sealOperation(callDigest, pending, true);
13132
- return { status: "unavailable" };
13209
+ return afterFailure("operation-observation-rejected");
13133
13210
  }
13134
13211
  sealOperation(callDigest, pending, observed.status !== "accepted");
13135
13212
  if (observed.status === "unavailable") {
13136
- return { status: "unavailable" };
13213
+ return afterFailure("operation-observation-rejected", observed.reasonCode);
13137
13214
  }
13138
13215
  if (observed.status !== "accepted")
13139
13216
  return { status: "ignored" };
@@ -13181,7 +13258,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13181
13258
  return;
13182
13259
  const result = await completeOperationObservation(callDigest, host, pending, output);
13183
13260
  if (result.status === "unavailable") {
13184
- markUnavailable();
13261
+ markUnavailable(result.cause);
13185
13262
  return;
13186
13263
  }
13187
13264
  if (result.status !== "accepted")
@@ -13216,7 +13293,7 @@ function createSessionRuntime(options, operationObservers, recoveredOperationCon
13216
13293
  await finishOperation(host, output);
13217
13294
  }
13218
13295
  } catch {
13219
- markUnavailable();
13296
+ markUnavailable(hookCause("tool-after", "hook-threw"));
13220
13297
  }
13221
13298
  }
13222
13299
  function isInternalSystem(system) {
@@ -13268,19 +13345,19 @@ ${marker}` : marker;
13268
13345
  },
13269
13346
  status: () => {
13270
13347
  ensureSynchronousRuntime();
13271
- return initialized ? guard.status() : unavailableWorkflowStatus();
13348
+ return initialized ? requireGuard().status() : unavailableWorkflowStatus();
13272
13349
  },
13273
13350
  readStatus,
13274
- unavailableCause: () => firstUnavailableCause,
13351
+ unavailableCause: () => firstUnavailableCause ?? pendingUnavailableCause,
13275
13352
  seedDeferrals: currentSeedDeferrals,
13276
13353
  refreshReadback,
13277
13354
  observeReceipt: (input) => {
13278
13355
  ensureSynchronousRuntime();
13279
- return initialized ? guard.observeReceipt(input) : { status: "unavailable", reasonCode: "guard-unavailable" };
13356
+ return initialized ? requireGuard().observeReceipt(input) : { status: "unavailable", reasonCode: "guard-unavailable" };
13280
13357
  },
13281
13358
  prepareTransition: (input) => {
13282
13359
  ensureSynchronousRuntime();
13283
- return initialized ? guard.prepareTransition(input) : { status: "unavailable", reasonCode: "guard-unavailable" };
13360
+ return initialized ? requireGuard().prepareTransition(input) : { status: "unavailable", reasonCode: "guard-unavailable" };
13284
13361
  },
13285
13362
  startUnit: (input, policy) => {
13286
13363
  ensureSynchronousRuntime();
@@ -13342,13 +13419,13 @@ function makeWorkflowTool(description, args2, getRuntime, execute) {
13342
13419
  metadata: runtime.metadata()
13343
13420
  });
13344
13421
  } catch {
13345
- runtime.markUnavailable();
13422
+ runtime.markUnavailable(hookCause("tool-execute", "hook-threw"));
13346
13423
  }
13347
13424
  }
13348
13425
  try {
13349
13426
  metadata2 = runtime.metadata();
13350
13427
  } catch {
13351
- runtime.markUnavailable();
13428
+ runtime.markUnavailable(hookCause("tool-execute", "hook-threw"));
13352
13429
  metadata2 = {
13353
13430
  protocolVersion: MARKER_PROTOCOL_VERSION,
13354
13431
  state: "unavailable",
@@ -13414,25 +13491,13 @@ function createOpencodeWorkflowGuard(options) {
13414
13491
  const host = parseHostBefore(input);
13415
13492
  if (!host)
13416
13493
  return;
13417
- const runtime = sessionRuntimeFor(host.sessionID);
13418
- try {
13419
- await runtime.hooks["tool.execute.before"](input, output);
13420
- } catch (error) {
13421
- if (isWorkflowGuardBlockedError(error))
13422
- throw error;
13423
- runtime.markUnavailable();
13424
- }
13494
+ await sessionRuntimeFor(host.sessionID).hooks["tool.execute.before"](input, output);
13425
13495
  }
13426
13496
  async function after(input, output) {
13427
13497
  const host = parseHostAfter(input);
13428
13498
  if (!host)
13429
13499
  return;
13430
- const runtime = sessionRuntimeFor(host.sessionID);
13431
- try {
13432
- await runtime.hooks["tool.execute.after"](input, output);
13433
- } catch {
13434
- runtime.markUnavailable();
13435
- }
13500
+ await sessionRuntimeFor(host.sessionID).hooks["tool.execute.after"](input, output);
13436
13501
  }
13437
13502
  async function event(input) {
13438
13503
  if (!isRecord7(input) || !isRecord7(input.event))
@@ -13445,7 +13510,7 @@ function createOpencodeWorkflowGuard(options) {
13445
13510
  try {
13446
13511
  await runtime.hooks.event(input);
13447
13512
  } catch {
13448
- runtime.markUnavailable();
13513
+ runtime.markUnavailable(hookCause("event", "hook-threw"));
13449
13514
  }
13450
13515
  }
13451
13516
  async function transform(input, output) {
@@ -13455,7 +13520,7 @@ function createOpencodeWorkflowGuard(options) {
13455
13520
  try {
13456
13521
  await runtime.hooks["experimental.chat.system.transform"](input, output);
13457
13522
  } catch {
13458
- runtime.markUnavailable();
13523
+ runtime.markUnavailable(hookCause("transform", "hook-threw"));
13459
13524
  }
13460
13525
  }
13461
13526
  return {